Model Card for Flex-DM¶
This package ports Flex-DM, the MFP masked multi-field document model from arXiv 2303.18248, to a 🤗transformers-style package for document layout completion, refinement, and Crello image/text feature infilling.
Model Details¶
Model Description¶
Flex-DM models document elements as rows with element class, position, size, color, image, and text fields. The public pipeline returns normalized center xywh boxes in [0, 1], dataset-local integer labels, a valid-element mask, and id2label. Released checkpoints are masked document models for Crello and RICO.
- Developed by: Naoto Inoue et al.
- Shared by: creative-graphic-design.
- Model type: content-agnostic; task: task-agnostic; conditioning: completion, refinement.
- Language(s) (NLP): not applicable.
- License: Apache-2.0.
Model Sources¶
- Repository: CyberAgentAILab/flex-dm
- Paper: Towards Flexible Multi-modal Document Models
Supported Checkpoints¶
| Checkpoint | Hub ID | Status |
|---|---|---|
Crello ours-exp-ft |
creative-graphic-design/flex-dm-crello |
not-published |
RICO ours-exp-ft |
creative-graphic-design/flex-dm-rico |
not-published |
Uses¶
Direct Use¶
Use this package for research inference, conversion checks, and original-implementation agreement checks for Flex-DM document infilling.
Downstream Use¶
The package can be used as a component in document design tooling that needs masked layout completion or multimodal field infilling after converted checkpoints are available locally.
Out-of-Scope Use¶
The package is not intended for production publishing workflows, legal document validation, or unrestricted generation of copyrighted design assets.
Bias, Risks, and Limitations¶
The released checkpoints reflect the visual and structural distributions of their training datasets. Crello image/text fields depend on original-implementation preprocessing artifacts, and RICO label ordering must remain compatible with the released vocabulary.
Recommendations¶
Validate outputs against the target dataset schema before using generated layouts in downstream evaluation. Run the original-implementation agreement checks before relying on converted checkpoints.
How to Get Started with the Model¶
Install the package directly from this repository. The command includes shared packages when they are not published on PyPI.
pip install \
"laygen @ git+https://github.com/creative-graphic-design/design-generators.git#subdirectory=lib/laygen" \
"posgen @ git+https://github.com/creative-graphic-design/design-generators.git#subdirectory=lib/posgen" \
"flex-dm @ git+https://github.com/creative-graphic-design/design-generators.git#subdirectory=models/flex-dm"
The Hub repos are not published yet. Until then, create a local converted checkpoint and load it from .cache/flex-dm/converted.
git clone https://github.com/creative-graphic-design/design-generators.git
cd design-generators
uv sync --package flex-dm
uv run --package flex-dm --extra data models/flex-dm/scripts/download_original_assets.py --output-dir .cache/flex-dm/original --dataset all --assets weights
uv run --package flex-dm --extra convert models/flex-dm/scripts/convert_original_checkpoint.py --dataset crello --variant ours-exp-ft --asset-dir .cache/flex-dm/original --output-dir .cache/flex-dm/converted/flex-dm-crello
See REPRODUCING.md for the full original-implementation reference-generation and agreement-check workflow.
from flex_dm import FlexDmPipeline
pipe = FlexDmPipeline.from_pretrained(".cache/flex-dm/converted/flex-dm-crello")
# After Hub publication: from_pretrained("creative-graphic-design/flex-dm-crello")
Flex-DM's public inference path is deterministic for the supported completion,
refinement, and image/text feature infilling modes. The pipeline accepts
seed and generator to match the common layout-generation API, and
generator takes precedence over seed when both are supplied, but the
current public path does not consume random numbers.
Training Details¶
Training Data¶
The original checkpoints were trained on data preprocessed by the original implementation for Crello and RICO. Crello uses cyberagent/crello as the ordinary dataset reference, while RICO uses creative-graphic-design/Rico with the semantic-annotation config after vocabulary compatibility is verified.
Training Procedure¶
Training follows the original TensorFlow implementation with latent_dim=256, num_blocks=4, block_type=deepsvg, seq_type=default, arch_type=oneshot, and fixed seed 0 in the released args.json files.
Evaluation¶
Parity Results¶
| checkpoint | dataset | original-implementation reference cases | exact state tensors | forward/layer probe | result |
|---|---|---|---|---|---|
ours-exp-ft |
Crello | 10 | 98 / 98 tensors, 2,812,257 params | 10 forward cases / 25 forward steps; max logit abs diff within atol=1.1e-5, rtol=0 |
reference generated with TF32 disabled; state mapping exact |
ours-exp-ft |
RICO | 6 | 88 / 88 tensors, 2,296,679 params | 6 forward cases / 15 forward steps; max logit abs diff within atol=5.5e-6, rtol=0 |
reference generated with TF32 disabled; state mapping exact |
Agreement-check tests load the saved TF32-disabled reference inputs from forward_cases/*.npz, load the converted checkpoints with from_pretrained, and execute every saved original-implementation forward step inside pytest. This covers Crello's 10 task/iteration cases and RICO's 6 cases, including the four forward steps used by num_iter=4. Layer probes also use one original-implementation test batch after preprocess_for_test for every supported task (elem, pos, attr, plus Crello img and txt). The first divergent block-0 operation in the default original-implementation GPU path was the attention score matmul tf.matmul(q, k^T): TensorFlow 2.15 on A100 used TF32 there, while the public PyTorch model used fp32. Direct q/k isolation showed the TF32 score differed from NumPy/PyTorch fp32 by 7.92e-3, and PyTorch CUDA TF32 matched the TensorFlow score. Final agreement checks instead disable TensorFlow TF32 during original-implementation reference and probe generation with NVIDIA_TF32_OVERRIDE=0 plus --disable-tf32, so the public PyTorch model keeps its ordinary fp32 attention path. GELU was not involved because the original-implementation MLP uses ReLU; Keras LayerNormalization epsilon is 1e-3 and is matched by FlexDmConfig.layer_norm_epsilon; the additive mask remains -1e9 before softmax.
With TF32 disabled in the original-implementation run, all probe metadata records tf32_enabled=false. The remaining first measurable difference is the fp32 attention-score reduction order at block 0, with max score diff up to 7.63e-6; block-0 attention output stays below 5.59e-8. Across the pytest-executed forward cases, Crello max logit diff is 1.00e-5 and RICO max logit diff is 5.25e-6.
Reproducibility¶
Reproduce the original-implementation agreement checks with the walkthrough in models/flex-dm/REPRODUCING.md.
License¶
Repository code is Apache-2.0. The original Flex-DM implementation is Apache-2.0. Dataset licensing follows the source dataset metadata.
Citation¶
@inproceedings{inoue2023flexdm,
title = {Towards Flexible Multi-modal Document Models},
booktitle = {CVPR},
year = {2023}
}
API Reference¶
Flex-DM masked document modeling package.
FlexDmConfig ¶
Bases: PretrainedConfig
Configuration for a converted Flex-DM MFP model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
Released dataset name. |
'crello'
|
checkpoint_variant
|
str
|
Released checkpoint variant name. |
'ours-exp-ft'
|
id2label
|
dict[int | str, str] | None
|
Public dataset-local label mapping. |
None
|
input_columns
|
dict[str, FlexDmColumnSpec] | None
|
Heterogeneous model column specs. |
None
|
attribute_groups
|
dict[str, tuple[str, ...] | list[str]] | None
|
Model feature groups used for infilling. |
None
|
max_seq_length
|
int
|
Maximum document elements. |
50
|
latent_dim
|
int
|
Transformer hidden dimension. |
256
|
num_blocks
|
int
|
Number of DeepSVG-style transformer blocks. |
4
|
block_type
|
str
|
Released block type. Only |
'deepsvg'
|
masking_method
|
str
|
Released masking task selector. |
'random'
|
seq_type
|
str
|
Released sequence model type. |
'default'
|
arch_type
|
str
|
Released architecture type. |
'oneshot'
|
context
|
str | None
|
Optional reference context embedding mode. |
None
|
input_dtype
|
str
|
Released input ordering mode. |
'set'
|
use_elemwise_noise
|
bool
|
Whether element-wise noise was enabled. |
False
|
dropout
|
float
|
Dropout probability. |
0.1
|
layer_norm_epsilon
|
float
|
LayerNorm epsilon matching Keras defaults. |
0.001
|
l2
|
float | None
|
Original L2 setting, stored for provenance. |
0.01
|
original_args
|
dict[str, FlexDmConfigValue] | None
|
Raw reference |
None
|
conversion_report
|
dict[str, FlexDmConfigValue] | None
|
Checkpoint conversion diagnostics. |
None
|
kwargs
|
str | int | float | bool | None
|
Extra |
{}
|
Source code in models/flex-dm/src/flex_dm/configuration_flex_dm.py
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 | |
max_seq_length_with_length_lookup
property
¶
max_seq_length_with_length_lookup: int
Return the max length used by the zero-based length lookup.
valid_sequence_keys
property
¶
valid_sequence_keys: tuple[str, ...]
Return non-demo sequence fields modeled by Flex-DM.
categorical_keys
property
¶
categorical_keys: tuple[str, ...]
Return sequence fields with categorical heads.
numerical_keys
property
¶
numerical_keys: tuple[str, ...]
Return sequence fields with numerical heads.
__init__ ¶
__init__(
dataset_name: str = "crello",
checkpoint_variant: str = "ours-exp-ft",
id2label: dict[int | str, str] | None = None,
input_columns: dict[str, FlexDmColumnSpec]
| None = None,
attribute_groups: dict[str, tuple[str, ...] | list[str]]
| None = None,
max_seq_length: int = 50,
latent_dim: int = 256,
num_blocks: int = 4,
block_type: str = "deepsvg",
masking_method: str = "random",
seq_type: str = "default",
arch_type: str = "oneshot",
context: str | None = None,
input_dtype: str = "set",
use_elemwise_noise: bool = False,
dropout: float = 0.1,
layer_norm_epsilon: float = 0.001,
l2: float | None = 0.01,
original_args: dict[str, FlexDmConfigValue]
| None = None,
conversion_report: dict[str, FlexDmConfigValue]
| None = None,
**kwargs: str | int | float | bool | None,
) -> None
Initialize a Flex-DM config.
Source code in models/flex-dm/src/flex_dm/configuration_flex_dm.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 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 | |
mask_token_id_for ¶
mask_token_id_for(key: str) -> int
Return the categorical mask token id for key.
Source code in models/flex-dm/src/flex_dm/configuration_flex_dm.py
209 210 211 212 213 214 215 | |
unused_token_id_for ¶
unused_token_id_for(key: str) -> int
Return the categorical unused token id for key.
Source code in models/flex-dm/src/flex_dm/configuration_flex_dm.py
217 218 219 | |
FlexDmForMaskedDocumentModeling ¶
Bases: FlexDmPreTrainedModel
Flex-DM MFP model with a standard Transformers forward method.
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
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 | |
__init__ ¶
__init__(config: FlexDmConfig) -> None
Initialize encoder, transformer blocks, and decoder.
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | |
forward ¶
forward(
*,
inputs: Mapping[str, Shaped[Tensor, "..."]],
masks: Mapping[str, Bool[Tensor, "..."]] | None = None,
labels: Mapping[str, Shaped[Tensor, "..."]]
| None = None,
task_ids: Int[Tensor, "batch"] | None = None,
output_hidden_states: bool = False,
return_dict: bool | None = None,
) -> (
FlexDmModelOutput
| tuple[
dict[str, Shaped[torch.Tensor, "..."]],
Float[torch.Tensor, ""] | None,
]
)
Run a Flex-DM forward pass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
Mapping[str, Shaped[Tensor, '...']]
|
Per-column model input tensors. |
required |
masks
|
Mapping[str, Bool[Tensor, '...']] | None
|
Optional hidden-field masks for diagnostics. |
None
|
labels
|
Mapping[str, Shaped[Tensor, '...']] | None
|
Optional per-column reconstruction targets. |
None
|
task_ids
|
Int[Tensor, 'batch'] | None
|
Optional task ids. |
None
|
output_hidden_states
|
bool
|
Whether to include final hidden states. |
False
|
return_dict
|
bool | None
|
Whether to return a |
None
|
Returns:
| Type | Description |
|---|---|
FlexDmModelOutput | tuple[dict[str, Shaped[Tensor, '...']], Float[Tensor, ''] | None]
|
|
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
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 | |
FlexDmModelOutput
dataclass
¶
Bases: ModelOutput
Output of FlexDmForMaskedDocumentModeling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
dict[str, Shaped[Tensor, '...']]
|
Per-column logits or numerical predictions. |
required |
loss
|
Float[Tensor, ''] | None
|
Optional summed reconstruction loss. |
None
|
hidden_states
|
Float[Tensor, 'batch seq channels'] | None
|
Optional final hidden states. |
None
|
masks
|
dict[str, Bool[Tensor, '...']] | None
|
Optional per-column hidden-field masks. |
None
|
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
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 | |
__post_init__ ¶
__post_init__() -> None
Keep the logits dictionary as one ModelOutput field.
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
37 38 39 40 41 42 43 44 45 46 | |
FlexDmPipeline ¶
Bases: LayoutGenerationPipeline
Run Flex-DM completion, refinement, and feature-level content infilling.
Source code in models/flex-dm/src/flex_dm/pipeline_flex_dm.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 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 | |
__init__ ¶
__init__(
model: FlexDmForMaskedDocumentModeling,
processor: FlexDmProcessor | None = None,
config: FlexDmConfig | None = None,
) -> None
Initialize model and processor components.
Source code in models/flex-dm/src/flex_dm/pipeline_flex_dm.py
82 83 84 85 86 87 88 89 90 91 92 | |
__call__ ¶
__call__(
*,
batch_size: int = 1,
seed: int | None = None,
generator: Generator | None = None,
condition_type: ConditionType
| str = ConditionType.completion,
labels: Int[Tensor, "batch elements"]
| Int[ndarray, "batch elements"]
| Sequence[ArrayLikeInput]
| None = None,
bbox: Float[Tensor, "batch elements 4"]
| Float[ndarray, "batch elements 4"]
| Sequence[ArrayLikeInput]
| None = None,
mask: Bool[Tensor, "batch elements"]
| Bool[ndarray, "batch elements"]
| Sequence[ArrayLikeInput]
| None = None,
num_elements: int
| list[int]
| Int[Tensor, "batch"]
| None = None,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
num_inference_steps: int | None = None,
output_type: Literal["dataclass", "dict"] = "dataclass",
return_intermediates: bool = False,
attributes: Mapping[str, FlexDmValue] | None = None,
content: Mapping[str, FlexDmValue] | None = None,
feature_group: str | None = None,
target_indices: Int[Tensor, "..."] | None = None,
**model_kwargs: FlexDmValue,
) -> (
LayoutGenerationOutput
| dict[
str,
Shaped[torch.Tensor, "..."]
| dict[int, str]
| Mapping[str, Shaped[torch.Tensor, "..."]]
| None,
]
)
Infills masked Flex-DM document fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Batch size used when synthetic empty inputs are created. |
1
|
seed
|
int | None
|
Common API compatibility argument. Flex-DM's public inference path is deterministic and does not currently consume randomness. |
None
|
generator
|
Generator | None
|
Common API compatibility argument. When supplied, it
takes precedence over |
None
|
condition_type
|
ConditionType | str
|
Canonical condition or local task alias. |
completion
|
labels
|
Int[Tensor, 'batch elements'] | Int[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Public element labels. |
None
|
bbox
|
Float[Tensor, 'batch elements 4'] | Float[ndarray, 'batch elements 4'] | Sequence[ArrayLikeInput] | None
|
Public element boxes. |
None
|
mask
|
Bool[Tensor, 'batch elements'] | Bool[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Public valid-element mask. |
None
|
num_elements
|
int | list[int] | Int[Tensor, 'batch'] | None
|
Optional element counts for synthetic inputs. |
None
|
box_format
|
BoxFormat | str
|
Input box coordinate format. |
xywh
|
normalized
|
bool
|
Whether input boxes are already normalized. |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size when |
None
|
num_inference_steps
|
int | None
|
Number of iterative decode steps. |
None
|
output_type
|
Literal['dataclass', 'dict']
|
|
'dataclass'
|
return_intermediates
|
bool
|
Whether to include logits and masks. |
False
|
attributes
|
Mapping[str, FlexDmValue] | None
|
Optional non-core document attributes. |
None
|
content
|
Mapping[str, FlexDmValue] | None
|
Optional Crello image/text embeddings. |
None
|
feature_group
|
str | None
|
Flex-DM task group such as |
None
|
target_indices
|
Int[Tensor, '...'] | None
|
Optional element indexes for |
None
|
model_kwargs
|
FlexDmValue
|
Reserved model keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
LayoutGenerationOutput | dict[str, Shaped[Tensor, '...'] | dict[int, str] | Mapping[str, Shaped[Tensor, '...']] | None]
|
Common layout-generation output. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the requested canonical condition is not supported by released Flex-DM MFP checkpoints. |
Source code in models/flex-dm/src/flex_dm/pipeline_flex_dm.py
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 | |
FlexDmProcessor ¶
Bases: ProcessorMixin
Serialize vocabularies and convert public layouts to Flex-DM tensors.
Flex-DM intentionally does not expose a PreTrainedTokenizer because the
model consumes a dictionary of heterogeneous categorical and continuous
fields rather than one discrete token stream.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
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 | |
__init__ ¶
__init__(
*,
config: FlexDmConfig,
vocabulary: dict[str, FlexDmValue] | None = None,
discretizers: dict[str, FlexDmDiscretizerSpec]
| None = None,
) -> None
Initialize metadata-only processor state.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | |
from_config
classmethod
¶
from_config(config: FlexDmConfig) -> 'FlexDmProcessor'
Create a processor from config metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
FlexDmConfig
|
Flex-DM configuration. |
required |
Returns:
| Type | Description |
|---|---|
'FlexDmProcessor'
|
Processor with built-in discretizers. |
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
81 82 83 84 85 86 87 88 89 90 91 | |
save_pretrained ¶
save_pretrained(
save_directory: str | PathLike[str],
push_to_hub: bool = False,
**kwargs: str | int | float | bool | None,
) -> None
Save processor metadata next to a converted checkpoint.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
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 | |
from_pretrained
classmethod
¶
from_pretrained(
pretrained_model_name_or_path: str | PathLike[str],
cache_dir: str | PathLike[str] | None = None,
force_download: bool = False,
local_files_only: bool = False,
token: str | bool | None = None,
revision: str = "main",
*,
subfolder: str | None = None,
**kwargs: str | int | float | bool | None,
) -> "FlexDmProcessor"
Load processor metadata from a local converted checkpoint.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
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 | |
from_vocabulary
classmethod
¶
from_vocabulary(
*,
dataset_name: str,
vocabulary: dict[str, FlexDmValue],
checkpoint_variant: str = "ours-exp-ft",
) -> "FlexDmProcessor"
Build config and processor metadata from vocabulary.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
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 | |
__call__ ¶
__call__(
*,
condition_type: ConditionType
| str = ConditionType.completion,
labels: Int[Tensor, "batch elements"]
| Int[ndarray, "batch elements"]
| Sequence[ArrayLikeInput]
| None = None,
bbox: Float[Tensor, "batch elements 4"]
| Float[ndarray, "batch elements 4"]
| Sequence[ArrayLikeInput]
| None = None,
mask: Bool[Tensor, "batch elements"]
| Bool[ndarray, "batch elements"]
| Sequence[ArrayLikeInput]
| None = None,
num_elements: int
| list[int]
| Int[Tensor, "batch"]
| None = None,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
attributes: Mapping[str, FlexDmValue] | None = None,
content: Mapping[str, FlexDmValue] | None = None,
feature_group: str | None = None,
target_indices: Int[Tensor, "..."] | None = None,
batch_size: int = 1,
return_tensors: Literal["pt"] = "pt",
) -> dict[
str,
dict[
str,
Shaped[torch.Tensor, "..."]
| Bool[torch.Tensor, "..."],
]
| Shaped[torch.Tensor, "..."]
| ConditionType
| str
| None,
]
Convert public layout fields into Flex-DM model tensors.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
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 | |
normalize_condition_and_feature ¶
normalize_condition_and_feature(
condition_type: ConditionType | str,
*,
feature_group: str | None = None,
) -> tuple[ConditionType, str | None]
Normalize canonical conditions plus local Flex-DM task aliases.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
261 262 263 264 265 266 267 268 269 270 271 272 273 274 | |
post_process_document ¶
post_process_document(
outputs: FlexDmModelOutput,
*,
original_inputs: Mapping[str, Shaped[Tensor, "..."]],
masks: Mapping[str, Bool[Tensor, "..."]],
output_type: Literal["dataclass", "dict"] = "dataclass",
return_intermediates: bool = False,
refinement_input: Mapping[str, Shaped[Tensor, "..."]]
| None = None,
) -> (
LayoutGenerationOutput
| dict[
str,
Shaped[torch.Tensor, "..."]
| dict[int, str]
| Mapping[str, Shaped[torch.Tensor, "..."]]
| None,
]
)
Decode Flex-DM model outputs to the common layout schema.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
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 | |
configuration_flex_dm ¶
Configuration objects for Flex-DM masked document modeling.
FlexDmDatasetName ¶
Bases: StrEnum
Dataset names supported by the Flex-DM MFP checkpoints.
Source code in models/flex-dm/src/flex_dm/configuration_flex_dm.py
22 23 24 25 26 | |
FlexDmColumnType ¶
Bases: StrEnum
Internal column storage type.
Source code in models/flex-dm/src/flex_dm/configuration_flex_dm.py
29 30 31 32 33 | |
FlexDmLossCondition ¶
Bases: TypedDict
Conditional loss filter for conditionally valid fields.
Source code in models/flex-dm/src/flex_dm/configuration_flex_dm.py
36 37 38 39 40 | |
FlexDmColumnSpec ¶
Bases: TypedDict
Tensor specification for one Flex-DM input/output column.
Source code in models/flex-dm/src/flex_dm/configuration_flex_dm.py
43 44 45 46 47 48 49 50 51 | |
FlexDmConfig ¶
Bases: PretrainedConfig
Configuration for a converted Flex-DM MFP model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
Released dataset name. |
'crello'
|
checkpoint_variant
|
str
|
Released checkpoint variant name. |
'ours-exp-ft'
|
id2label
|
dict[int | str, str] | None
|
Public dataset-local label mapping. |
None
|
input_columns
|
dict[str, FlexDmColumnSpec] | None
|
Heterogeneous model column specs. |
None
|
attribute_groups
|
dict[str, tuple[str, ...] | list[str]] | None
|
Model feature groups used for infilling. |
None
|
max_seq_length
|
int
|
Maximum document elements. |
50
|
latent_dim
|
int
|
Transformer hidden dimension. |
256
|
num_blocks
|
int
|
Number of DeepSVG-style transformer blocks. |
4
|
block_type
|
str
|
Released block type. Only |
'deepsvg'
|
masking_method
|
str
|
Released masking task selector. |
'random'
|
seq_type
|
str
|
Released sequence model type. |
'default'
|
arch_type
|
str
|
Released architecture type. |
'oneshot'
|
context
|
str | None
|
Optional reference context embedding mode. |
None
|
input_dtype
|
str
|
Released input ordering mode. |
'set'
|
use_elemwise_noise
|
bool
|
Whether element-wise noise was enabled. |
False
|
dropout
|
float
|
Dropout probability. |
0.1
|
layer_norm_epsilon
|
float
|
LayerNorm epsilon matching Keras defaults. |
0.001
|
l2
|
float | None
|
Original L2 setting, stored for provenance. |
0.01
|
original_args
|
dict[str, FlexDmConfigValue] | None
|
Raw reference |
None
|
conversion_report
|
dict[str, FlexDmConfigValue] | None
|
Checkpoint conversion diagnostics. |
None
|
kwargs
|
str | int | float | bool | None
|
Extra |
{}
|
Source code in models/flex-dm/src/flex_dm/configuration_flex_dm.py
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 | |
max_seq_length_with_length_lookup
property
¶
max_seq_length_with_length_lookup: int
Return the max length used by the zero-based length lookup.
valid_sequence_keys
property
¶
valid_sequence_keys: tuple[str, ...]
Return non-demo sequence fields modeled by Flex-DM.
categorical_keys
property
¶
categorical_keys: tuple[str, ...]
Return sequence fields with categorical heads.
numerical_keys
property
¶
numerical_keys: tuple[str, ...]
Return sequence fields with numerical heads.
__init__ ¶
__init__(
dataset_name: str = "crello",
checkpoint_variant: str = "ours-exp-ft",
id2label: dict[int | str, str] | None = None,
input_columns: dict[str, FlexDmColumnSpec]
| None = None,
attribute_groups: dict[str, tuple[str, ...] | list[str]]
| None = None,
max_seq_length: int = 50,
latent_dim: int = 256,
num_blocks: int = 4,
block_type: str = "deepsvg",
masking_method: str = "random",
seq_type: str = "default",
arch_type: str = "oneshot",
context: str | None = None,
input_dtype: str = "set",
use_elemwise_noise: bool = False,
dropout: float = 0.1,
layer_norm_epsilon: float = 0.001,
l2: float | None = 0.01,
original_args: dict[str, FlexDmConfigValue]
| None = None,
conversion_report: dict[str, FlexDmConfigValue]
| None = None,
**kwargs: str | int | float | bool | None,
) -> None
Initialize a Flex-DM config.
Source code in models/flex-dm/src/flex_dm/configuration_flex_dm.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 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 | |
mask_token_id_for ¶
mask_token_id_for(key: str) -> int
Return the categorical mask token id for key.
Source code in models/flex-dm/src/flex_dm/configuration_flex_dm.py
209 210 211 212 213 214 215 | |
unused_token_id_for ¶
unused_token_id_for(key: str) -> int
Return the categorical unused token id for key.
Source code in models/flex-dm/src/flex_dm/configuration_flex_dm.py
217 218 219 | |
conversion ¶
Tensor conversion helpers for TensorFlow-to-PyTorch Flex-DM checkpoints.
FlexDmConversionReport
dataclass
¶
Summary of a semantic checkpoint conversion.
Source code in models/flex-dm/src/flex_dm/conversion.py
12 13 14 15 16 17 18 19 | |
convert_dense_kernel ¶
convert_dense_kernel(
tf_kernel: Float[ndarray, "in_features out_features"],
) -> Float[torch.Tensor, "out_features in_features"]
Transpose a TensorFlow Dense kernel into PyTorch Linear layout.
Source code in models/flex-dm/src/flex_dm/conversion.py
22 23 24 25 26 | |
convert_dense_bias ¶
convert_dense_bias(
tf_bias: Float[ndarray, "features"],
) -> Float[torch.Tensor, "features"]
Convert a TensorFlow Dense bias without transposition.
Source code in models/flex-dm/src/flex_dm/conversion.py
29 30 31 32 33 | |
convert_embedding ¶
convert_embedding(
tf_embedding: Float[ndarray, "tokens channels"],
) -> Float[torch.Tensor, "tokens channels"]
Convert a TensorFlow embedding table without transposition.
Source code in models/flex-dm/src/flex_dm/conversion.py
36 37 38 39 40 | |
convert_layer_norm_gamma_beta ¶
convert_layer_norm_gamma_beta(
gamma: Float[ndarray, "features"],
beta: Float[ndarray, "features"],
) -> tuple[
Float[torch.Tensor, "features"],
Float[torch.Tensor, "features"],
]
Convert TensorFlow LayerNorm gamma/beta to PyTorch weight/bias.
Source code in models/flex-dm/src/flex_dm/conversion.py
43 44 45 46 47 48 | |
map_tensor_by_rule ¶
map_tensor_by_rule(
source_name: str, value: Shaped[ndarray, "..."]
) -> tuple[str, Shaped[torch.Tensor, "..."]] | None
Map one known vendor variable name to a PyTorch state-dict key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source_name
|
str
|
TensorFlow variable name. |
required |
value
|
Shaped[ndarray, '...']
|
TensorFlow variable value. |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, Shaped[Tensor, '...']] | None
|
Target state-dict key and converted tensor, or |
tuple[str, Shaped[Tensor, '...']] | None
|
name is not part of the current semantic mapping. |
Source code in models/flex-dm/src/flex_dm/conversion.py
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 | |
conversion_report ¶
conversion_report(
*,
converted: dict[str, Shaped[Tensor, "..."]],
target_keys: set[str],
source_keys: set[str],
consumed_source_keys: set[str],
) -> FlexDmConversionReport
Build a deterministic conversion summary.
Source code in models/flex-dm/src/flex_dm/conversion.py
130 131 132 133 134 135 136 137 138 139 140 141 142 143 | |
data_specs ¶
Built-in Flex-DM dataset schema helpers.
FlexDmBuiltinColumn ¶
Bases: TypedDict
Built-in dataset column metadata.
Source code in models/flex-dm/src/flex_dm/data_specs.py
15 16 17 18 19 20 | |
FlexDmBuiltinSpec ¶
Bases: TypedDict
Built-in dataset schema metadata.
Source code in models/flex-dm/src/flex_dm/data_specs.py
23 24 25 26 27 | |
FlexDmFeatureGroup ¶
Bases: StrEnum
Flex-DM feature groups.
Source code in models/flex-dm/src/flex_dm/data_specs.py
33 34 35 36 37 38 39 40 41 42 | |
load_builtin_spec ¶
load_builtin_spec(
dataset_name: FlexDmDatasetName | str,
) -> FlexDmBuiltinSpec
Return a lightweight copy of the Flex-DM column schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
FlexDmDatasetName | str
|
|
required |
Returns:
| Type | Description |
|---|---|
FlexDmBuiltinSpec
|
Dictionary with a |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the dataset name is unsupported. |
Examples:
>>> load_builtin_spec("crello")["name"]
'crello'
Source code in models/flex-dm/src/flex_dm/data_specs.py
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 | |
attribute_groups_for_dataset ¶
attribute_groups_for_dataset(
dataset_name: FlexDmDatasetName | str,
) -> dict[str, tuple[str, ...]]
Return attribute groups for a dataset.
Source code in models/flex-dm/src/flex_dm/data_specs.py
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 | |
build_column_specs ¶
build_column_specs(
*,
dataset_name: FlexDmDatasetName | str,
vocabulary: Mapping[str, FlexDmVocabularyValue],
) -> dict[str, FlexDmColumnSpec]
Build Flex-DM model column specs from vocabulary metadata.
Source code in models/flex-dm/src/flex_dm/data_specs.py
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 | |
id2label_from_vocabulary ¶
id2label_from_vocabulary(
dataset_name: FlexDmDatasetName | str,
vocabulary: Mapping[str, FlexDmVocabularyValue],
) -> dict[int, str]
Resolve the public type-label mapping from vocabulary data.
Source code in models/flex-dm/src/flex_dm/data_specs.py
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | |
masking ¶
Flex-DM multi-column masking and iterative decoding helpers.
get_seq_mask ¶
get_seq_mask(
length: Int[Tensor, "..."], *, maxlen: int | None = None
) -> Bool[torch.Tensor, "batch elements"]
Return the zero-based valid-element mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
length
|
Int[Tensor, '...']
|
Zero-based document length tensor shaped |
required |
maxlen
|
int | None
|
Optional output width. |
None
|
Returns:
| Type | Description |
|---|---|
Bool[Tensor, 'batch elements']
|
Boolean mask where |
Examples:
>>> get_seq_mask(torch.tensor([0, 2]), maxlen=4)
tensor([[ True, False, False, False],
[ True, True, True, False]])
Source code in models/flex-dm/src/flex_dm/masking.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | |
get_initial_masks ¶
get_initial_masks(
input_columns: Mapping[str, FlexDmColumnSpec],
seq_mask: Bool[Tensor, "batch elements"],
) -> dict[str, Bool[torch.Tensor, "..."]]
Return initial initial masks with no sequence fields hidden.
Source code in models/flex-dm/src/flex_dm/masking.py
52 53 54 55 56 57 58 59 60 61 62 63 64 | |
apply_token ¶
apply_token(
input_: Shaped[Tensor, "batch elements channels"],
column: FlexDmColumnSpec,
mask: Bool[Tensor, "batch elements"],
token_type: Literal["masked", "unused", "random"],
*,
generator: Generator | None = None,
) -> Shaped[torch.Tensor, "batch elements channels"]
Apply a masked, unused, or random model token to selected elements.
Source code in models/flex-dm/src/flex_dm/masking.py
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 | |
filter_padding ¶
filter_padding(
inputs: Mapping[str, Shaped[Tensor, "..."]],
input_columns: Mapping[str, FlexDmColumnSpec],
mask: Bool[Tensor, "batch elements"],
) -> dict[str, Shaped[torch.Tensor, "..."]]
Replace padded and conditionally invalid fields with model unused tokens.
Source code in models/flex-dm/src/flex_dm/masking.py
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 | |
build_feature_masks ¶
build_feature_masks(
input_columns: Mapping[str, FlexDmColumnSpec],
seq_mask: Bool[Tensor, "batch elements"],
*,
condition_type: ConditionType,
feature_group: str | None = None,
target_indices: Int[Tensor, "..."] | None = None,
) -> dict[str, Bool[torch.Tensor, "..."]]
Create explicit masks for Flex-DM completion/refinement tasks.
Source code in models/flex-dm/src/flex_dm/masking.py
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 | |
iterative_decode ¶
iterative_decode(
model: _DecodeModel,
*,
inputs: dict[str, Shaped[Tensor, "..."]],
masks: dict[str, Bool[Tensor, "..."]],
num_iter: int,
input_columns: Mapping[str, FlexDmColumnSpec],
source_inputs: Mapping[str, Shaped[Tensor, "..."]]
| None = None,
) -> _MutableLogitsOutput
Run a deterministic MaskGIT-like categorical decode loop.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
_DecodeModel
|
Flex-DM model object with a |
required |
inputs
|
dict[str, Shaped[Tensor, '...']]
|
Current model inputs. |
required |
masks
|
dict[str, Bool[Tensor, '...']]
|
Per-column masks where |
required |
num_iter
|
int
|
Number of decode iterations. |
required |
input_columns
|
Mapping[str, FlexDmColumnSpec]
|
Model column definitions. |
required |
source_inputs
|
Mapping[str, Shaped[Tensor, '...']] | None
|
Unmasked source inputs used for confidence-commit updates. |
None
|
Returns:
| Type | Description |
|---|---|
_MutableLogitsOutput
|
The final model output. |
Source code in models/flex-dm/src/flex_dm/masking.py
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 | |
modeling_flex_dm ¶
PyTorch model classes for Flex-DM masked document modeling.
FlexDmModelOutput
dataclass
¶
Bases: ModelOutput
Output of FlexDmForMaskedDocumentModeling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
dict[str, Shaped[Tensor, '...']]
|
Per-column logits or numerical predictions. |
required |
loss
|
Float[Tensor, ''] | None
|
Optional summed reconstruction loss. |
None
|
hidden_states
|
Float[Tensor, 'batch seq channels'] | None
|
Optional final hidden states. |
None
|
masks
|
dict[str, Bool[Tensor, '...']] | None
|
Optional per-column hidden-field masks. |
None
|
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
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 | |
__post_init__ ¶
__post_init__() -> None
Keep the logits dictionary as one ModelOutput field.
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
37 38 39 40 41 42 43 44 45 46 | |
FlexDmPreTrainedModel ¶
Bases: PreTrainedModel
Base class for Flex-DM Transformers models.
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
53 54 55 56 57 58 | |
FlexDmInputEncoder ¶
Bases: Module
Encode heterogeneous Flex-DM input columns into one hidden sequence.
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
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 | |
__init__ ¶
__init__(config: FlexDmConfig) -> None
Create per-column embeddings and projections.
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
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 | |
forward ¶
forward(
inputs: Mapping[str, Shaped[Tensor, "..."]],
*,
task_ids: Int[Tensor, "batch"] | None = None,
) -> tuple[
Float[torch.Tensor, "batch seq channels"],
Bool[torch.Tensor, "batch seq"],
]
Encode model inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
Mapping[str, Shaped[Tensor, '...']]
|
Per-column tensors. |
required |
task_ids
|
Int[Tensor, 'batch'] | None
|
Optional task ids. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Float[Tensor, 'batch seq channels'], Bool[Tensor, 'batch seq']]
|
Hidden sequence and valid-element mask. |
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
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 | |
FlexDmDeepSvgBlock ¶
Bases: Module
DeepSVG-style pre-norm transformer block.
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
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 | |
__init__ ¶
__init__(config: FlexDmConfig) -> None
Create one transformer block.
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
186 187 188 189 190 191 192 193 194 195 196 197 | |
forward ¶
forward(
hidden_states: Float[Tensor, "batch seq channels"],
attention_mask: Bool[Tensor, "batch seq"],
) -> Float[torch.Tensor, "batch seq channels"]
Apply pre-norm attention and MLP residuals.
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
199 200 201 202 203 204 205 206 207 208 | |
FlexDmDecoder ¶
Bases: Module
Decode hidden states into one head per model column.
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
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 | |
__init__ ¶
__init__(config: FlexDmConfig) -> None
Create per-column output heads.
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
214 215 216 217 218 219 220 221 222 223 224 | |
forward ¶
forward(
hidden_states: Float[Tensor, "batch seq channels"],
) -> dict[str, Shaped[torch.Tensor, "..."]]
Return per-column logits and predictions.
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | |
FlexDmForMaskedDocumentModeling ¶
Bases: FlexDmPreTrainedModel
Flex-DM MFP model with a standard Transformers forward method.
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
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 | |
__init__ ¶
__init__(config: FlexDmConfig) -> None
Initialize encoder, transformer blocks, and decoder.
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 | |
forward ¶
forward(
*,
inputs: Mapping[str, Shaped[Tensor, "..."]],
masks: Mapping[str, Bool[Tensor, "..."]] | None = None,
labels: Mapping[str, Shaped[Tensor, "..."]]
| None = None,
task_ids: Int[Tensor, "batch"] | None = None,
output_hidden_states: bool = False,
return_dict: bool | None = None,
) -> (
FlexDmModelOutput
| tuple[
dict[str, Shaped[torch.Tensor, "..."]],
Float[torch.Tensor, ""] | None,
]
)
Run a Flex-DM forward pass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
inputs
|
Mapping[str, Shaped[Tensor, '...']]
|
Per-column model input tensors. |
required |
masks
|
Mapping[str, Bool[Tensor, '...']] | None
|
Optional hidden-field masks for diagnostics. |
None
|
labels
|
Mapping[str, Shaped[Tensor, '...']] | None
|
Optional per-column reconstruction targets. |
None
|
task_ids
|
Int[Tensor, 'batch'] | None
|
Optional task ids. |
None
|
output_hidden_states
|
bool
|
Whether to include final hidden states. |
False
|
return_dict
|
bool | None
|
Whether to return a |
None
|
Returns:
| Type | Description |
|---|---|
FlexDmModelOutput | tuple[dict[str, Shaped[Tensor, '...']], Float[Tensor, ''] | None]
|
|
Source code in models/flex-dm/src/flex_dm/modeling_flex_dm.py
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 | |
pipeline_flex_dm ¶
Transformers-side pipeline for Flex-DM infilling.
FlexDmPipelineComponent ¶
Bases: Protocol
Runtime-checkable loaded pipeline component marker.
Source code in models/flex-dm/src/flex_dm/pipeline_flex_dm.py
28 29 30 | |
FlexDmPipeline ¶
Bases: LayoutGenerationPipeline
Run Flex-DM completion, refinement, and feature-level content infilling.
Source code in models/flex-dm/src/flex_dm/pipeline_flex_dm.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 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 | |
__init__ ¶
__init__(
model: FlexDmForMaskedDocumentModeling,
processor: FlexDmProcessor | None = None,
config: FlexDmConfig | None = None,
) -> None
Initialize model and processor components.
Source code in models/flex-dm/src/flex_dm/pipeline_flex_dm.py
82 83 84 85 86 87 88 89 90 91 92 | |
__call__ ¶
__call__(
*,
batch_size: int = 1,
seed: int | None = None,
generator: Generator | None = None,
condition_type: ConditionType
| str = ConditionType.completion,
labels: Int[Tensor, "batch elements"]
| Int[ndarray, "batch elements"]
| Sequence[ArrayLikeInput]
| None = None,
bbox: Float[Tensor, "batch elements 4"]
| Float[ndarray, "batch elements 4"]
| Sequence[ArrayLikeInput]
| None = None,
mask: Bool[Tensor, "batch elements"]
| Bool[ndarray, "batch elements"]
| Sequence[ArrayLikeInput]
| None = None,
num_elements: int
| list[int]
| Int[Tensor, "batch"]
| None = None,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
num_inference_steps: int | None = None,
output_type: Literal["dataclass", "dict"] = "dataclass",
return_intermediates: bool = False,
attributes: Mapping[str, FlexDmValue] | None = None,
content: Mapping[str, FlexDmValue] | None = None,
feature_group: str | None = None,
target_indices: Int[Tensor, "..."] | None = None,
**model_kwargs: FlexDmValue,
) -> (
LayoutGenerationOutput
| dict[
str,
Shaped[torch.Tensor, "..."]
| dict[int, str]
| Mapping[str, Shaped[torch.Tensor, "..."]]
| None,
]
)
Infills masked Flex-DM document fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Batch size used when synthetic empty inputs are created. |
1
|
seed
|
int | None
|
Common API compatibility argument. Flex-DM's public inference path is deterministic and does not currently consume randomness. |
None
|
generator
|
Generator | None
|
Common API compatibility argument. When supplied, it
takes precedence over |
None
|
condition_type
|
ConditionType | str
|
Canonical condition or local task alias. |
completion
|
labels
|
Int[Tensor, 'batch elements'] | Int[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Public element labels. |
None
|
bbox
|
Float[Tensor, 'batch elements 4'] | Float[ndarray, 'batch elements 4'] | Sequence[ArrayLikeInput] | None
|
Public element boxes. |
None
|
mask
|
Bool[Tensor, 'batch elements'] | Bool[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Public valid-element mask. |
None
|
num_elements
|
int | list[int] | Int[Tensor, 'batch'] | None
|
Optional element counts for synthetic inputs. |
None
|
box_format
|
BoxFormat | str
|
Input box coordinate format. |
xywh
|
normalized
|
bool
|
Whether input boxes are already normalized. |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size when |
None
|
num_inference_steps
|
int | None
|
Number of iterative decode steps. |
None
|
output_type
|
Literal['dataclass', 'dict']
|
|
'dataclass'
|
return_intermediates
|
bool
|
Whether to include logits and masks. |
False
|
attributes
|
Mapping[str, FlexDmValue] | None
|
Optional non-core document attributes. |
None
|
content
|
Mapping[str, FlexDmValue] | None
|
Optional Crello image/text embeddings. |
None
|
feature_group
|
str | None
|
Flex-DM task group such as |
None
|
target_indices
|
Int[Tensor, '...'] | None
|
Optional element indexes for |
None
|
model_kwargs
|
FlexDmValue
|
Reserved model keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
LayoutGenerationOutput | dict[str, Shaped[Tensor, '...'] | dict[int, str] | Mapping[str, Shaped[Tensor, '...']] | None]
|
Common layout-generation output. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the requested canonical condition is not supported by released Flex-DM MFP checkpoints. |
Source code in models/flex-dm/src/flex_dm/pipeline_flex_dm.py
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 | |
processing_flex_dm ¶
Processor for Flex-DM heterogeneous document fields.
FlexDmDiscretizerSpec ¶
Bases: TypedDict
Linear discretizer metadata for one numeric model field.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
40 41 42 43 44 45 | |
FlexDmProcessor ¶
Bases: ProcessorMixin
Serialize vocabularies and convert public layouts to Flex-DM tensors.
Flex-DM intentionally does not expose a PreTrainedTokenizer because the
model consumes a dictionary of heterogeneous categorical and continuous
fields rather than one discrete token stream.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
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 | |
__init__ ¶
__init__(
*,
config: FlexDmConfig,
vocabulary: dict[str, FlexDmValue] | None = None,
discretizers: dict[str, FlexDmDiscretizerSpec]
| None = None,
) -> None
Initialize metadata-only processor state.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | |
from_config
classmethod
¶
from_config(config: FlexDmConfig) -> 'FlexDmProcessor'
Create a processor from config metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
FlexDmConfig
|
Flex-DM configuration. |
required |
Returns:
| Type | Description |
|---|---|
'FlexDmProcessor'
|
Processor with built-in discretizers. |
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
81 82 83 84 85 86 87 88 89 90 91 | |
save_pretrained ¶
save_pretrained(
save_directory: str | PathLike[str],
push_to_hub: bool = False,
**kwargs: str | int | float | bool | None,
) -> None
Save processor metadata next to a converted checkpoint.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
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 | |
from_pretrained
classmethod
¶
from_pretrained(
pretrained_model_name_or_path: str | PathLike[str],
cache_dir: str | PathLike[str] | None = None,
force_download: bool = False,
local_files_only: bool = False,
token: str | bool | None = None,
revision: str = "main",
*,
subfolder: str | None = None,
**kwargs: str | int | float | bool | None,
) -> "FlexDmProcessor"
Load processor metadata from a local converted checkpoint.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
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 | |
from_vocabulary
classmethod
¶
from_vocabulary(
*,
dataset_name: str,
vocabulary: dict[str, FlexDmValue],
checkpoint_variant: str = "ours-exp-ft",
) -> "FlexDmProcessor"
Build config and processor metadata from vocabulary.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
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 | |
__call__ ¶
__call__(
*,
condition_type: ConditionType
| str = ConditionType.completion,
labels: Int[Tensor, "batch elements"]
| Int[ndarray, "batch elements"]
| Sequence[ArrayLikeInput]
| None = None,
bbox: Float[Tensor, "batch elements 4"]
| Float[ndarray, "batch elements 4"]
| Sequence[ArrayLikeInput]
| None = None,
mask: Bool[Tensor, "batch elements"]
| Bool[ndarray, "batch elements"]
| Sequence[ArrayLikeInput]
| None = None,
num_elements: int
| list[int]
| Int[Tensor, "batch"]
| None = None,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
attributes: Mapping[str, FlexDmValue] | None = None,
content: Mapping[str, FlexDmValue] | None = None,
feature_group: str | None = None,
target_indices: Int[Tensor, "..."] | None = None,
batch_size: int = 1,
return_tensors: Literal["pt"] = "pt",
) -> dict[
str,
dict[
str,
Shaped[torch.Tensor, "..."]
| Bool[torch.Tensor, "..."],
]
| Shaped[torch.Tensor, "..."]
| ConditionType
| str
| None,
]
Convert public layout fields into Flex-DM model tensors.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
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 | |
normalize_condition_and_feature ¶
normalize_condition_and_feature(
condition_type: ConditionType | str,
*,
feature_group: str | None = None,
) -> tuple[ConditionType, str | None]
Normalize canonical conditions plus local Flex-DM task aliases.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
261 262 263 264 265 266 267 268 269 270 271 272 273 274 | |
post_process_document ¶
post_process_document(
outputs: FlexDmModelOutput,
*,
original_inputs: Mapping[str, Shaped[Tensor, "..."]],
masks: Mapping[str, Bool[Tensor, "..."]],
output_type: Literal["dataclass", "dict"] = "dataclass",
return_intermediates: bool = False,
refinement_input: Mapping[str, Shaped[Tensor, "..."]]
| None = None,
) -> (
LayoutGenerationOutput
| dict[
str,
Shaped[torch.Tensor, "..."]
| dict[int, str]
| Mapping[str, Shaped[torch.Tensor, "..."]]
| None,
]
)
Decode Flex-DM model outputs to the common layout schema.
Source code in models/flex-dm/src/flex_dm/processing_flex_dm.py
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 | |
testing ¶
Testing helpers for Flex-DM package tests.
tiny_config ¶
tiny_config() -> FlexDmConfig
Return a small Flex-DM config for CPU tests.
Source code in models/flex-dm/src/flex_dm/testing.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | |
tiny_pipeline ¶
tiny_pipeline() -> FlexDmPipeline
Return a small random-weight pipeline.
Source code in models/flex-dm/src/flex_dm/testing.py
35 36 37 38 39 40 41 | |
tf_checkpoint ¶
Optional TensorFlow checkpoint inspection helpers for Flex-DM.
list_tf_checkpoint_variables ¶
list_tf_checkpoint_variables(
checkpoint_prefix: str | Path,
) -> list[tuple[str, tuple[int, ...]]]
List TensorFlow checkpoint variable names and shapes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
checkpoint_prefix
|
str | Path
|
Path to |
required |
Returns:
| Type | Description |
|---|---|
list[tuple[str, tuple[int, ...]]]
|
Sorted |
Raises:
| Type | Description |
|---|---|
ImportError
|
If TensorFlow is not installed. |
Source code in models/flex-dm/src/flex_dm/tf_checkpoint.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | |
load_tf_checkpoint_variables ¶
load_tf_checkpoint_variables(
checkpoint_prefix: str | Path,
) -> dict[str, Shaped[np.ndarray, "..."]]
Load all TensorFlow checkpoint variables into NumPy arrays.
Source code in models/flex-dm/src/flex_dm/tf_checkpoint.py
60 61 62 63 64 65 66 67 68 | |
tensorflow_version ¶
tensorflow_version() -> str
Return the TensorFlow version available in the active environment.
Source code in models/flex-dm/src/flex_dm/tf_checkpoint.py
71 72 73 74 75 76 77 | |