Skip to content
README.md 58.7 KiB
Newer Older
Luker's avatar
Luker committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
# Eigen Tensors

Tensors are multidimensional arrays of elements. Elements are typically scalars,
but more complex types such as strings are also supported.

[TOC]

## Tensor Classes

You can manipulate a tensor with one of the following classes.  They all are in
the namespace ```::Eigen.```


### Class Tensor<data_type, rank>

This is the class to use to create a tensor and allocate memory for it.  The
class is templatized with the tensor datatype, such as float or int, and the
tensor rank.  The rank is the number of dimensions, for example rank 2 is a
matrix.

Tensors of this class are resizable.  For example, if you assign a tensor of a
different size to a Tensor, that tensor is resized to match its new value.

#### Constructor Tensor<data_type, rank>(size0, size1, ...)

Constructor for a Tensor.  The constructor must be passed ```rank``` integers
indicating the sizes of the instance along each of the the ```rank```
dimensions.

    // Create a tensor of rank 3 of sizes 2, 3, 4.  This tensor owns
    // memory to hold 24 floating point values (24 = 2 x 3 x 4).
    Tensor<float, 3> t_3d(2, 3, 4);

    // Resize t_3d by assigning a tensor of different sizes, but same rank.
    t_3d = Tensor<float, 3>(3, 4, 3);

#### Constructor Tensor<data_type, rank>(size_array)

Constructor where the sizes for the constructor are specified as an array of
values instead of an explicitly list of parameters.  The array type to use is
```Eigen::array<Eigen::Index>```.  The array can be constructed automatically
from an initializer list.

    // Create a tensor of strings of rank 2 with sizes 5, 7.
    Tensor<string, 2> t_2d({5, 7});


### Class TensorFixedSize<data_type, Sizes<size0, size1, ...>>

Class to use for tensors of fixed size, where the size is known at compile
time.  Fixed sized tensors can provide very fast computations because all their
dimensions are known by the compiler.  FixedSize tensors are not resizable.

If the total number of elements in a fixed size tensor is small enough the
tensor data is held onto the stack and does not cause heap allocation and free.

    // Create a 4 x 3 tensor of floats.
    TensorFixedSize<float, Sizes<4, 3>> t_4x3;

### Class TensorMap<Tensor<data_type, rank>>

This is the class to use to create a tensor on top of memory allocated and
owned by another part of your code.  It allows to view any piece of allocated
memory as a Tensor.  Instances of this class do not own the memory where the
data are stored.

A TensorMap is not resizable because it does not own the memory where its data
are stored.

#### Constructor TensorMap<Tensor<data_type, rank>>(data, size0, size1, ...)

Constructor for a Tensor.  The constructor must be passed a pointer to the
storage for the data, and "rank" size attributes.  The storage has to be
large enough to hold all the data.

    // Map a tensor of ints on top of stack-allocated storage.
    int storage[128];  // 2 x 4 x 2 x 8 = 128
    TensorMap<Tensor<int, 4>> t_4d(storage, 2, 4, 2, 8);

    // The same storage can be viewed as a different tensor.
    // You can also pass the sizes as an array.
    TensorMap<Tensor<int, 2>> t_2d(storage, 16, 8);

    // You can also map fixed-size tensors.  Here we get a 1d view of
    // the 2d fixed-size tensor.
    Tensor<float, Sizes<4, 5>> t_4x3;
    TensorMap<Tensor<float, 1>> t_12(t_4x3, 12);


#### Class TensorRef

See Assigning to a TensorRef below.

## Accessing Tensor Elements

#### <data_type> tensor(index0, index1...)

Return the element at position ```(index0, index1...)``` in tensor
```tensor```.  You must pass as many parameters as the rank of ```tensor```.
The expression can be used as an l-value to set the value of the element at the
specified position.  The value returned is of the datatype of the tensor.

    // Set the value of the element at position (0, 1, 0);
    Tensor<float, 3> t_3d(2, 3, 4);
    t_3d(0, 1, 0) = 12.0f;

    // Initialize all elements to random values.
    for (int i = 0; i < 2; ++i) {
      for (int j = 0; j < 3; ++j) {
        for (int k = 0; k < 4; ++k) {
          t_3d(i, j, k) = ...some random value...;
        }
      }
    }

    // Print elements of a tensor.
    for (int i = 0; i < 2; ++i) {
      LOG(INFO) << t_3d(i, 0, 0);
    }


