Layoutdiffusion
LayoutDiffusion diffusers pipeline package.
LayoutDiffusionConfig ¶
Bases: ConfigMixin
Serializable LayoutDiffusion model, tokenizer, and scheduler settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
DatasetName | str
|
Dataset name or alias. |
rico25
|
id2label
|
dict[int | str, str] | None
|
Optional persisted dataset-local label mapping. |
None
|
vocab
|
dict[str, int] | None
|
Optional token-to-id vocabulary loaded from |
None
|
seq_length
|
int
|
Full internal token sequence length. |
121
|
max_num_elements
|
int
|
Maximum number of layout elements. |
20
|
num_coordinate_bins
|
int
|
Number of coordinate tokens. |
128
|
diffusion_steps
|
int
|
Number of training diffusion timesteps. |
200
|
noise_schedule
|
str
|
Reference diffusion schedule name. |
'gaussian_refine_pow2.5'
|
num_channels
|
int
|
OpenAI timestep embedding dimension. |
128
|
bert_config_name
|
str
|
Name of the BERT config used by the checkpoint. |
'bert-base-uncased'
|
max_position_embeddings
|
int
|
BERT position embedding count. |
512
|
hidden_size
|
int
|
Transformer hidden size. |
768
|
num_hidden_layers
|
int
|
BERT encoder layer count. |
12
|
num_attention_heads
|
int
|
Attention head count. |
12
|
intermediate_size
|
int
|
Feed-forward hidden size. |
3072
|
dropout
|
float
|
Dropout probability. |
0.1
|
training_mode
|
str
|
Reference training mode. |
'discrete'
|
vocab_size
|
int | None
|
Full vocabulary size including mask. |
None
|
refine_start_step
|
int | None
|
Dataset-specific refinement start step. |
None
|
type_start_step
|
int
|
Reference type-conditioned start step. |
160
|
element_count_prior
|
list[float] | None
|
Optional 20-entry unconditional element count prior. |
None
|
pow_num
|
float
|
Gaussian transition exponent. |
2.5
|
mul_num
|
float
|
Gaussian transition multiplier. |
12.4
|
Examples:
>>> cfg = LayoutDiffusionConfig(dataset_name="publaynet")
>>> cfg.mask_token_id == cfg.vocab_size - 1
True
Source code in models/layoutdiffusion/src/layoutdiffusion/configuration_layoutdiffusion.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 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 | |
special_token_ids
property
¶
special_token_ids: dict[str, int]
Return LayoutDiffusion special-token ids.
coordinate_token_offset
property
¶
coordinate_token_offset: int
Return the first coordinate-token id.
max_token_length
property
¶
max_token_length: int
Return the full LayoutDiffusion token sequence length.
__init__ ¶
__init__(
*,
dataset_name: DatasetName | str = DatasetName.rico25,
id2label: dict[int | str, str] | None = None,
vocab: dict[str, int] | None = None,
seq_length: int = 121,
max_num_elements: int = 20,
num_coordinate_bins: int = 128,
diffusion_steps: int = 200,
noise_schedule: str = "gaussian_refine_pow2.5",
num_channels: int = 128,
bert_config_name: str = "bert-base-uncased",
max_position_embeddings: int = 512,
hidden_size: int = 768,
num_hidden_layers: int = 12,
num_attention_heads: int = 12,
intermediate_size: int = 3072,
dropout: float = 0.1,
training_mode: str = "discrete",
vocab_size: int | None = None,
refine_start_step: int | None = None,
type_start_step: int = 160,
element_count_prior: list[float] | None = None,
pow_num: float = 2.5,
mul_num: float = 12.4,
) -> None
Initialize LayoutDiffusion configuration.
Source code in models/layoutdiffusion/src/layoutdiffusion/configuration_layoutdiffusion.py
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 | |
default_vocab ¶
default_vocab() -> dict[str, int]
Build the default LayoutDiffusion vocabulary for the dataset.
Source code in models/layoutdiffusion/src/layoutdiffusion/configuration_layoutdiffusion.py
159 160 161 162 163 164 165 166 167 | |
default_element_prior ¶
default_element_prior() -> list[float]
Return the reference unconditional element-count prior.
Source code in models/layoutdiffusion/src/layoutdiffusion/configuration_layoutdiffusion.py
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 | |
LayoutDiffusionTransformer ¶
Bases: ModelMixin, ConfigMixin
BERT-encoder denoiser for LayoutDiffusion token sequences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vocab_size
|
int
|
Full tokenizer vocabulary size including mask. |
required |
num_channels
|
int
|
OpenAI timestep embedding dimension. |
128
|
hidden_size
|
int
|
BERT hidden size. |
768
|
num_hidden_layers
|
int
|
Number of BERT encoder layers. |
12
|
num_attention_heads
|
int
|
Number of attention heads. |
12
|
intermediate_size
|
int
|
BERT feed-forward size. |
3072
|
dropout
|
float
|
Hidden dropout probability. |
0.1
|
max_position_embeddings
|
int
|
Position embedding count. |
512
|
constrained
|
str | None
|
Optional reference constraint mode. |
None
|
Examples:
>>> model = LayoutDiffusionTransformer(
... vocab_size=16, hidden_size=32, num_channels=8,
... num_hidden_layers=1, num_attention_heads=4, intermediate_size=64,
... )
>>> out = model(torch.zeros(2, 5, dtype=torch.long), torch.zeros(2, dtype=torch.long))
>>> out.logits.shape
torch.Size([2, 15, 5])
Source code in models/layoutdiffusion/src/layoutdiffusion/modeling_layoutdiffusion.py
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 | |
__init__ ¶
__init__(
*,
vocab_size: int,
num_channels: int = 128,
hidden_size: int = 768,
num_hidden_layers: int = 12,
num_attention_heads: int = 12,
intermediate_size: int = 3072,
dropout: float = 0.1,
max_position_embeddings: int = 512,
constrained: str | None = None,
) -> None
Initialize the transformer.
Source code in models/layoutdiffusion/src/layoutdiffusion/modeling_layoutdiffusion.py
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 | |
get_embeds ¶
get_embeds(
input_ids: Int[Tensor, "batch tokens"],
) -> Float[torch.Tensor, "batch tokens channels"]
Return token embeddings for parity diagnostics.
Source code in models/layoutdiffusion/src/layoutdiffusion/modeling_layoutdiffusion.py
110 111 112 113 114 | |
forward ¶
forward(
input_ids: Int[Tensor, "batch tokens"],
timesteps: Int[Tensor, "batch"],
condition_ids: Int[Tensor, "batch tokens"]
| None = None,
condition_type: str | None = None,
return_dict: bool = True,
) -> (
LayoutDiffusionTransformerOutput
| tuple[Float[torch.Tensor, "batch vocab tokens"]]
)
Predict start-token logits for a reverse diffusion step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_ids
|
Int[Tensor, 'batch tokens']
|
Current token ids shaped |
required |
timesteps
|
Int[Tensor, 'batch']
|
Diffusion timestep per batch item. |
required |
condition_ids
|
Int[Tensor, 'batch tokens'] | None
|
Optional internal condition token ids. |
None
|
condition_type
|
str | None
|
Optional condition mode. |
None
|
return_dict
|
bool
|
Whether to return a dataclass output. |
True
|
Returns:
| Type | Description |
|---|---|
LayoutDiffusionTransformerOutput | tuple[Float[Tensor, 'batch vocab tokens']]
|
Logits shaped |
Source code in models/layoutdiffusion/src/layoutdiffusion/modeling_layoutdiffusion.py
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 | |
LayoutDiffusionPipeline ¶
Bases: DiffusionPipeline
Generate layouts with a converted LayoutDiffusion pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transformer
|
LayoutDiffusionTransformer
|
LayoutDiffusion transformer denoiser. |
required |
scheduler
|
LayoutDiffusionScheduler
|
Categorical diffusion scheduler. |
required |
tokenizer
|
LayoutDiffusionTokenizer
|
LayoutDiffusion layout tokenizer. |
required |
processor
|
LayoutDiffusionProcessor | None
|
Optional processor. |
None
|
Examples:
>>> from layoutdiffusion import LayoutDiffusionConfig, LayoutDiffusionTokenizer
>>> from layoutdiffusion import LayoutDiffusionScheduler, LayoutDiffusionTransformer
>>> from layoutdiffusion.sampling import LayoutDiffusionSamplingConfig
>>> cfg = LayoutDiffusionConfig(dataset_name="publaynet", hidden_size=32, num_hidden_layers=1, num_attention_heads=4, intermediate_size=64, num_channels=8)
>>> tok = LayoutDiffusionTokenizer(cfg)
>>> pipe = LayoutDiffusionPipeline(
... LayoutDiffusionTransformer(vocab_size=cfg.vocab_size, hidden_size=32, num_hidden_layers=1, num_attention_heads=4, intermediate_size=64, num_channels=8),
... LayoutDiffusionScheduler(vocab_size=cfg.vocab_size, mask_token_id=cfg.mask_token_id, type_classes=cfg.type_classes, num_train_timesteps=2),
... tok,
... )
>>> pipe(batch_size=1, seed=0, sampling=LayoutDiffusionSamplingConfig(num_inference_steps=1)).bbox.shape[-1]
4
Source code in models/layoutdiffusion/src/layoutdiffusion/pipeline_layoutdiffusion.py
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 | |
__init__ ¶
__init__(
transformer: LayoutDiffusionTransformer,
scheduler: LayoutDiffusionScheduler,
tokenizer: LayoutDiffusionTokenizer,
processor: LayoutDiffusionProcessor | None = None,
) -> None
Initialize and register pipeline modules.
Source code in models/layoutdiffusion/src/layoutdiffusion/pipeline_layoutdiffusion.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
__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,
output_type: Literal["dataclass", "dict"] = "dataclass",
return_intermediates: bool = False,
sampling: LayoutDiffusionSamplingConfig,
**model_kwargs: str | int | float | bool | None,
) -> LayoutGenerationOutput | LayoutDiffusionOutputDict
Run LayoutDiffusion generation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Number of layouts for unconditional generation. |
1
|
seed
|
int | None
|
Seed used only when |
None
|
generator
|
Generator | None
|
Optional torch generator. Takes precedence over |
None
|
condition_type
|
ConditionType | str
|
Canonical condition type or supported alias. |
unconditional
|
labels
|
Int[Tensor, 'batch elements'] | Int[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional conditional labels. |
None
|
bbox
|
Float[Tensor, 'batch elements 4'] | Float[ndarray, 'batch elements 4'] | Sequence[ArrayLikeInput] | None
|
Optional conditional boxes. |
None
|
mask
|
Bool[Tensor, 'batch elements'] | Bool[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional conditional valid mask. |
None
|
num_elements
|
int | list[int] | Int[Tensor, 'batch'] | None
|
Optional element counts. |
None
|
box_format
|
BoxFormat | str
|
Input box format. |
xywh
|
normalized
|
bool
|
Whether conditional boxes are normalized. |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size for unnormalized inputs. |
None
|
num_inference_steps
|
int | None
|
Optional shortened inference steps. |
None
|
output_type
|
Literal['dataclass', 'dict']
|
|
'dataclass'
|
return_intermediates
|
bool
|
Whether to include trajectories. |
False
|
sampling
|
LayoutDiffusionSamplingConfig
|
Sampling config. |
required |
**model_kwargs
|
str | int | float | bool | None
|
Reserved compatibility kwargs. |
{}
|
Returns:
| Type | Description |
|---|---|
LayoutGenerationOutput | LayoutDiffusionOutputDict
|
Layout output dataclass or dictionary. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in models/layoutdiffusion/src/layoutdiffusion/pipeline_layoutdiffusion.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 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 | |
save_pretrained ¶
save_pretrained(
save_directory: str | Path,
**kwargs: LayoutDiffusionPipelineKwarg,
) -> None
Save a Diffusers pipeline directory.
Source code in models/layoutdiffusion/src/layoutdiffusion/pipeline_layoutdiffusion.py
275 276 277 278 279 | |
from_pretrained
classmethod
¶
from_pretrained(
pretrained_model_name_or_path: str | Path,
**kwargs: LayoutDiffusionPipelineKwarg,
) -> "LayoutDiffusionPipeline"
Load a LayoutDiffusion pipeline and rebuild its processor.
Source code in models/layoutdiffusion/src/layoutdiffusion/pipeline_layoutdiffusion.py
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
LayoutDiffusionProcessor ¶
Bases: ProcessorMixin
Normalize public layout inputs and delegate tokenization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokenizer
|
LayoutDiffusionTokenizer
|
LayoutDiffusion tokenizer. |
required |
Examples:
>>> from layoutdiffusion import LayoutDiffusionConfig, LayoutDiffusionTokenizer
>>> cfg = LayoutDiffusionConfig(dataset_name="publaynet")
>>> proc = LayoutDiffusionProcessor(LayoutDiffusionTokenizer(cfg))
>>> proc.num_elements_to_tensor(2, batch_size=1).tolist()
[2]
Source code in models/layoutdiffusion/src/layoutdiffusion/processing_layoutdiffusion.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 108 109 110 | |
__init__ ¶
__init__(tokenizer: LayoutDiffusionTokenizer) -> None
Initialize the processor.
Source code in models/layoutdiffusion/src/layoutdiffusion/processing_layoutdiffusion.py
35 36 37 | |
__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,
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 layout tensors for conditional generation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'batch elements 4'] | Float[ndarray, 'batch elements 4'] | Sequence[ArrayLikeInput] | None
|
Optional layout boxes. |
None
|
labels
|
Int[Tensor, 'batch elements'] | Int[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional labels. |
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. |
None
|
box_format
|
BoxFormat | str
|
Format of |
xywh
|
normalized
|
bool
|
Whether |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size. |
None
|
return_tensors
|
Literal['pt']
|
Only |
'pt'
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
Tokenizer output or element-count tensor. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If required conditional tensors are missing. |
Source code in models/layoutdiffusion/src/layoutdiffusion/processing_layoutdiffusion.py
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 | |
num_elements_to_tensor ¶
num_elements_to_tensor(
num_elements: int
| list[int]
| Int[Tensor, "batch"]
| None,
*,
batch_size: int,
) -> Int[torch.Tensor, "batch"] | None
Convert public element counts to a tensor.
Source code in models/layoutdiffusion/src/layoutdiffusion/processing_layoutdiffusion.py
98 99 100 101 102 103 104 105 106 107 108 109 110 | |
LayoutDiffusionScheduler ¶
Bases: SchedulerMixin, ConfigMixin
Diffusers scheduler for LayoutDiffusion categorical transitions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_train_timesteps
|
int
|
Number of training diffusion steps. |
200
|
vocab_size
|
int
|
Full vocabulary size including mask. |
required |
mask_token_id
|
int
|
Mask token id. |
required |
type_classes
|
int
|
Number of label/type classes. |
required |
num_special_tokens
|
int
|
Number of leading special tokens. |
5
|
num_coordinate_bins
|
int
|
Coordinate vocabulary size. |
128
|
noise_schedule
|
str
|
Reference schedule name. |
'gaussian_refine_pow2.5'
|
pow_num
|
float
|
Gaussian transition exponent. |
2.5
|
mul_num
|
float
|
Gaussian transition multiplier. |
12.4
|
type_start_step
|
int
|
Label-conditioned start step. |
160
|
rico_refine_start_step
|
int
|
RICO refinement start step. |
50
|
publaynet_refine_start_step
|
int
|
PubLayNet refinement start step. |
60
|
Examples:
>>> scheduler = LayoutDiffusionScheduler(vocab_size=139, mask_token_id=138, type_classes=5)
>>> scheduler.q_mats.shape[-2:]
torch.Size([128, 128])
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.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 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 | |
__init__ ¶
__init__(
*,
num_train_timesteps: int = 200,
vocab_size: int,
mask_token_id: int,
type_classes: int,
num_special_tokens: int = 5,
num_coordinate_bins: int = 128,
noise_schedule: str = "gaussian_refine_pow2.5",
pow_num: float = 2.5,
mul_num: float = 12.4,
type_start_step: int = 160,
rico_refine_start_step: int = 50,
publaynet_refine_start_step: int = 60,
) -> None
Initialize scheduler buffers.
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.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 | |
from_layout_config
classmethod
¶
from_layout_config(
config: LayoutDiffusionConfig,
) -> LayoutDiffusionScheduler
Build a scheduler from serialized LayoutDiffusion settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
LayoutDiffusionConfig
|
LayoutDiffusion model/tokenizer/scheduler settings. |
required |
Returns:
| Type | Description |
|---|---|
LayoutDiffusionScheduler
|
A scheduler initialized with the config's diffusion parameters. |
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
set_timesteps ¶
set_timesteps(
num_inference_steps: int | None = None,
*,
start_step: int | None = None,
device: device | None = None,
) -> None
Set reverse diffusion timesteps.
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
120 121 122 123 124 125 126 127 128 129 130 131 132 133 | |
predict_start ¶
predict_start(
logits: Float[
Tensor, "batch vocab_without_mask tokens"
],
batch_size: int,
seq_length: int,
) -> Float[torch.Tensor, "batch vocab tokens"]
Append the fixed mask logit and clamp model log probabilities.
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | |
q_pred_one_timestep ¶
q_pred_one_timestep(
log_x_t: Float[Tensor, "batch vocab tokens"],
t: Int[Tensor, "batch"],
) -> Float[torch.Tensor, "batch vocab tokens"]
Compute q(x_t | x_{t-1}).
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
151 152 153 154 155 156 157 158 | |
q_pred ¶
q_pred(
log_x_start: Float[Tensor, "batch vocab tokens"],
t: Int[Tensor, "batch"],
) -> Float[torch.Tensor, "batch vocab tokens"]
Compute cumulative q(x_t | x_0).
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
160 161 162 163 164 165 166 167 168 | |
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 p_theta(x_{t-1} | x_t) from predicted start logits.
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
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 | |
step ¶
step(
logits: Float[
Tensor, "batch vocab_without_mask tokens"
],
timestep: Int[Tensor, "batch"],
sample: Float[Tensor, "batch vocab tokens"],
*,
sampling: LayoutDiffusionSamplingConfig,
condition: LayoutDiffusionCondition | None = None,
generator: Generator | None = None,
) -> LayoutDiffusionSchedulerOutput
Run one reverse diffusion step.
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | |
log_sample_categorical ¶
log_sample_categorical(
logits: Float[Tensor, "batch vocab tokens"],
*,
generator: Generator | None = None,
) -> Float[torch.Tensor, "batch vocab tokens"]
Sample log one-hot categorical tokens with Gumbel-max.
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
245 246 247 248 249 250 251 252 253 | |
LayoutDiffusionTokenizer ¶
Bases: PreTrainedTokenizer
Tokenizer backed by the original LayoutDiffusion vocab.json.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
LayoutDiffusionConfig | Mapping[str, LayoutDiffusionConfigValue] | None
|
LayoutDiffusion config or serialized config mapping. |
None
|
vocab_file
|
str | Path | None
|
Optional saved vocabulary file. |
None
|
layout_config_file
|
str | Path | None
|
Optional saved layout config file. |
None
|
**kwargs
|
LayoutDiffusionConfigValue
|
Extra |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If required tokenizer files are absent. |
Examples:
>>> tok = LayoutDiffusionTokenizer(
... LayoutDiffusionConfig(dataset_name="publaynet")
... )
>>> tok.mask_token
'MASK'
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.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 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 | |
__init__ ¶
__init__(
config: LayoutDiffusionConfig
| Mapping[str, LayoutDiffusionConfigValue]
| None = None,
*,
vocab_file: str | Path | None = None,
layout_config_file: str | Path | None = None,
**kwargs: LayoutDiffusionConfigValue,
) -> None
Initialize the tokenizer.
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
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 | |
get_vocab ¶
get_vocab() -> dict[str, int]
Return a copy of token-to-id vocabulary.
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
110 111 112 | |
convert_tokens_to_string ¶
convert_tokens_to_string(tokens: list[str]) -> str
Join LayoutDiffusion tokens for debugging or parity fixtures.
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
127 128 129 | |
__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,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
) -> dict[str, Shaped[torch.Tensor, ...]]
Encode layout tensors into token ids.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'batch elements 4'] | Sequence[ArrayLikeInput]
|
Layout boxes. |
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
|
box_format
|
BoxFormat | str
|
Format of |
xywh
|
normalized
|
bool
|
Whether boxes are already normalized. |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size for unnormalized boxes. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, ...]]
|
Dictionary with |
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
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 | |
encode_layout ¶
encode_layout(
*,
bbox: Float[Tensor, "batch elements 4"],
labels: Int[Tensor, "batch elements"],
mask: Bool[Tensor, "batch elements"] | None = None,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
) -> dict[str, Shaped[torch.Tensor, ...]]
Encode public layout tensors into LayoutDiffusion token ids.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'batch elements 4']
|
Boxes shaped |
required |
labels
|
Int[Tensor, 'batch elements']
|
Labels shaped |
required |
mask
|
Bool[Tensor, 'batch elements'] | None
|
Optional valid mask shaped |
None
|
box_format
|
BoxFormat | str
|
Input box format. |
xywh
|
normalized
|
bool
|
Whether input boxes are normalized. |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size when |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, ...]]
|
Encoded token tensors. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If unnormalized boxes omit |
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 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 | |
decode_layout ¶
decode_layout(
input_ids: Int[Tensor, "batch tokens"],
*,
output_box_format: Literal["xywh", "ltrb"] = "xywh",
) -> dict[str, Shaped[torch.Tensor, ...]]
Decode token ids into public layout tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_ids
|
Int[Tensor, 'batch tokens']
|
Token ids shaped |
required |
output_box_format
|
Literal['xywh', 'ltrb']
|
|
'xywh'
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, ...]]
|
Dictionary with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
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 | |
build_initial_tokens ¶
build_initial_tokens(
*,
batch_size: int,
num_elements: Int[Tensor, "batch"]
| list[int]
| int
| None = None,
labels: Int[Tensor, "batch elements"] | None = None,
condition_type: str = "unconditional",
generator: Generator | None = None,
device: device | None = None,
) -> Int[torch.Tensor, "batch tokens"]
Build the LayoutDiffusion sampling start template.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Number of samples. |
required |
num_elements
|
Int[Tensor, 'batch'] | list[int] | int | None
|
Optional element counts in |
None
|
labels
|
Int[Tensor, 'batch elements'] | None
|
Optional labels for label-conditioned generation. |
None
|
condition_type
|
str
|
Canonical condition name. |
'unconditional'
|
generator
|
Generator | None
|
Optional random generator. |
None
|
device
|
device | None
|
Output device. |
None
|
Returns:
| Type | Description |
|---|---|
Int[Tensor, 'batch tokens']
|
Initial token ids shaped |
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
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 | |
token_ids_to_text ¶
token_ids_to_text(
input_ids: Int[Tensor, "batch tokens"],
) -> list[str]
Convert token ids to LayoutDiffusion text lines.
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
384 385 386 387 388 389 390 391 392 393 | |
text_to_token_ids ¶
text_to_token_ids(
lines: list[str],
) -> Int[torch.Tensor, "batch tokens"]
Convert LayoutDiffusion text lines into padded token ids.
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 | |
save_vocabulary ¶
save_vocabulary(
save_directory: str | Path,
filename_prefix: str | None = None,
) -> tuple[str, ...]
Save vocabulary and layout config files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_directory
|
str | Path
|
Target directory. |
required |
filename_prefix
|
str | None
|
Optional Transformers filename prefix. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
Saved file paths. |
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
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 | |
from_pretrained
classmethod
¶
from_pretrained(
path: str | PathLike[str],
*args: 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: LayoutDiffusionConfigValue,
) -> LayoutDiffusionTokenizer
Load tokenizer from a pipeline root or tokenizer directory.
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
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 | |
conditioning ¶
Condition normalization for LayoutDiffusion generation modes.
LayoutDiffusionCondition
dataclass
¶
Internal condition container used by the scheduler and pipeline.
Source code in models/layoutdiffusion/src/layoutdiffusion/conditioning.py
16 17 18 19 20 21 22 23 24 | |
build_condition ¶
build_condition(
tokenizer: LayoutDiffusionTokenizer,
*,
condition_type: ConditionType | str,
input_ids: Int[Tensor, "batch tokens"] | None = None,
labels: Int[Tensor, "batch elements"] | None = None,
num_elements: Int[Tensor, "batch"] | None = None,
) -> LayoutDiffusionCondition | None
Build a LayoutDiffusion condition from processed inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokenizer
|
LayoutDiffusionTokenizer
|
LayoutDiffusion tokenizer. |
required |
condition_type
|
ConditionType | str
|
Public condition type or alias. |
required |
input_ids
|
Int[Tensor, 'batch tokens'] | None
|
Optional encoded layout tokens. |
None
|
labels
|
Int[Tensor, 'batch elements'] | None
|
Optional label tensor for label conditioning. |
None
|
num_elements
|
Int[Tensor, 'batch'] | None
|
Optional element counts. |
None
|
Returns:
| Type | Description |
|---|---|
LayoutDiffusionCondition | None
|
Internal condition container or |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If a canonical mode is unsupported. |
ValueError
|
If required inputs are absent. |
Source code in models/layoutdiffusion/src/layoutdiffusion/conditioning.py
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 | |
configuration_layoutdiffusion ¶
Configuration for converted LayoutDiffusion checkpoints.
LayoutDiffusionConfig ¶
Bases: ConfigMixin
Serializable LayoutDiffusion model, tokenizer, and scheduler settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
DatasetName | str
|
Dataset name or alias. |
rico25
|
id2label
|
dict[int | str, str] | None
|
Optional persisted dataset-local label mapping. |
None
|
vocab
|
dict[str, int] | None
|
Optional token-to-id vocabulary loaded from |
None
|
seq_length
|
int
|
Full internal token sequence length. |
121
|
max_num_elements
|
int
|
Maximum number of layout elements. |
20
|
num_coordinate_bins
|
int
|
Number of coordinate tokens. |
128
|
diffusion_steps
|
int
|
Number of training diffusion timesteps. |
200
|
noise_schedule
|
str
|
Reference diffusion schedule name. |
'gaussian_refine_pow2.5'
|
num_channels
|
int
|
OpenAI timestep embedding dimension. |
128
|
bert_config_name
|
str
|
Name of the BERT config used by the checkpoint. |
'bert-base-uncased'
|
max_position_embeddings
|
int
|
BERT position embedding count. |
512
|
hidden_size
|
int
|
Transformer hidden size. |
768
|
num_hidden_layers
|
int
|
BERT encoder layer count. |
12
|
num_attention_heads
|
int
|
Attention head count. |
12
|
intermediate_size
|
int
|
Feed-forward hidden size. |
3072
|
dropout
|
float
|
Dropout probability. |
0.1
|
training_mode
|
str
|
Reference training mode. |
'discrete'
|
vocab_size
|
int | None
|
Full vocabulary size including mask. |
None
|
refine_start_step
|
int | None
|
Dataset-specific refinement start step. |
None
|
type_start_step
|
int
|
Reference type-conditioned start step. |
160
|
element_count_prior
|
list[float] | None
|
Optional 20-entry unconditional element count prior. |
None
|
pow_num
|
float
|
Gaussian transition exponent. |
2.5
|
mul_num
|
float
|
Gaussian transition multiplier. |
12.4
|
Examples:
>>> cfg = LayoutDiffusionConfig(dataset_name="publaynet")
>>> cfg.mask_token_id == cfg.vocab_size - 1
True
Source code in models/layoutdiffusion/src/layoutdiffusion/configuration_layoutdiffusion.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 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 | |
special_token_ids
property
¶
special_token_ids: dict[str, int]
Return LayoutDiffusion special-token ids.
coordinate_token_offset
property
¶
coordinate_token_offset: int
Return the first coordinate-token id.
max_token_length
property
¶
max_token_length: int
Return the full LayoutDiffusion token sequence length.
__init__ ¶
__init__(
*,
dataset_name: DatasetName | str = DatasetName.rico25,
id2label: dict[int | str, str] | None = None,
vocab: dict[str, int] | None = None,
seq_length: int = 121,
max_num_elements: int = 20,
num_coordinate_bins: int = 128,
diffusion_steps: int = 200,
noise_schedule: str = "gaussian_refine_pow2.5",
num_channels: int = 128,
bert_config_name: str = "bert-base-uncased",
max_position_embeddings: int = 512,
hidden_size: int = 768,
num_hidden_layers: int = 12,
num_attention_heads: int = 12,
intermediate_size: int = 3072,
dropout: float = 0.1,
training_mode: str = "discrete",
vocab_size: int | None = None,
refine_start_step: int | None = None,
type_start_step: int = 160,
element_count_prior: list[float] | None = None,
pow_num: float = 2.5,
mul_num: float = 12.4,
) -> None
Initialize LayoutDiffusion configuration.
Source code in models/layoutdiffusion/src/layoutdiffusion/configuration_layoutdiffusion.py
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 | |
default_vocab ¶
default_vocab() -> dict[str, int]
Build the default LayoutDiffusion vocabulary for the dataset.
Source code in models/layoutdiffusion/src/layoutdiffusion/configuration_layoutdiffusion.py
159 160 161 162 163 164 165 166 167 | |
default_element_prior ¶
default_element_prior() -> list[float]
Return the reference unconditional element-count prior.
Source code in models/layoutdiffusion/src/layoutdiffusion/configuration_layoutdiffusion.py
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 | |
conversion ¶
Conversion helpers for original LayoutDiffusion checkpoints.
find_ema_checkpoint ¶
find_ema_checkpoint(
checkpoint_dir: str | Path,
checkpoint_name: str | None = None,
) -> Path
Find an EMA checkpoint file in an original checkpoint directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
checkpoint_dir
|
str | Path
|
Original checkpoint directory. |
required |
checkpoint_name
|
str | None
|
Optional explicit checkpoint filename. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Path to the selected checkpoint. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If no checkpoint exists. |
Source code in models/layoutdiffusion/src/layoutdiffusion/conversion.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 | |
validate_checkpoint_artifacts ¶
validate_checkpoint_artifacts(
checkpoint_dir: str | Path,
) -> dict[str, Path]
Validate required original checkpoint artifacts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
checkpoint_dir
|
str | Path
|
Original checkpoint directory. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Path]
|
Mapping from artifact name to path. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If a required artifact is missing. |
Source code in models/layoutdiffusion/src/layoutdiffusion/conversion.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | |
config_from_original ¶
config_from_original(
checkpoint_dir: str | Path, *, dataset_name: str
) -> LayoutDiffusionConfig
Build LayoutDiffusionConfig from original JSON files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
checkpoint_dir
|
str | Path
|
Original checkpoint directory. |
required |
dataset_name
|
str
|
Canonical dataset name. |
required |
Returns:
| Type | Description |
|---|---|
LayoutDiffusionConfig
|
Converted configuration. |
Source code in models/layoutdiffusion/src/layoutdiffusion/conversion.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 | |
remap_transformer_state_dict ¶
remap_transformer_state_dict(
state_dict: dict[str, Shaped[Tensor, "..."]],
) -> dict[str, Shaped[torch.Tensor, "..."]]
Remap original EMA keys to the new transformer module.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dict
|
dict[str, Shaped[Tensor, '...']]
|
Original checkpoint state dict. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
Remapped state dict with |
Source code in models/layoutdiffusion/src/layoutdiffusion/conversion.py
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | |
load_original_state_dict ¶
load_original_state_dict(
checkpoint_path: str | Path,
) -> dict[str, Shaped[torch.Tensor, "..."]]
Load an original PyTorch checkpoint on CPU.
Source code in models/layoutdiffusion/src/layoutdiffusion/conversion.py
126 127 128 129 130 131 132 133 134 135 | |
labels ¶
LayoutDiffusion label vocabulary compatibility helpers.
layoutdiffusion_labels_for_dataset ¶
layoutdiffusion_labels_for_dataset(
dataset_name: DatasetName | str,
) -> tuple[str, ...]
Return LayoutDiffusion label strings in checkpoint order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
DatasetName | str
|
Dataset name or alias. |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
Ordered checkpoint label names. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the dataset is unsupported. |
Examples:
>>> layoutdiffusion_labels_for_dataset("publaynet")[0]
'text'
Source code in models/layoutdiffusion/src/layoutdiffusion/labels.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 | |
default_id2label ¶
default_id2label(
dataset_name: DatasetName | str,
) -> dict[int, str]
Return the public id-to-label mapping for LayoutDiffusion.
Source code in models/layoutdiffusion/src/layoutdiffusion/labels.py
71 72 73 | |
normalize_layoutdiffusion_label ¶
normalize_layoutdiffusion_label(label: str) -> str
Normalize public spelling to the internal vocabulary spelling.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
Label spelling from a public dataset or checkpoint. |
required |
Returns:
| Type | Description |
|---|---|
str
|
LayoutDiffusion checkpoint spelling. |
Source code in models/layoutdiffusion/src/layoutdiffusion/labels.py
76 77 78 79 80 81 82 83 84 85 | |
label_to_public_id ¶
label_to_public_id(
dataset_name: DatasetName | str, label: str
) -> int
Map a checkpoint label string to a dataset-local public id.
Source code in models/layoutdiffusion/src/layoutdiffusion/labels.py
88 89 90 91 92 | |
public_id_to_label ¶
public_id_to_label(
dataset_name: DatasetName | str, label_id: int
) -> str
Map a public dataset-local label id to a checkpoint label string.
Source code in models/layoutdiffusion/src/layoutdiffusion/labels.py
95 96 97 | |
modeling_layoutdiffusion ¶
Transformer denoiser for converted LayoutDiffusion checkpoints.
LayoutDiffusionTransformerOutput
dataclass
¶
Bases: BaseOutput
Output returned by LayoutDiffusionTransformer.
Source code in models/layoutdiffusion/src/layoutdiffusion/modeling_layoutdiffusion.py
19 20 21 22 23 | |
LayoutDiffusionTransformer ¶
Bases: ModelMixin, ConfigMixin
BERT-encoder denoiser for LayoutDiffusion token sequences.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vocab_size
|
int
|
Full tokenizer vocabulary size including mask. |
required |
num_channels
|
int
|
OpenAI timestep embedding dimension. |
128
|
hidden_size
|
int
|
BERT hidden size. |
768
|
num_hidden_layers
|
int
|
Number of BERT encoder layers. |
12
|
num_attention_heads
|
int
|
Number of attention heads. |
12
|
intermediate_size
|
int
|
BERT feed-forward size. |
3072
|
dropout
|
float
|
Hidden dropout probability. |
0.1
|
max_position_embeddings
|
int
|
Position embedding count. |
512
|
constrained
|
str | None
|
Optional reference constraint mode. |
None
|
Examples:
>>> model = LayoutDiffusionTransformer(
... vocab_size=16, hidden_size=32, num_channels=8,
... num_hidden_layers=1, num_attention_heads=4, intermediate_size=64,
... )
>>> out = model(torch.zeros(2, 5, dtype=torch.long), torch.zeros(2, dtype=torch.long))
>>> out.logits.shape
torch.Size([2, 15, 5])
Source code in models/layoutdiffusion/src/layoutdiffusion/modeling_layoutdiffusion.py
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 | |
__init__ ¶
__init__(
*,
vocab_size: int,
num_channels: int = 128,
hidden_size: int = 768,
num_hidden_layers: int = 12,
num_attention_heads: int = 12,
intermediate_size: int = 3072,
dropout: float = 0.1,
max_position_embeddings: int = 512,
constrained: str | None = None,
) -> None
Initialize the transformer.
Source code in models/layoutdiffusion/src/layoutdiffusion/modeling_layoutdiffusion.py
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 | |
get_embeds ¶
get_embeds(
input_ids: Int[Tensor, "batch tokens"],
) -> Float[torch.Tensor, "batch tokens channels"]
Return token embeddings for parity diagnostics.
Source code in models/layoutdiffusion/src/layoutdiffusion/modeling_layoutdiffusion.py
110 111 112 113 114 | |
forward ¶
forward(
input_ids: Int[Tensor, "batch tokens"],
timesteps: Int[Tensor, "batch"],
condition_ids: Int[Tensor, "batch tokens"]
| None = None,
condition_type: str | None = None,
return_dict: bool = True,
) -> (
LayoutDiffusionTransformerOutput
| tuple[Float[torch.Tensor, "batch vocab tokens"]]
)
Predict start-token logits for a reverse diffusion step.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_ids
|
Int[Tensor, 'batch tokens']
|
Current token ids shaped |
required |
timesteps
|
Int[Tensor, 'batch']
|
Diffusion timestep per batch item. |
required |
condition_ids
|
Int[Tensor, 'batch tokens'] | None
|
Optional internal condition token ids. |
None
|
condition_type
|
str | None
|
Optional condition mode. |
None
|
return_dict
|
bool
|
Whether to return a dataclass output. |
True
|
Returns:
| Type | Description |
|---|---|
LayoutDiffusionTransformerOutput | tuple[Float[Tensor, 'batch vocab tokens']]
|
Logits shaped |
Source code in models/layoutdiffusion/src/layoutdiffusion/modeling_layoutdiffusion.py
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 | |
pipeline_layoutdiffusion ¶
Diffusers pipeline for converted LayoutDiffusion checkpoints.
LayoutDiffusionOutputDict ¶
Bases: TypedDict
Dictionary form of LayoutDiffusion public output.
Source code in models/layoutdiffusion/src/layoutdiffusion/pipeline_layoutdiffusion.py
43 44 45 46 47 48 49 50 51 52 | |
LayoutDiffusionPipeline ¶
Bases: DiffusionPipeline
Generate layouts with a converted LayoutDiffusion pipeline.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
transformer
|
LayoutDiffusionTransformer
|
LayoutDiffusion transformer denoiser. |
required |
scheduler
|
LayoutDiffusionScheduler
|
Categorical diffusion scheduler. |
required |
tokenizer
|
LayoutDiffusionTokenizer
|
LayoutDiffusion layout tokenizer. |
required |
processor
|
LayoutDiffusionProcessor | None
|
Optional processor. |
None
|
Examples:
>>> from layoutdiffusion import LayoutDiffusionConfig, LayoutDiffusionTokenizer
>>> from layoutdiffusion import LayoutDiffusionScheduler, LayoutDiffusionTransformer
>>> from layoutdiffusion.sampling import LayoutDiffusionSamplingConfig
>>> cfg = LayoutDiffusionConfig(dataset_name="publaynet", hidden_size=32, num_hidden_layers=1, num_attention_heads=4, intermediate_size=64, num_channels=8)
>>> tok = LayoutDiffusionTokenizer(cfg)
>>> pipe = LayoutDiffusionPipeline(
... LayoutDiffusionTransformer(vocab_size=cfg.vocab_size, hidden_size=32, num_hidden_layers=1, num_attention_heads=4, intermediate_size=64, num_channels=8),
... LayoutDiffusionScheduler(vocab_size=cfg.vocab_size, mask_token_id=cfg.mask_token_id, type_classes=cfg.type_classes, num_train_timesteps=2),
... tok,
... )
>>> pipe(batch_size=1, seed=0, sampling=LayoutDiffusionSamplingConfig(num_inference_steps=1)).bbox.shape[-1]
4
Source code in models/layoutdiffusion/src/layoutdiffusion/pipeline_layoutdiffusion.py
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 | |
__init__ ¶
__init__(
transformer: LayoutDiffusionTransformer,
scheduler: LayoutDiffusionScheduler,
tokenizer: LayoutDiffusionTokenizer,
processor: LayoutDiffusionProcessor | None = None,
) -> None
Initialize and register pipeline modules.
Source code in models/layoutdiffusion/src/layoutdiffusion/pipeline_layoutdiffusion.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
__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,
output_type: Literal["dataclass", "dict"] = "dataclass",
return_intermediates: bool = False,
sampling: LayoutDiffusionSamplingConfig,
**model_kwargs: str | int | float | bool | None,
) -> LayoutGenerationOutput | LayoutDiffusionOutputDict
Run LayoutDiffusion generation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Number of layouts for unconditional generation. |
1
|
seed
|
int | None
|
Seed used only when |
None
|
generator
|
Generator | None
|
Optional torch generator. Takes precedence over |
None
|
condition_type
|
ConditionType | str
|
Canonical condition type or supported alias. |
unconditional
|
labels
|
Int[Tensor, 'batch elements'] | Int[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional conditional labels. |
None
|
bbox
|
Float[Tensor, 'batch elements 4'] | Float[ndarray, 'batch elements 4'] | Sequence[ArrayLikeInput] | None
|
Optional conditional boxes. |
None
|
mask
|
Bool[Tensor, 'batch elements'] | Bool[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional conditional valid mask. |
None
|
num_elements
|
int | list[int] | Int[Tensor, 'batch'] | None
|
Optional element counts. |
None
|
box_format
|
BoxFormat | str
|
Input box format. |
xywh
|
normalized
|
bool
|
Whether conditional boxes are normalized. |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size for unnormalized inputs. |
None
|
num_inference_steps
|
int | None
|
Optional shortened inference steps. |
None
|
output_type
|
Literal['dataclass', 'dict']
|
|
'dataclass'
|
return_intermediates
|
bool
|
Whether to include trajectories. |
False
|
sampling
|
LayoutDiffusionSamplingConfig
|
Sampling config. |
required |
**model_kwargs
|
str | int | float | bool | None
|
Reserved compatibility kwargs. |
{}
|
Returns:
| Type | Description |
|---|---|
LayoutGenerationOutput | LayoutDiffusionOutputDict
|
Layout output dataclass or dictionary. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in models/layoutdiffusion/src/layoutdiffusion/pipeline_layoutdiffusion.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 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 | |
save_pretrained ¶
save_pretrained(
save_directory: str | Path,
**kwargs: LayoutDiffusionPipelineKwarg,
) -> None
Save a Diffusers pipeline directory.
Source code in models/layoutdiffusion/src/layoutdiffusion/pipeline_layoutdiffusion.py
275 276 277 278 279 | |
from_pretrained
classmethod
¶
from_pretrained(
pretrained_model_name_or_path: str | Path,
**kwargs: LayoutDiffusionPipelineKwarg,
) -> "LayoutDiffusionPipeline"
Load a LayoutDiffusion pipeline and rebuild its processor.
Source code in models/layoutdiffusion/src/layoutdiffusion/pipeline_layoutdiffusion.py
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
processing_layoutdiffusion ¶
Input processor for LayoutDiffusion pipelines.
LayoutDiffusionProcessor ¶
Bases: ProcessorMixin
Normalize public layout inputs and delegate tokenization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokenizer
|
LayoutDiffusionTokenizer
|
LayoutDiffusion tokenizer. |
required |
Examples:
>>> from layoutdiffusion import LayoutDiffusionConfig, LayoutDiffusionTokenizer
>>> cfg = LayoutDiffusionConfig(dataset_name="publaynet")
>>> proc = LayoutDiffusionProcessor(LayoutDiffusionTokenizer(cfg))
>>> proc.num_elements_to_tensor(2, batch_size=1).tolist()
[2]
Source code in models/layoutdiffusion/src/layoutdiffusion/processing_layoutdiffusion.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 108 109 110 | |
__init__ ¶
__init__(tokenizer: LayoutDiffusionTokenizer) -> None
Initialize the processor.
Source code in models/layoutdiffusion/src/layoutdiffusion/processing_layoutdiffusion.py
35 36 37 | |
__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,
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 layout tensors for conditional generation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'batch elements 4'] | Float[ndarray, 'batch elements 4'] | Sequence[ArrayLikeInput] | None
|
Optional layout boxes. |
None
|
labels
|
Int[Tensor, 'batch elements'] | Int[ndarray, 'batch elements'] | Sequence[ArrayLikeInput] | None
|
Optional labels. |
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. |
None
|
box_format
|
BoxFormat | str
|
Format of |
xywh
|
normalized
|
bool
|
Whether |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size. |
None
|
return_tensors
|
Literal['pt']
|
Only |
'pt'
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
Tokenizer output or element-count tensor. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If required conditional tensors are missing. |
Source code in models/layoutdiffusion/src/layoutdiffusion/processing_layoutdiffusion.py
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 | |
num_elements_to_tensor ¶
num_elements_to_tensor(
num_elements: int
| list[int]
| Int[Tensor, "batch"]
| None,
*,
batch_size: int,
) -> Int[torch.Tensor, "batch"] | None
Convert public element counts to a tensor.
Source code in models/layoutdiffusion/src/layoutdiffusion/processing_layoutdiffusion.py
98 99 100 101 102 103 104 105 106 107 108 109 110 | |
sampling ¶
Sampling configuration for LayoutDiffusion.
LayoutDiffusionSamplingName ¶
Bases: StrEnum
Supported LayoutDiffusion sampling modes.
Source code in models/layoutdiffusion/src/layoutdiffusion/sampling.py
9 10 11 12 13 | |
LayoutDiffusionSamplingConfig
dataclass
¶
Runtime sampling options for the reverse diffusion loop.
Source code in models/layoutdiffusion/src/layoutdiffusion/sampling.py
16 17 18 19 20 21 22 23 | |
scheduling_layoutdiffusion ¶
Categorical Gaussian-refine scheduler for LayoutDiffusion.
LayoutDiffusionSchedulerOutput
dataclass
¶
Bases: BaseOutput
Output of one LayoutDiffusion scheduler step.
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
28 29 30 31 32 33 34 | |
LayoutDiffusionScheduler ¶
Bases: SchedulerMixin, ConfigMixin
Diffusers scheduler for LayoutDiffusion categorical transitions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_train_timesteps
|
int
|
Number of training diffusion steps. |
200
|
vocab_size
|
int
|
Full vocabulary size including mask. |
required |
mask_token_id
|
int
|
Mask token id. |
required |
type_classes
|
int
|
Number of label/type classes. |
required |
num_special_tokens
|
int
|
Number of leading special tokens. |
5
|
num_coordinate_bins
|
int
|
Coordinate vocabulary size. |
128
|
noise_schedule
|
str
|
Reference schedule name. |
'gaussian_refine_pow2.5'
|
pow_num
|
float
|
Gaussian transition exponent. |
2.5
|
mul_num
|
float
|
Gaussian transition multiplier. |
12.4
|
type_start_step
|
int
|
Label-conditioned start step. |
160
|
rico_refine_start_step
|
int
|
RICO refinement start step. |
50
|
publaynet_refine_start_step
|
int
|
PubLayNet refinement start step. |
60
|
Examples:
>>> scheduler = LayoutDiffusionScheduler(vocab_size=139, mask_token_id=138, type_classes=5)
>>> scheduler.q_mats.shape[-2:]
torch.Size([128, 128])
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.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 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 | |
__init__ ¶
__init__(
*,
num_train_timesteps: int = 200,
vocab_size: int,
mask_token_id: int,
type_classes: int,
num_special_tokens: int = 5,
num_coordinate_bins: int = 128,
noise_schedule: str = "gaussian_refine_pow2.5",
pow_num: float = 2.5,
mul_num: float = 12.4,
type_start_step: int = 160,
rico_refine_start_step: int = 50,
publaynet_refine_start_step: int = 60,
) -> None
Initialize scheduler buffers.
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.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 | |
from_layout_config
classmethod
¶
from_layout_config(
config: LayoutDiffusionConfig,
) -> LayoutDiffusionScheduler
Build a scheduler from serialized LayoutDiffusion settings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
LayoutDiffusionConfig
|
LayoutDiffusion model/tokenizer/scheduler settings. |
required |
Returns:
| Type | Description |
|---|---|
LayoutDiffusionScheduler
|
A scheduler initialized with the config's diffusion parameters. |
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 | |
set_timesteps ¶
set_timesteps(
num_inference_steps: int | None = None,
*,
start_step: int | None = None,
device: device | None = None,
) -> None
Set reverse diffusion timesteps.
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
120 121 122 123 124 125 126 127 128 129 130 131 132 133 | |
predict_start ¶
predict_start(
logits: Float[
Tensor, "batch vocab_without_mask tokens"
],
batch_size: int,
seq_length: int,
) -> Float[torch.Tensor, "batch vocab tokens"]
Append the fixed mask logit and clamp model log probabilities.
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | |
q_pred_one_timestep ¶
q_pred_one_timestep(
log_x_t: Float[Tensor, "batch vocab tokens"],
t: Int[Tensor, "batch"],
) -> Float[torch.Tensor, "batch vocab tokens"]
Compute q(x_t | x_{t-1}).
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
151 152 153 154 155 156 157 158 | |
q_pred ¶
q_pred(
log_x_start: Float[Tensor, "batch vocab tokens"],
t: Int[Tensor, "batch"],
) -> Float[torch.Tensor, "batch vocab tokens"]
Compute cumulative q(x_t | x_0).
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
160 161 162 163 164 165 166 167 168 | |
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 p_theta(x_{t-1} | x_t) from predicted start logits.
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
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 | |
step ¶
step(
logits: Float[
Tensor, "batch vocab_without_mask tokens"
],
timestep: Int[Tensor, "batch"],
sample: Float[Tensor, "batch vocab tokens"],
*,
sampling: LayoutDiffusionSamplingConfig,
condition: LayoutDiffusionCondition | None = None,
generator: Generator | None = None,
) -> LayoutDiffusionSchedulerOutput
Run one reverse diffusion step.
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | |
log_sample_categorical ¶
log_sample_categorical(
logits: Float[Tensor, "batch vocab tokens"],
*,
generator: Generator | None = None,
) -> Float[torch.Tensor, "batch vocab tokens"]
Sample log one-hot categorical tokens with Gumbel-max.
Source code in models/layoutdiffusion/src/layoutdiffusion/scheduling_layoutdiffusion.py
245 246 247 248 249 250 251 252 253 | |
tokenization_layoutdiffusion ¶
PreTrainedTokenizer for LayoutDiffusion layout token sequences.
LayoutDiffusionTokenizer ¶
Bases: PreTrainedTokenizer
Tokenizer backed by the original LayoutDiffusion vocab.json.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
LayoutDiffusionConfig | Mapping[str, LayoutDiffusionConfigValue] | None
|
LayoutDiffusion config or serialized config mapping. |
None
|
vocab_file
|
str | Path | None
|
Optional saved vocabulary file. |
None
|
layout_config_file
|
str | Path | None
|
Optional saved layout config file. |
None
|
**kwargs
|
LayoutDiffusionConfigValue
|
Extra |
{}
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If required tokenizer files are absent. |
Examples:
>>> tok = LayoutDiffusionTokenizer(
... LayoutDiffusionConfig(dataset_name="publaynet")
... )
>>> tok.mask_token
'MASK'
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.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 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 | |
__init__ ¶
__init__(
config: LayoutDiffusionConfig
| Mapping[str, LayoutDiffusionConfigValue]
| None = None,
*,
vocab_file: str | Path | None = None,
layout_config_file: str | Path | None = None,
**kwargs: LayoutDiffusionConfigValue,
) -> None
Initialize the tokenizer.
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
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 | |
get_vocab ¶
get_vocab() -> dict[str, int]
Return a copy of token-to-id vocabulary.
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
110 111 112 | |
convert_tokens_to_string ¶
convert_tokens_to_string(tokens: list[str]) -> str
Join LayoutDiffusion tokens for debugging or parity fixtures.
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
127 128 129 | |
__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,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
) -> dict[str, Shaped[torch.Tensor, ...]]
Encode layout tensors into token ids.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'batch elements 4'] | Sequence[ArrayLikeInput]
|
Layout boxes. |
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
|
box_format
|
BoxFormat | str
|
Format of |
xywh
|
normalized
|
bool
|
Whether boxes are already normalized. |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size for unnormalized boxes. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, ...]]
|
Dictionary with |
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
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 | |
encode_layout ¶
encode_layout(
*,
bbox: Float[Tensor, "batch elements 4"],
labels: Int[Tensor, "batch elements"],
mask: Bool[Tensor, "batch elements"] | None = None,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
) -> dict[str, Shaped[torch.Tensor, ...]]
Encode public layout tensors into LayoutDiffusion token ids.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'batch elements 4']
|
Boxes shaped |
required |
labels
|
Int[Tensor, 'batch elements']
|
Labels shaped |
required |
mask
|
Bool[Tensor, 'batch elements'] | None
|
Optional valid mask shaped |
None
|
box_format
|
BoxFormat | str
|
Input box format. |
xywh
|
normalized
|
bool
|
Whether input boxes are normalized. |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size when |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, ...]]
|
Encoded token tensors. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If unnormalized boxes omit |
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 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 | |
decode_layout ¶
decode_layout(
input_ids: Int[Tensor, "batch tokens"],
*,
output_box_format: Literal["xywh", "ltrb"] = "xywh",
) -> dict[str, Shaped[torch.Tensor, ...]]
Decode token ids into public layout tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_ids
|
Int[Tensor, 'batch tokens']
|
Token ids shaped |
required |
output_box_format
|
Literal['xywh', 'ltrb']
|
|
'xywh'
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, ...]]
|
Dictionary with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
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 | |
build_initial_tokens ¶
build_initial_tokens(
*,
batch_size: int,
num_elements: Int[Tensor, "batch"]
| list[int]
| int
| None = None,
labels: Int[Tensor, "batch elements"] | None = None,
condition_type: str = "unconditional",
generator: Generator | None = None,
device: device | None = None,
) -> Int[torch.Tensor, "batch tokens"]
Build the LayoutDiffusion sampling start template.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size
|
int
|
Number of samples. |
required |
num_elements
|
Int[Tensor, 'batch'] | list[int] | int | None
|
Optional element counts in |
None
|
labels
|
Int[Tensor, 'batch elements'] | None
|
Optional labels for label-conditioned generation. |
None
|
condition_type
|
str
|
Canonical condition name. |
'unconditional'
|
generator
|
Generator | None
|
Optional random generator. |
None
|
device
|
device | None
|
Output device. |
None
|
Returns:
| Type | Description |
|---|---|
Int[Tensor, 'batch tokens']
|
Initial token ids shaped |
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
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 | |
token_ids_to_text ¶
token_ids_to_text(
input_ids: Int[Tensor, "batch tokens"],
) -> list[str]
Convert token ids to LayoutDiffusion text lines.
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
384 385 386 387 388 389 390 391 392 393 | |
text_to_token_ids ¶
text_to_token_ids(
lines: list[str],
) -> Int[torch.Tensor, "batch tokens"]
Convert LayoutDiffusion text lines into padded token ids.
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 | |
save_vocabulary ¶
save_vocabulary(
save_directory: str | Path,
filename_prefix: str | None = None,
) -> tuple[str, ...]
Save vocabulary and layout config files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_directory
|
str | Path
|
Target directory. |
required |
filename_prefix
|
str | None
|
Optional Transformers filename prefix. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
Saved file paths. |
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
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 | |
from_pretrained
classmethod
¶
from_pretrained(
path: str | PathLike[str],
*args: 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: LayoutDiffusionConfigValue,
) -> LayoutDiffusionTokenizer
Load tokenizer from a pipeline root or tokenizer directory.
Source code in models/layoutdiffusion/src/layoutdiffusion/tokenization_layoutdiffusion.py
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 | |
training ¶
Training entry points for LayoutDiffusion.
config ¶
Configuration enums for LayoutDiffusion training.
LayoutDiffusionTrainingDatasetName
module-attribute
¶
LayoutDiffusionTrainingDatasetName: TypeAlias = Literal[
"rico25", "publaynet"
]
Dataset names supported by package-local LayoutDiffusion training data.
LayoutDiffusionTrainingDatasetSource
module-attribute
¶
LayoutDiffusionTrainingDatasetSource: TypeAlias = Literal[
"hf", "processed"
]
Dataset source modes supported by package-local LayoutDiffusion training data.
LayoutDiffusionTrainingSplit
module-attribute
¶
LayoutDiffusionTrainingSplit: TypeAlias = Literal[
"train", "validation", "test"
]
Split names supported by package-local LayoutDiffusion training data.
LayoutDiffusionTrainingTransform
module-attribute
¶
LayoutDiffusionTrainingTransform: TypeAlias = Literal[
"LexicographicOrder"
]
Training-only layout transforms supported by package-local data.
LayoutDiffusionTrainingScheduler
module-attribute
¶
LayoutDiffusionTrainingScheduler: TypeAlias = Literal[
"linear_anneal"
]
Scheduler names supported by package-local LayoutDiffusion training.
LayoutDiffusionTimeSampler
module-attribute
¶
LayoutDiffusionTimeSampler: TypeAlias = Literal[
"importance", "uniform"
]
Timestep-sampling strategies used by the categorical diffusion loss.
LayoutDiffusionSeedMode ¶
Bases: StrEnum
Seed modes for regular and deterministic LayoutDiffusion training.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/config.py
27 28 29 30 31 | |
datamodule ¶
LightningDataModule for LayoutDiffusion training.
LayoutDiffusionDataModule ¶
Bases: LightningDataModule
Package-local LightningDataModule for LayoutDiffusion data.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/datamodule.py
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 | |
__init__ ¶
__init__(
*,
dataset_name: LayoutDiffusionTrainingDatasetName = "publaynet",
config: LayoutDiffusionConfig,
batch_size: int = 64,
max_num_elements: int | None = None,
num_workers: int = 4,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
synthetic_size: int | None = None,
dataset_source: LayoutDiffusionTrainingDatasetSource = "hf",
processed_data_dir: str | None = None,
vocab_file: str | None = None,
preconsume_train_batches: int = 0,
processed_stream_rng_warmup: bool = False,
train_transforms: Sequence[
LayoutDiffusionTrainingTransform
]
| None = ("LexicographicOrder",),
) -> None
Initialize datamodule settings.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/datamodule.py
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 | |
setup ¶
setup(stage: str | None = None) -> None
Open datasets for the requested stage.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/datamodule.py
128 129 130 131 132 133 134 | |
train_dataloader ¶
train_dataloader() -> DataLoader[
dict[str, Shaped[torch.Tensor, ...] | str]
]
Return the training dataloader.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/datamodule.py
136 137 138 139 140 141 142 143 144 145 146 147 148 | |
val_dataloader ¶
val_dataloader() -> DataLoader[
dict[str, Shaped[torch.Tensor, ...] | str]
]
Return the validation dataloader.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/datamodule.py
150 151 152 153 154 155 156 | |
test_dataloader ¶
test_dataloader() -> DataLoader[
dict[str, Shaped[torch.Tensor, ...] | str]
]
Return the test dataloader.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/datamodule.py
158 159 160 161 162 163 164 | |
dataset ¶
Dataset helpers for LayoutDiffusion training.
LayoutDiffusionDataset ¶
Bases: Dataset[dict[str, Shaped[Tensor, '...'] | str]]
HF datasets-backed LayoutDiffusion training dataset.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/dataset.py
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 | |
__init__ ¶
__init__(
*,
dataset_name: LayoutDiffusionTrainingDatasetName,
config: LayoutDiffusionConfig,
split: LayoutDiffusionTrainingSplit = "train",
tokenizer: LayoutDiffusionTokenizer | None = None,
max_num_elements: int | None = None,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
lexicographic_order: bool = True,
) -> None
Load a LayoutDiffusion training split from approved HF sources.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/dataset.py
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 | |
__len__ ¶
__len__() -> int
Return dataset size.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/dataset.py
92 93 94 | |
__getitem__ ¶
__getitem__(
index: int,
) -> dict[str, Shaped[torch.Tensor, "..."] | str]
Return one tokenized training example.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/dataset.py
96 97 98 99 100 101 102 103 104 | |
LayoutDiffusionProcessedDataset ¶
Bases: Dataset[dict[str, Shaped[Tensor, '...'] | str]]
Processed LayoutDiffusion token stream used for parity reruns.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/dataset.py
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 | |
__init__ ¶
__init__(
*,
dataset_name: LayoutDiffusionTrainingDatasetName,
config: LayoutDiffusionConfig,
processed_data_dir: str | Path,
split: LayoutDiffusionTrainingSplit = "train",
tokenizer: LayoutDiffusionTokenizer | None = None,
) -> None
Load processed token ids or text lines from a local directory.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/dataset.py
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | |
__len__ ¶
__len__() -> int
Return the number of processed rows.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/dataset.py
158 159 160 | |
__getitem__ ¶
__getitem__(
index: int,
) -> dict[str, Shaped[torch.Tensor, "..."] | str]
Return one processed token row.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/dataset.py
162 163 164 165 166 167 168 169 170 | |
LayoutDiffusionSyntheticDataset ¶
Bases: Dataset[dict[str, Shaped[Tensor, '...'] | str]]
Small deterministic dataset for local LightningCLI smoke tests.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/dataset.py
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 | |
__init__ ¶
__init__(
*,
config: LayoutDiffusionConfig,
size: int = 8,
elements: int = 3,
) -> None
Initialize deterministic synthetic layout examples.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/dataset.py
178 179 180 181 182 183 184 185 186 187 188 189 190 | |
__len__ ¶
__len__() -> int
Return synthetic dataset size.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/dataset.py
192 193 194 | |
__getitem__ ¶
__getitem__(
index: int,
) -> dict[str, Shaped[torch.Tensor, "..."] | str]
Return one deterministic synthetic tokenized layout.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/dataset.py
196 197 198 199 200 201 202 203 204 205 206 207 208 209 | |
lightning_module ¶
PyTorch Lightning module for LayoutDiffusion discrete training.
LayoutDiffusionTrainingModule ¶
Bases: LightningModule
Lightning wrapper reproducing LayoutDiffusion categorical diffusion training.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/lightning_module.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 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 | |
__init__ ¶
__init__(
*,
config: LayoutDiffusionConfig,
model: LayoutDiffusionTransformer | None = None,
tokenizer: LayoutDiffusionTokenizer | None = None,
vocab_file: str | None = None,
learning_rate: float = 5e-05,
weight_decay: float = 0.0,
betas: tuple[float, float] = (0.9, 0.999),
auxiliary_loss_weight: float = 0.001,
time_sampler: LayoutDiffusionTimeSampler = "importance",
scheduler: LayoutDiffusionTrainingScheduler
| None = "linear_anneal",
lr_anneal_steps: int = 400000,
ema_rate: float = 0.9999,
seed_mode: LayoutDiffusionSeedMode
| str = LayoutDiffusionSeedMode.default,
) -> None
Initialize LayoutDiffusion training state.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/lightning_module.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | |
on_fit_start ¶
on_fit_start() -> None
Validate model/datamodule label order before training starts.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/lightning_module.py
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | |
configure_optimizers ¶
configure_optimizers() -> OptimizerLRScheduler
Return AdamW and optional linear annealing scheduler.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/lightning_module.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
training_step ¶
training_step(
batch: dict[str, Shaped[Tensor, "..."]], batch_idx: int
) -> Float[torch.Tensor, ""]
Run one LayoutDiffusion training step.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/lightning_module.py
239 240 241 242 243 244 245 246 247 | |
validation_step ¶
validation_step(
batch: dict[str, Shaped[Tensor, "..."]], batch_idx: int
) -> Float[torch.Tensor, ""]
Run one LayoutDiffusion validation step.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/lightning_module.py
249 250 251 252 253 254 255 256 257 258 | |
optimizer_step ¶
optimizer_step(
epoch: int,
batch_idx: int,
optimizer: Optimizer | LightningOptimizer,
optimizer_closure: Callable[[], Float[Tensor, ""]]
| None = None,
) -> None
Run the optimizer step and update EMA parameters.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/lightning_module.py
260 261 262 263 264 265 266 267 268 269 | |
update_ema ¶
update_ema() -> None
Update exponential moving average parameters.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/lightning_module.py
271 272 273 274 275 276 277 278 279 280 281 | |
ema_state_dict ¶
ema_state_dict() -> dict[str, Shaped[torch.Tensor, '...']]
Return a detached copy of EMA parameters.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/lightning_module.py
283 284 285 286 287 | |
on_save_checkpoint ¶
on_save_checkpoint(
checkpoint: dict[
str,
dict[str, Shaped[Tensor, "..."]]
| Shaped[Tensor, "..."]
| int
| float
| str
| bool
| None,
],
) -> None
Persist EMA parameters in Lightning checkpoints.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/lightning_module.py
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | |
on_load_checkpoint ¶
on_load_checkpoint(
checkpoint: dict[
str,
dict[str, Shaped[Tensor, "..."]]
| Shaped[Tensor, "..."]
| int
| float
| str
| bool
| None,
],
) -> None
Restore EMA parameters from Lightning checkpoints when available.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/lightning_module.py
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 | |
losses ¶
Categorical diffusion training-loss helpers for LayoutDiffusion.
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 | |
sum_except_batch ¶
sum_except_batch(
x: Float[Tensor, "batch ..."],
) -> Float[torch.Tensor, "batch"]
Sum every non-batch dimension using the reference reduction.
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 sum over all trailing dimensions. |
Examples:
>>> sum_except_batch(torch.ones(2, 3)).tolist()
[3.0, 3.0]
Source code in models/layoutdiffusion/src/layoutdiffusion/training/losses.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | |
parity ¶
LayoutDiffusion-specific S0-S2 training-parity helpers.
trace_layoutdiffusion_step ¶
trace_layoutdiffusion_step(
module: TrainingStepModule,
batch: dict[str, Shaped[Tensor, ...]],
rng_state: RNGState | None = None,
) -> StepTrace
Trace one LayoutDiffusion training step with canonical trace points.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/parity.py
21 22 23 24 25 26 27 | |
compare_layoutdiffusion_step ¶
compare_layoutdiffusion_step(
reference: StepTrace,
target: StepTrace,
*,
tolerance: TensorTolerance | None = None,
) -> StepReport
Compare S1 LayoutDiffusion pre-optimizer traces.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/parity.py
30 31 32 33 34 35 36 37 38 | |
compare_layoutdiffusion_optimizer_step ¶
compare_layoutdiffusion_optimizer_step(
reference_state: dict[str, Shaped[Tensor, ...]],
target_state: dict[str, Shaped[Tensor, ...]],
*,
tolerance: TensorTolerance | None = None,
) -> OptimizerStepReport
Compare S2 LayoutDiffusion post-optimizer parameters.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/parity.py
41 42 43 44 45 46 47 48 49 | |
seed ¶
Seed policy helpers for LayoutDiffusion training.
apply_layoutdiffusion_seed_mode ¶
apply_layoutdiffusion_seed_mode(
seed_mode: LayoutDiffusionSeedMode | str,
*,
seed: int = 102,
) -> None
Apply the selected LayoutDiffusion seed mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed_mode
|
LayoutDiffusionSeedMode | str
|
Regular or deterministic seed mode. |
required |
seed
|
int
|
Seed used by both modes. |
102
|
Returns:
| Type | Description |
|---|---|
None
|
None. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the seed mode is unsupported. |
Examples:
>>> apply_layoutdiffusion_seed_mode("default", seed=1)
Source code in models/layoutdiffusion/src/layoutdiffusion/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 | |
vocab ¶
Training vocabulary helpers for LayoutDiffusion.
build_training_tokenizer ¶
build_training_tokenizer(
config: LayoutDiffusionConfig,
*,
vocab_file: str | None = None,
) -> LayoutDiffusionTokenizer
Build a tokenizer while keeping training config vocabulary fields aligned.
Source code in models/layoutdiffusion/src/layoutdiffusion/training/vocab.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 | |