def test_concatenate(): data = numpy.asarray([[1, 2, 3], [4, 5, 6]], dtype="f") model = concatenate(Linear(), Linear()) model.initialize(data, data) Y, backprop = model(data, is_train=True) assert Y.shape[1] == sum([layer.predict(data).shape[1] for layer in model.layers]) dX = backprop(Y) assert dX.shape == data.shape
def build_mean_max_reducer(hidden_size: int) -> Model[Ragged, Floats2d]: """Reduce sequences by concatenating their mean and max pooled vectors, and then combine the concatenated vectors with a hidden layer. """ return chain( concatenate(reduce_last(), reduce_first(), reduce_mean(), reduce_max()), Maxout(nO=hidden_size, normalize=True, dropout=0.0), )
def concatenate_ragged(*layers): model = concatenate(*[chain(layer, getitem(0)) for layer in layers]) def begin_update(X_lengths, drop=0.): X, lengths = X_lengths Y, get_dX = model.begin_update(X_lengths, drop=drop) return (Y, lengths), get_dX output = wrap(begin_update, model) return output
def MultiHashEmbed(config): cols = config["columns"] width = config["width"] rows = config["rows"] tables = [HashEmbed(width, rows, column=cols.index("NORM"), name="embed_norm")] if config["use_subwords"]: for feature in ["PREFIX", "SUFFIX", "SHAPE"]: tables.append( HashEmbed( width, rows // 2, column=cols.index(feature), name="embed_%s" % feature.lower(), ) ) if config.get("@pretrained_vectors"): tables.append(make_layer(config["@pretrained_vectors"])) mix = make_layer(config["@mix"]) # This is a pretty ugly hack. Not sure what the best solution should be. mix._layers[0].nI = sum(table.nO for table in tables) layer = uniqued(chain(concatenate(*tables), mix), column=cols.index("ORTH")) layer.cfg = config return layer
def concatenate_lists(*layers, **kwargs): # pragma: no cover """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))` """ if not layers: return noop() drop_factor = kwargs.get('drop_factor', 1.0) ops = layers[0].ops layers = [chain(layer, flatten) for layer in layers] concat = concatenate(*layers) def concatenate_lists_fwd(Xs, drop=0.): drop *= drop_factor lengths = ops.asarray([len(X) for X in Xs], dtype='i') flat_y, bp_flat_y = concat.begin_update(Xs, drop=drop) ys = ops.unflatten(flat_y, lengths) def concatenate_lists_bwd(d_ys, sgd=None): return bp_flat_y(ops.flatten(d_ys), sgd=sgd) return ys, concatenate_lists_bwd model = wrap(concatenate_lists_fwd, concat) return model
def concatenate_lists(*layers, **kwargs): # pragma: no cover """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))` """ if not layers: return noop() drop_factor = kwargs.get("drop_factor", 1.0) ops = layers[0].ops layers = [chain(layer, flatten) for layer in layers] concat = concatenate(*layers) def concatenate_lists_fwd(Xs, drop=0.0): drop *= drop_factor lengths = ops.asarray([len(X) for X in Xs], dtype="i") flat_y, bp_flat_y = concat.begin_update(Xs, drop=drop) ys = ops.unflatten(flat_y, lengths) def concatenate_lists_bwd(d_ys, sgd=None): return bp_flat_y(ops.flatten(d_ys), sgd=sgd) return ys, concatenate_lists_bwd model = wrap(concatenate_lists_fwd, concat) return model
def CharacterEmbed( width: int, rows: int, nM: int, nC: int, include_static_vectors: bool, feature: Union[int, str] = "LOWER", ) -> Model[List[Doc], List[Floats2d]]: """Construct an embedded representation based on character embeddings, using a feed-forward network. A fixed number of UTF-8 byte characters are used for each word, taken from the beginning and end of the word equally. Padding is used in the centre for words that are too short. For instance, let's say nC=4, and the word is "jumping". The characters used will be jung (two from the start, two from the end). If we had nC=8, the characters would be "jumpping": 4 from the start, 4 from the end. This ensures that the final character is always in the last position, instead of being in an arbitrary position depending on the word length. The characters are embedded in a embedding table with a given number of rows, and the vectors concatenated. A hash-embedded vector of the LOWER of the word is also concatenated on, and the result is then passed through a feed-forward network to construct a single vector to represent the information. feature (int or str): An attribute to embed, to concatenate with the characters. width (int): The width of the output vector and the feature embedding. rows (int): The number of rows in the LOWER hash embedding table. nM (int): The dimensionality of the character embeddings. Recommended values are between 16 and 64. nC (int): The number of UTF-8 bytes to embed per word. Recommended values are between 3 and 8, although it may depend on the length of words in the language. include_static_vectors (bool): Whether to also use static word vectors. Requires a vectors table to be loaded in the Doc objects' vocab. """ feature = intify_attr(feature) if feature is None: raise ValueError(Errors.E911.format(feat=feature)) char_embed = chain( _character_embed.CharacterEmbed(nM=nM, nC=nC), cast(Model[List[Floats2d], Ragged], list2ragged()), ) feature_extractor: Model[List[Doc], Ragged] = chain( FeatureExtractor([feature]), cast(Model[List[Ints2d], Ragged], list2ragged()), with_array(HashEmbed(nO=width, nV=rows, column=0, seed=5)), # type: ignore ) max_out: Model[Ragged, Ragged] if include_static_vectors: max_out = with_array( Maxout(width, nM * nC + (2 * width), nP=3, normalize=True, dropout=0.0) # type: ignore ) model = chain( concatenate( char_embed, feature_extractor, StaticVectors(width, dropout=0.0), ), max_out, cast(Model[Ragged, List[Floats2d]], ragged2list()), ) else: max_out = with_array( Maxout(width, nM * nC + width, nP=3, normalize=True, dropout=0.0) # type: ignore ) model = chain( concatenate( char_embed, feature_extractor, ), max_out, cast(Model[Ragged, List[Floats2d]], ragged2list()), ) return model
def MultiHashEmbed( width: int, attrs: List[Union[str, int]], rows: List[int], include_static_vectors: bool, ) -> Model[List[Doc], List[Floats2d]]: """Construct an embedding layer that separately embeds a number of lexical attributes using hash embedding, concatenates the results, and passes it through a feed-forward subnetwork to build a mixed representation. The features used can be configured with the 'attrs' argument. The suggested attributes are NORM, PREFIX, SUFFIX and SHAPE. This lets the model take into account some subword information, without constructing a fully character-based representation. If pretrained vectors are available, they can be included in the representation as well, with the vectors table will be kept static (i.e. it's not updated). The `width` parameter specifies the output width of the layer and the widths of all embedding tables. If static vectors are included, a learned linear layer is used to map the vectors to the specified width before concatenating it with the other embedding outputs. A single Maxout layer is then used to reduce the concatenated vectors to the final width. The `rows` parameter controls the number of rows used by the `HashEmbed` tables. The HashEmbed layer needs surprisingly few rows, due to its use of the hashing trick. Generally between 2000 and 10000 rows is sufficient, even for very large vocabularies. A number of rows must be specified for each table, so the `rows` list must be of the same length as the `attrs` parameter. width (int): The output width. Also used as the width of the embedding tables. Recommended values are between 64 and 300. attrs (list of attr IDs): The token attributes to embed. A separate embedding table will be constructed for each attribute. rows (List[int]): The number of rows in the embedding tables. Must have the same length as attrs. include_static_vectors (bool): Whether to also use static word vectors. Requires a vectors table to be loaded in the Doc objects' vocab. """ if len(rows) != len(attrs): raise ValueError(f"Mismatched lengths: {len(rows)} vs {len(attrs)}") seed = 7 def make_hash_embed(index): nonlocal seed seed += 1 return HashEmbed(width, rows[index], column=index, seed=seed, dropout=0.0) embeddings = [make_hash_embed(i) for i in range(len(attrs))] concat_size = width * (len(embeddings) + include_static_vectors) max_out: Model[Ragged, Ragged] = with_array( Maxout(width, concat_size, nP=3, dropout=0.0, normalize=True) # type: ignore ) if include_static_vectors: feature_extractor: Model[List[Doc], Ragged] = chain( FeatureExtractor(attrs), cast(Model[List[Ints2d], Ragged], list2ragged()), with_array(concatenate(*embeddings)), ) model = chain( concatenate( feature_extractor, StaticVectors(width, dropout=0.0), ), max_out, cast(Model[Ragged, List[Floats2d]], ragged2list()), ) else: model = chain( FeatureExtractor(list(attrs)), cast(Model[List[Ints2d], Ragged], list2ragged()), with_array(concatenate(*embeddings)), max_out, cast(Model[Ragged, List[Floats2d]], ragged2list()), ) return model
from thinc.api import chain, Relu, reduce_max, Softmax, add, concatenate bad_model = chain(Relu(10), reduce_max(), Softmax()) bad_model2 = add(Relu(10), reduce_max(), Softmax()) bad_model_only_plugin = chain(Relu(10), Relu(10), Relu(10), Relu(10), reduce_max(), Softmax()) bad_model_only_plugin2 = add(Relu(10), Relu(10), Relu(10), Relu(10), reduce_max(), Softmax()) reveal_type(bad_model_only_plugin2) bad_model_only_plugin3 = concatenate(Relu(10), Relu(10), Relu(10), Relu(10), reduce_max(), Softmax()) reveal_type(bad_model_only_plugin3)
def test_concatenate_noop(): model = concatenate() assert len(model.layers) == 0 assert model.name == "noop"
def test_concatenate_three(model1, model2, model3): model = concatenate(model1, model2, model3) assert len(model.layers) == 3
def test_concatenate_two(model1, model2): model = concatenate(model1, model2) assert len(model.layers) == 2
def test_concatenate_one(model1): model = concatenate(model1) assert isinstance(model, Model)
def FancyEmbed(width, rows, cols=(ORTH, SHAPE, PREFIX, SUFFIX)): tables = [HashEmbed(width, rows, column=i) for i in range(len(cols))] return chain(concatenate(*tables), Maxout(width, width * len(tables), pieces=3))