## TensorLayout

The tensor library supports 2 layouts: ```ColMajor``` (the default) and
```RowMajor```.  Only the default column major layout is currently fully
supported, and it is therefore not recommended to attempt to use the row major
layout at the moment.

The layout of a tensor is optionally specified as part of its type. If not
specified explicitly column major is assumed.

    Tensor<float, 3, ColMajor> col_major;  // equivalent to Tensor<float, 3>
    TensorMap<Tensor<float, 3, RowMajor> > row_major(data, ...);

All the arguments to an expression must use the same layout. Attempting to mix
different layouts will result in a compilation error.

It is possible to change the layout of a tensor or an expression using the
```swap_layout()``` method.  Note that this will also reverse the order of the
dimensions.

    Tensor<float, 2, ColMajor> col_major(2, 4);
    Tensor<float, 2, RowMajor> row_major(2, 4);

    Tensor<float, 2> col_major_result = col_major;  // ok, layouts match
    Tensor<float, 2> col_major_result = row_major;  // will not compile

    // Simple layout swap
    col_major_result = row_major.swap_layout();
    eigen_assert(col_major_result.dimension(0) == 4);
    eigen_assert(col_major_result.dimension(1) == 2);

    // Swap the layout and preserve the order of the dimensions
    array<int, 2> shuffle(1, 0);
    col_major_result = row_major.swap_layout().shuffle(shuffle);
    eigen_assert(col_major_result.dimension(0) == 2);
    eigen_assert(col_major_result.dimension(1) == 4);


## Tensor Operations

The Eigen Tensor library provides a vast library of operations on Tensors:
numerical operations such as addition and multiplication, geometry operations
such as slicing and shuffling, etc.  These operations are available as methods
of the Tensor classes, and in some cases as operator overloads.  For example
the following code computes the elementwise addition of two tensors:

    Tensor<float, 3> t1(2, 3, 4);
    ...set some values in t1...
    Tensor<float, 3> t2(2, 3, 4);
    ...set some values in t2...
    // Set t3 to the element wise sum of t1 and t2
    Tensor<float, 3> t3 = t1 + t2;

While the code above looks easy enough, it is important to understand that the
expression ```t1 + t2``` is not actually adding the values of the tensors.  The
expression instead constructs a "tensor operator" object of the class
TensorCwiseBinaryOp<scalar_sum>, which has references to the tensors
```t1``` and ```t2```.  This is a small C++ object that knows how to add
```t1``` and ```t2```.  It is only when the value of the expression is assigned
to the tensor ```t3``` that the addition is actually performed.  Technically,
this happens through the overloading of ```operator=()``` in the Tensor class.

This mechanism for computing tensor expressions allows for lazy evaluation and
optimizations which are what make the tensor library very fast.

Of course, the tensor operators do nest, and the expression ```t1 + t2 *
0.3f``` is actually represented with the (approximate) tree of operators:

    TensorCwiseBinaryOp<scalar_sum>(t1, TensorCwiseUnaryOp<scalar_mul>(t2, 0.3f))


### Tensor Operations and C++ "auto"

Because Tensor operations create tensor operators, the C++ ```auto``` keyword
does not have its intuitive meaning.  Consider these 2 lines of code:

    Tensor<float, 3> t3 = t1 + t2;
    auto t4 = t1 + t2;

In the first line we allocate the tensor ```t3``` and it will contain the
result of the addition of ```t1``` and ```t2```.  In the second line, ```t4```
is actually the tree of tensor operators that will compute the addition of
```t1``` and ```t2```.  In fact, ```t4``` is *not* a tensor and you cannot get
the values of its elements:

    Tensor<float, 3> t3 = t1 + t2;
    cout << t3(0, 0, 0);  // OK prints the value of t1(0, 0, 0) + t2(0, 0, 0)

    auto t4 = t1 + t2;
    cout << t4(0, 0, 0);  // Compilation error!

When you use ```auto``` you do not get a Tensor as a result but instead a
non-evaluated expression.  So only use ```auto``` to delay evaluation.

Unfortunately, there is no single underlying concrete type for holding
non-evaluated expressions, hence you have to use auto in the case when you do
want to hold non-evaluated expressions.

