Layout dm
Public LayoutDM conversion and inference APIs.
ConditionType ¶
Bases: StrEnum
Canonical condition names used by layout generation interfaces.
Source code in lib/laygen/src/laygen/common/conditions.py
9 10 11 12 13 14 15 16 17 18 19 20 21 | |
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
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 | |
__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
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 | |
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
177 178 179 180 181 182 183 184 185 | |
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
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
LayoutDMDenoiserOutput
dataclass
¶
Bases: BaseOutput
Denoiser output containing token logits.
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
120 121 122 123 124 | |
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
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 | |
__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
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | |
__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
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 | |
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')
|
token_mask
|
list[list[bool]] | None
|
Optional valid-token mask for each sequence position. |
None
|
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
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 | |
__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"),
token_mask: list[list[bool]] | None = None,
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
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 | |
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
110 111 112 113 114 115 116 117 118 119 | |
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
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | |
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
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
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
157 158 159 160 161 162 163 164 165 166 | |
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
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 | |
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 | |
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 | |
normalize_condition_type ¶
normalize_condition_type(
condition_type: ConditionType | str,
) -> ConditionType
Normalize condition aliases to a canonical ConditionType.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
condition_type
|
ConditionType | str
|
Canonical condition enum or a public/release alias. |
required |
Returns:
| Type | Description |
|---|---|
ConditionType
|
Canonical condition enum. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the condition type is unknown. |
Examples:
>>> str(normalize_condition_type("gen_t"))
'label'
>>> str(normalize_condition_type("gen_r"))
'relation'
Source code in lib/laygen/src/laygen/common/conditions.py
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 | |
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 | |
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.
AdaLayerNorm ¶
Bases: _AdaNorm
Adaptive layer normalization conditioned on diffusion timestep.
Origin
This module follows VQ-Diffusion AdaLayerNorm and keeps the
submodule names used by LayoutDM, LACE, and Layout-Corrector checkpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_embd
|
int
|
Hidden dimension. |
required |
max_timestep
|
int
|
Maximum diffusion timestep. |
required |
emb_type
|
TimestepEmbeddingType | str
|
Timestep embedding variant. |
adalayernorm_abs
|
Source code in lib/laygen/src/laygen/nn/norms.py
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 | |
__init__ ¶
__init__(
n_embd: int,
max_timestep: int,
emb_type: TimestepEmbeddingType
| str = TimestepEmbeddingType.adalayernorm_abs,
) -> None
Initialize adaptive layer normalization.
Source code in lib/laygen/src/laygen/nn/norms.py
55 56 57 58 59 60 61 62 63 | |
forward ¶
forward(
x: Float[Tensor, "batch tokens channels"],
timestep: Int[Tensor, "batch"],
) -> Float[torch.Tensor, "batch tokens channels"]
Apply timestep-conditioned layer normalization.
Source code in lib/laygen/src/laygen/nn/norms.py
65 66 67 68 69 70 71 72 73 | |
ElementPositionalEmbedding ¶
Bases: Module
Learned element and attribute positional embedding.
Origin
This learned element/attribute positional embedding is specific to CyberAgentAILab LayoutDM and is reused by Layout-Corrector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim_model
|
int
|
Embedding dimension. |
required |
max_token_length
|
int
|
Maximum flattened token sequence length. |
required |
n_attr_per_elem
|
int
|
Number of attributes per layout element. |
5
|
Source code in lib/laygen/src/laygen/nn/embeddings.py
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 | |
no_decay_param_names
property
¶
no_decay_param_names: list[str]
Return parameter names that should skip weight decay.
__init__ ¶
__init__(
dim_model: int,
max_token_length: int,
n_attr_per_elem: int = 5,
) -> None
Initialize element and attribute embedding parameters.
Source code in lib/laygen/src/laygen/nn/embeddings.py
115 116 117 118 119 120 121 122 123 | |
forward ¶
forward(
h: Float[Tensor, "batch tokens channels"],
) -> Float[torch.Tensor, "batch tokens channels"]
Return positional embeddings matching hidden-state length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h
|
Float[Tensor, 'batch tokens channels']
|
Hidden states shaped |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'batch tokens channels']
|
Positional embedding tensor shaped like |
Source code in lib/laygen/src/laygen/nn/embeddings.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
SinusoidalPosEmb ¶
Bases: Module
Sinusoidal timestep or position embedding.
Origin
This is the VQ-Diffusion-style sinusoidal timestep embedding carried by
LayoutDM and LACE. The checkpoint operation order is preserved exactly
because LACE denoiser parity is bit-sensitive at rescale_steps=4000.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_steps
|
int
|
Maximum number of positions or timesteps. |
required |
dim
|
int
|
Embedding dimension. Odd dimensions keep the checkpoint truncation
behavior and return |
required |
rescale_steps
|
int
|
Rescaling constant used by the released checkpoints. |
4000
|
Source code in lib/laygen/src/laygen/nn/embeddings.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | |
__init__ ¶
__init__(
num_steps: int, dim: int, rescale_steps: int = 4000
) -> None
Initialize the embedding parameters.
Source code in lib/laygen/src/laygen/nn/embeddings.py
76 77 78 79 80 81 | |
forward ¶
forward(
x: Int[Tensor, "batch"],
) -> Float[torch.Tensor, "batch channels"]
Embed integer positions or timesteps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Int[Tensor, 'batch']
|
One-dimensional tensor of positions. |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'batch channels']
|
Sinusoidal embedding tensor. |
Source code in lib/laygen/src/laygen/nn/embeddings.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | |
CategoricalTransformer ¶
Bases: Module
Token transformer that predicts LayoutDM categorical logits.
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
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 | |
__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
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 | |
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
108 109 110 111 112 113 114 115 116 117 | |
LayoutDMDenoiserOutput
dataclass
¶
Bases: BaseOutput
Denoiser output containing token logits.
Source code in models/layout-dm/src/layout_dm/modeling_layout_dm.py
120 121 122 123 124 | |
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
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 | |
__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
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 | |
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
177 178 179 180 181 182 183 184 185 | |
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
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
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
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 | |
__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
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | |
__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
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 | |
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
29 30 31 32 33 34 35 | |
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')
|
token_mask
|
list[list[bool]] | None
|
Optional valid-token mask for each sequence position. |
None
|
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
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 | |
__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"),
token_mask: list[list[bool]] | None = None,
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
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 | |
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
110 111 112 113 114 115 116 117 118 119 | |
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
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | |
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
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
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
157 158 159 160 161 162 163 164 165 166 | |
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
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 | |
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 | |
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
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 | |
__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
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 | |
__len__ ¶
__len__() -> int
Return dataset size when the underlying split exposes it.
Source code in models/layout-dm/src/layout_dm/training/dataset.py
109 110 111 | |
__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
113 114 115 116 | |
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
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 | |
__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
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 | |
__len__ ¶
__len__() -> int
Return the number of layouts in the processed split.
Source code in models/layout-dm/src/layout_dm/training/dataset.py
191 192 193 | |
__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
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 | |
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
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 | |
__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
220 221 222 223 224 225 226 227 228 229 230 231 232 233 | |
__len__ ¶
__len__() -> int
Return synthetic dataset size.
Source code in models/layout-dm/src/layout_dm/training/dataset.py
235 236 237 | |
__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
239 240 241 242 243 244 245 246 247 248 249 250 251 252 | |
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.
log_categorical ¶
log_categorical(
log_x_start: Float[Tensor, "batch vocab tokens"],
log_prob: Float[Tensor, "batch vocab tokens"],
) -> Float[torch.Tensor, "batch tokens"]
Categorical log-likelihood of log_x_start under log_prob.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_x_start
|
Float[Tensor, 'batch vocab tokens']
|
Log one-hot targets. |
required |
log_prob
|
Float[Tensor, 'batch vocab tokens']
|
Predicted log probabilities. |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'batch tokens']
|
Per-token log-likelihood with the vocabulary dimension reduced. |
Examples:
>>> import torch
>>> target = torch.log(torch.tensor([[[1.0], [0.0]]]).clamp_min(1e-30))
>>> probs = torch.log(torch.tensor([[[0.25], [0.75]]]))
>>> log_categorical(target, probs).shape
torch.Size([1, 1])
Source code in lib/laygen/src/laygen/common/discrete.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
multinomial_kl ¶
multinomial_kl(
log_prob1: Float[Tensor, "batch vocab tokens"],
log_prob2: Float[Tensor, "batch vocab tokens"],
) -> Float[torch.Tensor, "batch tokens"]
Categorical KL divergence summed over the vocabulary dimension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
log_prob1
|
Float[Tensor, 'batch vocab tokens']
|
Log probabilities of the reference distribution. |
required |
log_prob2
|
Float[Tensor, 'batch vocab tokens']
|
Log probabilities of the compared distribution. |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'batch tokens']
|
Per-token KL divergence with the vocabulary dimension reduced. |
Examples:
>>> import torch
>>> a = torch.log(torch.tensor([[[1.0], [0.0]]]).clamp_min(1e-30))
>>> float(multinomial_kl(a, a).sum())
0.0
Source code in lib/laygen/src/laygen/common/discrete.py
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | |
sample_time_importance ¶
sample_time_importance(
batch_size: int,
*,
num_timesteps: int,
lt_history: Float[Tensor, "timesteps"],
lt_count: Float[Tensor, "timesteps"],
generator: Generator | None = None,
) -> tuple[
Int[torch.Tensor, "batch"], Float[torch.Tensor, "batch"]
]
Sample diffusion timesteps with loss-aware importance sampling.
Until every timestep bucket has more than ten observations the sampler falls back to a uniform draw. Afterwards timesteps are drawn proportionally to the square root of the running squared-loss history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Number of timesteps to draw. |
required |
num_timesteps
|
int
|
Total diffusion timesteps. |
required |
lt_history
|
Float[Tensor, 'timesteps']
|
Running squared-loss history buffer. |
required |
lt_count
|
Float[Tensor, 'timesteps']
|
Per-timestep observation-count buffer. |
required |
generator
|
Generator | None
|
Optional random generator for deterministic draws. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Int[Tensor, 'batch'], Float[Tensor, 'batch']]
|
Sampled timesteps and their sampling probabilities. |
Examples:
>>> import torch
>>> hist = torch.arange(1, 5, dtype=torch.float32)
>>> count = torch.full((4,), 11.0)
>>> gen = torch.Generator().manual_seed(0)
>>> t, pt = sample_time_importance(
... 2, num_timesteps=4, lt_history=hist, lt_count=count, generator=gen
... )
>>> t.shape, pt.shape
(torch.Size([2]), torch.Size([2]))
Source code in lib/laygen/src/laygen/common/discrete.py
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 | |
sample_time_uniform ¶
sample_time_uniform(
batch_size: int,
*,
num_timesteps: int,
device: device,
generator: Generator | None = None,
) -> tuple[
Int[torch.Tensor, "batch"], Float[torch.Tensor, "batch"]
]
Sample diffusion timesteps uniformly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Number of timesteps to draw. |
required |
num_timesteps
|
int
|
Total diffusion timesteps. |
required |
device
|
device
|
Device for the sampled tensors. |
required |
generator
|
Generator | None
|
Optional random generator for deterministic draws. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Int[Tensor, 'batch'], Float[Tensor, 'batch']]
|
Sampled timesteps and their uniform sampling probabilities. |
Examples:
>>> import torch
>>> gen = torch.Generator().manual_seed(0)
>>> t, pt = sample_time_uniform(
... 2, num_timesteps=4, device=torch.device("cpu"), generator=gen
... )
>>> t.shape, pt.tolist()
(torch.Size([2]), [0.25, 0.25])
Source code in lib/laygen/src/laygen/common/discrete.py
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 | |
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 S0-S2 training-parity helpers.
trace_layout_dm_step ¶
trace_layout_dm_step(
module: TrainingStepModule,
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
Compare S1 LayoutDM pre-optimizer traces.
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 S0/S2 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 | |