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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
|
---
title: Layers
teaser: Weights layers, transforms, combinators and wrappers
next: /docs/api-optimizers
---
This page describes functions for defining your model. Each layer is implemented
in its own module in
[`thinc.layers`](https://github.com/explosion/thinc/blob/master/thinc/layers)
and can be imported from `thinc.api`. Most layer files define two public
functions: a **creation function** that returns a [`Model`](/docs/api-model)
instance, and a **forward function** that performs the computation.
| | |
| ------------------------------------------ | -------------------------------------------------------------------------------- |
| [**Weights layers**](#weights-layers) | Layers that use an internal weights matrix for their computations. |
| [**Reduction operations**](#reduction-ops) | Layers that perform rank reductions, e.g. pooling from word to sentence vectors. |
| [**Combinators**](#combinators) | Layers that combine two or more existing layers. |
| [**Data type transfers**](#transfers) | Layers that transform data to different types. |
| [**Wrappers**](#wrappers) | Wrapper layers for other libraries like PyTorch and TensorFlow. |
## Weights layers {#weights-layers}
### CauchySimilarity {#cauchysimilarity tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Tuple[Floats2d, Floats2d]</ndarray>
- **Output:** <ndarray shape="batch_size">Floats1d</ndarray>
- **Parameters:** <ndarray shape="1, nI">W</ndarray>
</inline-list>
Compare input vectors according to the Cauchy similarity function proposed by
[Chen (2013)](https://tspace.library.utoronto.ca/bitstream/1807/43097/3/Liu_Chen_201311_MASc_thesis.pdf).
Primarily used within [`siamese`](#siamese) neural networks.
| Argument | Type | Description |
| ----------- | --------------------------------------------------- | ------------------------------ |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| **RETURNS** | <tt>Model[Tuple[Floats2d, Floats2d], Floats1d]</tt> | The created similarity layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/cauchysimilarity.py
```
### Dish {#dish tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO, nI">W</ndarray>,
<ndarray shape="nO,">b</ndarray>
</inline-list>
A dense layer with the Dish activation function. Dish or "Daniël's Swish-like
activation" is an activation function with a non-monotinic shape similar to
[GELU](#gelu), [Swish](#swish) and [Mish](#mish). However, Dish does not rely on
elementary functions like `exp` or `erf`, making it much
[faster to compute](https://twitter.com/danieldekok/status/1484898130441166853)
in most cases.
| Argument | Type | Description |
| -------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| _keyword-only_ | | |
| `init_W` | <tt>Optional[Callable]</tt> | A function to initialize the weights matrix. Defaults to [`he_normal_init`](/docs/api-initializers#he_normal_init) when set to `None`. |
| `init_b` | <tt>Optional[Callable]</tt> | A function to initialize the bias vector. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| `dropout` | <tt>Optional[float]</tt> | Dropout rate to avoid overfitting. |
| `normalize` | <tt>bool</tt> | Whether or not to apply [layer normalization](#layernorm). Defaults to `False`. |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created dense layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/dish.py
```
### Dropout {#dropout tag="function"}
<inline-list>
- **Input:** <ndarray>ArrayXd</ndarray> / <ndarray>Sequence[ArrayXd]</ndarray> /
<ndarray>Ragged</ndarray> / <ndarray>Padded</ndarray>
- **Output:** <ndarray>ArrayXd</ndarray> / <ndarray>Sequence[ArrayXd]</ndarray>
/ <ndarray>Ragged</ndarray> / <ndarray>Padded</ndarray>
- **Attrs:** `dropout_rate` <tt>float</tt>
</inline-list>
Helps prevent overfitting by adding a random distortion to the input data during
training. Specifically, cells of the input are zeroed with probability
determined by the `dropout_rate` argument. Cells which are not zeroed are
rescaled by `1-rate`. When not in training mode, the distortion is disabled (see
[Hinton et al., 2012](https://arxiv.org/abs/1207.0580)).
```python
### Example
from thinc.api import chain, Linear, Dropout
model = chain(Linear(10, 2), Dropout(0.2))
Y, backprop = model(X, is_train=True)
# Configure dropout rate via the dropout_rate attribute.
for node in model.walk():
if node.name == "dropout":
node.attrs["dropout_rate"] = 0.5
```
| Argument | Type | Description |
| -------------- | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `dropout_rate` | <tt>float</tt> | The probability of zeroing the activations (default: 0). Higher dropout rates mean more distortion. Values around `0.2` are often good. |
| **RETURNS** | <tt>Model[T, T]</tt> | The created dropout layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/dropout.py
```
### Embed {#embed tag="function"}
<inline-list>
- **Input:** <ndarray shape="n,">Union[Ints1d, Ints2d]</ndarray>
- **Output:** <ndarray shape="n, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nV, nO">E</ndarray>
- **Attrs:** `column` <tt>int</tt>, `dropout_rate` <tt>float</tt>
</inline-list>
Map integers to vectors, using a fixed-size lookup table. The input to the layer
should be a two-dimensional array of integers, one column of which the
embeddings table will slice as the indices.
| Argument | Type | Description |
| -------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nV` | <tt>int</tt> | Number of input vectors. Defaults to `1`. |
| _keyword-only_ | | |
| `column` | <tt>int</tt> | The column to slice from the input, to get the indices. |
| `initializer` | <tt>Optional[Callable]</tt> | A function to initialize the internal parameters. Defaults to [`uniform_init`](/docs/api-initializers#uniform_init) when set to `None`. |
| `dropout` | <tt>Optional[float]</tt> | Dropout rate to avoid overfitting (default `None`). |
| **RETURNS** | <tt>Model[Union[Ints1d, Ints2d], Floats2d]</tt> | The created embedding layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/embed.py
```
### HashEmbed {#hashembed tag="function"}
<inline-list>
- **Input:** <ndarray shape="n,">Union[Ints1d, Ints2d]</ndarray> /
- **Output:** <ndarray shape="n, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nV, nO">E</ndarray>
- **Attrs:** `seed` <tt>Optional[int]</tt>, `column` <tt>int</tt>,
`dropout_rate` <tt>float</tt>
</inline-list>
An embedding layer that uses the "hashing trick" to map keys to distinct values.
The hashing trick involves hashing each key four times with distinct seeds, to
produce four likely differing values. Those values are modded into the table,
and the resulting vectors summed to produce a single result. Because it's
unlikely that two different keys will collide on all four "buckets", most
distinct keys will receive a distinct vector under this scheme, even when the
number of vectors in the table is very low.
| Argument | Type | Description |
| -------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `nO` | <tt>int</tt> | The size of the output vectors. |
| `nV` | <tt>int</tt> | Number of input vectors. |
| _keyword-only_ | | |
| `seed` | <tt>Optional[int]</tt> | A seed to use for the hashing. |
| `column` | <tt>int</tt> | The column to select features from. |
| `initializer` | <tt>Optional[Callable]</tt> | A function to initialize the internal parameters. Defaults to [`uniform_init`](/docs/api-initializers#uniform_init) when set to `None`. |
| `dropout` | <tt>Optional[float]</tt> | Dropout rate to avoid overfitting (default `None`). |
| **RETURNS** | <tt>Model[Union[Ints1d, Ints2d], Floats2d]</tt> | The created embedding layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/hashembed.py
```
### LayerNorm {#layernorm tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nI,">b</ndarray>,
<ndarray shape="nI,">G</ndarray>
</inline-list>
Perform layer normalization on the inputs
([Ba et al., 2016](https://arxiv.org/abs/1607.06450)). This layer does not
change the dimensionality of the vectors.
| Argument | Type | Description |
| ----------- | ---------------------------------- | -------------------------------- |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created normalization layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/layernorm.py
```
### Linear {#linear tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO, nI">W</ndarray>,
<ndarray shape="nO,">b</ndarray>
</inline-list>
The `Linear` layer multiplies inputs by a weights matrix `W` and adds a bias
vector `b`. In PyTorch this is called a `Linear` layer, while Keras calls it a
`Dense` layer.
```python
### Example
from thinc.api import Linear
model = Linear(10, 5)
model.initialize()
Y = model.predict(model.ops.alloc2f(2, 5))
assert Y.shape == (2, 10)
```
| Argument | Type | Description |
| -------------- | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| _keyword-only_ | | |
| `init_W` | <tt>Callable</tt> | A function to initialize the weights matrix. Defaults to [`glorot_uniform_init`](/docs/api-initializers#glorot_uniform_init). |
| `init_b` | <tt>Callable</tt> | A function to initialize the bias vector. Defaults to [`zero_init`](/docs/api-initializers#zero_init). |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created `Linear` layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/linear.py
```
### Sigmoid {#sigmoid tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO, nI">W</ndarray>,
<ndarray shape="nO,">b</ndarray>
</inline-list>
A linear (aka dense) layer, followed by a sigmoid activation. This is usually
used as an output layer for multi-label classification (in contrast to the
`Softmax` layer, which is used for problems where exactly one class is correct
per example.
| Argument | Type | Description |
| ----------- | ---------------------------------- | -------------------------------- |
| `nOs` | <tt>Tuple[int, ...]</tt> | The sizes of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created sigmoid layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/sigmoid.py
```
### sigmoid_activation {#sigmoid_activation tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">FloatsXd</ndarray>
- **Output:** <ndarray shape="batch_size, nO">FloatsXd</ndarray>
</inline-list>
Apply the sigmoid logistic function as an activation to the inputs. This is
often used as an output activation for multi-label classification, because each
element of the output vectors will be between `0` and `1`.
| Argument | Type | Description |
| ----------- | ---------------------------------- | --------------------------------------- |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created `sigmoid_activation` layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/sigmoid_activation.py
```
### LSTM and BiLSTM {#lstm tag="function"}
<inline-list>
- **Input:** <ndarray>Padded</ndarray>
- **Output:** <ndarray>Padded</ndarray>
- **Parameters:** `depth` <tt>int</tt>, `dropout` <tt>float</tt>
</inline-list>
An LSTM recurrent neural network. The BiLSTM is bidirectional: that is, each
layer concatenated a forward LSTM with an LSTM running in the reverse direction.
If you are able to install PyTorch, you should usually prefer to use the
`PyTorchLSTM` layer instead of Thinc's implementations, as PyTorch's LSTM
implementation is significantly faster.
| Argument | Type | Description |
| -------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| _keyword-only_ | | |
| `bi` | <tt>bool</tt> | Use BiLSTM. |
| `depth` | <tt>int</tt> | Number of layers (default `1`). |
| `dropout` | <tt>float</tt> | Dropout rate to avoid overfitting (default `0`). |
| `init_W` | <tt>Optional[Callable]</tt> | A function to initialize the weights matrix. Defaults to [`glorot_uniform_init`](/docs/api-initializers#glorot_uniform_init) when set to `None`. |
| `init_b` | <tt>Optional[Callable]</tt> | A function to initialize the bias vector. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| **RETURNS** | <tt>Model[Padded, Padded]</tt> | The created LSTM layer(s). |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/lstm.py
```
### Maxout {#maxout tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO*nP">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO*nP, nI">W</ndarray>,
<ndarray shape="nO*nP,">b</ndarray>
</inline-list>
A dense layer with a "maxout" activation
([Goodfellow et al, 2013](https://arxiv.org/abs/1302.4389)). Maxout layers
require a weights array of shape `(nO, nP, nI)` in order to compute outputs of
width `nO` given inputs of width `nI`. The extra multiple, `nP`, determines the
number of "pieces" that the piecewise-linear activation will consider.
| Argument | Type | Description |
| -------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| `nP` | <tt>int</tt> | Number of maxout pieces (default: 3). |
| _keyword-only_ | | |
| `init_W` | <tt>Optional[Callable]</tt> | A function to initialize the weights matrix. Defaults to [`glorot_uniform_init`](/docs/api-initializers#glorot_uniform_init) when set to `None`. |
| `init_b` | <tt>Optional[Callable]</tt> | A function to initialize the bias vector. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| `dropout` | <tt>Optional[float]</tt> | Dropout rate to avoid overfitting. |
| `normalize` | <tt>bool</tt> | Whether or not to apply [layer normalization](#layernorm), (default: False). |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created maxout layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/maxout.py
```
### Mish {#mish tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO, nI">W</ndarray>,
<ndarray shape="nO,">b</ndarray>
</inline-list>
A dense layer with Mish activation
([Misra, 2019](https://arxiv.org/pdf/1908.08681.pdf)).
| Argument | Type | Description |
| -------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| _keyword-only_ | | |
| `init_W` | <tt>Optional[Callable]</tt> | A function to initialize the weights matrix. Defaults to [`glorot_uniform_init`](/docs/api-initializers#glorot_uniform_init) when set to `None`. |
| `init_b` | <tt>Optional[Callable]</tt> | A function to initialize the bias vector. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| `dropout` | <tt>Optional[float]</tt> | Dropout rate to avoid overfitting. |
| `normalize` | <tt>bool</tt> | Whether or not to apply [layer normalization](#layernorm), (default: False). |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created dense layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/mish.py
```
### Swish {#swish tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO, nI">W</ndarray>,
<ndarray shape="nO,">b</ndarray>
</inline-list>
A dense layer with the Swish activation function
[(Ramachandran et al., 2017)](https://arxiv.org/abs/1710.05941v2). Swish is a
self-gating non-monotonic activation function similar to [`GELU`](#gelu):
whereas GELU uses the CDF of the Gaussian distribution Φ for self-gating
`x * Φ(x)` Swish uses the logistic CDF `x * σ(x)`. Sometimes referred to as
"SiLU" for "Sigmoid Linear Unit".
| Argument | Type | Description |
| -------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| _keyword-only_ | | |
| `init_W` | <tt>Optional[Callable]</tt> | A function to initialize the weights matrix. Defaults to [`he_normal_init`](/docs/api-initializers#he_normal_init) when set to `None`. |
| `init_b` | <tt>Optional[Callable]</tt> | A function to initialize the bias vector. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| `dropout` | <tt>Optional[float]</tt> | Dropout rate to avoid overfitting. |
| `normalize` | <tt>bool</tt> | Whether or not to apply [layer normalization](#layernorm). Defaults to `False`. |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created dense layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/swish.py
```
### Gelu {#gelu tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO, nI">W</ndarray>,
<ndarray shape="nO,">b</ndarray>
</inline-list>
A dense layer with the GELU activation function
[(Hendrycks and Gimpel, 2016)](https://arxiv.org/abs/1606.08415). The GELU or
"Gaussian Error Linear Unit" is a self-gating non-monotonic activation function
similar to [Swish](#swish): whereas GELU uses the CDF of the Gaussian
distribution Φ for self-gating `x * Φ(x)` the Swish activation uses the logistic
CDF σ and computes `x * σ(x)`. Various approximations exist, but `thinc`
implements the exact GELU. The use of GELU is popular within transformer
feed-forward blocks.
| Argument | Type | Description |
| -------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| _keyword-only_ | | |
| `init_W` | <tt>Optional[Callable]</tt> | A function to initialize the weights matrix. Defaults to [`he_normal_init`](/docs/api-initializers#he_normal_init) when set to `None`. |
| `init_b` | <tt>Optional[Callable]</tt> | A function to initialize the bias vector. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| `dropout` | <tt>Optional[float]</tt> | Dropout rate to avoid overfitting. |
| `normalize` | <tt>bool</tt> | Whether or not to apply [layer normalization](#layernorm). Defaults to `False`. |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created dense layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/gelu.py
```
### ReluK {#reluk tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO, nI">W</ndarray>,
<ndarray shape="nO,">b</ndarray>
</inline-list>
A dense layer with the ReLU activation function where the maximum value is
clipped at `k`. A common choice is `k=6` introduced for convolutional deep
belief networks
[(Krizhevsky, 2010)](https://www.cs.toronto.edu/~kriz/conv-cifar10-aug2010.pdf).
The resulting function `relu6` is commonly used in low-precision scenarios.
| Argument | Type | Description |
| -------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| _keyword-only_ | | |
| `init_W` | <tt>Optional[Callable]</tt> | A function to initialize the weights matrix. Defaults to [`glorot_uniform_init`](/docs/api-initializers#glorot_uniform_init) when set to `None`. |
| `init_b` | <tt>Optional[Callable]</tt> | A function to initialize the bias vector. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| `dropout` | <tt>Optional[float]</tt> | Dropout rate to avoid overfitting. |
| `normalize` | <tt>bool</tt> | Whether or not to apply [layer normalization](#layernorm). Defaults to `False`. |
| `k` | <tt>float</tt> | Maximum value. Defaults to `6.0`.. |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created dense layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/clipped_linear.py#L132
```
### HardSigmoid {#hardsigmoid tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO, nI">W</ndarray>,
<ndarray shape="nO,">b</ndarray>
</inline-list>
A dense layer with hard sigmoid activation function, which is a fast linear
approximation of sigmoid, defined as `max(0, min(1, x * 0.2 + 0.5))`.
| Argument | Type | Description |
| -------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| _keyword-only_ | | |
| `init_W` | <tt>Optional[Callable]</tt> | A function to initialize the weights matrix. Defaults to [`glorot_uniform_init`](/docs/api-initializers#glorot_uniform_init) when set to `None`. |
| `init_b` | <tt>Optional[Callable]</tt> | A function to initialize the bias vector. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| `dropout` | <tt>Optional[float]</tt> | Dropout rate to avoid overfitting. |
| `normalize` | <tt>bool</tt> | Whether or not to apply [layer normalization](#layernorm). Defaults to `False`. |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created dense layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/clipped_linear.py#L90
```
### HardTanh {#hardtanh tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO, nI">W</ndarray>,
<ndarray shape="nO,">b</ndarray>
</inline-list>
A dense layer with hard tanh activation function, which is a fast linear
approximation of tanh, defined as `max(-1, min(1, x))`.
| Argument | Type | Description |
| -------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| _keyword-only_ | | |
| `init_W` | <tt>Optional[Callable]</tt> | A function to initialize the weights matrix. Defaults to [`glorot_uniform_init`](/docs/api-initializers#glorot_uniform_init) when set to `None`. |
| `init_b` | <tt>Optional[Callable]</tt> | A function to initialize the bias vector. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| `dropout` | <tt>Optional[float]</tt> | Dropout rate to avoid overfitting. |
| `normalize` | <tt>bool</tt> | Whether or not to apply [layer normalization](#layernorm). Defaults to `False`. |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created dense layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/clipped_linear.py#L111
```
### ClippedLinear {#clippedlinear tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO, nI">W</ndarray>,
<ndarray shape="nO,">b</ndarray>
</inline-list>
A dense layer implementing a flexible clipped linear activation function of the
form `max(min_value, min(max_value, x * slope + offset))`. It is used to
implement the [`ReluK`](#reluk), [`HardSigmoid`](#hardsigmoid), and
[`HardTanh`](#hardtanh) layers.
| Argument | Type | Description |
| -------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| _keyword-only_ | | |
| `init_W` | <tt>Optional[Callable]</tt> | A function to initialize the weights matrix. Defaults to [`glorot_uniform_init`](/docs/api-initializers#glorot_uniform_init) when set to `None`. |
| `init_b` | <tt>Optional[Callable]</tt> | A function to initialize the bias vector. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| `dropout` | <tt>Optional[float]</tt> | Dropout rate to avoid overfitting. |
| `normalize` | <tt>bool</tt> | Whether or not to apply [layer normalization](#layernorm). Defaults to `False`. |
| `slope` | <tt>float</tt> | The slope of the linear function: `input * slope`. |
| `offset` | <tt>float</tt> | The offset or intercept of the linear function: `input * slope + offset`. |
| `min_val` | <tt>float</tt> | Minimum value to clip to. |
| `max_val` | <tt>float</tt> | Maximum value to clip to. |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created dense layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/clipped_linear.py
```
### HardSwish {#hardswish tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO, nI">W</ndarray>,
<ndarray shape="nO,">b</ndarray>
</inline-list>
A dense layer implementing the hard Swish activation function, which is a fast
linear approximation of Swish: `x * hard_sigmoid(x)`.
| Argument | Type | Description |
| -------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| _keyword-only_ | | |
| `init_W` | <tt>Optional[Callable]</tt> | A function to initialize the weights matrix. Defaults to [`he_normal_init`](/docs/api-initializers#he_normal_init) when set to `None`. |
| `init_b` | <tt>Optional[Callable]</tt> | A function to initialize the bias vector. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| `dropout` | <tt>Optional[float]</tt> | Dropout rate to avoid overfitting. |
| `normalize` | <tt>bool</tt> | Whether or not to apply [layer normalization](#layernorm). Defaults to `False`. |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created dense layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/hard_swish.py
```
### HardSwishMobileNet {#hardswishmobilenet tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO, nI">W</ndarray>,
<ndarray shape="nO,">b</ndarray>
</inline-list>
A dense layer implementing the a variant of the fast linear hard Swish
activation function used in `MobileNetV3`
[(Howard et al., 2019)](https://arxiv.org/abs/1905.02244), defined as
`x * (relu6(x + 3) / 6)`.
| Argument | Type | Description |
| -------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| _keyword-only_ | | |
| `init_W` | <tt>Optional[Callable]</tt> | A function to initialize the weights matrix. Defaults to [`he_normal_init`](/docs/api-initializers#he_normal_init) when set to `None`. |
| `init_b` | <tt>Optional[Callable]</tt> | A function to initialize the bias vector. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| `dropout` | <tt>Optional[float]</tt> | Dropout rate to avoid overfitting. |
| `normalize` | <tt>bool</tt> | Whether or not to apply [layer normalization](#layernorm). Defaults to `False`. |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created dense layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/hard_swish_mobilenet.py
```
### MultiSoftmax {#multisoftmax tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO, nI">W</ndarray>,
<ndarray shape="nO,">b</ndarray>
</inline-list>
Neural network layer that predicts several multi-class attributes at once. For
instance, we might predict one class with six variables, and another with five.
We predict the 11 neurons required for this, and then softmax them such that
columns 0-6 make a probability distribution and columns 6-11 make another.
| Argument | Type | Description |
| ----------- | ---------------------------------- | -------------------------------- |
| `nOs` | <tt>Tuple[int, ...]</tt> | The sizes of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created multi softmax layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/multisoftmax.py
```
### ParametricAttention {#parametricattention tag="function"}
<inline-list>
- **Input:** <ndarray>Ragged</ndarray>
- **Output:** <ndarray>Ragged</ndarray>
- **Parameters:** <ndarray shape="nO,">Q</ndarray>
</inline-list>
A layer that uses the parametric attention scheme described by
[Yang et al. (2016)](https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-attention-networks.pdf).
The layer learns a parameter vector that is used as the keys in a single-headed
attention mechanism.
| Argument | Type | Description |
| ----------- | ------------------------------ | ------------------------------- |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| **RETURNS** | <tt>Model[Ragged, Ragged]</tt> | The created attention layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/parametricattention.py
```
### ParametricAttention_v2 {#parametricattention_v2 tag="function"}
<inline-list>
- **Input:** <ndarray>Ragged</ndarray>
- **Output:** <ndarray>Ragged</ndarray>
- **Parameters:** <ndarray shape="nO,">Q</ndarray>
</inline-list>
A layer that uses the parametric attention scheme described by
[Yang et al. (2016)](https://aclanthology.org/N16-1174).
The layer learns a parameter vector that is used as the keys in a single-headed
attention mechanism.
<infobox variant="warning">
The original `ParametricAttention` layer uses the hidden representation as-is
for the keys in the attention. This differs from the paper that introduces
parametric attention (Equation 5). `ParametricAttention_v2` adds the option to
transform the key representation in line with the paper by passing such a
transformation through the `key_transform` parameter.
</infobox>
| Argument | Type | Description |
|-----------------|----------------------------------------------|------------------------------------------------------------------------|
| `key_transform` | <tt>Optional[Model[Floats2d, Floats2d]]</tt> | Transformation to apply to the key representations. Defaults to `None` |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| **RETURNS** | <tt>Model[Ragged, Ragged]</tt> | The created attention layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/parametricattention_v2.py
```
### Relu {#relu tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO, nI">W</ndarray>,
<ndarray shape="nO,">b</ndarray>
</inline-list>
A dense layer with Relu activation.
| Argument | Type | Description |
| -------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| _keyword-only_ | | |
| `init_W` | <tt>Optional[Callable]</tt> | A function to initialize the weights matrix. Defaults to [`glorot_uniform_init`](/docs/api-initializers#glorot_uniform_init) when set to `None`. |
| `init_b` | <tt>Optional[Callable]</tt> | A function to initialize the bias vector. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| `dropout` | <tt>Optional[float]</tt> | Dropout rate to avoid overfitting. |
| `normalize` | <tt>bool</tt> | Whether or not to apply [layer normalization](#layernorm), (default: False). |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created Relu layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/relu.py
```
### Softmax {#softmax tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO, nI">W</ndarray>,
<ndarray shape="nO,">b</ndarray>
</inline-list>
A dense layer with a softmax activation. This is usually used as a prediction
layer. Vectors produced by the softmax function sum to 1, and have values
between 0 and 1, so each vector can be interpreted as a probability
distribution.
| Argument | Type | Description |
| -------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| _keyword-only_ | | |
| `init_W` | <tt>Optional[Callable]</tt> | A function to initialize the weights matrix. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| `init_b` | <tt>Optional[Callable]</tt> | A function to initialize the bias vector. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created softmax layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/softmax.py
```
### Softmax_v2 {#softmax_v2 tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
- **Parameters:** <ndarray shape="nO, nI">W</ndarray>,
<ndarray shape="nO,">b</ndarray>
</inline-list>
A dense layer with a softmax activation. This is usually used as a prediction
layer. Vectors produced by the softmax function sum to 1, and have values
between 0 and 1, so each vector can be interpreted as a probability
distribution.
`Softmax_v2` supports outputting unnormalized probabilities during inference by
using `normalize_outputs=False` as an argument. This is useful when we are only
interested in finding the top-k classes, but not their probabilities. Computing
unnormalized probabilities is faster, because it skips the expensive
normalization step.
The `temperature` argument of `Softmax_v2` provides control of the softmax
distribution. Values larger than 1 increase entropy and values between 0 and 1
(exclusive) decrease entropy of the distribution. The default temperature of 1
will calculate the unmodified softmax distribution. `temperature` is not used
during inference when `normalize_outputs=False`.
| Argument | Type | Description |
| ------------------- | ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `nI` | <tt>Optional[int]</tt> | The size of the input vectors. |
| _keyword-only_ | | |
| `init_W` | <tt>Optional[Callable]</tt> | A function to initialize the weights matrix. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| `init_b` | <tt>Optional[Callable]</tt> | A function to initialize the bias vector. Defaults to [`zero_init`](/docs/api-initializers#zero_init) when set to `None`. |
| `normalize_outputs` | <tt>bool</tt> | Return normalized probabilities during inference. Defaults to `True`. |
| `temperature` | <tt>float</tt> | Temperature to divide logits by. Defaults to `1.0`. |
| **RETURNS** | <tt>Model[Floats2d, Floats2d]</tt> | The created softmax layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/softmax.py
```
### SparseLinear {#sparselinear tag="function"}
<inline-list>
- **Input:** <ndarray>Tuple[ArrayXd, ArrayXd, ArrayXd]</ndarray>
- **Output:** <ndarray>ArrayXd</ndarray>
- **Parameters:** <ndarray shape="nO*length,">W</ndarray>,
<ndarray shape="nO,">b</ndarray>, `length` <tt>int</tt>
</inline-list>
A sparse linear layer using the "hashing trick". Useful for tasks such as text
classification. Inputs to the layer should be a tuple of arrays
`(keys, values, lengths)`, where the `keys` and `values` are arrays of the same
length, describing the concatenated batch of input features and their values.
The `lengths` array should have one entry per sequence in the batch, and the sum
of the lengths should equal the length of the keys and values array.
<infobox variant="warning">
`SparseLinear` should not be used for new models because it contains an indexing
bug. As a result, only a subset of the weights is used. Use
[`SparseLinear_v2`](#sparselinear_v2) instead.
</infobox>
| Argument | Type | Description |
| ----------- | --------------------------------------------------------- | -------------------------------------------------------- |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `length` | <tt>int</tt> | The size of the weights vector, to be tuned empirically. |
| **RETURNS** | <tt>Model[Tuple[ArrayXd, ArrayXd, ArrayXd], ArrayXd]</tt> | The created layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/sparselinear.pyx
```
### SparseLinear_v2 {#sparselinear_v2 tag="function" new="8.1.6"}
<inline-list>
- **Input:** <ndarray>Tuple[ArrayXd, ArrayXd, ArrayXd]</ndarray>
- **Output:** <ndarray>ArrayXd</ndarray>
- **Parameters:** <ndarray shape="nO*length,">W</ndarray>,
<ndarray shape="nO,">b</ndarray>, `length` <tt>int</tt>
</inline-list>
A sparse linear layer using the "hashing trick". Useful for tasks such as text
classification. Inputs to the layer should be a tuple of arrays
`(keys, values, lengths)`, where the `keys` and `values` are arrays of the same
length, describing the concatenated batch of input features and their values.
The `lengths` array should have one entry per sequence in the batch, and the sum
of the lengths should equal the length of the keys and values array.
| Argument | Type | Description |
| ----------- | --------------------------------------------------------- | -------------------------------------------------------- |
| `nO` | <tt>Optional[int]</tt> | The size of the output vectors. |
| `length` | <tt>int</tt> | The size of the weights vector, to be tuned empirically. |
| **RETURNS** | <tt>Model[Tuple[ArrayXd, ArrayXd, ArrayXd], ArrayXd]</tt> | The created layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/sparselinear.pyx
```
## Reduction operations {#reduction-ops}
### reduce_first {#reduce_first tag="function"}
<inline-list>
- **Input:** <ndarray>Ragged</ndarray>
- **Output:** <ndarray shape="batch_size, nO">ArrayXd</ndarray>
</inline-list>
Pooling layer that reduces the dimensions of the data by selecting the first
item of each sequence. This is most useful after multi-head attention layers,
which can learn to assign a good feature representation for the sequence to one
of its elements.
| Argument | Type | Description |
| ----------- | ------------------------------- | -------------------------- |
| **RETURNS** | <tt>Model[Ragged, ArrayXd]</tt> | The created pooling layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/reduce_first.py
```
### reduce_last {#reduce_last tag="function"}
Pooling layer that reduces the dimensions of the data by selecting the last item
of each sequence. This is typically used after multi-head attention or recurrent
neural network layers such as LSTMs, which can learn to assign a good feature
representation for the sequence to its final element.
<inline-list>
- **Input:** <ndarray>Ragged</ndarray>
- **Output:** <ndarray shape="batch_size, nO">ArrayXd</ndarray>
</inline-list>
| Argument | Type | Description |
| ----------- | ------------------------------- | -------------------------- |
| **RETURNS** | <tt>Model[Ragged, ArrayXd]</tt> | The created pooling layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/reduce_last.py
```
### reduce_max {#reduce_max tag="function"}
<inline-list>
- **Input:** <ndarray>Ragged</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
</inline-list>
Pooling layer that reduces the dimensions of the data by selecting the maximum
value for each feature. A `ValueError` is raised if any element in `lengths` is
zero.
| Argument | Type | Description |
| ----------- | -------------------------------- | -------------------------- |
| **RETURNS** | <tt>Model[Ragged, Floats2d]</tt> | The created pooling layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/reduce_max.py
```
### reduce_mean {#reduce_mean tag="function"}
<inline-list>
- **Input:** <ndarray>Ragged</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
</inline-list>
Pooling layer that reduces the dimensions of the data by computing the average
value of each feature. Zero-length sequences are reduced to the zero vector.
| Argument | Type | Description |
| ----------- | -------------------------------- | -------------------------- |
| **RETURNS** | <tt>Model[Ragged, Floats2d]</tt> | The created pooling layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/reduce_mean.py
```
### reduce_sum {#reduce_sum tag="function"}
<inline-list>
- **Input:** <ndarray>Ragged</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d</ndarray>
</inline-list>
Pooling layer that reduces the dimensions of the data by computing the sum for
each feature. Zero-length sequences are reduced to the zero vector.
| Argument | Type | Description |
| ----------- | -------------------------------- | -------------------------- |
| **RETURNS** | <tt>Model[Ragged, Floats2d]</tt> | The created pooling layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/reduce_sum.py
```
---
## Combinators {#combinators}
Combinators are layers that express **higher-order functions**: they take one or
more layers as arguments and express some relationship or perform some
additional logic around the child layers. Combinators can also be used to
[overload operators](/docs/usage-models#operators). For example, binding `chain`
to `>>` allows you to write `Relu(512) >> Softmax()` instead of
`chain(Relu(512), Softmax())`.
### add {#add tag="function"}
Compose two or more models `f`, `g`, etc, such that their outputs are added,
i.e. `add(f, g)(x)` computes `f(x) + g(x)`.
| Argument | Type | Description |
| ----------- | ---------------------------- | ---------------------- |
| `*layers` | <tt>Model[Any, ArrayXd]</tt> | The models to compose. |
| **RETURNS** | <tt>Model[Any, ArrayXd]</tt> | The composed model. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/add.py
```
### bidirectional {#bidirectional tag="function"}
Stitch two RNN models into a bidirectional layer. Expects squared sequences.
| Argument | Type | Description |
| ----------- | ---------------------------------------- | --------------------------------- |
| `l2r` | <tt>Model[Padded, Padded]</tt> | The first model. |
| `r2l` | <tt>Optional[Model[Padded, Padded]]</tt> | The second model. |
| **RETURNS** | <tt>Model[Padded, Padded]</tt> | The composed bidirectional layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/bidirectional.py
```
### chain {#chain tag="function"}
Compose two or more models such that they become layers of a single feed-forward
model, e.g. `chain(f, g)` computes `g(f(x))`.
| Argument | Type | Description |
| ----------- | -------------- | --------------------------------- |
| `layer1` | <tt>Model</tt> | The first model to compose. |
| `layer2` | <tt>Model</tt> | The second model to compose. |
| `*layers` | <tt>Model</tt> | Any additional models to compose. |
| **RETURNS** | <tt>Model</tt> | The composed feed-forward model. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/chain.py
```
### clone {#clone tag="function"}
Construct `n` copies of a layer, with distinct weights. For example,
`clone(f, 3)(x)` computes `f(f'(f''(x)))`.
| Argument | Type | Description |
| ----------- | -------------- | ------------------------------------------------ |
| `orig` | <tt>Model</tt> | The layer to copy. |
| `n` | <tt>int</tt> | The number of copies to construct. |
| **RETURNS** | <tt>Model</tt> | A composite model containing two or more copies. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/clone.py
```
### concatenate {#concatenate tag="function"}
Compose two or more models `f`, `g`, etc, such that their outputs are
concatenated, i.e. `concatenate(f, g)(x)` computes `hstack(f(x), g(x))`.
| Argument | Type | Description |
| ----------- | ------------------- | ---------------------- |
| `*layers` | <tt>Model</tt>, ... | The models to compose. |
| **RETURNS** | <tt>Model</tt> | The composed model. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/concatenate.py
```
### map_list {#map_list tag="function"}
Map a child layer across list inputs.
| Argument | Type | Description |
| ----------- | ------------------------------------- | ----------------------- |
| `layer` | <tt>Model[InT, OutT]</tt> | The child layer to map. |
| **RETURNS** | <tt>Model[List[InT], List[OutT]]</tt> | The composed model. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/map_list.py
```
### expand_window {#expand_window tag="function"}
<inline-list>
- **Input:** <ndarray shape="batch_size, nI">Floats2d, Ragged</ndarray>
- **Output:** <ndarray shape="batch_size, nO">Floats2d, Ragged</ndarray>
- **Attrs:** `window_size` <tt>int</tt>
</inline-list>
For each vector in an input, construct an output vector that contains the input
and a window of surrounding vectors. This is one step in a convolution. If the
`window_size` is three, the output size `nO` will be `nI * 7` after
concatenating three contextual vectors from the left, and three from the right,
to each input vector. In general, `nO` equals `nI * (2 * window_size + 1)`.
| Argument | Type | Description |
| ------------- | -------------------- | ------------------------------------------------------------------------------ |
| `window_size` | <tt>int</tt> | The window size (default 1) that determines the number of surrounding vectors. |
| **RETURNS** | <tt>Model[T, T]</tt> | The created layer for adding context to vectors. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/expand_window.py
```
### noop {#noop tag="function"}
Transform a sequences of layers into a null operation.
| Argument | Type | Description |
| ----------- | -------------- | ---------------------- |
| `*layers` | <tt>Model</tt> | The models to compose. |
| **RETURNS** | <tt>Model</tt> | The composed model. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/noop.py
```
### residual {#residual tag="function"}
<inline-list>
- **Input:** <ndarray>List[FloatsXd]</ndarray> / <ndarray>Ragged</ndarray> /
<ndarray>Padded</ndarray> / <ndarray>FloatsXd</ndarray>
<ndarray>Floats1d</ndarray> <ndarray>Floats2d</ndarray>
<ndarray>Floats3d</ndarray> <ndarray>Floats4d</ndarray>
- **Output:** <ndarray>List[FloatsXd]</ndarray> / <ndarray>Ragged</ndarray> /
<ndarray>Padded</ndarray> / <ndarray>FloatsXd</ndarray>
<ndarray>Floats1d</ndarray> <ndarray>Floats2d</ndarray>
<ndarray>Floats3d</ndarray> <ndarray>Floats4d</ndarray>
</inline-list>
A unary combinator creating a residual connection. This converts a layer
computing `f(x)` into one that computes `f(x)+x`. Gradients flow through
residual connections directly, helping the network to learn more smoothly.
| Argument | Type | Description |
| ----------- | -------------------- | -------------------------------------------------- |
| `layer` | <tt>Model[T, T]</tt> | A model with the same input and output types. |
| **RETURNS** | <tt>Model[T, T]</tt> | A model with the unchanged input and output types. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/residual.py
```
### tuplify {#tuplify tag="function"}
Give each child layer a separate copy of the input, and the combine the output
of the child layers into a tuple. Useful for providing original and modified
input to a downstream layer.
On the backward pass the loss from each child is added together, so when using
custom datatypes they should define an addition operator.
| Argument | Type | Description |
| ----------- | ----------------------------- | -------------------------------- |
| `*layers` | <tt>Model[Any, T] ...</tt> | The models to compose. |
| **RETURNS** | <tt>Model[Any, Tuple[T]]</tt> | The composed feed-forward model. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/tuplify.py
```
### siamese {#siamese tag="function"}
Combine and encode a layer and a similarity function to form a
[siamese architecture](https://en.wikipedia.org/wiki/Siamese_neural_network).
Typically used to learn symmetric relationships, such as redundancy detection.
| Argument | Type | Description |
| ------------ | ------------------------------ | ----------------------------------------- |
| `layer` | <tt>Model</tt> | The layer to run over the pair of inputs. |
| `similarity` | <tt>Model</tt> | The similarity layer. |
| **RETURNS** | <tt>Model[Tuple, ArrayXd]</tt> | The created siamese layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/siamese.py
```
### uniqued {#uniqued tag="function"}
Group inputs to a layer, so that the layer only has to compute for the unique
values. The data is transformed back before output, and the same transformation
is applied for the gradient. Effectively, this is a cache local to each
minibatch. The `uniqued` wrapper is useful for word inputs, because common words
are seen often, but we may want to compute complicated features for the words,
using e.g. character LSTM.
| Argument | Type | Description |
| -------------- | -------------------------------- | ---------------------------- |
| `layer` | <tt>Model</tt> | The layer. |
| _keyword-only_ | | |
| `column` | <tt>int</tt> | The column. Defaults to `0`. |
| **RETURNS** | <tt>Model[Ints2d, Floats2d]</tt> | The composed model. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/uniqued.py
```
---
## Data type transfers {#transfers}
### array_getitem, ints_getitem, floats_getitem {#array_getitem tag="function"}
<inline-list>
- **Input:** <ndarray>ArrayXd</ndarray>
- **Output:** <ndarray>ArrayXd</ndarray>
</inline-list>
Index into input arrays, and return the subarrays. Multi-dimensional indexing
can be performed by passing in a tuple, and slicing can be performed using the
slice object. For instance, `X[:, :-1]` would be
`(slice(None, None), slice(None, -1))`.
| Argument | Type | Description |
| -------- | --------------------------------------------------------------------------------------------- | -------------------------- |
| `index` | <tt>Union[Union[int, slice, Sequence[int]], Tuple[Union[int, slice, Sequence[int]], ...]</tt> | A valid numpy-style index. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/array_getitem.py
```
### list2array {#list2array tag="function"}
<inline-list>
- **Input:** <ndarray>List2d</ndarray>
- **Output:** <ndarray>Array2d</ndarray>
</inline-list>
Transform sequences to ragged arrays if necessary. If sequences are already
ragged, do nothing. A ragged array is a tuple `(data, lengths)`, where `data` is
the concatenated data.
| Argument | Type | Description |
| ----------- | ------------------------------- | ---------------------------------------- |
| **RETURNS** | <tt>Model[List2d, Array2d]</tt> | The layer to compute the transformation. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/list2array.py
```
### list2ragged {#list2ragged tag="function"}
<inline-list>
- **Input:** <ndarray>ListXd</ndarray>
- **Output:** <ndarray>Ragged</ndarray>
</inline-list>
Transform sequences to ragged arrays if necessary and return the ragged array.
If sequences are already ragged, do nothing. A ragged array is a tuple
`(data, lengths)`, where `data` is the concatenated data.
| Argument | Type | Description |
| ----------- | ------------------------------ | ---------------------------------------- |
| **RETURNS** | <tt>Model[ListXd, Ragged]</tt> | The layer to compute the transformation. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/list2ragged.py
```
### list2padded {#list2padded tag="function"}
<inline-list>
- **Input:** <ndarray>List2d</ndarray>
- **Output:** <ndarray>Padded</ndarray>
</inline-list>
Create a layer to convert a list of array inputs into
[`Padded`](/docs/api-types#padded).
| Argument | Type | Description |
| ----------- | ------------------------------ | ---------------------------------------- |
| **RETURNS** | <tt>Model[List2d, Padded]</tt> | The layer to compute the transformation. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/list2padded.py
```
### ragged2list {#ragged2list tag="function"}
<inline-list>
- **Input:** <ndarray>Ragged</ndarray>
- **Output:** <ndarray>ListXd</ndarray>
</inline-list>
Transform sequences from a ragged format into lists.
| Argument | Type | Description |
| ----------- | ------------------------------ | ---------------------------------------- |
| **RETURNS** | <tt>Model[Ragged, ListXd]</tt> | The layer to compute the transformation. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/ragged2list.py
```
### padded2list {#padded2list tag="function"}
<inline-list>
- **Input:** <ndarray>Padded</ndarray>
- **Output:** <ndarray>List2d</ndarray>
</inline-list>
Create a layer to convert a [`Padded`](/docs/api-types#padded) input into a list
of arrays.
| Argument | Type | Description |
| ----------- | ------------------------------ | ---------------------------------------- |
| **RETURNS** | <tt>Model[Padded, List2d]</tt> | The layer to compute the transformation. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/padded2list.py
```
### remap_ids {#remap_ids tag="function"}
<inline-list>
- **Input:** <tt>Union[Sequence[Hashable], Ints1d, Ints2d]</tt>
- **Output:** <ndarray>Ints2d</ndarray>
</inline-list>
Remap a sequence of strings, integers or other hashable inputs using a mapping
table, usually as a preprocessing step before embeddings. The input can also be
a two dimensional integer array in which case the `column` attribute tells the
`remap_ids` layer which column of the array to map with the `mapping_table`.
Both attributes can be passed on initialization, but since the layer is designed
to retrieve them from `model.attrs` during `forward`, they can be set any time
before calling `forward`. This means that they can also be changed between
calls. Before calling `forward` the `mapping_table` has to be set and for 2D
inputs the `column` is also required.
| Argument | Type | Description |
| --------------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `mapping_table` | <tt>Dict[Any, int]</tt> | The mapping table to use. Can also be set after initialization by writing to `model.attrs["mapping_table"]`. |
| `default` | <tt>int</tt> | The default value if the input does not have an entry in the mapping table. |
| `column` | <tt>int</tt> | The column to apply the mapper to in case of 2D input. |
| **RETURNS** | <tt>Model[Union[Sequence[Hashable], Ints1d, Ints2d], Ints2d]</tt> | The layer to compute the transformation. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/remap_ids.py
```
### strings2arrays {#strings2arrays tag="function"}
<inline-list>
- **Input:** <tt>Sequence[Sequence[str]]</tt>
- **Output:** <ndarray>List[Ints2d]</ndarray>
</inline-list>
Transform a sequence of string sequences to a list of arrays.
| Argument | Type | Description |
| ----------- | ----------------------------------------------------- | ---------------------------------------- |
| **RETURNS** | <tt>Model[Sequence[Sequence[str]], List[Ints2d]]</tt> | The layer to compute the transformation. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/strings2arrays.py
```
### with_array {#with_array tag="function"}
<inline-list>
- **Input / output:** <tt>Union[Padded, Ragged, ListXd, ArrayXd]</tt>
</inline-list>
Transform sequence data into a contiguous array on the way into and out of a
model. Handles a variety of sequence types: lists, padded and ragged. If the
input is an array, it is passed through unchanged.
| Argument | Type | Description |
| -------------- | -------------------------------- | ----------------------------- |
| `layer` | <tt>Model[ArrayXd, ArrayXd]</tt> | The layer to wrap. |
| _keyword-only_ | | |
| `pad` | <tt>int</tt> | The padding. Defaults to `0`. |
| **RETURNS** | <tt>Model</tt> | The wrapped layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/with_array2d.py
```
### with_array2d {#with_array2d tag="function"}
<inline-list>
- **Input / output:** <tt>Union[Padded, Ragged, List2d, Array2d]</tt>
</inline-list>
Transform sequence data into a contiguous two-dimensional array on the way into
and out of a model. In comparison to the `with_array` layer, the behavior of
this layer mostly differs on `Padded` inputs, as this layer merges the batch and
length axes to form a two-dimensional array. Handles a variety of sequence
types: lists, padded and ragged. If the input is a two-dimensional array, it is
passed through unchanged.
| Argument | Type | Description |
| -------------- | -------------------------------- | ----------------------------- |
| `layer` | <tt>Model[Array2d, Array2d]</tt> | The layer to wrap. |
| _keyword-only_ | | |
| `pad` | <tt>int</tt> | The padding. Defaults to `0`. |
| **RETURNS** | <tt>Model</tt> | The wrapped layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/with_array.py
```
### with_flatten {#with_flatten tag="function"}
<inline-list>
- **Input:** <tt>Sequence[Sequence[Any]]</tt>
- **Output:** <tt>ListXd</tt>
</inline-list>
Flatten nested inputs on the way into a layer and reverse the transformation
over the outputs.
<infobox variant="warning">
Even though `with_flatten` is a layer wrapper, it does not preserve symmetry
between the input and output data types. This often makes it hard to compose
with other layers. Use [`with_flatten_v2`](#with_flatten_v2) instead.
</infobox>
| Argument | Type | Description |
| ----------- | ----------------------------------------------- | ------------------ |
| `layer` | <tt>Model[Sequence[Any], ArrayXd]</tt> | The layer to wrap. |
| **RETURNS** | <tt>Model[Sequence[Sequence[Any]], ListXd]</tt> | The wrapped layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/with_flatten.py
```
### with_flatten_v2 {#with_flatten_v2 tag="function" new="8.1.6"}
<inline-list>
- **Input:** <tt>List[List[InItemT]]</tt>
- **Output:** <tt>List[List[OutItemT]]</tt>
</inline-list>
Flatten nested inputs on the way into a layer and reverse the transformation
over the outputs.
| Argument | Type | Description |
| ----------- | --------------------------------------------------------- | ------------------ |
| `layer` | <tt>Model[List[InItemT], List[OutItemT]]</tt> | The layer to wrap. |
| **RETURNS** | <tt>Model[List[List[InItemT]], List[List[OutItemT]]]</tt> | The wrapped layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/with_flatten_v2.py
```
### with_padded {#with_padded tag="function"}
<inline-list>
- **Input / output:** <tt>Union[Padded, Ragged, List2d, Floats3d,
Tuple[Floats3d, Ints1d, Ints1d, Ints1d]]</tt>
</inline-list>
Convert sequence input into the [`Padded`](/docs/api-types#padded) data type on
the way into a layer and reverse the transformation on the output.
| Argument | Type | Description |
| ----------- | ------------------------------ | ------------------ |
| `layer` | <tt>Model[Padded, Padded]</tt> | The layer to wrap. |
| **RETURNS** | <tt>Model</tt> | The wrapped layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/with_padded.py
```
### with_ragged {#with_ragged tag="function"}
<inline-list>
- **Input / output:** <tt>Union[Padded, Ragged, ListXd, Floats3d,
Tuple[Floats2d, Ints1d]]</tt>
</inline-list>
Convert sequence input into the [`Ragged`](/docs/api-types#ragged) data type on
the way into a layer and reverse the transformation on the output.
| Argument | Type | Description |
| ----------- | ------------------------------ | ------------------ |
| `layer` | <tt>Model[Ragged, Ragged]</tt> | The layer to wrap. |
| **RETURNS** | <tt>Model</tt> | The wrapped layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/with_ragged.py
```
### with_list {#with_list tag="function"}
<inline-list>
- **Input / output:** <tt>Union[Padded, Ragged, List2d]</tt>
</inline-list>
Convert sequence input into lists on the way into a layer and reverse the
transformation on the outputs.
| Argument | Type | Description |
| ----------- | ------------------------------ | ------------------ |
| `layer` | <tt>Model[List2d, List2d]</tt> | The layer to wrap. |
| **RETURNS** | <tt>Model</tt> | The wrapped layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/with_list.py
```
### with_getitem {#with_getitem tag="function"}
<inline-list>
- **Input:** <tt>Tuple</tt>
- **Output:** <tt>Tuple</tt>
</inline-list>
Transform data on the way into and out of a layer by plucking an item from a
tuple.
| Argument | Type | Description |
| ----------- | -------------------------------- | ---------------------------------- |
| `idx` | <tt>int</tt> | The index to pluck from the tuple. |
| `layer` | <tt>Model[ArrayXd, ArrayXd]</tt> | The layer to wrap. |
| **RETURNS** | <tt>Model[Tuple, Tuple]</tt> | The wrapped layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/with_getitem.py
```
### with_reshape {#with_reshape tag="function"}
<inline-list>
- **Input:** <ndarray>Array3d</tt>
- **Output:** <ndarray>Array3d</tt>
</inline-list>
Reshape data on the way into and out from a layer.
| Argument | Type | Description |
| ----------- | -------------------------------- | ------------------ |
| `layer` | <tt>Model[Array2d, Array2d]</tt> | The layer to wrap. |
| **RETURNS** | <tt>Model[Array3d, Array3d]</tt> | The wrapped layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/with_reshape.py
```
### with_debug {#with_debug tag="function"}
<inline-list>
- **Input:** <tt>Any</tt>
- **Output:** <tt>Any</tt>
</inline-list>
Debugging layer that wraps any layer and allows executing callbacks during the
forward pass, backward pass and initialization. The callbacks will receive the
same arguments as the functions they're called in and are executed before the
function runs.
<infobox variant="warning">
This layer should only be used for **debugging, logging, benchmarking etc.**,
not to modify data or perform any other side-effects that are relevant to the
network outside of debugging and testing it. If you need hooks that run in
specific places of the model lifecycle, you should write your own
[custom layer](/docs/usage-models#new-layers). You can use the implementation of
`with_debug` as a template.
</infobox>
```python
### Example
from thinc.api import Linear, with_debug
def on_init(model, X, Y):
print(f"X: {type(Y)}, Y ({type(Y)})")
model = with_debug(Linear(2, 5), on_init=on_init)
model.initialize()
```
| Argument | Type | Description |
| -------------- | ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| `layer` | <tt>Model</tt> | The layer to wrap. |
| `name` | <tt>Optional[str]</tt> | Optional name for the wrapped layer, will be prefixed by `debug:`. Defaults to name of the wrapped layer. |
| _keyword-only_ | | |
| `on_init` | <tt>Callable[[Model, Any, Any], None]</tt> | Function called on initialization. Receives the model and the `X` and `Y` passed to [`Model.initialize`](/docs/api-model#initialize), if available. |
| `on_forward` | <tt>Callable[[Model, Any, bool], None]</tt> | Function called at the start of the forward pass. Receives the model, the inputs and the value of `is_train`. |
| `on_backprop` | <tt>Callable[[Any], None] = do_nothing</tt> | Function called at the start of the backward pass. Receives the gradient. |
| **RETURNS** | <tt>Model</tt> | The wrapped layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/with_debug.py
```
### with_nvtx_range {#with_nvtx_range tag="function"}
<inline-list>
- **Input:** <tt>Any</tt>
- **Output:** <tt>Any</tt>
</inline-list>
Layer that wraps any layer and marks the forward and backprop passes as an NVTX
range. This can be helpful when profiling GPU performance of a layer.
```python
### Example
from thinc.api import Linear, with_nvtx_range
model = with_nvtx_range(Linear(2, 5))
model.initialize()
```
| Argument | Type | Description |
| ---------------- | ---------------------- | ------------------------------------------------------------------------------- |
| `layer` | <tt>Model</tt> | The layer to wrap. |
| `name` | <tt>Optional[str]</tt> | Optional name for the wrapped layer. Defaults to the name of the wrapped layer. |
| _keyword-only_ | | |
| `forward_color` | <tt>int</tt> | Identifier of the color to use for the forward pass |
| `backprop_color` | <tt>int</tt> | Identifier of the color to use for the backward pass |
| **RETURNS** | <tt>Model</tt> | The wrapped layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/with_nvtx_range.py
```
### with_signpost_interval {#with_signpost_interval tag="function" new="8.1.1"}
<inline-list>
- **Input:** <tt>Any</tt>
- **Output:** <tt>Any</tt>
</inline-list>
Layer that wraps any layer and marks the init, forward and backprop passes as a
(macOS) signpost interval. This can be helpful when profiling the performance of
a layer using macOS
[Instruments.app](https://help.apple.com/instruments/mac/current/). Use of this
layer requires that the
[`os-signpost`](https://github.com/explosion/os-signpost) package is installed.
```python
### Example
from os_signpost import Signposter
from thinc.api import Linear, with_signpost_interval
signposter = Signposter("com.example.my_subsystem",
Signposter.Category.DynamicTracing)
model = with_signpost_interval(Linear(2, 5), signposter)
model.initialize()
```
| Argument | Type | Description |
| ------------ | --------------------------------- | ------------------------------------------------------------------------------- |
| `layer` | <tt>Model</tt> | The layer to wrap. |
| `signposter` | <tt>os_signposter.Signposter</tt> | `Signposter` object to log the interval with. |
| `name` | <tt>Optional[str]</tt> | Optional name for the wrapped layer. Defaults to the name of the wrapped layer. |
| **RETURNS** | <tt>Model</tt> | The wrapped layer. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/with_signpost_interval.py
```
---
## Wrappers {#wrappers}
### PyTorchWrapper, PyTorchRNNWrapper {#pytorchwrapper tag="function"}
<inline-list>
- **Input:** <tt>Any</tt>
- **Output:** <tt>Any</tt>
</inline-list>
Wrap a [PyTorch](https://pytorch.org) model so that it has the same API as Thinc
models. To optimize the model, you'll need to create a PyTorch optimizer and
call `optimizer.step` after each batch. The `PyTorchRNNWrapper` has the same
signature as the `PyTorchWrapper` and lets you to pass in a custom sequence
model that has the same inputs and output behavior as a
[`torch.nn.RNN`](https://pytorch.org/docs/stable/nn.html#torch.nn.RNN) object.
Your PyTorch model's forward method can take arbitrary positional arguments and
keyword arguments, but must return either a **single tensor** as output or a
**tuple**. You may find
[PyTorch's `register_forward_hook`](https://pytorch.org/docs/stable/nn.html#torch.nn.Module.register_forward_hook)
helpful if you need to adapt the output. The convert functions are used to map
inputs and outputs to and from your PyTorch model. Each function should return
the converted output, and a callback to use during the backward pass:
```python
Xtorch, get_dX = convert_inputs(X)
Ytorch, torch_backprop = model.shims[0](Xtorch, is_train)
Y, get_dYtorch = convert_outputs(Ytorch)
```
To allow maximum flexibility, the [`PyTorchShim`](/docs/api-model#shims) expects
[`ArgsKwargs`](/docs/api-types#argskwargs) objects on the way into the forward
and backward passes. The `ArgsKwargs` objects will be passed straight into the
model in the forward pass, and straight into `torch.autograd.backward` during
the backward pass.
| Argument | Type | Description |
| ----------------- | ------------------------ | ---------------------------------------------------------------------------------------- |
| `pytorch_model` | <tt>Any</tt> | The PyTorch model. |
| `convert_inputs` | <tt>Callable</tt> | Function to convert inputs to PyTorch tensors (same signature as `forward` function). |
| `convert_outputs` | <tt>Callable</tt> | Function to convert outputs from PyTorch tensors (same signature as `forward` function). |
| **RETURNS** | <tt>Model[Any, Any]</tt> | The Thinc model. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/pytorchwrapper.py
```
### TorchScriptWrapper_v1 {#torchscriptwrapper tag="function" new="8.1.6"}
<inline-list>
- **Input:** <tt>Any</tt>
- **Output:** <tt>Any</tt>
</inline-list>
Wrap a [TorchScript](https://pytorch.org/docs/stable/jit.html) model so that it
has the same API as Thinc models. To optimize the model, you'll need to create a
PyTorch optimizer and call `optimizer.step` after each batch.
Your TorchScript model's forward method can take arbitrary positional arguments
and keyword arguments, but must return either a **single tensor** as output or a
**tuple**. The convert functions are used to map inputs and outputs to and from
your TorchScript model. Each function should return the converted output, and a
callback to use during the backward pass:
```python
Xtorch, get_dX = convert_inputs(X)
Ytorch, torch_backprop = model.shims[0](Xtorch, is_train)
Y, get_dYtorch = convert_outputs(Ytorch)
```
To allow maximum flexibility, the [`TorchScriptShim`](/docs/api-model#shims)
expects [`ArgsKwargs`](/docs/api-types#argskwargs) objects on the way into the
forward and backward passes. The `ArgsKwargs` objects will be passed straight
into the model in the forward pass, and straight into `torch.autograd.backward`
during the backward pass.
Note that the `torchscript_model` argument can be `None`. This is useful for
deserialization since serialized TorchScript contains both the model and its
weights.
A PyTorch wrapper can be converted to a TorchScript wrapper using the
`pytorch_to_torchscript_wrapper` function:
```python
from thinc.api import PyTorchWrapper_v2, pytorch_to_torchscript_wrapper
import torch
model = PyTorchWrapper_v2(torch.nn.Linear(nI, nO)).initialize()
script_model = pytorch_to_torchscript_wrapper(model)
```
| Argument | Type | Description |
| ------------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------- |
| `torchscript_model` | <tt>Optional[torch.jit.ScriptModule]</tt> | The TorchScript model. |
| `convert_inputs` | <tt>Callable</tt> | Function to convert inputs to PyTorch tensors (same signature as `forward` function). |
| `convert_outputs` | <tt>Callable</tt> | Function to convert outputs from PyTorch tensors (same signature as `forward` function). |
| `mixed_precision` | <tt>bool</tt> | Enable mixed-precision training. |
| `grad_scaler` | <tt>Optional[PyTorchGradScaler]</tt> | Gradient scaler to use during mixed-precision training. |
| `device` | <tt>Optional[torch.Device]</tt> | The Torch device to execute the model on. |
| **RETURNS** | <tt>Model[Any, Any]</tt> | The Thinc model. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/torchscriptwrapper.py
```
### TensorFlowWrapper {#tensorflowwrapper tag="function"}
<inline-list>
- **Input:** <tt>Any</tt>
- **Output:** <tt>Any</tt>
</inline-list>
<infobox variant="warning">
In Thinc v8.2+, TensorFlow support is not enabled by default. To enable TensorFlow:
```python
from thinc.api import enable_tensorflow
enable_tensorflow()
```
</infobox>
Wrap a [TensorFlow](https://tensorflow.org) model, so that it has the same API
as Thinc models. To optimize the model, you'll need to create a TensorFlow
optimizer and call `optimizer.apply_gradients` after each batch. To allow
maximum flexibility, the [`TensorFlowShim`](/docs/api-model#shims) expects
[`ArgsKwargs`](/docs/api-types#argskwargs) objects on the way into the forward
and backward passes.
| Argument | Type | Description |
| ------------------ | ------------------------ | --------------------- |
| `tensorflow_model` | <tt>Any</tt> | The TensorFlow model. |
| **RETURNS** | <tt>Model[Any, Any]</tt> | The Thinc model. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/tensorflowwrapper.py
```
### MXNetWrapper {#mxnetwrapper tag="function"}
<inline-list>
- **Input:** <tt>Any</tt>
- **Output:** <tt>Any</tt>
</inline-list>
<infobox variant="warning">
In Thinc v8.2+, MXNet support is not enabled by default. To enable MXNet:
```python
from thinc.api import enable_mxnet
enable_mxnet()
```
</infobox>
Wrap a [MXNet](https://mxnet.apache.org/) model, so that it has the same API as
Thinc models. To optimize the model, you'll need to create a MXNet optimizer and
call `optimizer.step()` after each batch. To allow maximum flexibility, the
[`MXNetShim`](/docs/api-model#shims) expects
[`ArgsKwargs`](/docs/api-types#argskwargs) objects on the way into the forward
and backward passes.
| Argument | Type | Description |
| ------------------ | ------------------------ | --------------------- |
| `tensorflow_model` | <tt>Any</tt> | The TensorFlow model. |
| **RETURNS** | <tt>Model[Any, Any]</tt> | The Thinc model. |
```python
https://github.com/explosion/thinc/blob/master/thinc/layers/mxnetwrapper.py
```
|