When you need the results of set of tensor computations you have to assign the
result to a Tensor that will be capable of holding onto them.  This can be
either a normal Tensor, a fixed size Tensor, or a TensorMap on an existing
piece of memory.  All the following will work:

    auto t4 = t1 + t2;

    Tensor<float, 3> result = t4;  // Could also be: result(t4);
    cout << result(0, 0, 0);

    TensorMap<float, 4> result(<a float* with enough space>, <size0>, ...) = t4;
    cout << result(0, 0, 0);

    TensorFixedSize<float, Sizes<size0, ...>> result = t4;
    cout << result(0, 0, 0);

Until you need the results, you can keep the operation around, and even reuse
it for additional operations.  As long as you keep the expression as an
operation, no computation is performed.

    // One way to compute exp((t1 + t2) * 0.2f);
    auto t3 = t1 + t2;
    auto t4 = t3 * 0.2f;
    auto t5 = t4.exp();
    Tensor<float, 3> result = t5;

    // Another way, exactly as efficient as the previous one:
    Tensor<float, 3> result = ((t1 + t2) * 0.2f).exp();

### Controlling When Expression are Evaluated

There are several ways to control when expressions are evaluated:

*   Assignment to a Tensor, TensorFixedSize, or TensorMap.
*   Use of the eval() method.
*   Assignment to a TensorRef.

#### Assigning to a Tensor, TensorFixedSize, or TensorMap.

The most common way to evaluate an expression is to assign it to a Tensor.  In
the example below, the ```auto``` declarations make the intermediate values
"Operations", not Tensors, and do not cause the expressions to be evaluated.
The assignment to the Tensor ```result``` causes the evaluation of all the
operations.

    auto t3 = t1 + t2;             // t3 is an Operation.
    auto t4 = t3 * 0.2f;           // t4 is an Operation.
    auto t5 = t4.exp();            // t5 is an Operation.
    Tensor<float, 3> result = t5;  // The operations are evaluated.

If you know the ranks and sizes of the Operation value you can assign the
Operation to a TensorFixedSize instead of a Tensor, which is a bit more
efficient.

    // We know that the result is a 4x4x2 tensor!
    TensorFixedSize<float, 4, 4, 2> result = t5;

Simiarly, assigning an expression to a TensorMap causes its evaluation.  Like
tensors of type TensorFixedSize, TensorMaps cannot be resized so they have to
have the rank and sizes of the expression that are assigned to them.

#### Calling eval().

When you compute large composite expressions, you sometimes want to tell Eigen
that an intermediate value in the expression tree is worth evaluating ahead of
time.  This is done by inserting a call to the ```eval()``` method of the
expression Operation.

    // The previous example could have been written:
    Tensor<float, 3> result = ((t1 + t2) * 0.2f).exp();

    // If you want to compute (t1 + t2) once ahead of time you can write:
    Tensor<float, 3> result = ((t1 + t2).eval() * 0.2f).exp();

Semantically, calling ```eval()``` is equivalent to materializing the value of
the expression in a temporary Tensor of the right size.  The code above in
effect does:

    // .eval() knows the size!
    TensorFixedSize<float, 4, 4, 2> tmp = t1 + t2;
    Tensor<float, 3> result = (tmp * 0.2f).exp();

Note that the return value of ```eval()``` is itself an Operation, so the
following code does not do what you may think:

    // Here t3 is an evaluation Operation.  t3 has not been evaluated yet.
    auto t3 = (t1 + t2).eval();

    // You can use t3 in another expression.  Still no evaluation.
    auto t4 = (t3 * 0.2f).exp();

    // The value is evaluated when you assign the Operation to a Tensor, using
    // an intermediate tensor to represent t3.x
    Tensor<float, 3> result = t4;

While in the examples above calling ```eval()``` does not make a difference in
performance, in other cases it can make a huge difference.  In the expression
below the ```broadcast()``` expression causes the ```X.maximum()``` expression
to be evaluated many times:

    Tensor<...> X ...;
    Tensor<...> Y = ((X - X.maximum(depth_dim).reshape(dims2d).broadcast(bcast))
                     * beta).exp();

Inserting a call to ```eval()``` between the ```maximum()``` and
```reshape()``` calls guarantees that maximum() is only computed once and
greatly speeds-up execution:

    Tensor<...> Y =
      ((X - X.maximum(depth_dim).eval().reshape(dims2d).broadcast(bcast))
        * beta).exp();

