Transformers¶
formed.integrations.transformers.analyzers
¶
Text analyzers using pretrained transformers tokenizers.
This module provides text analysis tools that leverage pretrained tokenizers from the Hugging Face transformers library to tokenize text into surface forms.
Available Classes
PretrainedAnalyzer: Analyzer using pretrained transformer tokenizers
Examples:
>>> from formed.integrations.transformers.analyzers import PretrainedAnalyzer
>>>
>>> # Initialize with model name
>>> analyzer = PretrainedAnalyzer("bert-base-uncased")
>>> result = analyzer("Hello world!")
>>> print(result.surfaces)
['hello', 'world', '!']
PretrainedTransformerAnalyzer
dataclass
¶
PretrainedTransformerAnalyzer(tokenizer)
Text analyzer using pretrained transformer tokenizers.
This analyzer uses tokenizers from the Hugging Face transformers library to split text into tokens (surface forms). It provides a simple interface for text tokenization that's compatible with the formed ML pipeline.
| PARAMETER | DESCRIPTION |
|---|---|
tokenizer
|
Either a tokenizer name/path string or a
TYPE:
|
Examples:
>>> # Initialize with model name
>>> analyzer = PretrainedAnalyzer("bert-base-uncased")
>>> result = analyzer("Hello, world!")
>>> print(result.surfaces)
['hello', ',', 'world', '!']
>>>
>>> # Initialize with tokenizer instance
>>> from transformers import AutoTokenizer
>>> tokenizer = AutoTokenizer.from_pretrained("roberta-base")
>>> analyzer = PretrainedAnalyzer(tokenizer)
>>> result = analyzer("Machine learning is great!")
>>> print(result.surfaces)
['Machine', 'Ġlearning', 'Ġis', 'Ġgreat', '!']
Note
Tokenizers are cached using LRU cache by the load_pretrained_tokenizer utility.
The returned AnalyzedText only contains surface forms; other fields like
postags are None.
formed.integrations.transformers.training
¶
MlflowTrainerCallback
¶
MlflowTrainerCallback()
Bases: TrainerCallback
Source code in src/formed/integrations/transformers/training.py
16 17 18 19 | |
on_train_begin
¶
on_train_begin(args, state, control, **kwargs)
Source code in src/formed/integrations/transformers/training.py
21 22 23 24 25 26 27 28 29 30 31 32 33 | |
on_log
¶
on_log(args, state, control, logs, model=None, **kwargs)
Source code in src/formed/integrations/transformers/training.py
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 | |
formed.integrations.transformers.utils
¶
load_pretrained_transformer
cached
¶
load_pretrained_transformer(
model_name_or_path,
auto_class=None,
submodule=None,
**kwargs,
)
Source code in src/formed/integrations/transformers/utils.py
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 | |
load_pretrained_tokenizer
cached
¶
load_pretrained_tokenizer(model_name_or_path, **kwargs)
Source code in src/formed/integrations/transformers/utils.py
41 42 43 44 45 46 47 48 | |
formed.integrations.transformers.workflow
¶
Workflow steps for Hugging Face Transformers integration.
This module provides workflow steps for loading, tokenizing, training, and converting transformer models using the Hugging Face Transformers library.
Available Steps
transformers::tokenize: Tokenize a dataset using a pre-trained tokenizer.transformers::load_model: Load a pre-trained transformer model.transformers::load_tokenizer: Load a pre-trained tokenizer.transformers::train_model: Train a transformer model using the Hugging Face Trainer.transformers::convert_tokenizer: Convert a transformer tokenizer to a formed Tokenizer (requires ml integration).
PretrainedModelT
module-attribute
¶
PretrainedModelT = TypeVar(
"PretrainedModelT", bound=PreTrainedModel
)
TransformersPretrainedModelFormat
¶
Bases: Generic[PretrainedModelT], Format[PretrainedModelT]
identifier
property
¶
identifier
Get the unique identifier for this format.
| RETURNS | DESCRIPTION |
|---|---|
str
|
Format identifier string. |
write
¶
write(artifact, directory)
Source code in src/formed/integrations/transformers/workflow.py
47 48 49 50 51 52 53 54 | |
read
¶
read(directory)
Source code in src/formed/integrations/transformers/workflow.py
56 57 58 59 60 61 62 63 64 65 66 | |
is_default_of
classmethod
¶
is_default_of(obj)
Check if this format is the default for the given object type.
| PARAMETER | DESCRIPTION |
|---|---|
obj
|
Object to check.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
bool
|
True if this format should be used by default for this type. |
Source code in src/formed/workflow/format.py
101 102 103 104 105 106 107 108 109 110 111 112 | |
tokenize_dataset
¶
tokenize_dataset(
dataset,
tokenizer,
text_column="text",
padding=False,
truncation=False,
return_special_tokens_mask=False,
max_length=None,
)
Tokenize a dataset using a pre-trained tokenizer.
This step applies tokenization to a text column in the dataset, removing the original text column and adding tokenized features.
| PARAMETER | DESCRIPTION |
|---|---|
dataset
|
Dataset or DatasetDict to tokenize.
TYPE:
|
tokenizer
|
Tokenizer identifier, path, or instance.
TYPE:
|
text_column
|
Name of the text column to tokenize.
TYPE:
|
padding
|
Padding strategy.
TYPE:
|
truncation
|
Truncation strategy.
TYPE:
|
return_special_tokens_mask
|
Whether to return special tokens mask.
TYPE:
|
max_length
|
Maximum sequence length.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Dataset | DatasetDict
|
Tokenized dataset with the text column removed. |
Source code in src/formed/integrations/transformers/workflow.py
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 | |
load_pretrained_model
¶
load_pretrained_model(
model_name_or_path,
auto_class=AutoModel,
submodule=None,
**kwargs,
)
Load a pre-trained transformer model.
| PARAMETER | DESCRIPTION |
|---|---|
model_name_or_path
|
Model identifier or path to model directory.
TYPE:
|
auto_class
|
Auto model class to use for loading (name or class).
TYPE:
|
submodule
|
Optional submodule to extract from the model.
TYPE:
|
**kwargs
|
Additional arguments to pass to the model constructor.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PreTrainedModel
|
Loaded pre-trained transformer model. |
Source code in src/formed/integrations/transformers/workflow.py
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 | |
load_pretrained_tokenizer_step
¶
load_pretrained_tokenizer_step(
pretrained_model_name_or_path, **kwargs
)
Load a pre-trained tokenizer.
| PARAMETER | DESCRIPTION |
|---|---|
pretrained_model_name_or_path
|
Model identifier or path to model directory.
TYPE:
|
**kwargs
|
Additional arguments to pass to the tokenizer constructor.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PreTrainedTokenizerBase
|
Loaded pre-trained tokenizer. |
Source code in src/formed/integrations/transformers/workflow.py
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | |
train_transformer_model
¶
train_transformer_model(
model,
args,
data_collator=None,
dataset=None,
processing_class=None,
model_init=None,
compute_loss_func=None,
compute_metrics=None,
callbacks=None,
optimizers=(None, None),
optimizer_cls_and_kwargs=None,
preprocess_logits_for_metrics=None,
train_dataset_key="train",
eval_dataset_key="validation",
)
Train a transformer model using the Hugging Face Trainer.
This step trains a transformer model on the provided datasets using the Hugging Face Trainer API.
| PARAMETER | DESCRIPTION |
|---|---|
model
|
Pre-trained model to train.
TYPE:
|
args
|
Training arguments configuration.
TYPE:
|
data_collator
|
Optional data collator for batching.
TYPE:
|
dataset
|
Training/validation datasets.
TYPE:
|
processing_class
|
Optional processing class (tokenizer, processor, etc.).
TYPE:
|
model_init
|
Optional model initialization function.
TYPE:
|
compute_loss_func
|
Optional custom loss computation function.
TYPE:
|
compute_metrics
|
Optional metrics computation function.
TYPE:
|
callbacks
|
Optional training callbacks.
TYPE:
|
optimizers
|
Optional optimizer and learning rate scheduler.
TYPE:
|
optimizer_cls_and_kwargs
|
Optional optimizer class and keyword arguments.
TYPE:
|
preprocess_logits_for_metrics
|
Optional logits preprocessing function.
TYPE:
|
train_dataset_key
|
Key for training dataset split.
TYPE:
|
eval_dataset_key
|
Key for evaluation dataset split.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
PreTrainedModel
|
Trained transformer model. |
Source code in src/formed/integrations/transformers/workflow.py
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 | |
convert_tokenizer
¶
convert_tokenizer(
tokenizer,
pad_token=VALUE,
unk_token=VALUE,
bos_token=VALUE,
eos_token=VALUE,
freeze=True,
accessor=None,
characters=None,
text_vector=None,
token_vectors=None,
)
Convert a transformer tokenizer to a formed Tokenizer.
This step converts a Hugging Face tokenizer into a formed Tokenizer with specified special tokens.
| PARAMETER | DESCRIPTION |
|---|---|
tokenizer
|
Tokenizer identifier, path, or instance.
TYPE:
|
pad_token
|
Padding token (uses tokenizer default if not specified).
TYPE:
|
unk_token
|
Unknown token (uses tokenizer default if not specified).
TYPE:
|
bos_token
|
Beginning-of-sequence token (uses tokenizer default if not specified).
TYPE:
|
eos_token
|
End-of-sequence token (uses tokenizer default if not specified).
TYPE:
|
freeze
|
Whether to freeze the vocabulary.
TYPE:
|
accessor
|
Optional accessor for token extraction.
TYPE:
|
| RETURNS | DESCRIPTION |
|---|---|
Tokenizer
|
Converted formed Tokenizer. |
| RAISES | DESCRIPTION |
|---|---|
AssertionError
|
If pad_token is not specified and not available in the tokenizer. |
Source code in src/formed/integrations/transformers/workflow.py
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 | |