Model Card for LayoutDM¶
This package ports LayoutDM, the CVPR 2023 discrete diffusion model for controllable layout generation, into a 🧨diffusers-style package.
Model Details¶
Model Description¶
LayoutDM is a discrete diffusion layout generator for controllable UI and document layouts. It denoises tokenized element categories, positions, and sizes, with condition aliases for unconditional, label, label-size, completion, and refinement workflows. Public outputs use normalized center xywh boxes in [0, 1], dataset-local integer labels, a valid-element mask, and id2label.
- Developed by: Naoto Inoue et al.
- Shared by: creative-graphic-design.
- Model type: content-agnostic; task: task-agnostic; conditioning: unconditional, label, label_size, completion, refinement.
- Language(s) (NLP): not applicable.
- License: Apache-2.0.
Model Sources¶
- Repository: LayoutDM repository
- Paper: CVPR 2023 paper page
- Project page: LayoutDM project page
- Starter checkpoint bundle: layoutdm_starter.zip
Supported Checkpoints¶
| Checkpoint | Hub ID | Status |
|---|---|---|
| RICO25 | creative-graphic-design/layoutdm-rico25 |
not-published |
| PubLayNet | creative-graphic-design/layoutdm-publaynet |
not-published |
Uses¶
Direct Use¶
Use this package for research inference, conversion checks, and agreement checks against the original implementation for generated layouts.
LayoutDM supports controllable discrete diffusion over layout tokens. The converted checkpoints follow the original release for RICO25 mobile UI layouts and PubLayNet document page layouts, both with at most 25 elements.
condition_type |
Required inputs | Effect |
|---|---|---|
unconditional |
none | samples labels and geometry |
label |
labels, bbox, mask |
keeps labels fixed and samples geometry |
label_size |
labels, bbox, mask |
keeps labels and element sizes fixed |
completion |
labels, bbox, mask |
preserves provided elements and fills the remainder |
refinement |
labels, bbox, mask |
refines an existing layout |
text, content_image, relation, hierarchical, retrieval |
not applicable | raises NotImplementedError |
Downstream Use¶
Generated layouts may feed rendering, design tooling, layout evaluation, or downstream content placement systems after task-specific validation.
Out-of-Scope Use¶
Do not treat generated layouts as production accessibility annotations, OCR output, semantic scene understanding, or license-cleared design assets without separate review.
Bias, Risks, and Limitations¶
The converted behavior follows the upstream checkpoints, prompt fixtures, and datasets. Dataset coverage, label vocabularies, and layout quality inherit the limits of those sources.
Recommendations¶
Re-run the agreement-check suite against the original implementation before publishing converted checkpoints or comparing new results.
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" \
"layout-dm @ git+https://github.com/creative-graphic-design/design-generators.git#subdirectory=models/layout-dm"
Clone this repository, install the workspace member, and run the download and conversion steps in REPRODUCING.md. Those steps create .cache/layout-dm/converted/layoutdm-rico25.
git clone https://github.com/creative-graphic-design/design-generators.git
cd design-generators
uv sync --package layout-dm
uv run --package layout-dm python
from layout_dm import LayoutDMPipeline
path = ".cache/layout-dm/converted/layoutdm-rico25"
# After Hub publication: from_pretrained("creative-graphic-design/layoutdm-rico25")
pipe = LayoutDMPipeline.from_pretrained(path)
out = pipe(batch_size=1, condition_type="unconditional", seed=0)
print(out.bbox.shape)
print(out.labels.shape)
print(out.id2label[int(out.labels[out.mask][0])])
labels = [[1, 2, 3]]
bbox = [[[0.2, 0.2, 0.1, 0.1], [0.5, 0.5, 0.2, 0.2], [0.7, 0.7, 0.1, 0.2]]]
mask = [[True, True, True]]
out = pipe(condition_type="label", labels=labels, bbox=bbox, mask=mask, seed=0)
print(out.bbox.shape)
Training Details¶
Training Data¶
| Dataset | Dataset ID | Notes |
|---|---|---|
| RICO25 | creative-graphic-design/Rico |
ui-screenshots-and-hierarchies-with-semantic-annotations |
| PubLayNet | creative-graphic-design/PubLayNet |
default |
Training Procedure¶
Package-local training reproduction is tracked in TRAINING.md. Exact step-level numeric agreement currently covers a fixed PubLayNet-style synthetic batch; deterministic loader checks cover tokenizer, loader row encoding, and preprocessed stream reader agreement for local fixtures; the full-run statistical comparison is pending.
Preprocessing¶
Inputs and outputs are normalized to the public layout schema at package boundaries. Boxes, tokens, prompts, or analog bits that follow the original implementation stay inside package adapters and fixtures used for agreement checks.
Training Hyperparameters¶
- Training regime: original upstream training; not rerun in this repository.
Speeds, Sizes, Times¶
Training-time and carbon measurements are unknown.
Evaluation¶
Testing Data, Factors & Metrics¶
Testing Data¶
Agreement checks use local-only generated fixtures and converted checkpoint directories. Large generated tensors, images, weights, and downloaded artifacts are not committed.
Factors¶
Agreement results are reported separately by dataset, checkpoint, condition mode, seed, or prompt fixture where the package has recorded evidence.
Metrics¶
Metrics are exact tensor equality, exact token or byte equality, or an explicitly stated numeric tolerance against the original implementation.
Parity Results¶
| Dataset | Tokenizer exact | Deterministic exact | Denoiser logits assertion |
|---|---|---|---|
| RICO25 | 1 sample (25 elements x 5 attributes = 125 token positions) | 1 sample (25 elements x 5 attributes = 125 token positions) | torch.allclose(atol=1e-5, rtol=1e-5) |
| PubLayNet | 1 sample (25 elements x 5 attributes = 125 token positions) | 1 sample (25 elements x 5 attributes = 125 token positions) | torch.allclose(atol=1e-5, rtol=1e-5) |
The deterministic sequence check uses the non-default argmax sampling mode (sampling="deterministic"), not the pipeline's stochastic default.
Reproducibility¶
See REPRODUCING.md for the commands that download original-implementation assets, generate reference outputs, run agreement checks, convert checkpoints, and smoke-test local loading. See TRAINING.md for package-local LightningCLI training reproduction.
Environmental Impact¶
No new model training is performed by these conversion packages. Conversion and parity costs depend on the selected checkpoint and local hardware.
Technical Specifications¶
Model Architecture and Objective¶
LayoutDM represents each layout as discrete category, position, and size tokens and denoises those tokens through a discrete diffusion process. The processor normalizes aliases from the original implementation, such as gen_t, gen_ts, partial, and refine, into public condition modes before decoding generated tokens into normalized boxes and labels.
Compute Infrastructure¶
Agreement-check commands are intended for one explicitly selected GPU when the original implementation requires CUDA.
Hardware¶
CPU is sufficient for import and most smoke tests. CUDA is required for heavyweight agreement checks when the original implementation requires it.
Software¶
Use uv run --package layout-dm ... from the repository root so workspace dependency sources and extras resolve correctly.
License¶
Repository wrapper code is Apache-2.0. The original implementation is released under the Apache-2.0 license.
Citation¶
@inproceedings{inoue2023layout,
title = {{LayoutDM: Discrete Diffusion Model for Controllable Layout Generation}},
author = {Naoto Inoue and Kotaro Kikuchi and Edgar Simo-Serra and Mayu Otani and Kota Yamaguchi},
booktitle = {Proceedings of the IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR)},
year = {2023},
pages = {10167-10176}
}
API Reference¶
Public LayoutDM conversion and inference APIs.
LayoutDMCondition
dataclass
¶
Strong and weak token constraints for conditional LayoutDM sampling.
Source code in models/layout-dm/src/layout_dm/conditioning.py
16 17 18 19 20 21 22 23 24 25 26 | |
LayoutDMConfig ¶
Bases: ConfigMixin
Serializable LayoutDM architecture and tokenizer configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
DatasetName | str
|
Dataset name or alias used to initialize labels. |
required |
id2label
|
dict[int | str, str] | None
|
Optional persisted label-id mapping. |
None
|
max_seq_length
|
int
|
Maximum number of layout elements. |
25
|
num_bin_bboxes
|
int
|
Number of bins per bounding-box attribute. |
32
|
var_order
|
str
|
Per-element token order. |
'c-x-y-w-h'
|
shared_bbox_vocab
|
str
|
Bounding-box vocabulary sharing mode. |
'x-y-w-h'
|
bbox_quantization
|
str
|
Bounding-box quantization mode. |
'kmeans'
|
special_tokens
|
tuple[str, ...]
|
Special token names. |
('pad', 'mask')
|
cluster_centers
|
dict[str, list[float]] | None
|
Optional bbox cluster centers stored with tokenizer files. |
None
|
cluster_centers_path
|
str | None
|
Optional local path to released cluster centers. |
None
|
hidden_size
|
int
|
Transformer hidden size. |
464
|
num_attention_heads
|
int
|
Number of attention heads. |
8
|
num_hidden_layers
|
int
|
Number of transformer layers. |
4
|
intermediate_size
|
int
|
Feed-forward hidden size. |
1856
|
dropout
|
float
|
Transformer dropout probability. |
0.0
|
timestep_type
|
str | None
|
Timestep-conditioning type. |
'adalayernorm'
|
num_timesteps
|
int
|
Number of diffusion timesteps. |
100
|
q_type
|
str
|
Diffusion transition type. |
'constrained'
|
att_1
|
float
|
Initial keep probability schedule value. |
0.99999
|
att_T
|
float
|
Final keep probability schedule value. |
9e-06
|
ctt_1
|
float
|
Initial mask probability schedule value. |
9e-06
|
ctt_T
|
float
|
Final mask probability schedule value. |
0.99999
|
Examples:
>>> cfg = LayoutDMConfig(dataset_name="publaynet")
>>> cfg.vocab_size > cfg.num_categories
True
Source code in models/layout-dm/src/layout_dm/configuration_layout_dm.py
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 | |
num_bbox_tokens
property
¶
num_bbox_tokens: int
Return the number of bounding-box vocabulary tokens.
num_attributes_per_element
property
¶
num_attributes_per_element: int
Return the number of tokens used for each layout element.
bbox_slices
property
¶
bbox_slices: dict[str, tuple[int, int]]
Return full-vocabulary slices for bbox attributes.
__init__ ¶
__init__(
*,
dataset_name: DatasetName | str,
id2label: dict[int | str, str] | None = None,
max_seq_length: int = 25,
num_bin_bboxes: int = 32,
var_order: str = "c-x-y-w-h",
shared_bbox_vocab: str = "x-y-w-h",
bbox_quantization: str = "kmeans",
special_tokens: tuple[str, ...] = ("pad", "mask"),
cluster_centers: dict[str, list[float]] | None = None,
cluster_centers_path: str | None = None,
hidden_size: int = 464,
num_attention_heads: int = 8,
num_hidden_layers: int = 4,
intermediate_size: int = 1856,
dropout: float = 0.0,
timestep_type: str | None = "adalayernorm",
num_timesteps: int = 100,
q_type: str = "constrained",
att_1: float = 0.99999,
att_T: float = 9e-06,
ctt_1: float = 9e-06,
ctt_T: float = 0.99999,
) -> None
Initialize a serializable LayoutDM configuration.
Source code in models/layout-dm/src/layout_dm/configuration_layout_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 | |
LayoutDMDenoiser ¶
Bases: ModelMixin, ConfigMixin
Diffusers-compatible LayoutDM denoiser.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vocab_size
|
int
|
Size of the LayoutDM tokenizer vocabulary. |
required |
max_token_length
|
int
|
Flattened token sequence length. |
required |
hidden_size
|
int
|
Transformer hidden size. |
464
|
num_attention_heads
|
int
|
Number of attention heads. |
8
|
num_hidden_layers
|
int
|
Number of transformer layers. |
4
|
intermediate_size
|
int
|
Feed-forward hidden size. |
1856
|
dropout
|
float
|
Dropout probability. |
0.0
|
timestep_type
|
Literal['adalayernorm', 'adalayernorm_abs'] | None
|
Timestep-conditioning type. |
'adalayernorm'
|
Examples:
>>> model = LayoutDMDenoiser(vocab_size=10, max_token_length=5, hidden_size=8,
... num_attention_heads=2, num_hidden_layers=1, intermediate_size=16)
>>> model.config.vocab_size
10
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
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 | |
__init__ ¶
__init__(
*,
vocab_size: int,
max_token_length: int,
hidden_size: int = 464,
num_attention_heads: int = 8,
num_hidden_layers: int = 4,
intermediate_size: int = 1856,
dropout: float = 0.0,
timestep_type: Literal[
"adalayernorm", "adalayernorm_abs"
]
| None = "adalayernorm",
) -> None
Initialize the categorical transformer denoiser.
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
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 | |
initialize_weights ¶
initialize_weights() -> None
Apply the released denoiser initialization to the active device.
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
194 195 196 | |
forward ¶
forward(
input_ids: Int[Tensor, "batch tokens"],
timesteps: Int[Tensor, "batch"],
) -> LayoutDMDenoiserOutput
Predict token logits for noised LayoutDM sequences.
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
198 199 200 201 202 203 204 205 206 | |
predict_start_log_probs ¶
predict_start_log_probs(
input_ids: Int[Tensor, "batch tokens"],
timesteps: Int[Tensor, "batch"],
) -> Float[torch.Tensor, "batch tokens vocab"]
Predict log probabilities for the denoised start sequence.
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | |
LayoutDMDenoiserOutput
dataclass
¶
Bases: BaseOutput
Denoiser output containing token logits.
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
136 137 138 139 140 | |
LayoutDMPipeline ¶
Bases: DiffusionPipeline
Generate layouts with a converted LayoutDM denoiser and scheduler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
denoiser
|
LayoutDMDenoiser
|
LayoutDM denoiser model. |
required |
scheduler
|
LayoutDMScheduler
|
Discrete diffusion scheduler. |
required |
tokenizer
|
LayoutDMTokenizer
|
Structured layout tokenizer. |
required |
processor
|
LayoutDMProcessor | None
|
Optional input processor. A default processor is created when omitted. |
None
|
Examples:
>>> from collections.abc import Mapping, Sequence
from pathlib import Path >>> path = Path(".cache/layout-dm/converted/layoutdm-rico25") >>> path.exists() # doctest: +SKIP True >>> pipe = LayoutDMPipeline.from_pretrained(path) # doctest: +SKIP >>> out = pipe(batch_size=1, seed=0, num_inference_steps=1) # doctest: +SKIP >>> out.bbox.shape[-1] # doctest: +SKIP 4
Source code in models/layout-dm/src/layout_dm/pipeline_layout_dm.py
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 | |
__init__ ¶
__init__(
denoiser: LayoutDMDenoiser,
scheduler: LayoutDMScheduler,
tokenizer: LayoutDMTokenizer,
processor: LayoutDMProcessor | None = None,
) -> None
Initialize and register LayoutDM pipeline modules.
Source code in models/layout-dm/src/layout_dm/pipeline_layout_dm.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | |
__call__ ¶
__call__(
*,
batch_size: int = 1,
seed: int | None = None,
generator: Generator | None = None,
condition_type: ConditionType
| str = ConditionType.unconditional,
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,
sampling: SamplingMode | str = SamplingMode.random,
temperature: float = 1.0,
top_k: int = 5,
top_p: float = 0.9,
output_type: Literal["dataclass", "dict"] = "dataclass",
return_intermediates: bool = False,
**model_kwargs: str | int | float | bool | None,
) -> (
LayoutGenerationOutput
| dict[str, Shaped[torch.Tensor, "..."]]
)
Run unconditional or conditional layout generation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Number of layouts generated for unconditional sampling. |
1
|
seed
|
int | None
|
Optional seed used only when |
None
|
generator
|
Generator | None
|
Optional torch generator. Takes precedence over |
None
|
condition_type
|
ConditionType | str
|
Canonical condition type or supported source alias. |
unconditional
|
labels
|
Int[Tensor, 'batch elements'] | Int[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional labels used by conditional modes. |
None
|
bbox
|
Float[Tensor, 'batch elements 4'] | Float[ndarray, 'batch elements 4'] | Sequence[ArrayLikeInput] | None
|
Optional boxes used by conditional modes. |
None
|
mask
|
Bool[Tensor, 'batch elements'] | Bool[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional valid-element mask for conditional inputs. |
None
|
num_elements
|
int | list[int] | Int[Tensor, 'batch'] | None
|
Reserved compatibility argument. |
None
|
box_format
|
BoxFormat | str
|
Format of conditional input boxes. |
xywh
|
normalized
|
bool
|
Whether conditional boxes are already normalized. |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size used when |
None
|
num_inference_steps
|
int | None
|
Optional shortened diffusion step count. |
None
|
sampling
|
SamplingMode | str
|
Sampling strategy. |
random
|
temperature
|
float
|
Random sampling temperature. |
1.0
|
top_k
|
int
|
Top-k value for top-k modes. |
5
|
top_p
|
float
|
Top-p value for top-p modes. |
0.9
|
output_type
|
Literal['dataclass', 'dict']
|
|
'dataclass'
|
return_intermediates
|
bool
|
Whether to return sampling trajectory data. |
False
|
**model_kwargs
|
str | int | float | bool | None
|
Reserved compatibility keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
LayoutGenerationOutput | dict[str, Shaped[Tensor, '...']]
|
|
LayoutGenerationOutput | dict[str, Shaped[Tensor, '...']]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a conditional mode is missing |
Source code in models/layout-dm/src/layout_dm/pipeline_layout_dm.py
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 | |
save_pretrained ¶
save_pretrained(
save_directory: str | Path,
**kwargs: LayoutDMPipelineKwarg,
) -> None
Save the pipeline and tokenizer to a Diffusers directory.
Source code in models/layout-dm/src/layout_dm/pipeline_layout_dm.py
243 244 245 246 247 | |
from_pretrained
classmethod
¶
from_pretrained(
pretrained_model_name_or_path: str | Path,
**kwargs: LayoutDMPipelineKwarg,
) -> "LayoutDMPipeline"
Load a LayoutDM pipeline from a local directory or Hub repo.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pretrained_model_name_or_path
|
str | Path
|
Diffusers pipeline directory or Hub id. |
required |
**kwargs
|
LayoutDMPipelineKwarg
|
Additional arguments forwarded to Diffusers. |
{}
|
Returns:
| Type | Description |
|---|---|
'LayoutDMPipeline'
|
Loaded pipeline with a matching |
Source code in models/layout-dm/src/layout_dm/pipeline_layout_dm.py
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 | |
LayoutDMProcessor ¶
Bases: ProcessorMixin
Normalize layout arrays and encode them with LayoutDMTokenizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokenizer
|
LayoutDMTokenizer
|
Tokenizer used to encode processed layouts. |
required |
Examples:
>>> from layout_dm.configuration_layout_dm import LayoutDMConfig
>>> from layout_dm.tokenization_layout_dm import LayoutDMTokenizer
>>> processor = LayoutDMProcessor(LayoutDMTokenizer(LayoutDMConfig(dataset_name="publaynet")))
>>> sorted(processor(bbox=[[[0.5, 0.5, 0.2, 0.2]]], labels=[[0]]))
['attention_mask', 'input_ids', 'mask']
Source code in models/layout-dm/src/layout_dm/processing_layout_dm.py
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 | |
__init__ ¶
__init__(tokenizer: LayoutDMTokenizer) -> None
Initialize the processor with a tokenizer.
Source code in models/layout-dm/src/layout_dm/processing_layout_dm.py
40 41 42 | |
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",
**kwargs: str | int | float | bool | None,
) -> "LayoutDMProcessor"
Load a processor with the LayoutDM tokenizer implementation.
Source code in models/layout-dm/src/layout_dm/processing_layout_dm.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | |
__call__ ¶
__call__(
*,
bbox: Float[Tensor, "batch elements 4"]
| Float[ndarray, "batch elements 4"]
| Sequence[ArrayLikeInput],
labels: Int[Tensor, "batch elements"]
| Int[ndarray, "batch elements"]
| Sequence[ArrayLikeInput],
mask: Bool[Tensor, "batch elements"]
| Bool[ndarray, "batch elements"]
| Sequence[ArrayLikeInput]
| None = None,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
return_tensors: Literal["pt"] = "pt",
) -> dict[str, Shaped[torch.Tensor, "..."]]
Process a layout batch into model input tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'batch elements 4'] | Float[ndarray, 'batch elements 4'] | Sequence[ArrayLikeInput]
|
Layout boxes in |
required |
labels
|
Int[Tensor, 'batch elements'] | Int[ndarray, 'batch elements'] | Sequence[ArrayLikeInput]
|
Integer labels matching the layout boxes. |
required |
mask
|
Bool[Tensor, 'batch elements'] | Bool[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional valid-element mask. All elements are valid when omitted. |
None
|
box_format
|
BoxFormat | str
|
Input box format. |
xywh
|
normalized
|
bool
|
Whether boxes are already normalized to |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size required when |
None
|
return_tensors
|
Literal['pt']
|
Tensor backend. Only |
'pt'
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
Tokenizer output containing |
dict[str, Shaped[Tensor, '...']]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in models/layout-dm/src/layout_dm/processing_layout_dm.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 111 112 113 114 115 | |
LayoutDMSamplingConfig
dataclass
¶
Sampling parameters passed from the pipeline to the scheduler.
Source code in models/layout-dm/src/layout_dm/sampling.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
__post_init__ ¶
__post_init__() -> None
Normalize public string sampling values to SamplingMode.
Source code in models/layout-dm/src/layout_dm/sampling.py
25 26 27 | |
LayoutDMScheduler ¶
Bases: SchedulerMixin, ConfigMixin
Diffusers-compatible scheduler for LayoutDM categorical diffusion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_timesteps
|
int
|
Number of training diffusion timesteps. |
100
|
q_type
|
Literal['constrained', 'vanilla']
|
Transition type from the original LayoutDM implementation. |
'constrained'
|
vocab_size
|
int
|
Full tokenizer vocabulary size. |
required |
mask_token_id
|
int
|
Full vocabulary id used for mask tokens. |
required |
pad_token_id
|
int
|
Full vocabulary id used for padding tokens. |
required |
var_order
|
tuple[str, ...]
|
Per-element token variable order. |
('c', 'x', 'y', 'w', 'h')
|
per_var_full_ids
|
dict[str, list[int]] | None
|
Optional constrained vocabulary ids per variable. |
None
|
att_1
|
float
|
Initial keep-probability schedule value. |
0.99999
|
att_T
|
float
|
Final keep-probability schedule value. |
9e-06
|
ctt_1
|
float
|
Initial mask-probability schedule value. |
9e-06
|
ctt_T
|
float
|
Final mask-probability schedule value. |
0.99999
|
Examples:
>>> scheduler = LayoutDMScheduler(vocab_size=8, mask_token_id=7, pad_token_id=6)
>>> scheduler.timesteps.shape[0]
100
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
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 | |
__init__ ¶
__init__(
*,
num_timesteps: int = 100,
q_type: Literal[
"constrained", "vanilla"
] = "constrained",
vocab_size: int,
mask_token_id: int,
pad_token_id: int,
var_order: tuple[str, ...] = ("c", "x", "y", "w", "h"),
per_var_full_ids: dict[str, list[int]] | None = None,
att_1: float = 0.99999,
att_T: float = 9e-06,
ctt_1: float = 9e-06,
ctt_T: float = 0.99999,
) -> None
Initialize LayoutDM transition schedules.
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
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 | |
set_timesteps ¶
set_timesteps(
num_inference_steps: int | None = None,
device: device | None = None,
) -> None
Set reverse-diffusion timesteps for inference.
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
107 108 109 110 111 112 113 114 115 116 | |
initial_sample ¶
initial_sample(
batch_size: int,
token_length: int,
*,
device: device,
condition: LayoutDMCondition | None = None,
) -> Float[torch.Tensor, "batch vocab tokens"]
Create the initial log one-hot sample for reverse diffusion.
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
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 | |
predict_start ¶
predict_start(
denoiser_output: Float[Tensor, "batch tokens vocab"],
) -> Float[torch.Tensor, "batch vocab tokens"]
Convert denoiser logits to start-sequence log probabilities.
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
146 147 148 149 150 151 152 153 154 155 156 157 158 | |
q_posterior ¶
q_posterior(
log_x_start: Float[Tensor, "batch vocab tokens"],
log_x_t: Float[Tensor, "batch vocab tokens"],
t: Int[Tensor, "batch"],
) -> Float[torch.Tensor, "batch vocab tokens"]
Compute the LayoutDM posterior transition distribution.
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
160 161 162 163 164 165 166 167 168 169 | |
step ¶
step(
denoiser_output: Float[Tensor, "batch tokens vocab"],
timestep: Int[Tensor, "batch"],
sample: Float[Tensor, "batch vocab tokens"],
*,
previous_timestep: int,
sampling: LayoutDMSamplingConfig,
condition: LayoutDMCondition | None = None,
generator: Generator | None = None,
) -> LayoutDMSchedulerOutput
Run one reverse-diffusion scheduler step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
denoiser_output
|
Float[Tensor, 'batch tokens vocab']
|
Raw denoiser logits. |
required |
timestep
|
Int[Tensor, 'batch']
|
Current timestep tensor. |
required |
sample
|
Float[Tensor, 'batch vocab tokens']
|
Current log one-hot sample. |
required |
previous_timestep
|
int
|
Previous timestep value from the sampling loop. |
required |
sampling
|
LayoutDMSamplingConfig
|
Sampling configuration. |
required |
condition
|
LayoutDMCondition | None
|
Optional strong condition mask and ids. |
None
|
generator
|
Generator | None
|
Optional torch generator for stochastic sampling. |
None
|
Returns:
| Type | Description |
|---|---|
LayoutDMSchedulerOutput
|
Scheduler output containing the previous sample and log-probability |
LayoutDMSchedulerOutput
|
intermediates. |
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
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 | |
apply_condition ¶
apply_condition(
model_log_prob: Float[Tensor, "batch vocab tokens"],
condition: LayoutDMCondition | None,
) -> Float[torch.Tensor, "batch vocab tokens"]
Apply strong conditions and conditional padding restrictions.
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
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 | |
LayoutDMTokenizer ¶
Bases: PreTrainedTokenizer
Structured LayoutDM tokenizer backed by a synthetic vocabulary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
LayoutDMConfig | Mapping[str, LayoutDMConfigValue] | None
|
LayoutDM tokenizer/model configuration or serialized config dict. |
None
|
vocab_file
|
str | Path | None
|
Optional saved vocabulary file. |
None
|
layout_config_file
|
str | Path | None
|
Optional saved layout config file. |
None
|
cluster_centers_file
|
str | Path | None
|
Optional saved cluster-center file. |
None
|
**kwargs
|
LayoutDMConfigValue
|
Extra |
{}
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the config uses an unsupported token order. |
ValueError
|
If LayoutDM special-token ordering is invalid. |
Examples:
>>> from layout_dm.configuration_layout_dm import LayoutDMConfig
>>> tokenizer = LayoutDMTokenizer(LayoutDMConfig(dataset_name="publaynet"))
>>> tokenizer.mask_token
'mask'
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.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 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 | |
var_names
property
¶
var_names: tuple[str, ...]
Return the per-element variable names in token order.
__init__ ¶
__init__(
config: LayoutDMConfig
| Mapping[str, LayoutDMConfigValue]
| None = None,
*,
vocab_file: str | Path | None = None,
layout_config_file: str | Path | None = None,
cluster_centers_file: str | Path | None = None,
**kwargs: LayoutDMConfigValue,
) -> None
Initialize a LayoutDM tokenizer from config or saved files.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
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 | |
__call__ ¶
__call__(
*,
bbox: Float[Tensor, "batch elements 4"]
| Sequence[ArrayLikeInput],
labels: Int[Tensor, "batch elements"]
| Sequence[ArrayLikeInput],
mask: Bool[Tensor, "batch elements"]
| Sequence[ArrayLikeInput]
| None = None,
) -> dict[str, Shaped[torch.Tensor, "..."]]
Encode structured layout tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'batch elements 4'] | Sequence[ArrayLikeInput]
|
Normalized center |
required |
labels
|
Int[Tensor, 'batch elements'] | Sequence[ArrayLikeInput]
|
Dataset-local labels. |
required |
mask
|
Bool[Tensor, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional valid-element mask. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
Dictionary containing |
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
get_vocab ¶
get_vocab() -> dict[str, int]
Return a copy of the synthetic token-to-id vocabulary.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
147 148 149 | |
convert_tokens_to_string ¶
convert_tokens_to_string(tokens: list[str]) -> str
Join synthetic tokens for human-readable debugging.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
164 165 166 | |
save_vocabulary ¶
save_vocabulary(
save_directory: str | Path,
filename_prefix: str | None = None,
) -> tuple[str, ...]
Save vocabulary, layout config, and cluster centers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_directory
|
str | Path
|
Directory where tokenizer files are written. |
required |
filename_prefix
|
str | None
|
Optional filename prefix used by Transformers. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
Tuple of saved file paths. |
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
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 | |
from_pretrained
classmethod
¶
from_pretrained(
path: str | PathLike[str],
*args: str | PathLike[str] | bool,
cache_dir: str | PathLike[str] | None = None,
force_download: bool = False,
local_files_only: bool = False,
token: str | bool | None = None,
revision: str = "main",
**kwargs: LayoutDMConfigValue,
) -> LayoutDMTokenizer
Load a tokenizer from a pipeline or tokenizer directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Pipeline root or tokenizer subdirectory. |
required |
*args
|
str | PathLike[str] | bool
|
Additional |
()
|
cache_dir
|
str | PathLike[str] | None
|
Optional Transformers cache directory. |
None
|
force_download
|
bool
|
Whether to force file downloads. |
False
|
local_files_only
|
bool
|
Whether to avoid network access. |
False
|
token
|
str | bool | None
|
Optional Hub authentication token. |
None
|
revision
|
str
|
Hub revision to load. |
'main'
|
**kwargs
|
LayoutDMConfigValue
|
Additional |
{}
|
Returns:
| Type | Description |
|---|---|
LayoutDMTokenizer
|
Loaded tokenizer. |
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
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 | |
encode_layout ¶
encode_layout(
*,
bbox: Float[Tensor, "elements 4"]
| Float[Tensor, "batch elements 4"],
labels: Int[Tensor, "elements"]
| Int[Tensor, "batch elements"],
mask: Bool[Tensor, "elements"]
| Bool[Tensor, "batch elements"]
| None = None,
) -> dict[str, Shaped[torch.Tensor, "..."]]
Encode normalized layout tensors into flattened token sequences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'elements 4'] | Float[Tensor, 'batch elements 4']
|
Normalized center |
required |
labels
|
Int[Tensor, 'elements'] | Int[Tensor, 'batch elements']
|
Dataset-local labels with shape |
required |
mask
|
Bool[Tensor, 'elements'] | Bool[Tensor, 'batch elements'] | None
|
Optional valid-element mask. Missing masks mark all elements valid. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
Dictionary containing flattened |
dict[str, Shaped[Tensor, '...']]
|
and |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the sequence length exceeds the configured maximum. |
Examples:
>>> import torch
>>> from layout_dm.configuration_layout_dm import LayoutDMConfig
>>> tok = LayoutDMTokenizer(LayoutDMConfig(dataset_name="publaynet"))
>>> encoded = tok.encode_layout(
... bbox=torch.zeros(1, 1, 4),
... labels=torch.zeros(1, 1, dtype=torch.long),
... )
>>> encoded["input_ids"].shape[-1]
125
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
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 | |
decode_layout ¶
decode_layout(
input_ids: Int[Tensor, "batch tokens"],
) -> dict[str, Shaped[torch.Tensor, "..."]]
Decode flattened token sequences into public layout tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_ids
|
Int[Tensor, 'batch tokens']
|
Flattened LayoutDM token ids with shape
|
required |
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
Dictionary with |
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | |
token_mask ¶
token_mask() -> Bool[torch.Tensor, 'tokens vocab']
Return the valid vocabulary mask for every flattened token position.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | |
full_to_partial_ids ¶
full_to_partial_ids(
ids: Int[Tensor, "batch tokens"], key: str
) -> Int[torch.Tensor, "batch tokens"]
Map full vocabulary bbox ids to per-variable partial ids.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
399 400 401 402 403 404 | |
partial_to_full_ids ¶
partial_to_full_ids(
ids: Int[Tensor, "batch tokens"], key: str
) -> Int[torch.Tensor, "batch tokens"]
Map per-variable partial ids to full vocabulary bbox ids.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
406 407 408 409 410 411 | |
full_to_partial_log_probs ¶
full_to_partial_log_probs(
log_probs: Float[Tensor, "batch vocab tokens"], key: str
) -> Float[torch.Tensor, "batch vocab tokens"]
Gather full-vocabulary log probabilities into a partial bbox space.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
413 414 415 416 417 418 419 420 421 | |
partial_to_full_log_probs ¶
partial_to_full_log_probs(
log_probs: Float[Tensor, "batch vocab tokens"], key: str
) -> Float[torch.Tensor, "batch vocab tokens"]
Scatter partial bbox log probabilities into the full vocabulary.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 | |
full_id_maps ¶
full_id_maps() -> dict[str, list[int]]
Return full vocabulary id lists for every token variable.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
439 440 441 | |
conditioning ¶
Condition construction helpers for LayoutDM generation modes.
LayoutDMCondition
dataclass
¶
Strong and weak token constraints for conditional LayoutDM sampling.
Source code in models/layout-dm/src/layout_dm/conditioning.py
16 17 18 19 20 21 22 23 24 25 26 | |
build_condition ¶
build_condition(
tokenizer: LayoutDMTokenizer,
*,
cond_type: ConditionType | str,
bbox: Float[Tensor, "batch elements 4"],
labels: Int[Tensor, "batch elements"],
mask: Bool[Tensor, "batch elements"],
noisy_bbox: Float[Tensor, "batch elements 4"]
| None = None,
) -> LayoutDMCondition
Build token-level conditioning masks for a LayoutDM layout condition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokenizer
|
LayoutDMTokenizer
|
LayoutDM tokenizer used to encode structured layouts. |
required |
cond_type
|
ConditionType | str
|
Canonical condition type or release alias. |
required |
bbox
|
Float[Tensor, 'batch elements 4']
|
Normalized center |
required |
labels
|
Int[Tensor, 'batch elements']
|
Dataset-local labels. |
required |
mask
|
Bool[Tensor, 'batch elements']
|
Valid-element mask. |
required |
noisy_bbox
|
Float[Tensor, 'batch elements 4'] | None
|
Optional noised boxes for refinement mode. |
None
|
Returns:
| Type | Description |
|---|---|
LayoutDMCondition
|
Token ids and masks consumed by the scheduler. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the condition type is unsupported. |
Source code in models/layout-dm/src/layout_dm/conditioning.py
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 | |
configuration_layout_dm ¶
Configuration objects for converted LayoutDM checkpoints.
LayoutDMConfig ¶
Bases: ConfigMixin
Serializable LayoutDM architecture and tokenizer configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
DatasetName | str
|
Dataset name or alias used to initialize labels. |
required |
id2label
|
dict[int | str, str] | None
|
Optional persisted label-id mapping. |
None
|
max_seq_length
|
int
|
Maximum number of layout elements. |
25
|
num_bin_bboxes
|
int
|
Number of bins per bounding-box attribute. |
32
|
var_order
|
str
|
Per-element token order. |
'c-x-y-w-h'
|
shared_bbox_vocab
|
str
|
Bounding-box vocabulary sharing mode. |
'x-y-w-h'
|
bbox_quantization
|
str
|
Bounding-box quantization mode. |
'kmeans'
|
special_tokens
|
tuple[str, ...]
|
Special token names. |
('pad', 'mask')
|
cluster_centers
|
dict[str, list[float]] | None
|
Optional bbox cluster centers stored with tokenizer files. |
None
|
cluster_centers_path
|
str | None
|
Optional local path to released cluster centers. |
None
|
hidden_size
|
int
|
Transformer hidden size. |
464
|
num_attention_heads
|
int
|
Number of attention heads. |
8
|
num_hidden_layers
|
int
|
Number of transformer layers. |
4
|
intermediate_size
|
int
|
Feed-forward hidden size. |
1856
|
dropout
|
float
|
Transformer dropout probability. |
0.0
|
timestep_type
|
str | None
|
Timestep-conditioning type. |
'adalayernorm'
|
num_timesteps
|
int
|
Number of diffusion timesteps. |
100
|
q_type
|
str
|
Diffusion transition type. |
'constrained'
|
att_1
|
float
|
Initial keep probability schedule value. |
0.99999
|
att_T
|
float
|
Final keep probability schedule value. |
9e-06
|
ctt_1
|
float
|
Initial mask probability schedule value. |
9e-06
|
ctt_T
|
float
|
Final mask probability schedule value. |
0.99999
|
Examples:
>>> cfg = LayoutDMConfig(dataset_name="publaynet")
>>> cfg.vocab_size > cfg.num_categories
True
Source code in models/layout-dm/src/layout_dm/configuration_layout_dm.py
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 | |
num_bbox_tokens
property
¶
num_bbox_tokens: int
Return the number of bounding-box vocabulary tokens.
num_attributes_per_element
property
¶
num_attributes_per_element: int
Return the number of tokens used for each layout element.
bbox_slices
property
¶
bbox_slices: dict[str, tuple[int, int]]
Return full-vocabulary slices for bbox attributes.
__init__ ¶
__init__(
*,
dataset_name: DatasetName | str,
id2label: dict[int | str, str] | None = None,
max_seq_length: int = 25,
num_bin_bboxes: int = 32,
var_order: str = "c-x-y-w-h",
shared_bbox_vocab: str = "x-y-w-h",
bbox_quantization: str = "kmeans",
special_tokens: tuple[str, ...] = ("pad", "mask"),
cluster_centers: dict[str, list[float]] | None = None,
cluster_centers_path: str | None = None,
hidden_size: int = 464,
num_attention_heads: int = 8,
num_hidden_layers: int = 4,
intermediate_size: int = 1856,
dropout: float = 0.0,
timestep_type: str | None = "adalayernorm",
num_timesteps: int = 100,
q_type: str = "constrained",
att_1: float = 0.99999,
att_T: float = 9e-06,
ctt_1: float = 9e-06,
ctt_T: float = 0.99999,
) -> None
Initialize a serializable LayoutDM configuration.
Source code in models/layout-dm/src/layout_dm/configuration_layout_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 | |
LayoutDMRuntimeConfig
dataclass
¶
Container for runtime defaults used by lightweight integrations.
Source code in models/layout-dm/src/layout_dm/configuration_layout_dm.py
169 170 171 172 173 174 175 | |
conversion ¶
Checkpoint conversion helpers for original LayoutDM releases.
remap_denoiser_key ¶
remap_denoiser_key(key: str) -> str
Map an original checkpoint key to the converted denoiser key.
Source code in models/layout-dm/src/layout_dm/conversion.py
15 16 17 18 19 20 21 22 23 24 25 26 | |
split_original_state_dict ¶
split_original_state_dict(
state_dict: dict[str, Shaped[Tensor, "..."]],
) -> dict[str, Shaped[torch.Tensor, "..."]]
Extract converted denoiser weights from an original state dict.
Source code in models/layout-dm/src/layout_dm/conversion.py
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 | |
load_cluster_centers ¶
load_cluster_centers(
starter_dir: Path, dataset: str
) -> dict[str, list[float]]
Load sorted bbox cluster centers from the original starter bundle.
Source code in models/layout-dm/src/layout_dm/conversion.py
59 60 61 62 63 64 65 66 67 68 69 | |
write_layoutdm_model_card ¶
write_layoutdm_model_card(
output_dir: Path, dataset: DatasetName | str
) -> Path
Write a LayoutDM model card to a converted pipeline directory.
Source code in models/layout-dm/src/layout_dm/conversion.py
72 73 74 75 76 | |
modeling_layout_dm ¶
Modeling components for converted LayoutDM checkpoints.
CategoricalTransformer ¶
Bases: Module
Token transformer that predicts LayoutDM categorical logits.
Source code in models/layout-dm/src/layout_dm/modeling_layout_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 | |
__init__ ¶
__init__(
*,
vocab_size: int,
max_token_length: int,
hidden_size: int,
num_attention_heads: int,
num_hidden_layers: int,
intermediate_size: int,
dropout: float = 0.0,
timestep_type: Literal[
"adalayernorm", "adalayernorm_abs"
]
| None = "adalayernorm",
) -> None
Initialize the categorical transformer denoiser backbone.
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
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 | |
forward ¶
forward(
input_ids: Int[Tensor, "batch tokens"],
timestep: Int[Tensor, "batch"] | None = None,
) -> dict[str, Shaped[torch.Tensor, "..."]]
Predict logits for flattened LayoutDM token ids.
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
124 125 126 127 128 129 130 131 132 133 | |
LayoutDMDenoiserOutput
dataclass
¶
Bases: BaseOutput
Denoiser output containing token logits.
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
136 137 138 139 140 | |
LayoutDMDenoiser ¶
Bases: ModelMixin, ConfigMixin
Diffusers-compatible LayoutDM denoiser.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vocab_size
|
int
|
Size of the LayoutDM tokenizer vocabulary. |
required |
max_token_length
|
int
|
Flattened token sequence length. |
required |
hidden_size
|
int
|
Transformer hidden size. |
464
|
num_attention_heads
|
int
|
Number of attention heads. |
8
|
num_hidden_layers
|
int
|
Number of transformer layers. |
4
|
intermediate_size
|
int
|
Feed-forward hidden size. |
1856
|
dropout
|
float
|
Dropout probability. |
0.0
|
timestep_type
|
Literal['adalayernorm', 'adalayernorm_abs'] | None
|
Timestep-conditioning type. |
'adalayernorm'
|
Examples:
>>> model = LayoutDMDenoiser(vocab_size=10, max_token_length=5, hidden_size=8,
... num_attention_heads=2, num_hidden_layers=1, intermediate_size=16)
>>> model.config.vocab_size
10
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
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 | |
__init__ ¶
__init__(
*,
vocab_size: int,
max_token_length: int,
hidden_size: int = 464,
num_attention_heads: int = 8,
num_hidden_layers: int = 4,
intermediate_size: int = 1856,
dropout: float = 0.0,
timestep_type: Literal[
"adalayernorm", "adalayernorm_abs"
]
| None = "adalayernorm",
) -> None
Initialize the categorical transformer denoiser.
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
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 | |
initialize_weights ¶
initialize_weights() -> None
Apply the released denoiser initialization to the active device.
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
194 195 196 | |
forward ¶
forward(
input_ids: Int[Tensor, "batch tokens"],
timesteps: Int[Tensor, "batch"],
) -> LayoutDMDenoiserOutput
Predict token logits for noised LayoutDM sequences.
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
198 199 200 201 202 203 204 205 206 | |
predict_start_log_probs ¶
predict_start_log_probs(
input_ids: Int[Tensor, "batch tokens"],
timesteps: Int[Tensor, "batch"],
) -> Float[torch.Tensor, "batch tokens vocab"]
Predict log probabilities for the denoised start sequence.
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | |
skip_layoutdm_initialization ¶
skip_layoutdm_initialization() -> Iterator[None]
Temporarily defer denoiser initialization until after device placement.
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
49 50 51 52 53 54 55 56 | |
pipeline_layout_dm ¶
Diffusers pipeline for converted LayoutDM checkpoints.
LayoutDMPipeline ¶
Bases: DiffusionPipeline
Generate layouts with a converted LayoutDM denoiser and scheduler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
denoiser
|
LayoutDMDenoiser
|
LayoutDM denoiser model. |
required |
scheduler
|
LayoutDMScheduler
|
Discrete diffusion scheduler. |
required |
tokenizer
|
LayoutDMTokenizer
|
Structured layout tokenizer. |
required |
processor
|
LayoutDMProcessor | None
|
Optional input processor. A default processor is created when omitted. |
None
|
Examples:
>>> from collections.abc import Mapping, Sequence
from pathlib import Path >>> path = Path(".cache/layout-dm/converted/layoutdm-rico25") >>> path.exists() # doctest: +SKIP True >>> pipe = LayoutDMPipeline.from_pretrained(path) # doctest: +SKIP >>> out = pipe(batch_size=1, seed=0, num_inference_steps=1) # doctest: +SKIP >>> out.bbox.shape[-1] # doctest: +SKIP 4
Source code in models/layout-dm/src/layout_dm/pipeline_layout_dm.py
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 | |
__init__ ¶
__init__(
denoiser: LayoutDMDenoiser,
scheduler: LayoutDMScheduler,
tokenizer: LayoutDMTokenizer,
processor: LayoutDMProcessor | None = None,
) -> None
Initialize and register LayoutDM pipeline modules.
Source code in models/layout-dm/src/layout_dm/pipeline_layout_dm.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | |
__call__ ¶
__call__(
*,
batch_size: int = 1,
seed: int | None = None,
generator: Generator | None = None,
condition_type: ConditionType
| str = ConditionType.unconditional,
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,
sampling: SamplingMode | str = SamplingMode.random,
temperature: float = 1.0,
top_k: int = 5,
top_p: float = 0.9,
output_type: Literal["dataclass", "dict"] = "dataclass",
return_intermediates: bool = False,
**model_kwargs: str | int | float | bool | None,
) -> (
LayoutGenerationOutput
| dict[str, Shaped[torch.Tensor, "..."]]
)
Run unconditional or conditional layout generation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Number of layouts generated for unconditional sampling. |
1
|
seed
|
int | None
|
Optional seed used only when |
None
|
generator
|
Generator | None
|
Optional torch generator. Takes precedence over |
None
|
condition_type
|
ConditionType | str
|
Canonical condition type or supported source alias. |
unconditional
|
labels
|
Int[Tensor, 'batch elements'] | Int[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional labels used by conditional modes. |
None
|
bbox
|
Float[Tensor, 'batch elements 4'] | Float[ndarray, 'batch elements 4'] | Sequence[ArrayLikeInput] | None
|
Optional boxes used by conditional modes. |
None
|
mask
|
Bool[Tensor, 'batch elements'] | Bool[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional valid-element mask for conditional inputs. |
None
|
num_elements
|
int | list[int] | Int[Tensor, 'batch'] | None
|
Reserved compatibility argument. |
None
|
box_format
|
BoxFormat | str
|
Format of conditional input boxes. |
xywh
|
normalized
|
bool
|
Whether conditional boxes are already normalized. |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size used when |
None
|
num_inference_steps
|
int | None
|
Optional shortened diffusion step count. |
None
|
sampling
|
SamplingMode | str
|
Sampling strategy. |
random
|
temperature
|
float
|
Random sampling temperature. |
1.0
|
top_k
|
int
|
Top-k value for top-k modes. |
5
|
top_p
|
float
|
Top-p value for top-p modes. |
0.9
|
output_type
|
Literal['dataclass', 'dict']
|
|
'dataclass'
|
return_intermediates
|
bool
|
Whether to return sampling trajectory data. |
False
|
**model_kwargs
|
str | int | float | bool | None
|
Reserved compatibility keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
LayoutGenerationOutput | dict[str, Shaped[Tensor, '...']]
|
|
LayoutGenerationOutput | dict[str, Shaped[Tensor, '...']]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If a conditional mode is missing |
Source code in models/layout-dm/src/layout_dm/pipeline_layout_dm.py
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 | |
save_pretrained ¶
save_pretrained(
save_directory: str | Path,
**kwargs: LayoutDMPipelineKwarg,
) -> None
Save the pipeline and tokenizer to a Diffusers directory.
Source code in models/layout-dm/src/layout_dm/pipeline_layout_dm.py
243 244 245 246 247 | |
from_pretrained
classmethod
¶
from_pretrained(
pretrained_model_name_or_path: str | Path,
**kwargs: LayoutDMPipelineKwarg,
) -> "LayoutDMPipeline"
Load a LayoutDM pipeline from a local directory or Hub repo.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pretrained_model_name_or_path
|
str | Path
|
Diffusers pipeline directory or Hub id. |
required |
**kwargs
|
LayoutDMPipelineKwarg
|
Additional arguments forwarded to Diffusers. |
{}
|
Returns:
| Type | Description |
|---|---|
'LayoutDMPipeline'
|
Loaded pipeline with a matching |
Source code in models/layout-dm/src/layout_dm/pipeline_layout_dm.py
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 | |
processing_layout_dm ¶
Input processor for LayoutDM structured layout tensors.
LayoutDMProcessor ¶
Bases: ProcessorMixin
Normalize layout arrays and encode them with LayoutDMTokenizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokenizer
|
LayoutDMTokenizer
|
Tokenizer used to encode processed layouts. |
required |
Examples:
>>> from layout_dm.configuration_layout_dm import LayoutDMConfig
>>> from layout_dm.tokenization_layout_dm import LayoutDMTokenizer
>>> processor = LayoutDMProcessor(LayoutDMTokenizer(LayoutDMConfig(dataset_name="publaynet")))
>>> sorted(processor(bbox=[[[0.5, 0.5, 0.2, 0.2]]], labels=[[0]]))
['attention_mask', 'input_ids', 'mask']
Source code in models/layout-dm/src/layout_dm/processing_layout_dm.py
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 | |
__init__ ¶
__init__(tokenizer: LayoutDMTokenizer) -> None
Initialize the processor with a tokenizer.
Source code in models/layout-dm/src/layout_dm/processing_layout_dm.py
40 41 42 | |
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",
**kwargs: str | int | float | bool | None,
) -> "LayoutDMProcessor"
Load a processor with the LayoutDM tokenizer implementation.
Source code in models/layout-dm/src/layout_dm/processing_layout_dm.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | |
__call__ ¶
__call__(
*,
bbox: Float[Tensor, "batch elements 4"]
| Float[ndarray, "batch elements 4"]
| Sequence[ArrayLikeInput],
labels: Int[Tensor, "batch elements"]
| Int[ndarray, "batch elements"]
| Sequence[ArrayLikeInput],
mask: Bool[Tensor, "batch elements"]
| Bool[ndarray, "batch elements"]
| Sequence[ArrayLikeInput]
| None = None,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
return_tensors: Literal["pt"] = "pt",
) -> dict[str, Shaped[torch.Tensor, "..."]]
Process a layout batch into model input tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'batch elements 4'] | Float[ndarray, 'batch elements 4'] | Sequence[ArrayLikeInput]
|
Layout boxes in |
required |
labels
|
Int[Tensor, 'batch elements'] | Int[ndarray, 'batch elements'] | Sequence[ArrayLikeInput]
|
Integer labels matching the layout boxes. |
required |
mask
|
Bool[Tensor, 'batch elements'] | Bool[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional valid-element mask. All elements are valid when omitted. |
None
|
box_format
|
BoxFormat | str
|
Input box format. |
xywh
|
normalized
|
bool
|
Whether boxes are already normalized to |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size required when |
None
|
return_tensors
|
Literal['pt']
|
Tensor backend. Only |
'pt'
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
Tokenizer output containing |
dict[str, Shaped[Tensor, '...']]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in models/layout-dm/src/layout_dm/processing_layout_dm.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 111 112 113 114 115 | |
sampling ¶
Sampling configuration for LayoutDM reverse diffusion.
LayoutDMSamplingConfig
dataclass
¶
Sampling parameters passed from the pipeline to the scheduler.
Source code in models/layout-dm/src/layout_dm/sampling.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | |
__post_init__ ¶
__post_init__() -> None
Normalize public string sampling values to SamplingMode.
Source code in models/layout-dm/src/layout_dm/sampling.py
25 26 27 | |
scheduling_layout_dm ¶
Discrete diffusion scheduler for converted LayoutDM pipelines.
LayoutDMSchedulerOutput
dataclass
¶
Bases: BaseOutput
Scheduler step output for LayoutDM reverse diffusion.
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
31 32 33 34 35 36 37 | |
LayoutDMScheduler ¶
Bases: SchedulerMixin, ConfigMixin
Diffusers-compatible scheduler for LayoutDM categorical diffusion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_timesteps
|
int
|
Number of training diffusion timesteps. |
100
|
q_type
|
Literal['constrained', 'vanilla']
|
Transition type from the original LayoutDM implementation. |
'constrained'
|
vocab_size
|
int
|
Full tokenizer vocabulary size. |
required |
mask_token_id
|
int
|
Full vocabulary id used for mask tokens. |
required |
pad_token_id
|
int
|
Full vocabulary id used for padding tokens. |
required |
var_order
|
tuple[str, ...]
|
Per-element token variable order. |
('c', 'x', 'y', 'w', 'h')
|
per_var_full_ids
|
dict[str, list[int]] | None
|
Optional constrained vocabulary ids per variable. |
None
|
att_1
|
float
|
Initial keep-probability schedule value. |
0.99999
|
att_T
|
float
|
Final keep-probability schedule value. |
9e-06
|
ctt_1
|
float
|
Initial mask-probability schedule value. |
9e-06
|
ctt_T
|
float
|
Final mask-probability schedule value. |
0.99999
|
Examples:
>>> scheduler = LayoutDMScheduler(vocab_size=8, mask_token_id=7, pad_token_id=6)
>>> scheduler.timesteps.shape[0]
100
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
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 | |
__init__ ¶
__init__(
*,
num_timesteps: int = 100,
q_type: Literal[
"constrained", "vanilla"
] = "constrained",
vocab_size: int,
mask_token_id: int,
pad_token_id: int,
var_order: tuple[str, ...] = ("c", "x", "y", "w", "h"),
per_var_full_ids: dict[str, list[int]] | None = None,
att_1: float = 0.99999,
att_T: float = 9e-06,
ctt_1: float = 9e-06,
ctt_T: float = 0.99999,
) -> None
Initialize LayoutDM transition schedules.
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
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 | |
set_timesteps ¶
set_timesteps(
num_inference_steps: int | None = None,
device: device | None = None,
) -> None
Set reverse-diffusion timesteps for inference.
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
107 108 109 110 111 112 113 114 115 116 | |
initial_sample ¶
initial_sample(
batch_size: int,
token_length: int,
*,
device: device,
condition: LayoutDMCondition | None = None,
) -> Float[torch.Tensor, "batch vocab tokens"]
Create the initial log one-hot sample for reverse diffusion.
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
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 | |
predict_start ¶
predict_start(
denoiser_output: Float[Tensor, "batch tokens vocab"],
) -> Float[torch.Tensor, "batch vocab tokens"]
Convert denoiser logits to start-sequence log probabilities.
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
146 147 148 149 150 151 152 153 154 155 156 157 158 | |
q_posterior ¶
q_posterior(
log_x_start: Float[Tensor, "batch vocab tokens"],
log_x_t: Float[Tensor, "batch vocab tokens"],
t: Int[Tensor, "batch"],
) -> Float[torch.Tensor, "batch vocab tokens"]
Compute the LayoutDM posterior transition distribution.
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
160 161 162 163 164 165 166 167 168 169 | |
step ¶
step(
denoiser_output: Float[Tensor, "batch tokens vocab"],
timestep: Int[Tensor, "batch"],
sample: Float[Tensor, "batch vocab tokens"],
*,
previous_timestep: int,
sampling: LayoutDMSamplingConfig,
condition: LayoutDMCondition | None = None,
generator: Generator | None = None,
) -> LayoutDMSchedulerOutput
Run one reverse-diffusion scheduler step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
denoiser_output
|
Float[Tensor, 'batch tokens vocab']
|
Raw denoiser logits. |
required |
timestep
|
Int[Tensor, 'batch']
|
Current timestep tensor. |
required |
sample
|
Float[Tensor, 'batch vocab tokens']
|
Current log one-hot sample. |
required |
previous_timestep
|
int
|
Previous timestep value from the sampling loop. |
required |
sampling
|
LayoutDMSamplingConfig
|
Sampling configuration. |
required |
condition
|
LayoutDMCondition | None
|
Optional strong condition mask and ids. |
None
|
generator
|
Generator | None
|
Optional torch generator for stochastic sampling. |
None
|
Returns:
| Type | Description |
|---|---|
LayoutDMSchedulerOutput
|
Scheduler output containing the previous sample and log-probability |
LayoutDMSchedulerOutput
|
intermediates. |
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
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 | |
apply_condition ¶
apply_condition(
model_log_prob: Float[Tensor, "batch vocab tokens"],
condition: LayoutDMCondition | None,
) -> Float[torch.Tensor, "batch vocab tokens"]
Apply strong conditions and conditional padding restrictions.
Source code in models/layout-dm/src/layout_dm/scheduling_layout_dm.py
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 | |
tokenization_layout_dm ¶
Transformers tokenizer for LayoutDM discrete layout sequences.
LayoutDMTokenizer ¶
Bases: PreTrainedTokenizer
Structured LayoutDM tokenizer backed by a synthetic vocabulary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
LayoutDMConfig | Mapping[str, LayoutDMConfigValue] | None
|
LayoutDM tokenizer/model configuration or serialized config dict. |
None
|
vocab_file
|
str | Path | None
|
Optional saved vocabulary file. |
None
|
layout_config_file
|
str | Path | None
|
Optional saved layout config file. |
None
|
cluster_centers_file
|
str | Path | None
|
Optional saved cluster-center file. |
None
|
**kwargs
|
LayoutDMConfigValue
|
Extra |
{}
|
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If the config uses an unsupported token order. |
ValueError
|
If LayoutDM special-token ordering is invalid. |
Examples:
>>> from layout_dm.configuration_layout_dm import LayoutDMConfig
>>> tokenizer = LayoutDMTokenizer(LayoutDMConfig(dataset_name="publaynet"))
>>> tokenizer.mask_token
'mask'
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.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 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 | |
var_names
property
¶
var_names: tuple[str, ...]
Return the per-element variable names in token order.
__init__ ¶
__init__(
config: LayoutDMConfig
| Mapping[str, LayoutDMConfigValue]
| None = None,
*,
vocab_file: str | Path | None = None,
layout_config_file: str | Path | None = None,
cluster_centers_file: str | Path | None = None,
**kwargs: LayoutDMConfigValue,
) -> None
Initialize a LayoutDM tokenizer from config or saved files.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
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 | |
__call__ ¶
__call__(
*,
bbox: Float[Tensor, "batch elements 4"]
| Sequence[ArrayLikeInput],
labels: Int[Tensor, "batch elements"]
| Sequence[ArrayLikeInput],
mask: Bool[Tensor, "batch elements"]
| Sequence[ArrayLikeInput]
| None = None,
) -> dict[str, Shaped[torch.Tensor, "..."]]
Encode structured layout tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'batch elements 4'] | Sequence[ArrayLikeInput]
|
Normalized center |
required |
labels
|
Int[Tensor, 'batch elements'] | Sequence[ArrayLikeInput]
|
Dataset-local labels. |
required |
mask
|
Bool[Tensor, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional valid-element mask. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
Dictionary containing |
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
get_vocab ¶
get_vocab() -> dict[str, int]
Return a copy of the synthetic token-to-id vocabulary.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
147 148 149 | |
convert_tokens_to_string ¶
convert_tokens_to_string(tokens: list[str]) -> str
Join synthetic tokens for human-readable debugging.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
164 165 166 | |
save_vocabulary ¶
save_vocabulary(
save_directory: str | Path,
filename_prefix: str | None = None,
) -> tuple[str, ...]
Save vocabulary, layout config, and cluster centers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_directory
|
str | Path
|
Directory where tokenizer files are written. |
required |
filename_prefix
|
str | None
|
Optional filename prefix used by Transformers. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
Tuple of saved file paths. |
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
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 | |
from_pretrained
classmethod
¶
from_pretrained(
path: str | PathLike[str],
*args: str | PathLike[str] | bool,
cache_dir: str | PathLike[str] | None = None,
force_download: bool = False,
local_files_only: bool = False,
token: str | bool | None = None,
revision: str = "main",
**kwargs: LayoutDMConfigValue,
) -> LayoutDMTokenizer
Load a tokenizer from a pipeline or tokenizer directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | PathLike[str]
|
Pipeline root or tokenizer subdirectory. |
required |
*args
|
str | PathLike[str] | bool
|
Additional |
()
|
cache_dir
|
str | PathLike[str] | None
|
Optional Transformers cache directory. |
None
|
force_download
|
bool
|
Whether to force file downloads. |
False
|
local_files_only
|
bool
|
Whether to avoid network access. |
False
|
token
|
str | bool | None
|
Optional Hub authentication token. |
None
|
revision
|
str
|
Hub revision to load. |
'main'
|
**kwargs
|
LayoutDMConfigValue
|
Additional |
{}
|
Returns:
| Type | Description |
|---|---|
LayoutDMTokenizer
|
Loaded tokenizer. |
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
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 | |
encode_layout ¶
encode_layout(
*,
bbox: Float[Tensor, "elements 4"]
| Float[Tensor, "batch elements 4"],
labels: Int[Tensor, "elements"]
| Int[Tensor, "batch elements"],
mask: Bool[Tensor, "elements"]
| Bool[Tensor, "batch elements"]
| None = None,
) -> dict[str, Shaped[torch.Tensor, "..."]]
Encode normalized layout tensors into flattened token sequences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'elements 4'] | Float[Tensor, 'batch elements 4']
|
Normalized center |
required |
labels
|
Int[Tensor, 'elements'] | Int[Tensor, 'batch elements']
|
Dataset-local labels with shape |
required |
mask
|
Bool[Tensor, 'elements'] | Bool[Tensor, 'batch elements'] | None
|
Optional valid-element mask. Missing masks mark all elements valid. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
Dictionary containing flattened |
dict[str, Shaped[Tensor, '...']]
|
and |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the sequence length exceeds the configured maximum. |
Examples:
>>> import torch
>>> from layout_dm.configuration_layout_dm import LayoutDMConfig
>>> tok = LayoutDMTokenizer(LayoutDMConfig(dataset_name="publaynet"))
>>> encoded = tok.encode_layout(
... bbox=torch.zeros(1, 1, 4),
... labels=torch.zeros(1, 1, dtype=torch.long),
... )
>>> encoded["input_ids"].shape[-1]
125
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
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 | |
decode_layout ¶
decode_layout(
input_ids: Int[Tensor, "batch tokens"],
) -> dict[str, Shaped[torch.Tensor, "..."]]
Decode flattened token sequences into public layout tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_ids
|
Int[Tensor, 'batch tokens']
|
Flattened LayoutDM token ids with shape
|
required |
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
Dictionary with |
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | |
token_mask ¶
token_mask() -> Bool[torch.Tensor, 'tokens vocab']
Return the valid vocabulary mask for every flattened token position.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 | |
full_to_partial_ids ¶
full_to_partial_ids(
ids: Int[Tensor, "batch tokens"], key: str
) -> Int[torch.Tensor, "batch tokens"]
Map full vocabulary bbox ids to per-variable partial ids.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
399 400 401 402 403 404 | |
partial_to_full_ids ¶
partial_to_full_ids(
ids: Int[Tensor, "batch tokens"], key: str
) -> Int[torch.Tensor, "batch tokens"]
Map per-variable partial ids to full vocabulary bbox ids.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
406 407 408 409 410 411 | |
full_to_partial_log_probs ¶
full_to_partial_log_probs(
log_probs: Float[Tensor, "batch vocab tokens"], key: str
) -> Float[torch.Tensor, "batch vocab tokens"]
Gather full-vocabulary log probabilities into a partial bbox space.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
413 414 415 416 417 418 419 420 421 | |
partial_to_full_log_probs ¶
partial_to_full_log_probs(
log_probs: Float[Tensor, "batch vocab tokens"], key: str
) -> Float[torch.Tensor, "batch vocab tokens"]
Scatter partial bbox log probabilities into the full vocabulary.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 | |
full_id_maps ¶
full_id_maps() -> dict[str, list[int]]
Return full vocabulary id lists for every token variable.
Source code in models/layout-dm/src/layout_dm/tokenization_layout_dm.py
439 440 441 | |
training ¶
Training entry points for LayoutDM.
config ¶
Configuration enums for LayoutDM training.
LayoutDMTrainingDatasetName
module-attribute
¶
LayoutDMTrainingDatasetName: TypeAlias = Literal[
"rico25", "publaynet"
]
Dataset names supported by package-local LayoutDM training data.
LayoutDMTrainingDatasetSource
module-attribute
¶
LayoutDMTrainingDatasetSource: TypeAlias = Literal[
"hf", "processed"
]
Dataset source modes supported by package-local LayoutDM training data.
LayoutDMTrainingSplit
module-attribute
¶
LayoutDMTrainingSplit: TypeAlias = Literal[
"train", "validation", "test"
]
Split names supported by package-local LayoutDM training data.
LayoutDMTrainingTransform
module-attribute
¶
LayoutDMTrainingTransform: TypeAlias = Literal[
"RandomOrder"
]
Training-only layout transforms supported by package-local LayoutDM data.
LayoutDMTrainingScheduler
module-attribute
¶
LayoutDMTrainingScheduler: TypeAlias = Literal[
"reduce_on_plateau"
]
Scheduler names supported by package-local LayoutDM training.
LayoutDMTimeSampler
module-attribute
¶
LayoutDMTimeSampler: TypeAlias = Literal[
"importance", "uniform"
]
Timestep-sampling strategies used by the categorical diffusion loss.
LayoutDMSeedMode ¶
Bases: StrEnum
Seed modes for regular and deterministic LayoutDM training.
Source code in models/layout-dm/src/layout_dm/training/config.py
27 28 29 30 31 | |
datamodule ¶
LightningDataModule for LayoutDM training.
LayoutDMDataModule ¶
Bases: LightningDataModule
Package-local LightningDataModule for LayoutDM training data.
Source code in models/layout-dm/src/layout_dm/training/datamodule.py
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 | |
__init__ ¶
__init__(
*,
dataset_name: LayoutDMTrainingDatasetName = "publaynet",
config: LayoutDMConfig,
batch_size: int = 256,
max_seq_length: int | None = None,
num_workers: int = 4,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
synthetic_size: int | None = None,
dataset_source: LayoutDMTrainingDatasetSource = "hf",
processed_data_dir: str | None = None,
train_transforms: Sequence[LayoutDMTrainingTransform]
| None = ("RandomOrder",),
) -> None
Initialize datamodule settings.
Source code in models/layout-dm/src/layout_dm/training/datamodule.py
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 | |
setup ¶
setup(stage: str | None = None) -> None
Open datasets for the requested stage.
Source code in models/layout-dm/src/layout_dm/training/datamodule.py
73 74 75 76 77 78 79 | |
train_dataloader ¶
train_dataloader() -> DataLoader[
dict[str, Shaped[torch.Tensor, "..."] | str]
]
Return the training dataloader.
Source code in models/layout-dm/src/layout_dm/training/datamodule.py
81 82 83 84 85 86 87 | |
val_dataloader ¶
val_dataloader() -> DataLoader[
dict[str, Shaped[torch.Tensor, "..."] | str]
]
Return the validation dataloader.
Source code in models/layout-dm/src/layout_dm/training/datamodule.py
89 90 91 92 93 94 95 | |
test_dataloader ¶
test_dataloader() -> DataLoader[
dict[str, Shaped[torch.Tensor, "..."] | str]
]
Return the test dataloader.
Source code in models/layout-dm/src/layout_dm/training/datamodule.py
97 98 99 100 101 102 103 | |
dataset ¶
Dataset and collation helpers for LayoutDM training.
LayoutDMDataset ¶
Bases: Dataset[dict[str, Shaped[Tensor, '...'] | str]]
HF datasets-backed LayoutDM training dataset.
Source code in models/layout-dm/src/layout_dm/training/dataset.py
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 | |
__init__ ¶
__init__(
*,
dataset_name: LayoutDMTrainingDatasetName,
config: LayoutDMConfig,
split: LayoutDMTrainingSplit = "train",
tokenizer: LayoutDMTokenizer | None = None,
max_seq_length: int | None = None,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
random_order: bool = False,
) -> None
Load a LayoutDM training split from the approved HF dataset source.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
LayoutDMTrainingDatasetName
|
|
required |
split
|
LayoutDMTrainingSplit
|
Dataset split to load. |
'train'
|
config
|
LayoutDMConfig
|
Optional LayoutDM configuration. |
required |
tokenizer
|
LayoutDMTokenizer | None
|
Optional tokenizer. Built from |
None
|
max_seq_length
|
int | None
|
Optional element cap before tokenization. |
None
|
box_format
|
BoxFormat | str
|
Source box format. |
xywh
|
normalized
|
bool
|
Whether source boxes are already normalized. |
True
|
random_order
|
bool
|
Whether to apply the RandomOrder transform before tokenization. |
False
|
Source code in models/layout-dm/src/layout_dm/training/dataset.py
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 | |
__len__ ¶
__len__() -> int
Return dataset size when the underlying split exposes it.
Source code in models/layout-dm/src/layout_dm/training/dataset.py
110 111 112 | |
__getitem__ ¶
__getitem__(
index: int,
) -> dict[str, Shaped[torch.Tensor, "..."] | str]
Return one tokenized training example.
Source code in models/layout-dm/src/layout_dm/training/dataset.py
114 115 116 117 | |
LayoutDMProcessedDataset ¶
Bases: Dataset[dict[str, Shaped[Tensor, '...'] | str]]
Preprocessed LayoutDM training data stream.
Source code in models/layout-dm/src/layout_dm/training/dataset.py
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 | |
__init__ ¶
__init__(
*,
dataset_name: LayoutDMTrainingDatasetName,
config: LayoutDMConfig,
processed_data_dir: str | Path,
split: LayoutDMTrainingSplit = "train",
tokenizer: LayoutDMTokenizer | None = None,
max_seq_length: int | None = None,
random_order: bool = False,
) -> None
Load a preprocessed split from a local data directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
LayoutDMTrainingDatasetName
|
|
required |
config
|
LayoutDMConfig
|
LayoutDM configuration. |
required |
processed_data_dir
|
str | Path
|
Directory containing |
required |
split
|
LayoutDMTrainingSplit
|
Package split name. |
'train'
|
tokenizer
|
LayoutDMTokenizer | None
|
Optional tokenizer. Built from |
None
|
max_seq_length
|
int | None
|
Optional element cap used in the processed directory name. |
None
|
random_order
|
bool
|
Whether to apply the RandomOrder transform before tokenization. |
False
|
Source code in models/layout-dm/src/layout_dm/training/dataset.py
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 | |
__len__ ¶
__len__() -> int
Return the number of layouts in the processed split.
Source code in models/layout-dm/src/layout_dm/training/dataset.py
192 193 194 | |
__getitem__ ¶
__getitem__(
index: int,
) -> dict[str, Shaped[torch.Tensor, "..."] | str]
Return one tokenized training example.
Source code in models/layout-dm/src/layout_dm/training/dataset.py
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |
LayoutDMSyntheticDataset ¶
Bases: Dataset[dict[str, Shaped[Tensor, '...'] | str]]
Small deterministic dataset for local CLI smoke tests.
Source code in models/layout-dm/src/layout_dm/training/dataset.py
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 | |
__init__ ¶
__init__(
*,
config: LayoutDMConfig,
size: int = 8,
elements: int = 3,
) -> None
Initialize synthetic examples from a LayoutDM config.
Source code in models/layout-dm/src/layout_dm/training/dataset.py
221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
__len__ ¶
__len__() -> int
Return synthetic dataset size.
Source code in models/layout-dm/src/layout_dm/training/dataset.py
236 237 238 | |
__getitem__ ¶
__getitem__(
index: int,
) -> dict[str, Shaped[torch.Tensor, "..."] | str]
Return one deterministic synthetic tokenized layout.
Source code in models/layout-dm/src/layout_dm/training/dataset.py
240 241 242 243 244 245 246 247 248 249 250 251 252 253 | |
lightning_module ¶
PyTorch Lightning module for LayoutDM discrete-diffusion training.
LayoutDMTrainingModule ¶
Bases: LightningModule
Lightning wrapper reproducing LayoutDM categorical-diffusion training.
Source code in models/layout-dm/src/layout_dm/training/lightning_module.py
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 | |
__init__ ¶
__init__(
*,
config: LayoutDMConfig,
model: LayoutDMDenoiser | None = None,
tokenizer: LayoutDMTokenizer | None = None,
learning_rate: float = 0.0005,
weight_decay: float = 0.1,
betas: tuple[float, float] = (0.9, 0.98),
auxiliary_loss_weight: float = 0.1,
adaptive_auxiliary_loss: bool = True,
time_sampler: LayoutDMTimeSampler = "importance",
scheduler: LayoutDMTrainingScheduler
| None = "reduce_on_plateau",
scheduler_factor: float = 0.5,
scheduler_patience: int = 2,
scheduler_threshold: float = 0.01,
seed_mode: LayoutDMSeedMode
| str = LayoutDMSeedMode.default,
) -> None
Initialize LayoutDM training state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
LayoutDMConfig
|
LayoutDM architecture and tokenizer configuration. |
required |
model
|
LayoutDMDenoiser | None
|
Optional pre-built denoiser. Built from |
None
|
tokenizer
|
LayoutDMTokenizer | None
|
Optional pre-built tokenizer. Built from |
None
|
learning_rate
|
float
|
AdamW learning rate. |
0.0005
|
weight_decay
|
float
|
Weight decay applied to the decay parameter group. |
0.1
|
betas
|
tuple[float, float]
|
AdamW beta coefficients. |
(0.9, 0.98)
|
auxiliary_loss_weight
|
float
|
Weight of the auxiliary cross-entropy term. |
0.1
|
adaptive_auxiliary_loss
|
bool
|
Whether to scale the auxiliary term by the per-timestep adaptive weight. |
True
|
time_sampler
|
LayoutDMTimeSampler
|
Timestep-sampling strategy. |
'importance'
|
scheduler
|
LayoutDMTrainingScheduler | None
|
Optional learning-rate scheduler name. |
'reduce_on_plateau'
|
scheduler_factor
|
float
|
|
0.5
|
scheduler_patience
|
int
|
|
2
|
scheduler_threshold
|
float
|
|
0.01
|
seed_mode
|
LayoutDMSeedMode | str
|
Regular or deterministic seed mode. |
default
|
Source code in models/layout-dm/src/layout_dm/training/lightning_module.py
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 | |
optim_groups ¶
optim_groups() -> list[
dict[str, list[nn.Parameter] | float]
]
Split parameters into weight-decayed and decay-free groups.
Source code in models/layout-dm/src/layout_dm/training/lightning_module.py
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 | |
configure_optimizers ¶
configure_optimizers() -> OptimizerLRScheduler
Return AdamW and an optional ReduceLROnPlateau scheduler.
Source code in models/layout-dm/src/layout_dm/training/lightning_module.py
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | |
training_step ¶
training_step(
batch: dict[str, Shaped[Tensor, "..."]], batch_idx: int
) -> Float[torch.Tensor, ""]
Run one LayoutDM training step.
Source code in models/layout-dm/src/layout_dm/training/lightning_module.py
309 310 311 312 313 314 315 316 317 | |
validation_step ¶
validation_step(
batch: dict[str, Shaped[Tensor, "..."]], batch_idx: int
) -> Float[torch.Tensor, ""]
Run one LayoutDM validation step.
Source code in models/layout-dm/src/layout_dm/training/lightning_module.py
319 320 321 322 323 324 325 326 327 328 | |
losses ¶
Categorical diffusion training-loss helpers for LayoutDM.
mean_except_batch ¶
mean_except_batch(
x: Float[Tensor, "batch ..."],
) -> Float[torch.Tensor, "batch"]
Average every non-batch dimension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Float[Tensor, 'batch ...']
|
Tensor whose leading dimension is the batch. |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'batch']
|
Per-example mean over all trailing dimensions. |
Examples:
>>> mean_except_batch(torch.ones(2, 3)).tolist()
[1.0, 1.0]
Source code in models/layout-dm/src/layout_dm/training/losses.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | |
parity ¶
LayoutDM-specific initial-state and single-step package-versus-original-implementation parity helpers.
trace_layout_dm_step ¶
trace_layout_dm_step(
module: TrainingStepModule[
dict[str, Shaped[Tensor, "..."]]
],
batch: dict[str, Shaped[Tensor, "..."]],
rng_state: RNGState | None = None,
) -> StepTrace
Trace one LayoutDM training step with the canonical trace points.
Source code in models/layout-dm/src/layout_dm/training/parity.py
31 32 33 34 35 36 37 | |
compare_layout_dm_step ¶
compare_layout_dm_step(
reference: StepTrace,
target: StepTrace,
*,
tolerance: TensorTolerance | None = None,
) -> StepReport
Perform a single-step pre-optimizer trace comparison for LayoutDM.
Source code in models/layout-dm/src/layout_dm/training/parity.py
40 41 42 43 44 45 46 47 48 49 | |
compare_layout_dm_optimizer_step ¶
compare_layout_dm_optimizer_step(
reference_state: dict[str, Shaped[Tensor, "..."]],
target_state: dict[str, Shaped[Tensor, "..."]],
*,
tolerance: TensorTolerance | None = None,
) -> OptimizerStepReport
Compare initial and post-optimizer LayoutDM parameter state dictionaries.
Source code in models/layout-dm/src/layout_dm/training/parity.py
52 53 54 55 56 57 58 59 60 61 | |
seed ¶
Seed policy helpers for LayoutDM training.
apply_layout_dm_seed_mode ¶
apply_layout_dm_seed_mode(
seed_mode: LayoutDMSeedMode | str, *, seed: int = 42975
) -> None
Apply the selected LayoutDM seed mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed_mode
|
LayoutDMSeedMode | str
|
Regular or deterministic seed mode. |
required |
seed
|
int
|
Seed used by both modes. |
42975
|
Returns:
| Type | Description |
|---|---|
None
|
None. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the seed mode is unsupported. |
Examples:
>>> apply_layout_dm_seed_mode("default", seed=1)
Source code in models/layout-dm/src/layout_dm/training/seed.py
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 | |