In the other example below, the tensor ```Y``` is both used in the expression
and its assignment.  This is an aliasing problem and if the evaluation is not
done in the right order Y will be updated incrementally during the evaluation
resulting in bogus results:

     Tensor<...> Y ...;
     Y = Y / (Y.sum(depth_dim).reshape(dims2d).broadcast(bcast));

Inserting a call to ```eval()``` between the ```sum()``` and ```reshape()```
expressions ensures that the sum is computed before any updates to ```Y``` are
done.

     Y = Y / (Y.sum(depth_dim).eval().reshape(dims2d).broadcast(bcast));

Note that an eval around the full right hand side expression is not needed
because the generated has to compute the i-th value of the right hand side
before assigning it to the left hand side.

However, if you were assigning the expression value to a shuffle of ```Y```
then you would need to force an eval for correctness by adding an ```eval()```
call for the right hand side:

     Y.shuffle(...) =
        (Y / (Y.sum(depth_dim).eval().reshape(dims2d).broadcast(bcast))).eval();


#### Assigning to a TensorRef.

If you need to access only a few elements from the value of an expression you
can avoid materializing the value in a full tensor by using a TensorRef.

A TensorRef is a small wrapper class for any Eigen Operation.  It provides
overloads for the ```()``` operator that let you access individual values in
the expression.  TensorRef is convenient, because the Operation themselves do
not provide a way to access individual elements.

    // Create a TensorRef for the expression.  The expression is not
    // evaluated yet.
    TensorRef<Tensor<float, 3> > ref = ((t1 + t2) * 0.2f).exp();

    // Use "ref" to access individual elements.  The expression is evaluated
    // on the fly.
    float at_0 = ref(0, 0, 0);
    cout << ref(0, 1, 0);

Only use TensorRef when you need a subset of the values of the expression.
TensorRef only computes the values you access.  However note that if you are
going to access all the values it will be much faster to materialize the
results in a Tensor first.

In some cases, if the full Tensor result would be very large, you may save
memory by accessing it as a TensorRef.  But not always.  So don't count on it.


### Controlling How Expressions Are Evaluated

The tensor library provides several implementations of the various operations
such as contractions and convolutions.  The implementations are optimized for
different environments: single threaded on CPU, multi threaded on CPU, or on a
GPU using cuda.  Additional implementations may be added later.

You can choose which implementation to use with the ```device()``` call.  If
you do not choose an implementation explicitly the default implementation that
uses a single thread on the CPU is used.

The default implementation has been optimized for recent Intel CPUs, taking
advantage of SSE, AVX, and FMA instructions.  Work is ongoing to tune the
library on ARM CPUs.  Note that you need to pass compiler-dependent flags
to enable the use of SSE, AVX, and other instructions.

For example, the following code adds two tensors using the default
single-threaded CPU implementation:

    Tensor<float, 2> a(30, 40);
    Tensor<float, 2> b(30, 40);
    Tensor<float, 2> c = a + b;

To choose a different implementation you have to insert a ```device()``` call
before the assignment of the result.  For technical C++ reasons this requires
that the Tensor for the result be declared on its own.  This means that you
have to know the size of the result.

    Eigen::Tensor<float, 2> c(30, 40);
    c.device(...) = a + b;

The call to ```device()``` must be the last call on the left of the operator=.

You must pass to the ```device()``` call an Eigen device object.  There are
presently three devices you can use: DefaultDevice, ThreadPoolDevice and
GpuDevice.


#### Evaluating With the DefaultDevice

This is exactly the same as not inserting a ```device()``` call.

    DefaultDevice my_device;
    c.device(my_device) = a + b;

#### Evaluating with a Thread Pool

    // Create the Eigen ThreadPoolDevice.
    Eigen::ThreadPoolDevice my_device(4 /* number of threads to use */);

    // Now just use the device when evaluating expressions.
    Eigen::Tensor<float, 2> c(30, 50);
    c.device(my_device) = a.contract(b, dot_product_dims);


#### Evaluating On GPU

This is presently a bit more complicated than just using a thread pool device.
You need to create a GPU device but you also need to explicitly allocate the
memory for tensors with cuda.


## API Reference

### Datatypes

In the documentation of the tensor methods and Operation we mention datatypes
that are tensor-type specific:

#### <Tensor-Type>::Dimensions

