Model Card for LayoutFlow¶
This package ports LayoutFlow, the ECCV 2024 flow-matching model for layout generation, into a 🧨diffusers-style package.
Model Details¶
Model Description¶
LayoutFlow is a continuous-flow diffusers pipeline that predicts layout vector fields for RICO25 and PubLayNet. It supports unconditional and conditional generation through normalized condition aliases while converting layout coordinate conventions into the shared public schema. Public outputs use normalized center xywh boxes in [0, 1], dataset-local integer labels, a valid-element mask, and id2label.
- Developed by: Julian Jorge Andrade Guerreiro et al.
- Shared by: creative-graphic-design.
- Model type: content-agnostic; task: task-agnostic; conditioning: unconditional, label, label_size, completion, refinement.
- Language(s) (NLP): not applicable.
- License: MIT.
Model Sources¶
- Repository: LayoutFlow repository
- Paper: arXiv 2403.18187
- Project page: LayoutFlow project page
- Original checkpoint host: JulianGuerreiro/LayoutFlow
Supported Checkpoints¶
| Checkpoint | Hub ID | Status |
|---|---|---|
| RICO25 | creative-graphic-design/layout-flow-rico25 |
not-published |
| PubLayNet | creative-graphic-design/layout-flow-publaynet |
not-published |
Uses¶
Direct Use¶
Use this package for research inference, conversion checks, and agreement checks against the original implementation for generated layouts.
The original method models layouts as continuous flow-matching trajectories over normalized boxes and analog-bit category labels, then solves the generation path with an increasing-time ODE from t=0 to t=1.
Downstream Use¶
Generated layouts may feed rendering, design tooling, layout evaluation, or downstream content placement systems after task-specific validation.
Out-of-Scope Use¶
Do not treat generated layouts as production accessibility annotations, OCR output, semantic scene understanding, or license-cleared design assets without separate review.
Bias, Risks, and Limitations¶
The converted behavior follows the upstream checkpoints, prompt fixtures, and datasets. Dataset coverage, label vocabularies, and layout quality inherit the limits of those sources.
Recommendations¶
Re-run the agreement-check suite against the original implementation before publishing converted checkpoints or comparing new results.
How to Get Started with the Model¶
Install the package directly from this repository. The command includes shared packages when they are not published on PyPI.
pip install \
"laygen @ git+https://github.com/creative-graphic-design/design-generators.git#subdirectory=lib/laygen" \
"layout-flow @ git+https://github.com/creative-graphic-design/design-generators.git#subdirectory=models/layout-flow"
Clone this repository, install the workspace member, and run the download and conversion steps in REPRODUCING.md. Those steps create .cache/layout-flow/converted/rico25.
git clone https://github.com/creative-graphic-design/design-generators.git
cd design-generators
uv sync --package layout-flow
uv run --package layout-flow python
from layout_flow import LayoutFlowPipeline
path = ".cache/layout-flow/converted/rico25"
# After Hub publication: from_pretrained("creative-graphic-design/layout-flow-rico25")
pipe = LayoutFlowPipeline.from_pretrained(path)
out = pipe(batch_size=1, seed=0)
print(out.bbox)
print(out.labels)
print(out.mask)
Training Details¶
Training Data¶
| Dataset | Dataset ID | Notes |
|---|---|---|
| RICO25 | creative-graphic-design/Rico |
ui-screenshots-and-hierarchies-with-semantic-annotations |
| PubLayNet | creative-graphic-design/PubLayNet |
default |
The released LayoutFlow checkpoints were trained on the RICO and PubLayNet splits distributed by the original authors; this repository aligns dataset metadata to the org datasets above.
Training Procedure¶
This package includes package-local LightningCLI configs for reproducing LayoutFlow training. See TRAINING.md for config names, seed modes, launch commands, staged agreement checks, and trained-checkpoint conversion.
Speeds, Sizes, Times¶
Training-time and carbon measurements are unknown.
Evaluation¶
Testing Data, Factors & Metrics¶
Testing Data¶
Agreement checks use local-only generated fixtures and converted checkpoint directories. Large generated tensors, images, weights, and downloaded artifacts are not committed.
Factors¶
Agreement results are reported separately by dataset, checkpoint, condition mode, seed, or prompt fixture where the package has recorded evidence.
Metrics¶
Metrics are exact tensor equality, exact token or byte equality, or an explicitly stated numeric tolerance against the original implementation.
Parity Results¶
| Dataset | Compared path | Cases | Assertion |
|---|---|---|---|
| PubLayNet | Original-implementation LayoutDMBackbone vector field vs. converted vector field |
1 synthetic batch | max_abs <= 1e-6 (atol=1e-6), max_rel <= 1e-5 (rtol=1e-5) |
| RICO25 | Original-implementation LayoutDMBackbone vector field vs. converted vector field |
1 synthetic batch | max_abs <= 1e-6 (atol=1e-6), max_rel <= 1e-5 (rtol=1e-5) |
| Training parity stages | LightningCLI training wrapper vs. original-implementation training protocol | 1 synthetic PubLayNet-shaped batch on GPU 4 | static state exact, fixed-batch trace exact, one optimizer step exact |
Agreement checks compare the released checkpoints against the original LayoutDMBackbone vector-field path. The local pipeline uses LayoutFlowEulerScheduler for inference, but no committed agreement check compares an Euler trajectory against the original implementation.
Reproducibility¶
See REPRODUCING.md for the commands that download original-implementation assets, generate reference outputs, run agreement checks, convert checkpoints, and smoke-test local loading.
Environmental Impact¶
No new model training is performed by these conversion packages. Conversion and agreement-check costs depend on the selected checkpoint and local hardware.
Technical Specifications¶
Model Architecture and Objective¶
LayoutFlow models layouts as continuous vectors and predicts the flow field used to sample element boxes and labels. The processor accepts unconditional and conditional aliases such as gen_t, cat_cond, and size_cond, then converts layout coordinate conventions to normalized center xywh outputs.
Compute Infrastructure¶
Agreement-check commands are intended for one explicitly selected GPU when the original implementation requires CUDA.
Hardware¶
CPU is sufficient for import and most smoke tests. CUDA is required for heavyweight agreement checks when the original implementation requires it.
Software¶
Use uv run --package layout-flow ... from the repository root so workspace dependency sources and extras resolve correctly.
License¶
Repository wrapper code is Apache-2.0. The original implementation is MIT licensed.
Citation¶
@inproceedings{guerreiro2024layoutflow,
title={LayoutFlow: Flow Matching For Layout Generation},
author={Guerreiro, Julian Jorge Andrade and Inoue, Naoto and Masui, Kento and Otani, Mayu and Nakayama, Hideki},
booktitle={European Conference on Computer Vision},
pages={56--72},
year={2024},
organization={Springer}
}
API Reference¶
Diffusers-compatible LayoutFlow components.
LayoutFlowConfig ¶
Bases: ConfigMixin
Configuration saved with converted LayoutFlow pipelines.
Source code in models/layout-flow/src/layout_flow/configuration_layout_flow.py
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 | |
__init__ ¶
__init__(
*,
dataset_name: str = "publaynet",
id2label: dict[int | str, str] | None = None,
max_length: int = 20,
latent_dim: int = 128,
d_model: int = 512,
nhead: int = 8,
dim_feedforward: int = 2048,
num_layers: int = 4,
dropout: float = 0.1,
use_pos_enc: bool = False,
tr_enc_only: bool = True,
attr_encoding: AttrEncoding = AttrEncoding.analog_bit,
seq_type: SeqType = SeqType.stacked,
distribution: InitialDistributionName = InitialDistributionName.gaussian,
sample_padding: bool = False,
inference_steps: int = 100,
ode_solver: OdeSolverName = OdeSolverName.euler,
bbox_format: BoxFormat | str = "xywh",
coordinate_range: CoordinateRange = CoordinateRange.normalized_0_1,
) -> None
Initialize LayoutFlow pipeline and model settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
Dataset variant or alias. |
'publaynet'
|
id2label
|
dict[int | str, str] | None
|
Optional explicit id-to-label mapping. |
None
|
max_length
|
int
|
Maximum number of layout elements. |
20
|
latent_dim
|
int
|
Latent dimension. |
128
|
d_model
|
int
|
Transformer hidden size. |
512
|
nhead
|
int
|
Number of attention heads. |
8
|
dim_feedforward
|
int
|
Feed-forward hidden size. |
2048
|
num_layers
|
int
|
Number of transformer layers. |
4
|
dropout
|
float
|
Dropout probability. |
0.1
|
use_pos_enc
|
bool
|
Whether to add sinusoidal position encodings. |
False
|
tr_enc_only
|
bool
|
Whether to use the encoder-only path. |
True
|
attr_encoding
|
AttrEncoding
|
Attribute encoding used by the checkpoint. |
analog_bit
|
seq_type
|
SeqType
|
Sequence layout type. |
stacked
|
distribution
|
InitialDistributionName
|
Initial sampling distribution. |
gaussian
|
sample_padding
|
bool
|
Whether sampling includes padded elements. |
False
|
inference_steps
|
int
|
Default Euler inference steps. |
100
|
ode_solver
|
OdeSolverName
|
ODE solver name. |
euler
|
bbox_format
|
BoxFormat | str
|
Public bounding-box format. |
'xywh'
|
coordinate_range
|
CoordinateRange
|
Public coordinate range. |
normalized_0_1
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in models/layout-flow/src/layout_flow/configuration_layout_flow.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 213 214 215 216 217 | |
LayoutFlowModelOutput
dataclass
¶
Bases: BaseOutput
Output of LayoutFlowTransformerModel.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
329 330 331 332 333 | |
LayoutFlowTransformerModel ¶
Bases: ModelMixin, ConfigMixin
Diffusers model wrapper around the LayoutFlow backbone.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
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 | |
__init__ ¶
__init__(
*,
num_labels: int = 6,
latent_dim: int = 128,
tr_enc_only: bool = True,
d_model: int = 512,
nhead: int = 8,
dim_feedforward: int = 2048,
num_layers: int = 4,
dropout: float = 0.1,
use_pos_enc: bool = False,
attr_encoding: AttrEncoding = AttrEncoding.analog_bit,
seq_type: SeqType = SeqType.stacked,
) -> None
Initialize the converted LayoutFlow transformer model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_labels
|
int
|
Number of dataset labels. |
6
|
latent_dim
|
int
|
Latent dimension. |
128
|
tr_enc_only
|
bool
|
Whether to use the encoder-only path. |
True
|
d_model
|
int
|
Transformer hidden size. |
512
|
nhead
|
int
|
Number of attention heads. |
8
|
dim_feedforward
|
int
|
Feed-forward hidden size. |
2048
|
num_layers
|
int
|
Number of transformer layers. |
4
|
dropout
|
float
|
Dropout probability. |
0.1
|
use_pos_enc
|
bool
|
Whether to add positional encodings. |
False
|
attr_encoding
|
AttrEncoding
|
Attribute encoding. |
analog_bit
|
seq_type
|
SeqType
|
Sequence type. |
stacked
|
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
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 | |
forward ¶
forward(
sample: Float[Tensor, "batch elements channels"],
timestep: Float[Tensor, ""],
cond_mask: Bool[Tensor, "batch elements channels"],
return_dict: bool = True,
) -> (
LayoutFlowModelOutput
| tuple[Float[torch.Tensor, "batch elements channels"]]
)
Predict the vector field for a model state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample
|
Float[Tensor, 'batch elements channels']
|
Current model state. |
required |
timestep
|
Float[Tensor, '']
|
Current integration timestep. |
required |
cond_mask
|
Bool[Tensor, 'batch elements channels']
|
Condition mask. |
required |
return_dict
|
bool
|
Whether to return a dataclass output. |
True
|
Returns:
| Type | Description |
|---|---|
LayoutFlowModelOutput | tuple[Float[Tensor, 'batch elements channels']]
|
Model output dataclass or single-item tuple. |
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
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 | |
LayoutFlowPipeline ¶
Bases: DiffusionPipeline
Generate layouts with a converted LayoutFlow checkpoint.
Source code in models/layout-flow/src/layout_flow/pipeline_layout_flow.py
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 | |
__init__ ¶
__init__(
model: LayoutFlowTransformerModel,
scheduler: LayoutFlowEulerScheduler,
config: LayoutFlowConfig,
processor: LayoutFlowProcessor | None = None,
) -> None
Create a LayoutFlow pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
LayoutFlowTransformerModel
|
Converted LayoutFlow transformer model. |
required |
scheduler
|
LayoutFlowEulerScheduler
|
Increasing-time Euler scheduler. |
required |
config
|
LayoutFlowConfig
|
Pipeline configuration. |
required |
processor
|
LayoutFlowProcessor | None
|
Optional input/output processor. |
None
|
Source code in models/layout-flow/src/layout_flow/pipeline_layout_flow.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | |
__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 = "xywh",
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
num_inference_steps: int | None = None,
guidance_scale: float = 0.0,
output_type: OutputType | str = "dataclass",
return_intermediates: bool = False,
) -> (
LayoutGenerationOutput
| dict[str, Shaped[torch.Tensor, "..."]]
)
Generate layout boxes and labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Number of layouts to generate. |
1
|
seed
|
int | None
|
Optional seed used when |
None
|
generator
|
Generator | None
|
Optional torch random generator. |
None
|
condition_type
|
ConditionType | str
|
Public condition name or supported alias. |
unconditional
|
labels
|
Int[Tensor, 'batch elements'] | Int[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional condition labels. |
None
|
bbox
|
Float[Tensor, 'batch elements 4'] | Float[ndarray, 'batch elements 4'] | Sequence[ArrayLikeInput] | None
|
Optional condition boxes. |
None
|
mask
|
Bool[Tensor, 'batch elements'] | Bool[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional valid-element mask. |
None
|
num_elements
|
int | list[int] | Int[Tensor, 'batch'] | None
|
Optional element counts for unconditional masks. |
None
|
box_format
|
BoxFormat | str
|
Input and output box format. |
'xywh'
|
normalized
|
bool
|
Whether coordinates are normalized. |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size for denormalized coordinates. |
None
|
num_inference_steps
|
int | None
|
Number of Euler steps. |
None
|
guidance_scale
|
float
|
Classifier-free guidance scale. |
0.0
|
output_type
|
OutputType | str
|
|
'dataclass'
|
return_intermediates
|
bool
|
Whether to include intermediate samples. |
False
|
Returns:
| Type | Description |
|---|---|
LayoutGenerationOutput | dict[str, Shaped[Tensor, '...']]
|
Layout generation output dataclass, or a dictionary when requested. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> pipe = LayoutFlowPipeline(
... model=LayoutFlowTransformerModel(
... num_labels=6, latent_dim=8, d_model=16, nhead=4,
... dim_feedforward=32, num_layers=1
... ),
... scheduler=LayoutFlowEulerScheduler(num_inference_steps=2),
... config=LayoutFlowConfig(max_length=2, latent_dim=8, d_model=16),
... )
>>> out = pipe(batch_size=1, num_elements=1, seed=0, num_inference_steps=2)
>>> out.bbox.shape[-1]
4
Source code in models/layout-flow/src/layout_flow/pipeline_layout_flow.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 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 | |
save_pretrained ¶
save_pretrained(save_directory: str | Path) -> None
Save pipeline components and LayoutFlow config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_directory
|
str | Path
|
Output directory. |
required |
Source code in models/layout-flow/src/layout_flow/pipeline_layout_flow.py
216 217 218 219 220 221 222 223 | |
from_pretrained
classmethod
¶
from_pretrained(
pretrained_model_name_or_path: str | Path,
) -> LayoutFlowPipeline
Load a saved LayoutFlow pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pretrained_model_name_or_path
|
str | Path
|
Local directory or Hub id. |
required |
Returns:
| Type | Description |
|---|---|
LayoutFlowPipeline
|
Loaded LayoutFlow pipeline. |
Source code in models/layout-flow/src/layout_flow/pipeline_layout_flow.py
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | |
LayoutFlowProcessor ¶
Bases: ProcessorMixin
Prepare public layout tensors for the LayoutFlow model.
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
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 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 | |
__init__ ¶
__init__(config: LayoutFlowConfig) -> None
Create a processor for a LayoutFlow configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
LayoutFlowConfig
|
LayoutFlow pipeline configuration. |
required |
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
35 36 37 38 39 40 41 42 43 44 | |
__call__ ¶
__call__(
*,
bbox: Float[Tensor, "batch elements 4"]
| Float[ndarray, "batch elements 4"]
| Sequence[ArrayLikeInput]
| None = None,
labels: Int[Tensor, "batch elements"]
| Int[ndarray, "batch elements"]
| 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,
batch_size: int = 1,
box_format: BoxFormat | str = "xywh",
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
device: device | str | None = None,
) -> dict[str, Shaped[torch.Tensor, "..."]]
Convert public inputs into padded model-ready tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'batch elements 4'] | Float[ndarray, 'batch elements 4'] | Sequence[ArrayLikeInput] | None
|
Optional boxes in the requested |
None
|
labels
|
Int[Tensor, 'batch elements'] | Int[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional dataset-local label ids. |
None
|
mask
|
Bool[Tensor, 'batch elements'] | Bool[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional valid-element mask. |
None
|
num_elements
|
int | list[int] | Int[Tensor, 'batch'] | None
|
Optional element counts used when |
None
|
batch_size
|
int
|
Batch size used when tensors are omitted. |
1
|
box_format
|
BoxFormat | str
|
Format of |
'xywh'
|
normalized
|
bool
|
Whether |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size required for denormalized boxes. |
None
|
device
|
device | str | None
|
Target torch device. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
Dictionary with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If denormalized boxes are missing |
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
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 | |
encode_labels ¶
encode_labels(
labels: Int[Tensor, "batch elements"],
) -> Float[torch.Tensor, "batch elements bits"]
Encode integer labels as analog-bit vectors.
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
139 140 141 142 143 144 145 146 | |
decode_labels ¶
decode_labels(
bits: Float[Tensor, "batch elements bits"],
) -> Int[torch.Tensor, "batch elements"]
Decode analog-bit vectors into integer labels.
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
148 149 150 151 152 153 154 155 156 | |
model_state ¶
model_state(
bbox: Float[Tensor, "batch elements 4"],
labels: Int[Tensor, "batch elements"],
) -> Float[torch.Tensor, "batch elements channels"]
Concatenate normalized boxes and analog-bit labels.
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
158 159 160 161 162 163 164 | |
preprocess_state ¶
preprocess_state(
state: Float[Tensor, "batch elements channels"],
*,
reverse: bool = False,
) -> Float[torch.Tensor, "batch elements channels"]
Map between public [0, 1] state and model distribution range.
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
166 167 168 169 170 171 172 173 174 175 | |
make_condition_mask ¶
make_condition_mask(
condition_type: ConditionType,
*,
mask: Bool[Tensor, "batch elements"],
generator: Generator | None = None,
) -> Int[torch.Tensor, "batch elements channels"]
Create the condition mask for a conditioning mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
condition_type
|
ConditionType
|
Canonical condition or alias. |
required |
mask
|
Bool[Tensor, 'batch elements']
|
Valid-element mask. |
required |
generator
|
Generator | None
|
Optional generator used by completion masking. |
None
|
Returns:
| Type | Description |
|---|---|
Int[Tensor, 'batch elements channels']
|
Long tensor where |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the condition type is unsupported. |
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
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 | |
postprocess ¶
postprocess(
state: Float[Tensor, "batch elements channels"],
*,
mask: Bool[Tensor, "batch elements"],
box_format: BoxFormat | str = "xywh",
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
) -> dict[str, Shaped[torch.Tensor, "..."]]
Convert model state back to public layout tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
Float[Tensor, 'batch elements channels']
|
Model state tensor. |
required |
mask
|
Bool[Tensor, 'batch elements']
|
Valid-element mask. |
required |
box_format
|
BoxFormat | str
|
Requested output box format. |
'xywh'
|
normalized
|
bool
|
Whether to return normalized coordinates. |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size for denormalized coordinates. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
Dictionary with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If denormalized output is requested without
|
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
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 | |
LayoutFlowEulerScheduler ¶
Bases: SchedulerMixin, ConfigMixin
Increasing-time Euler scheduler used by LayoutFlow.
Source code in models/layout-flow/src/layout_flow/scheduling_layout_flow.py
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 | |
__init__ ¶
__init__(
num_inference_steps: int = 100,
start: float = 0.0,
end: float = 1.0,
) -> None
Initialize the scheduler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_inference_steps
|
int
|
Number of Euler steps. |
100
|
start
|
float
|
Initial integration time. |
0.0
|
end
|
float
|
Final integration time. |
1.0
|
Source code in models/layout-flow/src/layout_flow/scheduling_layout_flow.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | |
set_timesteps ¶
set_timesteps(
num_inference_steps: int | None = None,
*,
device: device | str | None = None,
start: float | None = None,
end: float | None = None,
) -> None
Set the integration timesteps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_inference_steps
|
int | None
|
Optional number of inference steps. |
None
|
device
|
device | str | None
|
Optional target device. |
None
|
start
|
float | None
|
Optional start time. |
None
|
end
|
float | None
|
Optional end time. |
None
|
Source code in models/layout-flow/src/layout_flow/scheduling_layout_flow.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | |
scale_model_input ¶
scale_model_input(
sample: Float[Tensor, "batch elements channels"],
timestep: Float[Tensor, ""]
| Float[Tensor, "batch"]
| float,
) -> Float[torch.Tensor, "batch elements channels"]
Return the sample unchanged for Diffusers scheduler compatibility.
Source code in models/layout-flow/src/layout_flow/scheduling_layout_flow.py
65 66 67 68 69 70 71 72 | |
step ¶
step(
model_output: Float[Tensor, "batch elements channels"],
timestep: Float[Tensor, ""]
| Float[Tensor, "batch"]
| float,
sample: Float[Tensor, "batch elements channels"],
*,
next_timestep: Float[Tensor, ""]
| Float[Tensor, "batch"]
| float
| None = None,
return_dict: Literal[True] = True,
) -> LayoutFlowSchedulerOutput
step(
model_output: Float[Tensor, "batch elements channels"],
timestep: Float[Tensor, ""]
| Float[Tensor, "batch"]
| float,
sample: Float[Tensor, "batch elements channels"],
*,
next_timestep: Float[Tensor, ""]
| Float[Tensor, "batch"]
| float
| None = None,
return_dict: Literal[False],
) -> tuple[Float[torch.Tensor, "batch elements channels"]]
step(
model_output: Float[Tensor, "batch elements channels"],
timestep: Float[Tensor, ""]
| Float[Tensor, "batch"]
| float,
sample: Float[Tensor, "batch elements channels"],
*,
next_timestep: Float[Tensor, ""]
| Float[Tensor, "batch"]
| float
| None = None,
return_dict: bool = True,
) -> (
LayoutFlowSchedulerOutput
| tuple[Float[torch.Tensor, "batch elements channels"]]
)
Advance the sample with one Euler step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_output
|
Float[Tensor, 'batch elements channels']
|
Predicted vector field. |
required |
timestep
|
Float[Tensor, ''] | Float[Tensor, 'batch'] | float
|
Current integration time. |
required |
sample
|
Float[Tensor, 'batch elements channels']
|
Current sample state. |
required |
next_timestep
|
Float[Tensor, ''] | Float[Tensor, 'batch'] | float | None
|
Optional next integration time. |
None
|
return_dict
|
bool
|
Whether to return a scheduler output dataclass. |
True
|
Returns:
| Type | Description |
|---|---|
LayoutFlowSchedulerOutput | tuple[Float[Tensor, 'batch elements channels']]
|
Scheduler output dataclass or single-item tuple. |
Source code in models/layout-flow/src/layout_flow/scheduling_layout_flow.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 | |
configuration_layout_flow ¶
Configuration objects and dataset metadata for LayoutFlow.
AttrEncoding ¶
Bases: StrEnum
Closed set of LayoutFlow attribute encodings.
Source code in models/layout-flow/src/layout_flow/configuration_layout_flow.py
18 19 20 21 22 23 | |
SeqType ¶
Bases: StrEnum
Closed set of LayoutFlow sequence layouts.
Source code in models/layout-flow/src/layout_flow/configuration_layout_flow.py
26 27 28 29 30 31 | |
InitialDistributionName ¶
Bases: StrEnum
Closed set of initial-state distributions accepted by LayoutFlow config.
Source code in models/layout-flow/src/layout_flow/configuration_layout_flow.py
34 35 36 37 38 39 40 | |
OdeSolverName ¶
Bases: StrEnum
Closed set of ODE solvers accepted by LayoutFlow config.
Source code in models/layout-flow/src/layout_flow/configuration_layout_flow.py
43 44 45 46 | |
CoordinateRange ¶
Bases: StrEnum
Closed set of public coordinate ranges.
Source code in models/layout-flow/src/layout_flow/configuration_layout_flow.py
49 50 51 52 | |
LayoutFlowConfig ¶
Bases: ConfigMixin
Configuration saved with converted LayoutFlow pipelines.
Source code in models/layout-flow/src/layout_flow/configuration_layout_flow.py
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 | |
__init__ ¶
__init__(
*,
dataset_name: str = "publaynet",
id2label: dict[int | str, str] | None = None,
max_length: int = 20,
latent_dim: int = 128,
d_model: int = 512,
nhead: int = 8,
dim_feedforward: int = 2048,
num_layers: int = 4,
dropout: float = 0.1,
use_pos_enc: bool = False,
tr_enc_only: bool = True,
attr_encoding: AttrEncoding = AttrEncoding.analog_bit,
seq_type: SeqType = SeqType.stacked,
distribution: InitialDistributionName = InitialDistributionName.gaussian,
sample_padding: bool = False,
inference_steps: int = 100,
ode_solver: OdeSolverName = OdeSolverName.euler,
bbox_format: BoxFormat | str = "xywh",
coordinate_range: CoordinateRange = CoordinateRange.normalized_0_1,
) -> None
Initialize LayoutFlow pipeline and model settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
str
|
Dataset variant or alias. |
'publaynet'
|
id2label
|
dict[int | str, str] | None
|
Optional explicit id-to-label mapping. |
None
|
max_length
|
int
|
Maximum number of layout elements. |
20
|
latent_dim
|
int
|
Latent dimension. |
128
|
d_model
|
int
|
Transformer hidden size. |
512
|
nhead
|
int
|
Number of attention heads. |
8
|
dim_feedforward
|
int
|
Feed-forward hidden size. |
2048
|
num_layers
|
int
|
Number of transformer layers. |
4
|
dropout
|
float
|
Dropout probability. |
0.1
|
use_pos_enc
|
bool
|
Whether to add sinusoidal position encodings. |
False
|
tr_enc_only
|
bool
|
Whether to use the encoder-only path. |
True
|
attr_encoding
|
AttrEncoding
|
Attribute encoding used by the checkpoint. |
analog_bit
|
seq_type
|
SeqType
|
Sequence layout type. |
stacked
|
distribution
|
InitialDistributionName
|
Initial sampling distribution. |
gaussian
|
sample_padding
|
bool
|
Whether sampling includes padded elements. |
False
|
inference_steps
|
int
|
Default Euler inference steps. |
100
|
ode_solver
|
OdeSolverName
|
ODE solver name. |
euler
|
bbox_format
|
BoxFormat | str
|
Public bounding-box format. |
'xywh'
|
coordinate_range
|
CoordinateRange
|
Public coordinate range. |
normalized_0_1
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in models/layout-flow/src/layout_flow/configuration_layout_flow.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 213 214 215 216 217 | |
normalize_dataset_name ¶
normalize_dataset_name(
dataset_name: DatasetName | str,
) -> DatasetName
Normalize LayoutFlow dataset aliases.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
DatasetName | str
|
Dataset enum value or string alias. |
required |
Returns:
| Type | Description |
|---|---|
DatasetName
|
Canonical shared dataset enum. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the dataset name is unsupported. |
Examples:
>>> str(normalize_dataset_name("rico25_max25"))
'rico25'
Source code in models/layout-flow/src/layout_flow/configuration_layout_flow.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | |
default_id2label ¶
default_id2label(
dataset_name: DatasetName | str,
) -> dict[int, str]
Return the LayoutFlow label vocabulary for a dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
DatasetName | str
|
Dataset enum value or string alias. |
required |
Returns:
| Type | Description |
|---|---|
dict[int, str]
|
Integer-id to label-name mapping. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the dataset name is unsupported. |
Examples:
>>> default_id2label("publaynet")[1]
'text'
Source code in models/layout-flow/src/layout_flow/configuration_layout_flow.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
conversion ¶
Checkpoint conversion helpers for LayoutFlow.
build_pipeline ¶
build_pipeline(
config: LayoutFlowConfig,
) -> LayoutFlowPipeline
Build a randomly initialized pipeline for a LayoutFlow config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
LayoutFlowConfig
|
LayoutFlow configuration. |
required |
Returns:
| Type | Description |
|---|---|
LayoutFlowPipeline
|
Pipeline with model and scheduler modules initialized from |
Examples:
>>> pipe = build_pipeline(LayoutFlowConfig(max_length=2, latent_dim=8, d_model=16))
>>> pipe.layout_flow_config.max_length
2
Source code in models/layout-flow/src/layout_flow/conversion.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | |
convert_lightning_state_dict ¶
convert_lightning_state_dict(
state_dict: dict[str, Shaped[Tensor, "..."]],
) -> dict[str, Shaped[torch.Tensor, "..."]]
Convert original Lightning checkpoint keys to local model keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dict
|
dict[str, Shaped[Tensor, '...']]
|
Original LayoutFlow Lightning state dict. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
State dict keyed for |
Examples:
>>> import torch
>>> out = convert_lightning_state_dict({"model.linear.weight": torch.zeros(1)})
>>> list(out)
['backbone.linear.weight']
>>> out = convert_lightning_state_dict({"model.backbone.linear.weight": torch.zeros(1)})
>>> list(out)
['backbone.linear.weight']
Source code in models/layout-flow/src/layout_flow/conversion.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | |
model_card ¶
Model-card generation for converted LayoutFlow checkpoints.
layoutflow_model_card ¶
layoutflow_model_card(dataset: str) -> ModelCard
Build a model card for a converted LayoutFlow checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
str
|
LayoutFlow dataset name or alias. |
required |
Returns:
| Type | Description |
|---|---|
ModelCard
|
Validated Hugging Face model card. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> card = layoutflow_model_card("publaynet")
>>> card.data.to_dict()["library_name"]
'diffusers'
Source code in models/layout-flow/src/layout_flow/model_card.py
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 | |
save_layoutflow_model_card ¶
save_layoutflow_model_card(
output_dir: str | Path, *, dataset: str
) -> Path
Write a LayoutFlow model card as README.md.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
|
str | Path
|
Directory that receives |
required |
dataset
|
str
|
LayoutFlow dataset name or alias. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Path to the written README. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> from tempfile import TemporaryDirectory
>>> with TemporaryDirectory() as tmp:
... path = save_layoutflow_model_card(tmp, dataset="publaynet")
... path.name
'README.md'
Source code in models/layout-flow/src/layout_flow/model_card.py
114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | |
modeling_layout_flow ¶
PyTorch modules for the converted LayoutFlow vector-field model.
PositionalEncoding ¶
Bases: Module
Sinusoidal positional encoding used by the LayoutFlow backbone.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.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 | |
__init__ ¶
__init__(
d_model: int, dropout: float = 0.1, max_len: int = 10000
) -> None
Initialize positional encodings.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 | |
forward ¶
forward(
x: Float[Tensor, "batch tokens channels"],
) -> Float[torch.Tensor, "1 tokens channels"]
Return positional encodings matching the sequence length of x.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
62 63 64 65 66 | |
AdaLayerNorm ¶
Bases: Module
Adaptive layer norm conditioned on the integration timestep.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | |
__init__ ¶
__init__(n_embd: int) -> None
Initialize timestep-conditioned normalization.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
72 73 74 75 76 77 78 79 80 81 82 83 | |
forward ¶
forward(
x: Float[Tensor, "batch tokens channels"],
timestep: Float[Tensor, "batch"],
) -> Float[torch.Tensor, "batch tokens channels"]
Normalize x with scale and shift predicted from timestep.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
85 86 87 88 89 90 91 92 93 | |
LayoutFlowBlock ¶
Bases: Module
Transformer encoder block used by the LayoutFlow backbone.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
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 | |
__init__ ¶
__init__(
d_model: int = 1024,
nhead: int = 16,
dim_feedforward: int = 2048,
dropout: float = 0.0,
activation: str
| Callable[
[Shaped[Tensor, "..."]], Shaped[Tensor, "..."]
] = F.relu,
batch_first: bool = False,
norm_first: bool = False,
) -> None
Initialize one LayoutFlow transformer block.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
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 | |
forward ¶
forward(
src: Float[Tensor, "batch tokens channels"],
src_mask: Bool[Tensor, "..."] | None = None,
src_key_padding_mask: Bool[Tensor, "batch tokens"]
| None = None,
timestep: Float[Tensor, "batch"] | None = None,
) -> Float[torch.Tensor, "batch tokens channels"]
Apply self-attention and feed-forward layers.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 | |
LayoutFlowTransformerEncoder ¶
Bases: Module
Stack of LayoutFlow transformer blocks.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
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 | |
__init__ ¶
__init__(
encoder_layer: Module,
num_layers: int,
norm: Module | None = None,
) -> None
Clone and stack encoder_layer num_layers times.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
170 171 172 173 174 175 176 177 | |
forward ¶
forward(
src: Float[Tensor, "batch tokens channels"],
mask: Shaped[Tensor, "..."] | None = None,
src_key_padding_mask: Bool[Tensor, "batch tokens"]
| None = None,
timestep: Float[Tensor, "batch"] | None = None,
) -> Float[torch.Tensor, "batch tokens channels"]
Run the stacked encoder blocks.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | |
LayoutDMBackbone ¶
Bases: Module
LayoutFlow backbone module.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
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 | |
__init__ ¶
__init__(
latent_dim: int = 128,
tr_enc_only: bool = True,
d_model: int = 256,
nhead: int = 8,
dim_feedforward: int = 2048,
num_layers: int = 8,
dropout: float = 0.1,
use_pos_enc: bool = False,
num_cat: int = 6,
attr_encoding: AttrEncoding = AttrEncoding.continuous,
seq_type: SeqType = SeqType.stacked,
) -> None
Initialize the LayoutFlow backbone.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
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 | |
forward ¶
forward(
geom: Float[Tensor, "batch elements 4"],
attr: Float[Tensor, "batch elements bits"],
cond_flags: Int[Tensor, "batch elements channels"],
t: Float[Tensor, "batch"],
) -> Float[torch.Tensor, "batch elements channels"]
Predict vector-field values for geometry and attribute inputs.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
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 | |
LayoutFlowModelOutput
dataclass
¶
Bases: BaseOutput
Output of LayoutFlowTransformerModel.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
329 330 331 332 333 | |
LayoutFlowTransformerModel ¶
Bases: ModelMixin, ConfigMixin
Diffusers model wrapper around the LayoutFlow backbone.
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
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 | |
__init__ ¶
__init__(
*,
num_labels: int = 6,
latent_dim: int = 128,
tr_enc_only: bool = True,
d_model: int = 512,
nhead: int = 8,
dim_feedforward: int = 2048,
num_layers: int = 4,
dropout: float = 0.1,
use_pos_enc: bool = False,
attr_encoding: AttrEncoding = AttrEncoding.analog_bit,
seq_type: SeqType = SeqType.stacked,
) -> None
Initialize the converted LayoutFlow transformer model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_labels
|
int
|
Number of dataset labels. |
6
|
latent_dim
|
int
|
Latent dimension. |
128
|
tr_enc_only
|
bool
|
Whether to use the encoder-only path. |
True
|
d_model
|
int
|
Transformer hidden size. |
512
|
nhead
|
int
|
Number of attention heads. |
8
|
dim_feedforward
|
int
|
Feed-forward hidden size. |
2048
|
num_layers
|
int
|
Number of transformer layers. |
4
|
dropout
|
float
|
Dropout probability. |
0.1
|
use_pos_enc
|
bool
|
Whether to add positional encodings. |
False
|
attr_encoding
|
AttrEncoding
|
Attribute encoding. |
analog_bit
|
seq_type
|
SeqType
|
Sequence type. |
stacked
|
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
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 | |
forward ¶
forward(
sample: Float[Tensor, "batch elements channels"],
timestep: Float[Tensor, ""],
cond_mask: Bool[Tensor, "batch elements channels"],
return_dict: bool = True,
) -> (
LayoutFlowModelOutput
| tuple[Float[torch.Tensor, "batch elements channels"]]
)
Predict the vector field for a model state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample
|
Float[Tensor, 'batch elements channels']
|
Current model state. |
required |
timestep
|
Float[Tensor, '']
|
Current integration timestep. |
required |
cond_mask
|
Bool[Tensor, 'batch elements channels']
|
Condition mask. |
required |
return_dict
|
bool
|
Whether to return a dataclass output. |
True
|
Returns:
| Type | Description |
|---|---|
LayoutFlowModelOutput | tuple[Float[Tensor, 'batch elements channels']]
|
Model output dataclass or single-item tuple. |
Source code in models/layout-flow/src/layout_flow/modeling_layout_flow.py
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 | |
pipeline_layout_flow ¶
Diffusers pipeline for LayoutFlow inference.
OutputType ¶
Bases: StrEnum
Pipeline output containers supported by LayoutFlow.
Source code in models/layout-flow/src/layout_flow/pipeline_layout_flow.py
30 31 32 33 34 | |
LayoutFlowPipeline ¶
Bases: DiffusionPipeline
Generate layouts with a converted LayoutFlow checkpoint.
Source code in models/layout-flow/src/layout_flow/pipeline_layout_flow.py
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 | |
__init__ ¶
__init__(
model: LayoutFlowTransformerModel,
scheduler: LayoutFlowEulerScheduler,
config: LayoutFlowConfig,
processor: LayoutFlowProcessor | None = None,
) -> None
Create a LayoutFlow pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
LayoutFlowTransformerModel
|
Converted LayoutFlow transformer model. |
required |
scheduler
|
LayoutFlowEulerScheduler
|
Increasing-time Euler scheduler. |
required |
config
|
LayoutFlowConfig
|
Pipeline configuration. |
required |
processor
|
LayoutFlowProcessor | None
|
Optional input/output processor. |
None
|
Source code in models/layout-flow/src/layout_flow/pipeline_layout_flow.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | |
__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 = "xywh",
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
num_inference_steps: int | None = None,
guidance_scale: float = 0.0,
output_type: OutputType | str = "dataclass",
return_intermediates: bool = False,
) -> (
LayoutGenerationOutput
| dict[str, Shaped[torch.Tensor, "..."]]
)
Generate layout boxes and labels.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Number of layouts to generate. |
1
|
seed
|
int | None
|
Optional seed used when |
None
|
generator
|
Generator | None
|
Optional torch random generator. |
None
|
condition_type
|
ConditionType | str
|
Public condition name or supported alias. |
unconditional
|
labels
|
Int[Tensor, 'batch elements'] | Int[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional condition labels. |
None
|
bbox
|
Float[Tensor, 'batch elements 4'] | Float[ndarray, 'batch elements 4'] | Sequence[ArrayLikeInput] | None
|
Optional condition boxes. |
None
|
mask
|
Bool[Tensor, 'batch elements'] | Bool[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional valid-element mask. |
None
|
num_elements
|
int | list[int] | Int[Tensor, 'batch'] | None
|
Optional element counts for unconditional masks. |
None
|
box_format
|
BoxFormat | str
|
Input and output box format. |
'xywh'
|
normalized
|
bool
|
Whether coordinates are normalized. |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size for denormalized coordinates. |
None
|
num_inference_steps
|
int | None
|
Number of Euler steps. |
None
|
guidance_scale
|
float
|
Classifier-free guidance scale. |
0.0
|
output_type
|
OutputType | str
|
|
'dataclass'
|
return_intermediates
|
bool
|
Whether to include intermediate samples. |
False
|
Returns:
| Type | Description |
|---|---|
LayoutGenerationOutput | dict[str, Shaped[Tensor, '...']]
|
Layout generation output dataclass, or a dictionary when requested. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> pipe = LayoutFlowPipeline(
... model=LayoutFlowTransformerModel(
... num_labels=6, latent_dim=8, d_model=16, nhead=4,
... dim_feedforward=32, num_layers=1
... ),
... scheduler=LayoutFlowEulerScheduler(num_inference_steps=2),
... config=LayoutFlowConfig(max_length=2, latent_dim=8, d_model=16),
... )
>>> out = pipe(batch_size=1, num_elements=1, seed=0, num_inference_steps=2)
>>> out.bbox.shape[-1]
4
Source code in models/layout-flow/src/layout_flow/pipeline_layout_flow.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 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 | |
save_pretrained ¶
save_pretrained(save_directory: str | Path) -> None
Save pipeline components and LayoutFlow config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_directory
|
str | Path
|
Output directory. |
required |
Source code in models/layout-flow/src/layout_flow/pipeline_layout_flow.py
216 217 218 219 220 221 222 223 | |
from_pretrained
classmethod
¶
from_pretrained(
pretrained_model_name_or_path: str | Path,
) -> LayoutFlowPipeline
Load a saved LayoutFlow pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pretrained_model_name_or_path
|
str | Path
|
Local directory or Hub id. |
required |
Returns:
| Type | Description |
|---|---|
LayoutFlowPipeline
|
Loaded LayoutFlow pipeline. |
Source code in models/layout-flow/src/layout_flow/pipeline_layout_flow.py
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | |
processing_layout_flow ¶
Input and output processing for LayoutFlow pipelines.
LayoutFlowProcessor ¶
Bases: ProcessorMixin
Prepare public layout tensors for the LayoutFlow model.
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
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 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 | |
__init__ ¶
__init__(config: LayoutFlowConfig) -> None
Create a processor for a LayoutFlow configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
LayoutFlowConfig
|
LayoutFlow pipeline configuration. |
required |
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
35 36 37 38 39 40 41 42 43 44 | |
__call__ ¶
__call__(
*,
bbox: Float[Tensor, "batch elements 4"]
| Float[ndarray, "batch elements 4"]
| Sequence[ArrayLikeInput]
| None = None,
labels: Int[Tensor, "batch elements"]
| Int[ndarray, "batch elements"]
| 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,
batch_size: int = 1,
box_format: BoxFormat | str = "xywh",
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
device: device | str | None = None,
) -> dict[str, Shaped[torch.Tensor, "..."]]
Convert public inputs into padded model-ready tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'batch elements 4'] | Float[ndarray, 'batch elements 4'] | Sequence[ArrayLikeInput] | None
|
Optional boxes in the requested |
None
|
labels
|
Int[Tensor, 'batch elements'] | Int[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional dataset-local label ids. |
None
|
mask
|
Bool[Tensor, 'batch elements'] | Bool[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional valid-element mask. |
None
|
num_elements
|
int | list[int] | Int[Tensor, 'batch'] | None
|
Optional element counts used when |
None
|
batch_size
|
int
|
Batch size used when tensors are omitted. |
1
|
box_format
|
BoxFormat | str
|
Format of |
'xywh'
|
normalized
|
bool
|
Whether |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size required for denormalized boxes. |
None
|
device
|
device | str | None
|
Target torch device. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
Dictionary with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If denormalized boxes are missing |
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
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 | |
encode_labels ¶
encode_labels(
labels: Int[Tensor, "batch elements"],
) -> Float[torch.Tensor, "batch elements bits"]
Encode integer labels as analog-bit vectors.
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
139 140 141 142 143 144 145 146 | |
decode_labels ¶
decode_labels(
bits: Float[Tensor, "batch elements bits"],
) -> Int[torch.Tensor, "batch elements"]
Decode analog-bit vectors into integer labels.
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
148 149 150 151 152 153 154 155 156 | |
model_state ¶
model_state(
bbox: Float[Tensor, "batch elements 4"],
labels: Int[Tensor, "batch elements"],
) -> Float[torch.Tensor, "batch elements channels"]
Concatenate normalized boxes and analog-bit labels.
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
158 159 160 161 162 163 164 | |
preprocess_state ¶
preprocess_state(
state: Float[Tensor, "batch elements channels"],
*,
reverse: bool = False,
) -> Float[torch.Tensor, "batch elements channels"]
Map between public [0, 1] state and model distribution range.
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
166 167 168 169 170 171 172 173 174 175 | |
make_condition_mask ¶
make_condition_mask(
condition_type: ConditionType,
*,
mask: Bool[Tensor, "batch elements"],
generator: Generator | None = None,
) -> Int[torch.Tensor, "batch elements channels"]
Create the condition mask for a conditioning mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
condition_type
|
ConditionType
|
Canonical condition or alias. |
required |
mask
|
Bool[Tensor, 'batch elements']
|
Valid-element mask. |
required |
generator
|
Generator | None
|
Optional generator used by completion masking. |
None
|
Returns:
| Type | Description |
|---|---|
Int[Tensor, 'batch elements channels']
|
Long tensor where |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the condition type is unsupported. |
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
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 | |
postprocess ¶
postprocess(
state: Float[Tensor, "batch elements channels"],
*,
mask: Bool[Tensor, "batch elements"],
box_format: BoxFormat | str = "xywh",
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
) -> dict[str, Shaped[torch.Tensor, "..."]]
Convert model state back to public layout tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
Float[Tensor, 'batch elements channels']
|
Model state tensor. |
required |
mask
|
Bool[Tensor, 'batch elements']
|
Valid-element mask. |
required |
box_format
|
BoxFormat | str
|
Requested output box format. |
'xywh'
|
normalized
|
bool
|
Whether to return normalized coordinates. |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size for denormalized coordinates. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
Dictionary with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If denormalized output is requested without
|
Source code in models/layout-flow/src/layout_flow/processing_layout_flow.py
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 | |
sampling ¶
Initial-state sampling helpers for LayoutFlow.
InitialDistribution ¶
Bases: StrEnum
Supported initial-state distributions.
Source code in models/layout-flow/src/layout_flow/sampling.py
14 15 16 17 18 | |
sample_initial_state ¶
sample_initial_state(
*,
batch_size: int,
max_length: int,
lengths: Int[Tensor, "batch"],
dim: int,
distribution: InitialDistribution | str = "gaussian",
generator: Generator | None = None,
device: device | str | None = None,
dtype: dtype = torch.float32,
) -> Float[torch.Tensor, "batch elements channels"]
Sample a padded initial LayoutFlow state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Number of layouts. |
required |
max_length
|
int
|
Maximum number of elements per layout. |
required |
lengths
|
Int[Tensor, 'batch']
|
Valid element counts. |
required |
dim
|
int
|
Per-element state dimension. |
required |
distribution
|
InitialDistribution | str
|
Initial sampling distribution. |
'gaussian'
|
generator
|
Generator | None
|
Optional torch random generator. |
None
|
device
|
device | str | None
|
Target torch device. |
None
|
dtype
|
dtype
|
Target tensor dtype. |
float32
|
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'batch elements channels']
|
Initial state tensor with padded elements zeroed. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> lengths = torch.tensor([1])
>>> sample_initial_state(batch_size=1, max_length=2, lengths=lengths, dim=3).shape
torch.Size([1, 2, 3])
Source code in models/layout-flow/src/layout_flow/sampling.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 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 | |
scheduling_layout_flow ¶
Euler scheduler for LayoutFlow flow-matching inference.
LayoutFlowSchedulerOutput
dataclass
¶
Bases: BaseOutput
Output of one LayoutFlow Euler scheduler step.
Source code in models/layout-flow/src/layout_flow/scheduling_layout_flow.py
15 16 17 18 19 | |
LayoutFlowEulerScheduler ¶
Bases: SchedulerMixin, ConfigMixin
Increasing-time Euler scheduler used by LayoutFlow.
Source code in models/layout-flow/src/layout_flow/scheduling_layout_flow.py
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 | |
__init__ ¶
__init__(
num_inference_steps: int = 100,
start: float = 0.0,
end: float = 1.0,
) -> None
Initialize the scheduler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_inference_steps
|
int
|
Number of Euler steps. |
100
|
start
|
float
|
Initial integration time. |
0.0
|
end
|
float
|
Final integration time. |
1.0
|
Source code in models/layout-flow/src/layout_flow/scheduling_layout_flow.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | |
set_timesteps ¶
set_timesteps(
num_inference_steps: int | None = None,
*,
device: device | str | None = None,
start: float | None = None,
end: float | None = None,
) -> None
Set the integration timesteps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_inference_steps
|
int | None
|
Optional number of inference steps. |
None
|
device
|
device | str | None
|
Optional target device. |
None
|
start
|
float | None
|
Optional start time. |
None
|
end
|
float | None
|
Optional end time. |
None
|
Source code in models/layout-flow/src/layout_flow/scheduling_layout_flow.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | |
scale_model_input ¶
scale_model_input(
sample: Float[Tensor, "batch elements channels"],
timestep: Float[Tensor, ""]
| Float[Tensor, "batch"]
| float,
) -> Float[torch.Tensor, "batch elements channels"]
Return the sample unchanged for Diffusers scheduler compatibility.
Source code in models/layout-flow/src/layout_flow/scheduling_layout_flow.py
65 66 67 68 69 70 71 72 | |
step ¶
step(
model_output: Float[Tensor, "batch elements channels"],
timestep: Float[Tensor, ""]
| Float[Tensor, "batch"]
| float,
sample: Float[Tensor, "batch elements channels"],
*,
next_timestep: Float[Tensor, ""]
| Float[Tensor, "batch"]
| float
| None = None,
return_dict: Literal[True] = True,
) -> LayoutFlowSchedulerOutput
step(
model_output: Float[Tensor, "batch elements channels"],
timestep: Float[Tensor, ""]
| Float[Tensor, "batch"]
| float,
sample: Float[Tensor, "batch elements channels"],
*,
next_timestep: Float[Tensor, ""]
| Float[Tensor, "batch"]
| float
| None = None,
return_dict: Literal[False],
) -> tuple[Float[torch.Tensor, "batch elements channels"]]
step(
model_output: Float[Tensor, "batch elements channels"],
timestep: Float[Tensor, ""]
| Float[Tensor, "batch"]
| float,
sample: Float[Tensor, "batch elements channels"],
*,
next_timestep: Float[Tensor, ""]
| Float[Tensor, "batch"]
| float
| None = None,
return_dict: bool = True,
) -> (
LayoutFlowSchedulerOutput
| tuple[Float[torch.Tensor, "batch elements channels"]]
)
Advance the sample with one Euler step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_output
|
Float[Tensor, 'batch elements channels']
|
Predicted vector field. |
required |
timestep
|
Float[Tensor, ''] | Float[Tensor, 'batch'] | float
|
Current integration time. |
required |
sample
|
Float[Tensor, 'batch elements channels']
|
Current sample state. |
required |
next_timestep
|
Float[Tensor, ''] | Float[Tensor, 'batch'] | float | None
|
Optional next integration time. |
None
|
return_dict
|
bool
|
Whether to return a scheduler output dataclass. |
True
|
Returns:
| Type | Description |
|---|---|
LayoutFlowSchedulerOutput | tuple[Float[Tensor, 'batch elements channels']]
|
Scheduler output dataclass or single-item tuple. |
Source code in models/layout-flow/src/layout_flow/scheduling_layout_flow.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 | |
training ¶
Training entry points for LayoutFlow.
config ¶
Configuration enums for LayoutFlow training.
LayoutFlowTrainingDatasetName
module-attribute
¶
LayoutFlowTrainingDatasetName: TypeAlias = Literal[
"rico25", "publaynet"
]
Dataset names supported by package-local LayoutFlow training data.
LayoutFlowTrainingSplit
module-attribute
¶
LayoutFlowTrainingSplit: TypeAlias = Literal[
"train", "validation", "test"
]
HDF5 split names supported by package-local LayoutFlow training data.
LayoutFlowTrainingScheduler
module-attribute
¶
LayoutFlowTrainingScheduler: TypeAlias = Literal[
"reduce_on_plateau"
]
Scheduler names supported by package-local LayoutFlow training.
LayoutFlowConditionPolicy
module-attribute
¶
LayoutFlowConditionPolicy: TypeAlias = Literal['random4']
Condition-mask policy names supported by package-local LayoutFlow training.
LayoutFlowSeedMode ¶
Bases: StrEnum
Seed modes for regular and deterministic LayoutFlow training.
Source code in models/layout-flow/src/layout_flow/training/config.py
22 23 24 25 26 | |
datamodule ¶
LightningDataModule for LayoutFlow training.
LayoutFlowDataModule ¶
Bases: LightningDataModule
Package-local LightningDataModule for LayoutFlow HDF5 data.
Source code in models/layout-flow/src/layout_flow/training/datamodule.py
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 | |
__init__ ¶
__init__(
*,
data_path: str | Path,
dataset_name: LayoutFlowTrainingDatasetName = "publaynet",
batch_size: int = 256,
max_length: int = 20,
num_workers: int = 4,
box_format: BoxFormat | str = BoxFormat.xywh,
lex_order: bool = False,
permute_elements: bool = False,
inoue_split: bool = False,
) -> None
Initialize datamodule settings.
Source code in models/layout-flow/src/layout_flow/training/datamodule.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | |
setup ¶
setup(stage: str | None = None) -> None
Open datasets for the requested stage.
Source code in models/layout-flow/src/layout_flow/training/datamodule.py
49 50 51 52 53 54 55 | |
train_dataloader ¶
train_dataloader() -> DataLoader[
dict[str, Shaped[torch.Tensor, ...] | str]
]
Return the training dataloader.
Source code in models/layout-flow/src/layout_flow/training/datamodule.py
57 58 59 60 61 62 63 | |
val_dataloader ¶
val_dataloader() -> DataLoader[
dict[str, Shaped[torch.Tensor, ...] | str]
]
Return the validation dataloader.
Source code in models/layout-flow/src/layout_flow/training/datamodule.py
65 66 67 68 69 70 71 | |
test_dataloader ¶
test_dataloader() -> DataLoader[
dict[str, Shaped[torch.Tensor, ...] | str]
]
Return the test dataloader.
Source code in models/layout-flow/src/layout_flow/training/datamodule.py
73 74 75 76 77 78 79 | |
dataset ¶
HDF5 dataset and collation helpers for LayoutFlow training.
LayoutFlowH5Dataset ¶
Bases: Dataset[dict[str, Shaped[Tensor, '...'] | str]]
HDF5 dataset for LayoutFlow training.
Source code in models/layout-flow/src/layout_flow/training/dataset.py
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 | |
__init__ ¶
__init__(
*,
data_path: str | Path,
dataset_name: LayoutFlowTrainingDatasetName,
split: LayoutFlowTrainingSplit = "train",
lex_order: bool = False,
permute_elements: bool = False,
inoue_split: bool = False,
) -> None
Open one LayoutFlow HDF5 split.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data_path
|
str | Path
|
Directory containing LayoutFlow HDF5 files. |
required |
dataset_name
|
LayoutFlowTrainingDatasetName
|
|
required |
split
|
LayoutFlowTrainingSplit
|
|
'train'
|
lex_order
|
bool
|
Whether to use lexical-order files. |
False
|
permute_elements
|
bool
|
Whether to permute elements at access time. |
False
|
inoue_split
|
bool
|
Whether PubLayNet uses Inoue split filenames. |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the dataset or split is unsupported. |
FileNotFoundError
|
If the expected HDF5 file is absent. |
Source code in models/layout-flow/src/layout_flow/training/dataset.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 | |
__len__ ¶
__len__() -> int
Return dataset size.
Source code in models/layout-flow/src/layout_flow/training/dataset.py
74 75 76 | |
__getitem__ ¶
__getitem__(
index: int,
) -> dict[str, Shaped[torch.Tensor, "..."] | str]
Return a raw sample from the HDF5 file.
Source code in models/layout-flow/src/layout_flow/training/dataset.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 | |
collate_layout_flow_batch ¶
collate_layout_flow_batch(
batch: Sequence[dict[str, Shaped[Tensor, "..."] | str]],
*,
max_length: int | None = None,
box_format: BoxFormat | str = BoxFormat.xywh,
) -> dict[str, Shaped[torch.Tensor, "..."] | list[str]]
Collate LayoutFlow samples with fixed-length padding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
Sequence[dict[str, Shaped[Tensor, '...'] | str]]
|
Raw sample dictionaries. |
required |
max_length
|
int | None
|
Optional fixed maximum sequence length. |
None
|
box_format
|
BoxFormat | str
|
Output box format. |
xywh
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...'] | list[str]]
|
Collated batch with |
dict[str, Shaped[Tensor, '...'] | list[str]]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If box format is unsupported. |
Examples:
>>> sample = {"bbox": torch.tensor([[0.0, 0.0, 0.2, 0.4]]), "type": torch.tensor([1]), "length": torch.tensor(1)}
>>> collate_layout_flow_batch([sample], max_length=2)["bbox"].shape
torch.Size([1, 2, 4])
Source code in models/layout-flow/src/layout_flow/training/dataset.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 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 | |
lightning_module ¶
PyTorch Lightning module for LayoutFlow training.
LayoutFlowTrainingModule ¶
Bases: LightningModule
Lightning training wrapper around LayoutFlowTransformerModel.
Source code in models/layout-flow/src/layout_flow/training/lightning_module.py
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 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 | |
__init__ ¶
__init__(
*,
config: LayoutFlowConfig,
model: LayoutFlowTransformerModel | None = None,
learning_rate: float = 0.0005,
scheduler: LayoutFlowTrainingScheduler
| None = "reduce_on_plateau",
condition_policy: LayoutFlowConditionPolicy = "random4",
geom_l1_weight: float = 0.2,
seed_mode: LayoutFlowSeedMode
| str = LayoutFlowSeedMode.default,
fid_calc_every_n: int = 20,
) -> None
Initialize LayoutFlow training state.
Source code in models/layout-flow/src/layout_flow/training/lightning_module.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 | |
configure_optimizers ¶
configure_optimizers() -> OptimizerLRScheduler
Return AdamW and optional ReduceLROnPlateau.
Source code in models/layout-flow/src/layout_flow/training/lightning_module.py
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | |
forward ¶
forward(
xt: Float[Tensor, "batch elements channels"],
cond_mask: Int[Tensor, "batch elements channels"],
timestep: Float[Tensor, "batch"],
) -> Float[torch.Tensor, "batch elements channels"]
Predict the vector field for LayoutFlow training.
Source code in models/layout-flow/src/layout_flow/training/lightning_module.py
81 82 83 84 85 86 87 88 | |
training_step ¶
training_step(
batch: dict[str, Shaped[Tensor, "..."]], batch_idx: int
) -> Float[torch.Tensor, ""]
Run one LayoutFlow training step.
Source code in models/layout-flow/src/layout_flow/training/lightning_module.py
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 | |
get_start_end ¶
get_start_end(
batch: dict[str, Shaped[Tensor, "..."]],
) -> tuple[
Float[torch.Tensor, "batch elements channels"],
Float[torch.Tensor, "batch elements channels"],
]
Return sampled x0 and preprocessed data sample x1.
Source code in models/layout-flow/src/layout_flow/training/lightning_module.py
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 | |
sample_t ¶
sample_t(
x0: Float[Tensor, "batch elements channels"],
) -> Float[torch.Tensor, "batch"]
Sample uniform training times.
Source code in models/layout-flow/src/layout_flow/training/lightning_module.py
157 158 159 160 161 | |
sample_xt ¶
sample_xt(
batch: dict[str, Shaped[Tensor, "..."]],
x0: Float[Tensor, "batch elements channels"],
x1: Float[Tensor, "batch elements channels"],
cond_mask: Int[Tensor, "batch elements channels"],
t: Float[Tensor, "batch"],
) -> tuple[
Float[torch.Tensor, "batch elements channels"],
Float[torch.Tensor, "batch elements channels"],
]
Return linear x_t and vector field u_t.
Source code in models/layout-flow/src/layout_flow/training/lightning_module.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | |
random4_condition_mask ¶
random4_condition_mask(
lengths: Int[Tensor, "batch"], seq_len: int
) -> Int[torch.Tensor, "batch elements channels"]
Return the random4 condition mask.
Source code in models/layout-flow/src/layout_flow/training/lightning_module.py
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |
losses ¶
Loss functions for LayoutFlow training parity.
layout_flow_losses ¶
layout_flow_losses(
cond_mask: Float[Tensor, "batch elements channels"],
ut: Float[Tensor, "batch elements channels"],
vt: Float[Tensor, "batch elements channels"],
*,
geom_dim: int = 4,
geom_l1_weight: float = 0.2,
) -> dict[str, Float[torch.Tensor, ""]]
Compute the LayoutFlow training losses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cond_mask
|
Float[Tensor, 'batch elements channels']
|
Condition mask where |
required |
ut
|
Float[Tensor, 'batch elements channels']
|
Target conditional vector field. |
required |
vt
|
Float[Tensor, 'batch elements channels']
|
Predicted vector field. |
required |
geom_dim
|
int
|
Number of geometry channels. |
4
|
geom_l1_weight
|
float
|
Weight applied to the geometry L1 auxiliary loss. |
0.2
|
Returns:
| Type | Description |
|---|---|
dict[str, Float[Tensor, '']]
|
Dictionary with |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If tensor shapes are incompatible. |
Examples:
>>> x = torch.ones(1, 2, 3)
>>> out = layout_flow_losses(x, x, x, geom_dim=2)
>>> out["train_loss"].item()
0.0
Source code in models/layout-flow/src/layout_flow/training/losses.py
9 10 11 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 40 41 42 43 44 45 46 47 48 | |
parity ¶
LayoutFlow-specific initial-state and single-step package-versus-original-implementation parity helpers.
trace_layout_flow_step ¶
trace_layout_flow_step(
module: TrainingStepModule[
dict[str, Shaped[Tensor, "..."]]
],
batch: dict[str, Shaped[Tensor, "..."]],
rng_state: RNGState | None = None,
) -> StepTrace
Trace one LayoutFlow training step with the canonical trace points.
Source code in models/layout-flow/src/layout_flow/training/parity.py
36 37 38 39 40 41 42 | |
compare_layout_flow_step ¶
compare_layout_flow_step(
reference: StepTrace,
target: StepTrace,
*,
tolerance: TensorTolerance | None = None,
) -> StepReport
Perform a single-step pre-optimizer trace comparison for LayoutFlow.
Source code in models/layout-flow/src/layout_flow/training/parity.py
45 46 47 48 49 50 51 52 53 | |
compare_layout_flow_optimizer_step ¶
compare_layout_flow_optimizer_step(
reference_state: dict[str, Shaped[Tensor, "..."]],
target_state: dict[str, Shaped[Tensor, "..."]],
*,
tolerance: TensorTolerance | None = None,
) -> OptimizerStepReport
Perform a post-optimizer parameter comparison for LayoutFlow.
Source code in models/layout-flow/src/layout_flow/training/parity.py
56 57 58 59 60 61 62 63 64 | |
seed ¶
Seed policy helpers for LayoutFlow training.
apply_layout_flow_seed_mode ¶
apply_layout_flow_seed_mode(
seed_mode: LayoutFlowSeedMode | str,
*,
seed: int = 42975,
) -> None
Apply the selected LayoutFlow seed mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed_mode
|
LayoutFlowSeedMode | 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_flow_seed_mode("default", seed=1)
Source code in models/layout-flow/src/layout_flow/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 | |