Acts like an array of ints.  Has an ```int size``` attribute, and can be
indexed like an array to access individual values.  Used to represent the
dimensions of a tensor.  See ```dimensions()```.

#### <Tensor-Type>::Index

Acts like an ```int```.  Used for indexing tensors along their dimensions.  See
```operator()```, ```dimension()```, and ```size()```.

#### <Tensor-Type>::Scalar

Represents the datatype of individual tensor elements.  For example, for a
```Tensor<float>```, ```Scalar``` is the type ```float```.  See
```setConstant()```.

#### <Operation>

We use this pseudo type to indicate that a tensor Operation is returned by a
method.  We indicate in the text the type and dimensions of the tensor that the
Operation returns after evaluation.

The Operation will have to be evaluated, for example by assigning it to a
tensor, before you can access the values of the resulting tensor.  You can also
access the values through a TensorRef.


## Built-in Tensor Methods

These are usual C++ methods that act on tensors immediately.  They are not
Operations which provide delayed evaluation of their results.  Unless specified
otherwise, all the methods listed below are available on all tensor classes:
Tensor, TensorFixedSize, and TensorMap.

## Metadata

### int NumDimensions

Constant value indicating the number of dimensions of a Tensor.  This is also
known as the tensor "rank".

      Eigen::Tensor<float, 2> a(3, 4);
      cout << "Dims " << a.NumDimensions;
      => Dims 2

### Dimensions dimensions()

Returns an array-like object representing the dimensions of the tensor.
The actual type of the dimensions() result is <Tensor-Type>::Dimensions.

    Eigen::Tensor<float, 2> a(3, 4);
    const Eigen::Tensor<float, 2>::Dimensions& d = a.dimensions();
    cout << "Dim size: " << d.size << ", dim 0: " << d[0]
         << ", dim 1: " << d[1];
    => Dim size: 2, dim 0: 3, dim 1: 4

If you use a C++11 compiler, you can use ```auto``` to simplify the code:

    const auto& d = a.dimensions();
    cout << "Dim size: " << d.size << ", dim 0: " << d[0]
         << ", dim 1: " << d[1];
    => Dim size: 2, dim 0: 3, dim 1: 4

### Index dimension(Index n)

Returns the n-th dimension of the tensor.  The actual type of the
```dimension()``` result is ```<Tensor-Type>::Index```, but you can
always use it like an int.

      Eigen::Tensor<float, 2> a(3, 4);
      int dim1 = a.dimension(1);
      cout << "Dim 1: " << dim1;
      => Dim 1: 4

### Index size()

Returns the total number of elements in the tensor.  This is the product of all
the tensor dimensions.  The actual type of the ```size()``` result is
```<Tensor-Type>::Index```, but you can always use it like an int.

    Eigen::Tensor<float, 2> a(3, 4);
    cout << "Size: " << a.size();
    => Size: 12


### Getting Dimensions From An Operation

A few operations provide ```dimensions()``` directly,
e.g. ```TensorReslicingOp```.  Most operations defer calculating dimensions
until the operation is being evaluated.  If you need access to the dimensions
of a deferred operation, you can wrap it in a TensorRef (see Assigning to a
TensorRef above), which provides ```dimensions()``` and ```dimension()``` as
above.

TensorRef can also wrap the plain Tensor types, so this is a useful idiom in
templated contexts where the underlying object could be either a raw Tensor
or some deferred operation (e.g. a slice of a Tensor).  In this case, the
template code can wrap the object in a TensorRef and reason about its
dimensionality while remaining agnostic to the underlying type.


## Constructors

### Tensor

Creates a tensor of the specified size. The number of arguments must be equal
to the rank of the tensor. The content of the tensor is not initialized.

    Eigen::Tensor<float, 2> a(3, 4);
    cout << "NumRows: " << a.dimension(0) << " NumCols: " << a.dimension(1) << endl;
    => NumRows: 3 NumCols: 4

### TensorFixedSize

Creates a tensor of the specified size. The number of arguments in the Size<>
template parameter determines the rank of the tensor. The content of the tensor
is not initialized.

    Eigen::TensorFixedSize<float, Size<3, 4>> a;
    cout << "Rank: " << a.rank() << endl;
    => Rank: 2
    cout << "NumRows: " << a.dimension(0) << " NumCols: " << a.dimension(1) << endl;
    => NumRows: 3 NumCols: 4

### TensorMap

Creates a tensor mapping an existing array of data. The data must not be freed
until the TensorMap is discarded, and the size of the data must be large enough
to accomodate of the coefficients of the tensor.

    float data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
    Eigen::TensorMap<float, 2> a(data, 3, 4);
    cout << "NumRows: " << a.dimension(0) << " NumCols: " << a.dimension(1) << endl;
    => NumRows: 3 NumCols: 4
    cout << "a(1, 2): " << a(1, 2) << endl;
    => a(1, 2): 9


## Contents Initialization

When a new Tensor or a new TensorFixedSize are created, memory is allocated to
hold all the tensor elements, but the memory is not initialized.  Similarly,
when a new TensorMap is created on top of non-initialized memory the memory its
contents are not initialized.

You can use one of the methods below to initialize the tensor memory.  These
have an immediate effect on the tensor and return the tensor itself as a
result.  These are not tensor Operations which delay evaluation.

### <Tensor-Type> setConstant(const Scalar& val)

Sets all elements of the tensor to the constant value ```val```.  ```Scalar```
is the type of data stored in the tensor.  You can pass any value that is
convertible to that type.

Returns the tensor itself in case you want to chain another call.

    a.setConstant(12.3f);
    cout << "Constant: " << endl << a << endl << endl;
    =>
    Constant:
    12.3 12.3 12.3 12.3
    12.3 12.3 12.3 12.3
    12.3 12.3 12.3 12.3

Note that ```setConstant()``` can be used on any tensor where the element type
has a copy constructor and an ```operator=()```:

    Eigen::Tensor<string, 2> a(2, 3);
    a.setConstant("yolo");
    cout << "String tensor: " << endl << a << endl << endl;
    =>
    String tensor:
    yolo yolo yolo
    yolo yolo yolo


### <Tensor-Type> setZero()

Fills the tensor with zeros.  Equivalent to ```setConstant(Scalar(0))```.
Returns the tensor itself in case you want to chain another call.

    a.setZero();
    cout << "Zeros: " << endl << a << endl << endl;
    =>
    Zeros:
    0 0 0 0
    0 0 0 0
    0 0 0 0


### <Tensor-Type> setValues({..initializer_list})

Fills the tensor with explicit values specified in a std::initializer_list.
The type of the initializer list depends on the type and rank of the tensor.

If the tensor has rank N, the initializer list must be nested N times.  The
most deeply nested lists must contains P scalars of the Tensor type where P is
the size of the last dimension of the Tensor.

For example, for a ```TensorFixedSize<float, 2, 3>``` the initializer list must
contains 2 lists of 3 floats each.

```setValues()``` returns the tensor itself in case you want to chain another
call.

    Eigen::Tensor<float, 2> a(2, 3);
    a.setValues({{0.0f, 1.0f, 2.0f}, {3.0f, 4.0f, 5.0f}});
    cout << "a" << endl << a << endl << endl;
    =>
    a
    0 1 2
    3 4 5

If a list is too short, the corresponding elements of the tensor will not be
changed.  This is valid at each level of nesting.  For example the following
code only sets the values of the first row of the tensor.

    Eigen::Tensor<int, 2> a(2, 3);
    a.setConstant(1000);
    a.setValues({{10, 20, 30}});
    cout << "a" << endl << a << endl << endl;
    =>
    a
    10   20   30
    1000 1000 1000

### <Tensor-Type> setRandom()

Fills the tensor with random values.  Returns the tensor itself in case you
want to chain another call.

    a.setRandom();
    cout << "Random: " << endl << a << endl << endl;
    =>
    Random:
      0.680375    0.59688  -0.329554    0.10794
     -0.211234   0.823295   0.536459 -0.0452059
      0.566198  -0.604897  -0.444451   0.257742

You can customize ```setRandom()``` by providing your own random number
generator as a template argument:

    a.setRandom<MyRandomGenerator>();

Here, ```MyRandomGenerator``` must be a struct with the following member
functions, where Scalar and Index are the same as ```<Tensor-Type>::Scalar```
and ```<Tensor-Type>::Index```.

See ```struct UniformRandomGenerator``` in TensorFunctors.h for an example.

    // Custom number generator for use with setRandom().
    struct MyRandomGenerator {
      // Default and copy constructors. Both are needed
      MyRandomGenerator() { }
      MyRandomGenerator(const MyRandomGenerator& ) { }

      // Return a random value to be used.  "element_location" is the
      // location of the entry to set in the tensor, it can typically
      // be ignored.
      Scalar operator()(Eigen::DenseIndex element_location,
                        Eigen::DenseIndex /*unused*/ = 0) const {
        return <randomly generated value of type T>;
      }

      // Same as above but generates several numbers at a time.
      typename internal::packet_traits<Scalar>::type packetOp(
          Eigen::DenseIndex packet_location, Eigen::DenseIndex /*unused*/ = 0) const {
        return <a packet of randomly generated values>;
      }
    };

You can also use one of the 2 random number generators that are part of the
tensor library:
*   UniformRandomGenerator
*   NormalRandomGenerator


## Data Access

The Tensor, TensorFixedSize, and TensorRef classes provide the following
accessors to access the tensor coefficients:

    const Scalar& operator()(const array<Index, NumIndices>& indices)
    const Scalar& operator()(Index firstIndex, IndexTypes... otherIndices)
    Scalar& operator()(const array<Index, NumIndices>& indices)
    Scalar& operator()(Index firstIndex, IndexTypes... otherIndices)

The number of indices must be equal to the rank of the tensor. Moreover, these
accessors are not available on tensor expressions. In order to access the
values of a tensor expression, the expression must either be evaluated or
wrapped in a TensorRef.


### Scalar* data() and const Scalar* data() const

Returns a pointer to the storage for the tensor.  The pointer is const if the
tensor was const.  This allows direct access to the data.  The layout of the
data depends on the tensor layout: RowMajor or ColMajor.

This access is usually only needed for special cases, for example when mixing
Eigen Tensor code with other libraries.

Scalar is the type of data stored in the tensor.

    Eigen::Tensor<float, 2> a(3, 4);
    float* a_data = a.data();
    a_data[0] = 123.45f;
    cout << "a(0, 0): " << a(0, 0);
    => a(0, 0): 123.45


## Tensor Operations

All the methods documented below return non evaluated tensor ```Operations```.
These can be chained: you can apply another Tensor Operation to the value
returned by the method.

The chain of Operation is evaluated lazily, typically when it is assigned to a
tensor.  See "Controlling when Expression are Evaluated" for more details about
their evaluation.

### <Operation> constant(const Scalar& val)

Returns a tensor of the same type and dimensions as the original tensor but
where all elements have the value ```val```.

This is useful, for example, when you want to add or subtract a constant from a
tensor, or multiply every element of a tensor by a scalar.

    Eigen::Tensor<float, 2> a(2, 3);
    a.setConstant(1.0f);
    Eigen::Tensor<float, 2> b = a + a.constant(2.0f);
    Eigen::Tensor<float, 2> c = b * b.constant(0.2f);
    cout << "a" << endl << a << endl << endl;
    cout << "b" << endl << b << endl << endl;
    cout << "c" << endl << c << endl << endl;
    =>
    a
    1 1 1
    1 1 1

    b
    3 3 3
    3 3 3

    c
    0.6 0.6 0.6
    0.6 0.6 0.6

### <Operation> random()

Returns a tensor of the same type and dimensions as the current tensor
but where all elements have random values.

This is for example useful to add random values to an existing tensor.
The generation of random values can be customized in the same manner
as for ```setRandom()```.

    Eigen::Tensor<float, 2> a(2, 3);
    a.setConstant(1.0f);
    Eigen::Tensor<float, 2> b = a + a.random();
    cout << "a" << endl << a << endl << endl;
    cout << "b" << endl << b << endl << endl;
    =>
    a
    1 1 1
    1 1 1

    b
    1.68038   1.5662  1.82329
    0.788766  1.59688 0.395103


## Unary Element Wise Operations

All these operations take a single input tensor as argument and return a tensor
of the same type and dimensions as the tensor to which they are applied.  The
requested operations are applied to each element independently.

### <Operation> operator-()

Returns a tensor of the same type and dimensions as the original tensor
containing the opposite values of the original tensor.

    Eigen::Tensor<float, 2> a(2, 3);
    a.setConstant(1.0f);
    Eigen::Tensor<float, 2> b = -a;
    cout << "a" << endl << a << endl << endl;
    cout << "b" << endl << b << endl << endl;
    =>
    a
    1 1 1
    1 1 1

    b
    -1 -1 -1
    -1 -1 -1

### <Operation> sqrt()

Returns a tensor of the same type and dimensions as the original tensor
containing the square roots of the original tensor.

### <Operation> rsqrt()

Returns a tensor of the same type and dimensions as the original tensor
containing the inverse square roots of the original tensor.

### <Operation> square()

Returns a tensor of the same type and dimensions as the original tensor
containing the squares of the original tensor values.

### <Operation> inverse()

Returns a tensor of the same type and dimensions as the original tensor
containing the inverse of the original tensor values.

### <Operation> exp()

Returns a tensor of the same type and dimensions as the original tensor
containing the exponential of the original tensor.

### <Operation> log()

Returns a tensor of the same type and dimensions as the original tensor
containing the natural logarithms of the original tensor.

### <Operation> abs()

Returns a tensor of the same type and dimensions as the original tensor
containing the absolute values of the original tensor.

### <Operation> pow(Scalar exponent)

Returns a tensor of the same type and dimensions as the original tensor
containing the coefficients of the original tensor to the power of the
exponent.

The type of the exponent, Scalar, is always the same as the type of the
tensor coefficients.  For example, only integer exponents can be used in
conjuntion with tensors of integer values.

You can use cast() to lift this restriction.  For example this computes
cubic roots of an int Tensor:

    Eigen::Tensor<int, 2> a(2, 3);
    a.setValues({{0, 1, 8}, {27, 64, 125}});
    Eigen::Tensor<double, 2> b = a.cast<double>().pow(1.0 / 3.0);
    cout << "a" << endl << a << endl << endl;
    cout << "b" << endl << b << endl << endl;
    =>
    a
    0   1   8
    27  64 125

    b
    0 1 2
    3 4 5

### <Operation>  operator * (Scalar scale)

Multiplies all the coefficients of the input tensor by the provided scale.

### <Operation>  cwiseMax(Scalar threshold)
TODO

### <Operation>  cwiseMin(Scalar threshold)
TODO

### <Operation>  unaryExpr(const CustomUnaryOp& func)
TODO


## Binary Element Wise Operations

These operations take two input tensors as arguments. The 2 input tensors should
be of the same type and dimensions. The result is a tensor of the same
dimensions as the tensors to which they are applied, and unless otherwise
specified it is also of the same type. The requested operations are applied to
each pair of elements independently.

### <Operation> operator+(const OtherDerived& other)

Returns a tensor of the same type and dimensions as the input tensors
containing the coefficient wise sums of the inputs.

### <Operation> operator-(const OtherDerived& other)

Returns a tensor of the same type and dimensions as the input tensors
containing the coefficient wise differences of the inputs.

### <Operation> operator*(const OtherDerived& other)

Returns a tensor of the same type and dimensions as the input tensors
containing the coefficient wise products of the inputs.

### <Operation> operator/(const OtherDerived& other)

Returns a tensor of the same type and dimensions as the input tensors
containing the coefficient wise quotients of the inputs.

This operator is not supported for integer types.

### <Operation> cwiseMax(const OtherDerived& other)

Returns a tensor of the same type and dimensions as the input tensors
containing the coefficient wise maximums of the inputs.

### <Operation> cwiseMin(const OtherDerived& other)

Returns a tensor of the same type and dimensions as the input tensors
containing the coefficient wise mimimums of the inputs.

### <Operation> Logical operators

The following logical operators are supported as well:

*   operator&&(const OtherDerived& other)
*   operator||(const OtherDerived& other)
*   operator<(const OtherDerived& other)
*   operator<=(const OtherDerived& other)
*   operator>(const OtherDerived& other)
*   operator>=(const OtherDerived& other)
*   operator==(const OtherDerived& other)
*   operator!=(const OtherDerived& other)

They all return a tensor of boolean values.


## Selection (select(const ThenDerived& thenTensor, const ElseDerived& elseTensor)

Selection is a coefficient-wise ternary operator that is the tensor equivalent
to the if-then-else operation.

    Tensor<bool, 3> if = ...;
    Tensor<float, 3> then = ...;
    Tensor<float, 3> else = ...;
    Tensor<float, 3> result = if.select(then, else);

The 3 arguments must be of the same dimensions, which will also be the dimension
of the result.  The 'if' tensor must be of type boolean, the 'then' and the
'else' tensor must be of the same type, which will also be the type of the
result.