Laygen
Shared layout-generation utilities.
agents ¶
Shared agent building blocks for text-conditioned layout generators.
Importing this module requires the optional laygen[agents] extra because
provider execution is delegated to Pydantic AI. The rest of laygen remains
usable without that extra.
BaseLayoutAgent ¶
Bases: Generic[RawResponseT], ABC
Base Pydantic AI runner for text-conditioned layout agents.
Subclasses own model-specific exemplar selection, prompt serialization, and
response parsing. This base class centralizes provider model resolution,
Pydantic AI Agent construction, common public request validation, and
shared output dictionary serialization.
Source code in lib/laygen/src/laygen/agents/core.py
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 | |
__init__ ¶
__init__(
*,
model: ModelLike = None,
model_env_var: str,
raw_response_type: type[RawResponseT],
instructions: str,
) -> None
Initialize the provider runner.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
ModelLike
|
Optional Pydantic AI model object or provider model id. |
None
|
model_env_var
|
str
|
Environment variable used when |
required |
raw_response_type
|
type[RawResponseT]
|
Structured response model expected from the LLM. |
required |
instructions
|
str
|
Provider instructions passed to Pydantic AI. |
required |
Source code in lib/laygen/src/laygen/agents/core.py
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | |
resolve_model ¶
resolve_model(model: ModelLike = None) -> ModelLike
Resolve a per-call model override, constructor model, or env model id.
Source code in lib/laygen/src/laygen/agents/core.py
254 255 256 | |
build_pydantic_agent ¶
build_pydantic_agent(
*, model: ModelLike = None
) -> Agent[None]
Build the underlying Pydantic AI agent.
Source code in lib/laygen/src/laygen/agents/core.py
258 259 260 261 262 263 264 | |
run_raw_sync ¶
run_raw_sync(
model_prompt: str | Sequence[ChatMessageLike],
*,
model: ModelLike = None,
model_settings: ModelSettings | None = None,
) -> RawResponseT
Run the provider synchronously and return the structured raw response.
Source code in lib/laygen/src/laygen/agents/core.py
266 267 268 269 270 271 272 273 274 275 276 277 278 279 | |
validate_generation_request ¶
validate_generation_request(
*,
batch_size: int,
condition_type: str | ConditionType,
box_format: str | BoxFormat,
canvas_size: tuple[int, int] | None,
configured_canvas_size: int,
supported_condition_types: tuple[
ConditionType, ...
] = DEFAULT_SUPPORTED_CONDITIONS,
) -> tuple[ConditionType, BoxFormat]
Validate shared generation arguments before provider execution.
Source code in lib/laygen/src/laygen/agents/core.py
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 | |
output_to_dict ¶
output_to_dict(
output: LayoutOutputLike,
) -> LayoutOutputDict
Serialize the shared output with canonical layout schema keys.
Source code in lib/laygen/src/laygen/agents/core.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 | |
repair_response_text ¶
repair_response_text(text: str) -> str
Hook for model-specific response repair before parsing.
Source code in lib/laygen/src/laygen/agents/core.py
335 336 337 | |
should_retry ¶
should_retry(exc: Exception, *, attempt: int) -> bool
Hook for model-specific retry policy after provider or parse failure.
Source code in lib/laygen/src/laygen/agents/core.py
339 340 341 342 | |
retry_delay_seconds ¶
retry_delay_seconds(*, attempt: int) -> float
Hook for retry backoff policies used by subclasses.
Source code in lib/laygen/src/laygen/agents/core.py
344 345 346 347 | |
run_with_repair_policy ¶
run_with_repair_policy(
operation: Callable[[], RawResponseT],
*,
max_attempts: int = 1,
) -> RawResponseT
Run an operation with subclass retry-policy hooks.
Source code in lib/laygen/src/laygen/agents/core.py
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 | |
BaseExemplarSelector
dataclass
¶
Bases: Generic[ExampleT], ABC
Small base for selector strategies with shared candidate validation.
Source code in lib/laygen/src/laygen/agents/core.py
123 124 125 126 127 128 129 130 131 132 133 134 135 | |
validate_examples ¶
validate_examples(examples: Sequence[ExampleT]) -> None
Validate the selector has at least one candidate exemplar.
Source code in lib/laygen/src/laygen/agents/core.py
127 128 129 130 131 | |
selection_error ¶
selection_error(message: str) -> ValueError
Build a consistent selector error.
Source code in lib/laygen/src/laygen/agents/core.py
133 134 135 | |
BaseResponseParser
dataclass
¶
Bases: Generic[ParsedOutputT], ABC
Small base for parser strategies with shared repair/error hooks.
Source code in lib/laygen/src/laygen/agents/core.py
108 109 110 111 112 113 114 115 116 117 118 119 120 | |
repair_response_text ¶
repair_response_text(text: str) -> str
Repair provider text before parser-specific extraction.
Source code in lib/laygen/src/laygen/agents/core.py
114 115 116 | |
parser_error ¶
parser_error(message: str) -> RuntimeError
Build a consistent parser error with parser context.
Source code in lib/laygen/src/laygen/agents/core.py
118 119 120 | |
ExemplarSelector ¶
Bases: Protocol[ExampleT]
Strategy that chooses in-context examples for a layout prompt.
Source code in lib/laygen/src/laygen/agents/core.py
82 83 84 85 86 87 | |
__call__ ¶
__call__(
prompt: str, examples: Sequence[ExampleT]
) -> Sequence[ExampleT]
Return examples selected for prompt.
Source code in lib/laygen/src/laygen/agents/core.py
85 86 87 | |
LayoutItem2DLike ¶
Bases: Protocol
Minimal parsed 2D item required by the shared output builder.
Source code in lib/laygen/src/laygen/agents/core.py
138 139 140 141 142 143 144 145 146 147 148 149 | |
LayoutOutputDict ¶
Bases: TypedDict
Dictionary form of the canonical layout generation schema.
Source code in lib/laygen/src/laygen/agents/core.py
67 68 69 70 71 72 73 74 75 76 77 78 79 | |
PromptBuilder ¶
Bases: Protocol[ExampleT]
Strategy that serializes a user request and exemplars for a provider.
Source code in lib/laygen/src/laygen/agents/core.py
90 91 92 93 94 95 96 97 | |
__call__ ¶
__call__(
prompt: str, exemplars: Sequence[ExampleT]
) -> str | Sequence[ChatMessageLike]
Serialize prompt and exemplars for model execution.
Source code in lib/laygen/src/laygen/agents/core.py
93 94 95 96 97 | |
ResponseParser ¶
Bases: Protocol
Strategy that converts provider text into a shared layout output.
Source code in lib/laygen/src/laygen/agents/core.py
100 101 102 103 104 105 | |
__call__ ¶
__call__(
text: str, *, canvas_size: int
) -> LayoutGenerationOutput
Parse provider text into the shared output schema.
Source code in lib/laygen/src/laygen/agents/core.py
103 104 105 | |
layout_items_to_output ¶
layout_items_to_output(
items: Sequence[LayoutItem2DLike],
*,
id2label: Mapping[int, str],
intermediates: Mapping[str, LayoutAuxValue]
| None = None,
) -> LayoutGenerationOutput
Build the torch-backed shared normalized center-xywh output schema.
Source code in lib/laygen/src/laygen/agents/core.py
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 | |
messages_to_text ¶
messages_to_text(
messages: str | Sequence[ChatMessageLike],
) -> str
Convert provider chat messages to deterministic plain text.
Pydantic AI accepts both provider-native strings and structured chat-like messages. The shared base class sends one plain string to keep downstream behavior independent of provider-specific chat transport details.
Source code in lib/laygen/src/laygen/agents/core.py
184 185 186 187 188 189 190 191 192 193 194 195 | |
core ¶
Provider-independent base classes for layout-generation agents.
ChatMessageLike ¶
Bases: TypedDict
Chat-style message with role and content text fields.
Source code in lib/laygen/src/laygen/agents/core.py
52 53 54 55 56 | |
LayoutOutputDict ¶
Bases: TypedDict
Dictionary form of the canonical layout generation schema.
Source code in lib/laygen/src/laygen/agents/core.py
67 68 69 70 71 72 73 74 75 76 77 78 79 | |
ExemplarSelector ¶
Bases: Protocol[ExampleT]
Strategy that chooses in-context examples for a layout prompt.
Source code in lib/laygen/src/laygen/agents/core.py
82 83 84 85 86 87 | |
__call__ ¶
__call__(
prompt: str, examples: Sequence[ExampleT]
) -> Sequence[ExampleT]
Return examples selected for prompt.
Source code in lib/laygen/src/laygen/agents/core.py
85 86 87 | |
PromptBuilder ¶
Bases: Protocol[ExampleT]
Strategy that serializes a user request and exemplars for a provider.
Source code in lib/laygen/src/laygen/agents/core.py
90 91 92 93 94 95 96 97 | |
__call__ ¶
__call__(
prompt: str, exemplars: Sequence[ExampleT]
) -> str | Sequence[ChatMessageLike]
Serialize prompt and exemplars for model execution.
Source code in lib/laygen/src/laygen/agents/core.py
93 94 95 96 97 | |
ResponseParser ¶
Bases: Protocol
Strategy that converts provider text into a shared layout output.
Source code in lib/laygen/src/laygen/agents/core.py
100 101 102 103 104 105 | |
__call__ ¶
__call__(
text: str, *, canvas_size: int
) -> LayoutGenerationOutput
Parse provider text into the shared output schema.
Source code in lib/laygen/src/laygen/agents/core.py
103 104 105 | |
BaseResponseParser
dataclass
¶
Bases: Generic[ParsedOutputT], ABC
Small base for parser strategies with shared repair/error hooks.
Source code in lib/laygen/src/laygen/agents/core.py
108 109 110 111 112 113 114 115 116 117 118 119 120 | |
repair_response_text ¶
repair_response_text(text: str) -> str
Repair provider text before parser-specific extraction.
Source code in lib/laygen/src/laygen/agents/core.py
114 115 116 | |
parser_error ¶
parser_error(message: str) -> RuntimeError
Build a consistent parser error with parser context.
Source code in lib/laygen/src/laygen/agents/core.py
118 119 120 | |
BaseExemplarSelector
dataclass
¶
Bases: Generic[ExampleT], ABC
Small base for selector strategies with shared candidate validation.
Source code in lib/laygen/src/laygen/agents/core.py
123 124 125 126 127 128 129 130 131 132 133 134 135 | |
validate_examples ¶
validate_examples(examples: Sequence[ExampleT]) -> None
Validate the selector has at least one candidate exemplar.
Source code in lib/laygen/src/laygen/agents/core.py
127 128 129 130 131 | |
selection_error ¶
selection_error(message: str) -> ValueError
Build a consistent selector error.
Source code in lib/laygen/src/laygen/agents/core.py
133 134 135 | |
LayoutItem2DLike ¶
Bases: Protocol
Minimal parsed 2D item required by the shared output builder.
Source code in lib/laygen/src/laygen/agents/core.py
138 139 140 141 142 143 144 145 146 147 148 149 | |
LayoutOutputLike ¶
Bases: Protocol
Minimal shared layout output fields used for dict serialization.
Source code in lib/laygen/src/laygen/agents/core.py
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 | |
bbox
property
¶
bbox: (
Float[ndarray, "batch elements 4"]
| Float[Tensor, "batch elements 4"]
)
Layout boxes.
labels
property
¶
labels: (
Int[ndarray, "batch elements"]
| Int[Tensor, "batch elements"]
)
Layout labels.
mask
property
¶
mask: (
Bool[ndarray, "batch elements"]
| Bool[Tensor, "batch elements"]
)
Valid element mask.
BaseLayoutAgent ¶
Bases: Generic[RawResponseT], ABC
Base Pydantic AI runner for text-conditioned layout agents.
Subclasses own model-specific exemplar selection, prompt serialization, and
response parsing. This base class centralizes provider model resolution,
Pydantic AI Agent construction, common public request validation, and
shared output dictionary serialization.
Source code in lib/laygen/src/laygen/agents/core.py
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 | |
__init__ ¶
__init__(
*,
model: ModelLike = None,
model_env_var: str,
raw_response_type: type[RawResponseT],
instructions: str,
) -> None
Initialize the provider runner.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
ModelLike
|
Optional Pydantic AI model object or provider model id. |
None
|
model_env_var
|
str
|
Environment variable used when |
required |
raw_response_type
|
type[RawResponseT]
|
Structured response model expected from the LLM. |
required |
instructions
|
str
|
Provider instructions passed to Pydantic AI. |
required |
Source code in lib/laygen/src/laygen/agents/core.py
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 | |
resolve_model ¶
resolve_model(model: ModelLike = None) -> ModelLike
Resolve a per-call model override, constructor model, or env model id.
Source code in lib/laygen/src/laygen/agents/core.py
254 255 256 | |
build_pydantic_agent ¶
build_pydantic_agent(
*, model: ModelLike = None
) -> Agent[None]
Build the underlying Pydantic AI agent.
Source code in lib/laygen/src/laygen/agents/core.py
258 259 260 261 262 263 264 | |
run_raw_sync ¶
run_raw_sync(
model_prompt: str | Sequence[ChatMessageLike],
*,
model: ModelLike = None,
model_settings: ModelSettings | None = None,
) -> RawResponseT
Run the provider synchronously and return the structured raw response.
Source code in lib/laygen/src/laygen/agents/core.py
266 267 268 269 270 271 272 273 274 275 276 277 278 279 | |
validate_generation_request ¶
validate_generation_request(
*,
batch_size: int,
condition_type: str | ConditionType,
box_format: str | BoxFormat,
canvas_size: tuple[int, int] | None,
configured_canvas_size: int,
supported_condition_types: tuple[
ConditionType, ...
] = DEFAULT_SUPPORTED_CONDITIONS,
) -> tuple[ConditionType, BoxFormat]
Validate shared generation arguments before provider execution.
Source code in lib/laygen/src/laygen/agents/core.py
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 | |
output_to_dict ¶
output_to_dict(
output: LayoutOutputLike,
) -> LayoutOutputDict
Serialize the shared output with canonical layout schema keys.
Source code in lib/laygen/src/laygen/agents/core.py
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 | |
repair_response_text ¶
repair_response_text(text: str) -> str
Hook for model-specific response repair before parsing.
Source code in lib/laygen/src/laygen/agents/core.py
335 336 337 | |
should_retry ¶
should_retry(exc: Exception, *, attempt: int) -> bool
Hook for model-specific retry policy after provider or parse failure.
Source code in lib/laygen/src/laygen/agents/core.py
339 340 341 342 | |
retry_delay_seconds ¶
retry_delay_seconds(*, attempt: int) -> float
Hook for retry backoff policies used by subclasses.
Source code in lib/laygen/src/laygen/agents/core.py
344 345 346 347 | |
run_with_repair_policy ¶
run_with_repair_policy(
operation: Callable[[], RawResponseT],
*,
max_attempts: int = 1,
) -> RawResponseT
Run an operation with subclass retry-policy hooks.
Source code in lib/laygen/src/laygen/agents/core.py
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 | |
messages_to_text ¶
messages_to_text(
messages: str | Sequence[ChatMessageLike],
) -> str
Convert provider chat messages to deterministic plain text.
Pydantic AI accepts both provider-native strings and structured chat-like messages. The shared base class sends one plain string to keep downstream behavior independent of provider-specific chat transport details.
Source code in lib/laygen/src/laygen/agents/core.py
184 185 186 187 188 189 190 191 192 193 194 195 | |
layout_items_to_output ¶
layout_items_to_output(
items: Sequence[LayoutItem2DLike],
*,
id2label: Mapping[int, str],
intermediates: Mapping[str, LayoutAuxValue]
| None = None,
) -> LayoutGenerationOutput
Build the torch-backed shared normalized center-xywh output schema.
Source code in lib/laygen/src/laygen/agents/core.py
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 | |
testing ¶
Testing helpers for provider-backed layout agents.
function_model_from_text ¶
function_model_from_text(text: str) -> FunctionModel
Build a deterministic FunctionModel returning one text response.
Source code in lib/laygen/src/laygen/agents/testing.py
21 22 23 24 25 26 27 | |
test_model_from_text ¶
test_model_from_text(text: str) -> TestModel
Build a deterministic TestModel returning one custom text response.
Source code in lib/laygen/src/laygen/agents/testing.py
30 31 32 | |
assert_agent_output_schema ¶
assert_agent_output_schema(
run_agent: Callable[[], LayoutGenerationOutput],
*,
batch_size: int = 1,
) -> LayoutGenerationOutput
Run an agent callable and assert the shared output schema.
Source code in lib/laygen/src/laygen/agents/testing.py
35 36 37 38 39 40 41 42 43 | |
common ¶
Shared public APIs for layout-generation packages.
BoxFormat ¶
Bases: StrEnum
Supported bounding-box coordinate formats.
Source code in lib/laygen/src/laygen/common/bbox.py
21 22 23 24 25 26 | |
ConditionAlias ¶
Bases: StrEnum
Supported public and release-specific condition aliases.
Source code in lib/laygen/src/laygen/common/conditions.py
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 | |
ConditionType ¶
Bases: StrEnum
Canonical condition names used by layout generation interfaces.
Source code in lib/laygen/src/laygen/common/conditions.py
9 10 11 12 13 14 15 16 17 18 19 20 21 | |
SamplingMode ¶
Bases: StrEnum
Supported categorical sampling modes.
Source code in lib/laygen/src/laygen/common/discrete.py
21 22 23 24 25 26 27 28 29 | |
DatasetName ¶
Bases: StrEnum
Canonical dataset names supported by the shared label registry.
Source code in lib/laygen/src/laygen/common/labels.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
ParityMetric
dataclass
¶
Reference-parity metric row included in generated model cards.
Attributes:
| Name | Type | Description |
|---|---|---|
dataset |
str
|
Dataset or checkpoint name. |
tokenizer_exact |
str
|
Exact-match ratio for tokenizer round-trips. |
deterministic_exact |
str
|
Exact-match ratio for deterministic samples. |
logits_max_abs |
float
|
Maximum absolute denoiser-logit difference. |
logits_max_rel |
float
|
Maximum relative denoiser-logit difference. |
Source code in lib/laygen/src/laygen/common/model_card.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | |
WhitespaceTokenizerMixin ¶
Mixin for tokenizers backed by tokenizer-local id dictionaries.
Source code in lib/laygen/src/laygen/common/tokenization.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | |
get_vocab ¶
get_vocab() -> dict[str, int]
Return token-to-id mapping.
Source code in lib/laygen/src/laygen/common/tokenization.py
86 87 88 | |
convert_tokens_to_string ¶
convert_tokens_to_string(tokens: list[str]) -> str
Join layout tokens with spaces.
Source code in lib/laygen/src/laygen/common/tokenization.py
102 103 104 | |
normalize_box_format ¶
normalize_box_format(
box_format: BoxFormat | str,
) -> BoxFormat
Convert a public box-format value to BoxFormat.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
box_format
|
BoxFormat | str
|
Box format enum or its string value. |
required |
Returns:
| Type | Description |
|---|---|
BoxFormat
|
Normalized |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in lib/laygen/src/laygen/common/bbox.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | |
normalize_condition_type ¶
normalize_condition_type(
condition_type: ConditionType | str,
) -> ConditionType
Normalize condition aliases to a canonical ConditionType.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
condition_type
|
ConditionType | str
|
Canonical condition enum or a public/release alias. |
required |
Returns:
| Type | Description |
|---|---|
ConditionType
|
Canonical condition enum. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the condition type is unknown. |
Examples:
>>> str(normalize_condition_type("gen_t"))
'label'
>>> str(normalize_condition_type("gen_r"))
'relation'
Source code in lib/laygen/src/laygen/common/conditions.py
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
normalize_sampling_mode ¶
normalize_sampling_mode(
sampling: SamplingMode | str,
) -> SamplingMode
Convert a public sampling value to SamplingMode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sampling
|
SamplingMode | str
|
Sampling enum or its string value. |
required |
Returns:
| Type | Description |
|---|---|
SamplingMode
|
Normalized |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in lib/laygen/src/laygen/common/discrete.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | |
normalize_enum_value ¶
normalize_enum_value(
value: EnumT | str,
enum_type: type[EnumT],
*,
option_name: str,
) -> EnumT
Normalize a public string-or-enum option to a StrEnum value.
Source code in lib/laygen/src/laygen/common/enums.py
11 12 13 14 15 16 17 18 19 20 21 22 23 | |
max_elements_for_dataset ¶
max_elements_for_dataset(
dataset_name: DatasetName | str,
) -> int
Return the shared maximum element count for a dataset.
Source code in lib/laygen/src/laygen/common/labels.py
202 203 204 | |
normalize_dataset_name ¶
normalize_dataset_name(
dataset_name: DatasetName | str,
) -> DatasetName
Normalize common dataset aliases to canonical registry names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
DatasetName | str
|
User-facing dataset name or release alias. |
required |
Returns:
| Type | Description |
|---|---|
DatasetName
|
Canonical dataset name used by the shared label registry. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the dataset name is unknown. |
Examples:
>>> str(normalize_dataset_name("rico25_max25"))
'rico25'
Source code in lib/laygen/src/laygen/common/labels.py
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
build_layout_model_card ¶
build_layout_model_card(
*,
model_id: str,
model_name: str,
dataset_ids: Sequence[str],
license: str,
library_name: str,
pipeline_tag: str,
tags: Sequence[str],
model_details: str,
intended_uses: str,
limitations: str,
how_to_use: str,
training_data: str,
parity_metrics: Sequence[ParityMetricInput],
citation_bibtex: str,
original_implementation_url: str,
model_summary: str | None = None,
developers: str | None = None,
model_type: str = "Layout generation model.",
base_model: str | None = None,
paper: str | None = None,
preprocessing: str | None = None,
training_regime: str | None = None,
testing_data: str | None = None,
testing_metrics: str | None = None,
results_summary: str | None = None,
model_specs: str | None = None,
compute_infrastructure: str | None = None,
hardware_requirements: str | None = None,
software: str | None = None,
citation_apa: str | None = None,
) -> ModelCard
Build a Hugging Face model card for a layout-generation checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
Hub model id displayed in the card title. |
required |
model_name
|
str
|
Human-readable model name. |
required |
dataset_ids
|
Sequence[str]
|
Hub dataset ids used by the checkpoint. |
required |
license
|
str
|
SPDX-style license id for YAML metadata. |
required |
library_name
|
str
|
Hub library name, such as |
required |
pipeline_tag
|
str
|
Hub task tag. |
required |
tags
|
Sequence[str]
|
Additional Hub tags. |
required |
model_details
|
str
|
User-facing model description. |
required |
intended_uses
|
str
|
Direct-use description. |
required |
limitations
|
str
|
Known limitations and risks. |
required |
how_to_use
|
str
|
Python snippet without surrounding fences. |
required |
training_data
|
str
|
Training-data description. |
required |
parity_metrics
|
Sequence[ParityMetricInput]
|
Parity table rows. |
required |
citation_bibtex
|
str
|
BibTeX citation without surrounding fences. |
required |
original_implementation_url
|
str
|
URL for the upstream implementation. |
required |
model_summary
|
str | None
|
Short model summary for the card header. |
None
|
developers
|
str | None
|
Original developer attribution. |
None
|
model_type
|
str
|
User-facing model family/type. |
'Layout generation model.'
|
base_model
|
str | None
|
Base-model or conversion-relationship statement. |
None
|
paper
|
str | None
|
Paper URL. |
None
|
preprocessing
|
str | None
|
Preprocessing description. |
None
|
training_regime
|
str | None
|
Training-regime description. |
None
|
testing_data
|
str | None
|
Evaluation data or fixture description. |
None
|
testing_metrics
|
str | None
|
Evaluation metric description. |
None
|
results_summary
|
str | None
|
Summary of recorded parity results. |
None
|
model_specs
|
str | None
|
Architecture and objective summary. |
None
|
compute_infrastructure
|
str | None
|
Conversion/parity compute description. |
None
|
hardware_requirements
|
str | None
|
Runtime and parity hardware requirements. |
None
|
software
|
str | None
|
Runtime and parity software requirements. |
None
|
citation_apa
|
str | None
|
Optional APA-style citation. |
None
|
Returns:
| Type | Description |
|---|---|
ModelCard
|
Rendered |
ModelCard
|
metadata attached. |
Examples:
>>> card = layoutdm_model_card(dataset="rico25")
>>> card.data.to_dict()["library_name"]
'diffusers'
Source code in lib/laygen/src/laygen/common/model_card.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 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 | |
layoutdm_model_card ¶
layoutdm_model_card(
*,
dataset: DatasetName | str,
parity_metrics: Sequence[ParityMetricInput]
| None = None,
) -> ModelCard
Build the LayoutDM model card for a converted checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
DatasetName | str
|
LayoutDM dataset name, either |
required |
parity_metrics
|
Sequence[ParityMetricInput] | None
|
Optional parity rows. Defaults to the checked conversion metrics used by this package. |
None
|
Returns:
| Type | Description |
|---|---|
ModelCard
|
Validated model card for the requested LayoutDM checkpoint. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> card = layoutdm_model_card(dataset="publaynet")
>>> card.data.to_dict()["datasets"]
['creative-graphic-design/PubLayNet']
Source code in lib/laygen/src/laygen/common/model_card.py
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 | |
sanitize_for_yaml ¶
sanitize_for_yaml(value: YamlInputValue) -> YamlValue
Convert enum-rich metadata into objects accepted by yaml.safe_dump.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
YamlInputValue
|
Metadata value that may contain |
required |
Returns:
| Type | Description |
|---|---|
YamlValue
|
A recursively sanitized value containing only YAML-safe scalar and |
YamlValue
|
container types. |
Examples:
>>> from laygen.common import DatasetName
>>> sanitize_for_yaml({"dataset": DatasetName.rico25})
{'dataset': 'rico25'}
Source code in lib/laygen/src/laygen/common/serialization.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 | |
build_token_maps ¶
build_token_maps(
*,
vocab_file: str | PathLike[str] | None,
tokens: Sequence[str] | None,
base_tokens: Sequence[str],
numeric_id_vocab: bool = False,
) -> tuple[dict[str, int], dict[int, str]]
Build token/id maps from a JSON vocabulary file or synthetic token list.
Source code in lib/laygen/src/laygen/common/tokenization.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | |
convert_id_to_token ¶
convert_id_to_token(
id2token: dict[int, str], index: int, unk_token: str
) -> str
Convert an id to a token using a tokenizer-local unknown token string.
Source code in lib/laygen/src/laygen/common/tokenization.py
46 47 48 | |
convert_token_to_id ¶
convert_token_to_id(
token2id: dict[str, int], token: str, unk_token_id: int
) -> int
Convert a token to an id using a tokenizer-local unknown-token id.
Source code in lib/laygen/src/laygen/common/tokenization.py
41 42 43 | |
join_tokens ¶
join_tokens(tokens: Sequence[str]) -> str
Join already-tokenized layout tokens with spaces.
Source code in lib/laygen/src/laygen/common/tokenization.py
51 52 53 | |
save_json_vocabulary ¶
save_json_vocabulary(
*,
save_directory: str | PathLike[str],
filename: str,
data: dict[str, int] | dict[str, str],
filename_prefix: str | None = None,
) -> tuple[str]
Save tokenizer vocabulary JSON and return the generated path.
Source code in lib/laygen/src/laygen/common/tokenization.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | |
split_whitespace_tokens ¶
split_whitespace_tokens(text: str) -> list[str]
Split a layout token string on whitespace.
Source code in lib/laygen/src/laygen/common/tokenization.py
36 37 38 | |
bbox ¶
Bounding-box conversion and quantization helpers for layout packages.
BoxFormat ¶
Bases: StrEnum
Supported bounding-box coordinate formats.
Source code in lib/laygen/src/laygen/common/bbox.py
21 22 23 24 25 26 | |
normalize_box_format ¶
normalize_box_format(
box_format: BoxFormat | str,
) -> BoxFormat
Convert a public box-format value to BoxFormat.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
box_format
|
BoxFormat | str
|
Box format enum or its string value. |
required |
Returns:
| Type | Description |
|---|---|
BoxFormat
|
Normalized |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in lib/laygen/src/laygen/common/bbox.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | |
xywh_to_ltrb ¶
xywh_to_ltrb(
bbox: Float[Tensor, "... 4"],
) -> Float[torch.Tensor, "... 4"]
Convert normalized center xywh boxes to ltrb boxes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, '... 4']
|
torch.Tensor with the last dimension ordered as center x, center y, width, and height. |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, '... 4']
|
torch.Tensor with the same leading shape and last dimension ordered as left, |
Float[Tensor, '... 4']
|
top, right, and bottom. |
Examples:
>>> import torch
>>> xywh_to_ltrb(torch.tensor([[0.5, 0.5, 0.2, 0.4]])).shape
torch.Size([1, 4])
Source code in lib/laygen/src/laygen/common/bbox.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | |
ltrb_to_xywh ¶
ltrb_to_xywh(
bbox: Float[Tensor, "... 4"],
) -> Float[torch.Tensor, "... 4"]
Convert ltrb boxes to normalized center xywh boxes.
Source code in lib/laygen/src/laygen/common/bbox.py
75 76 77 78 79 80 81 82 83 | |
ltwh_to_xywh ¶
ltwh_to_xywh(
bbox: Float[Tensor, "... 4"],
) -> Float[torch.Tensor, "... 4"]
Convert left-top-width-height boxes to center xywh boxes.
Source code in lib/laygen/src/laygen/common/bbox.py
86 87 88 89 90 91 | |
xywh_to_ltwh ¶
xywh_to_ltwh(
bbox: Float[Tensor, "... 4"],
) -> Float[torch.Tensor, "... 4"]
Convert center xywh boxes to left-top-width-height boxes.
Source code in lib/laygen/src/laygen/common/bbox.py
94 95 96 97 98 99 | |
clamp_boxes ¶
clamp_boxes(
bbox: Float[Tensor, "... 4"],
) -> Float[torch.Tensor, "... 4"]
Clamp normalized box coordinates into the inclusive [0, 1] range.
Source code in lib/laygen/src/laygen/common/bbox.py
102 103 104 | |
normalize_boxes ¶
normalize_boxes(
bbox: Float[Tensor, "batch elements 4"],
*,
canvas_size: tuple[int, int],
box_format: BoxFormat | str,
) -> Float[torch.Tensor, "batch elements 4"]
Normalize pixel boxes to center xywh coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'batch elements 4']
|
torch.Tensor containing pixel-space boxes. |
required |
canvas_size
|
tuple[int, int]
|
Canvas size as |
required |
box_format
|
BoxFormat | str
|
Input box format. |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'batch elements 4']
|
torch.Tensor containing normalized center |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import torch
>>> normalize_boxes(
... torch.tensor([[[0.0, 0.0, 10.0, 10.0]]]),
... canvas_size=(100, 100),
... box_format="ltrb",
... ).shape
torch.Size([1, 1, 4])
Source code in lib/laygen/src/laygen/common/bbox.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 | |
prepare_layout_tensors ¶
prepare_layout_tensors(
*,
bbox: Float[Tensor, "... 4"]
| Float[ndarray, "... 4"]
| Sequence[Sequence[Sequence[float]]]
| Sequence[Sequence[float]]
| Sequence[ArrayLikeInput],
labels: Int[Tensor, "..."]
| Int[ndarray, "..."]
| Sequence[Sequence[int]]
| Sequence[int]
| Sequence[ArrayLikeInput],
mask: Bool[Tensor, "..."]
| Bool[ndarray, "..."]
| Sequence[Sequence[bool]]
| Sequence[bool]
| Sequence[ArrayLikeInput]
| None = None,
box_format: BoxFormat | str = BoxFormat.xywh,
normalized: bool = True,
canvas_size: tuple[int, int] | None = None,
clamp_converted_normalized: bool = False,
) -> tuple[
Float[torch.Tensor, "batch elements 4"],
Int[torch.Tensor, "batch elements"],
Bool[torch.Tensor, "batch elements"],
]
Convert public layout arrays to batched normalized tensor inputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, '... 4'] | Float[ndarray, '... 4'] | Sequence[Sequence[Sequence[float]]] | Sequence[Sequence[float]] | Sequence[ArrayLikeInput]
|
Layout boxes in |
required |
labels
|
Int[Tensor, '...'] | Int[ndarray, '...'] | Sequence[Sequence[int]] | Sequence[int] | Sequence[ArrayLikeInput]
|
Integer labels matching the layout boxes. |
required |
mask
|
Bool[Tensor, '...'] | Bool[ndarray, '...'] | Sequence[Sequence[bool]] | Sequence[bool] | Sequence[ArrayLikeInput] | None
|
Optional valid-element mask. All elements are valid when omitted. |
None
|
box_format
|
BoxFormat | str
|
Input box format. |
xywh
|
normalized
|
bool
|
Whether boxes are already normalized to |
True
|
canvas_size
|
tuple[int, int] | None
|
Pixel canvas size required when |
None
|
clamp_converted_normalized
|
bool
|
Whether normalized |
False
|
Returns:
| Type | Description |
|---|---|
tuple[Float[Tensor, 'batch elements 4'], Int[Tensor, 'batch elements'], Bool[Tensor, 'batch elements']]
|
Batched |
Raises:
| Type | Description |
|---|---|
ValueError
|
If pixel-space boxes are passed without |
Source code in lib/laygen/src/laygen/common/bbox.py
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 | |
denormalize_boxes ¶
denormalize_boxes(
bbox: Float[Tensor, "batch elements 4"],
*,
canvas_size: tuple[int, int],
box_format: BoxFormat | str,
) -> Float[torch.Tensor, "batch elements 4"]
Convert normalized center xywh boxes to pixel-space boxes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'batch elements 4']
|
Normalized center |
required |
canvas_size
|
tuple[int, int]
|
Canvas size as |
required |
box_format
|
BoxFormat | str
|
Requested output box format. |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'batch elements 4']
|
torch.Tensor in the requested pixel-space format. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in lib/laygen/src/laygen/common/bbox.py
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 | |
linear_discretize ¶
linear_discretize(
values: Float[Tensor, "..."], *, num_bins: int
) -> Int[torch.Tensor, "..."]
Map normalized continuous values to evenly spaced integer bins.
Source code in lib/laygen/src/laygen/common/bbox.py
268 269 270 271 272 273 274 | |
linear_continuize ¶
linear_continuize(
ids: Int[Tensor, "..."], *, num_bins: int
) -> Float[torch.Tensor, "..."]
Map evenly spaced integer bins back to normalized continuous values.
Source code in lib/laygen/src/laygen/common/bbox.py
277 278 279 280 281 | |
conditions ¶
Shared condition-type vocabulary for layout generation packages.
ConditionType ¶
Bases: StrEnum
Canonical condition names used by layout generation interfaces.
Source code in lib/laygen/src/laygen/common/conditions.py
9 10 11 12 13 14 15 16 17 18 19 20 21 | |
ConditionAlias ¶
Bases: StrEnum
Supported public and release-specific condition aliases.
Source code in lib/laygen/src/laygen/common/conditions.py
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 | |
normalize_condition_type ¶
normalize_condition_type(
condition_type: ConditionType | str,
) -> ConditionType
Normalize condition aliases to a canonical ConditionType.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
condition_type
|
ConditionType | str
|
Canonical condition enum or a public/release alias. |
required |
Returns:
| Type | Description |
|---|---|
ConditionType
|
Canonical condition enum. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the condition type is unknown. |
Examples:
>>> str(normalize_condition_type("gen_t"))
'label'
>>> str(normalize_condition_type("gen_r"))
'relation'
Source code in lib/laygen/src/laygen/common/conditions.py
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 | |
discrete ¶
Discrete diffusion tensor utilities shared by layout generators.
SamplingMode ¶
Bases: StrEnum
Supported categorical sampling modes.
Source code in lib/laygen/src/laygen/common/discrete.py
21 22 23 24 25 26 27 28 29 | |
normalize_sampling_mode ¶
normalize_sampling_mode(
sampling: SamplingMode | str,
) -> SamplingMode
Convert a public sampling value to SamplingMode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sampling
|
SamplingMode | str
|
Sampling enum or its string value. |
required |
Returns:
| Type | Description |
|---|---|
SamplingMode
|
Normalized |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in lib/laygen/src/laygen/common/discrete.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | |
index_to_log_onehot ¶
index_to_log_onehot(
input_ids: Int[Tensor, "batch ..."], vocab_size: int
) -> Float[torch.Tensor, "batch vocab ..."]
Convert categorical ids to log one-hot tensors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_ids
|
Int[Tensor, 'batch ...']
|
Integer tensor with categorical ids. |
required |
vocab_size
|
int
|
Size of the categorical vocabulary. |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'batch vocab ...']
|
Log one-hot tensor shaped |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any id is outside the vocabulary. |
Examples:
>>> import torch
>>> index_to_log_onehot(torch.tensor([[0, 1]]), 3).shape
torch.Size([1, 3, 2])
Source code in lib/laygen/src/laygen/common/discrete.py
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 | |
log_onehot_to_index ¶
log_onehot_to_index(
log_x: Float[Tensor, "batch vocab ..."],
) -> Int[torch.Tensor, "batch ..."]
Convert log one-hot tensors back to categorical ids.
Source code in lib/laygen/src/laygen/common/discrete.py
85 86 87 88 89 | |
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 | |
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 | |
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 | |
update_loss_history ¶
update_loss_history(
kl_loss: Float[Tensor, "batch"],
t: Int[Tensor, "batch"],
lt_history: Float[Tensor, "timesteps"],
lt_count: Float[Tensor, "timesteps"],
) -> None
Update squared-loss history buffers in place.
The update matches the D3PM-style training loop used by LayoutDM and
LayoutDiffusion: each sampled timestep receives 0.1 * loss**2 + 0.9
times the previous bucket value, and the observation count is incremented.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kl_loss
|
Float[Tensor, 'batch']
|
Per-example KL or decoder loss for the sampled timesteps. |
required |
t
|
Int[Tensor, 'batch']
|
Sampled timestep ids for each example. |
required |
lt_history
|
Float[Tensor, 'timesteps']
|
Running squared-loss history buffer to mutate. |
required |
lt_count
|
Float[Tensor, 'timesteps']
|
Per-timestep observation count buffer to mutate. |
required |
Returns:
| Type | Description |
|---|---|
None
|
None. The history and count tensors are updated in place. |
Examples:
>>> import torch
>>> history = torch.zeros(3)
>>> count = torch.zeros(3)
>>> update_loss_history(torch.tensor([2.0]), torch.tensor([1]), history, count)
>>> history.tolist(), count.tolist()
([0.0, 0.4000000059604645, 0.0], [0.0, 1.0, 0.0])
Source code in lib/laygen/src/laygen/common/discrete.py
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 | |
log_add_exp ¶
log_add_exp(
a: Float[Tensor, "..."], b: Float[Tensor, "..."]
) -> Float[torch.Tensor, "..."]
Compute a numerically stable elementwise log(exp(a) + exp(b)).
Source code in lib/laygen/src/laygen/common/discrete.py
266 267 268 269 270 271 272 273 | |
extract ¶
extract(
values: Float[Tensor, "timesteps"],
timesteps: Int[Tensor, "batch"],
broadcast_shape: Size,
) -> Float[torch.Tensor, "batch ..."]
Gather timestep values and reshape them for broadcast operations.
Source code in lib/laygen/src/laygen/common/discrete.py
276 277 278 279 280 281 282 283 284 | |
gumbel_noise_like ¶
gumbel_noise_like(
x: Float[Tensor, "..."],
*,
generator: Generator | None = None,
) -> Float[torch.Tensor, "..."]
Sample Gumbel noise with the same shape, dtype, and device as x.
Source code in lib/laygen/src/laygen/common/discrete.py
287 288 289 290 291 292 293 294 295 296 | |
log_sample_categorical ¶
log_sample_categorical(
logits: Float[Tensor, "batch vocab ..."],
*,
generator: Generator | None = None,
) -> Int[torch.Tensor, "batch ..."]
Sample categorical ids from log probabilities with Gumbel-max.
Source code in lib/laygen/src/laygen/common/discrete.py
299 300 301 302 303 304 305 | |
top_k_logits ¶
top_k_logits(
logits: Float[Tensor, "... vocab"],
k: int,
dim: int = -1,
) -> Float[torch.Tensor, "... vocab"]
Mask logits outside the top-k entries along dim.
Source code in lib/laygen/src/laygen/common/discrete.py
308 309 310 311 312 313 314 315 316 317 318 | |
sample_categorical ¶
sample_categorical(
logits: Float[Tensor, "... vocab"],
*,
sampling: SamplingMode | str = SamplingMode.random,
temperature: float = 1.0,
top_k: int | None = None,
top_p: float | None = None,
generator: Generator | None = None,
) -> Int[torch.Tensor, "batch ..."]
Sample categorical ids from logits using LayoutDM sampling modes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
|
Float[Tensor, '... vocab']
|
torch.Tensor whose last dimension is the categorical vocabulary. |
required |
sampling
|
SamplingMode | str
|
Sampling mode name. |
random
|
temperature
|
float
|
Positive temperature used before random sampling. |
1.0
|
top_k
|
int | None
|
Number of logits retained for top-k modes. |
None
|
top_p
|
float | None
|
Cumulative probability retained for top-p modes. |
None
|
generator
|
Generator | None
|
Optional torch generator for deterministic sampling. |
None
|
Returns:
| Type | Description |
|---|---|
Int[Tensor, 'batch ...']
|
torch.Tensor of sampled ids with shape |
Examples:
>>> import torch
>>> sample_categorical(
... torch.tensor([[[0.0, 1.0]]]),
... sampling="deterministic",
... )
tensor([[1]])
Source code in lib/laygen/src/laygen/common/discrete.py
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 | |
batch_topk_mask ¶
batch_topk_mask(
scores: Float[Tensor, "batch candidates"],
k: Int[Tensor, "batch"],
) -> Bool[torch.Tensor, "batch candidates"]
Return a per-row boolean mask for the top k scores.
Source code in lib/laygen/src/laygen/common/discrete.py
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | |
enums ¶
Shared enum normalization helpers.
normalize_enum_value ¶
normalize_enum_value(
value: EnumT | str,
enum_type: type[EnumT],
*,
option_name: str,
) -> EnumT
Normalize a public string-or-enum option to a StrEnum value.
Source code in lib/laygen/src/laygen/common/enums.py
11 12 13 14 15 16 17 18 19 20 21 22 23 | |
labels ¶
Dataset label registries shared by layout generation packages.
DatasetName ¶
Bases: StrEnum
Canonical dataset names supported by the shared label registry.
Source code in lib/laygen/src/laygen/common/labels.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
Rico25Label ¶
Bases: StrEnum
RICO25 label names in dataset id order.
Source code in lib/laygen/src/laygen/common/labels.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 | |
Rico13Label ¶
Bases: StrEnum
RICO13 label names in dataset id order.
Source code in lib/laygen/src/laygen/common/labels.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | |
PubLayNetLabel ¶
Bases: StrEnum
PubLayNet label names in dataset id order.
Source code in lib/laygen/src/laygen/common/labels.py
74 75 76 77 78 79 80 81 | |
MagazineLabel ¶
Bases: StrEnum
Magazine label names in dataset id order.
Source code in lib/laygen/src/laygen/common/labels.py
84 85 86 87 88 89 90 91 | |
DatasetMetadata ¶
Bases: TypedDict
Shared metadata keyed by canonical dataset name.
Source code in lib/laygen/src/laygen/common/labels.py
94 95 96 97 98 | |
normalize_dataset_name ¶
normalize_dataset_name(
dataset_name: DatasetName | str,
) -> DatasetName
Normalize common dataset aliases to canonical registry names.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_name
|
DatasetName | str
|
User-facing dataset name or release alias. |
required |
Returns:
| Type | Description |
|---|---|
DatasetName
|
Canonical dataset name used by the shared label registry. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the dataset name is unknown. |
Examples:
>>> str(normalize_dataset_name("rico25_max25"))
'rico25'
Source code in lib/laygen/src/laygen/common/labels.py
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
labels_for_dataset ¶
labels_for_dataset(
dataset_name: DatasetName | str,
) -> tuple[str, ...]
Return the ordered label vocabulary for a dataset.
Source code in lib/laygen/src/laygen/common/labels.py
186 187 188 189 | |
id2label_for_dataset ¶
id2label_for_dataset(
dataset_name: DatasetName | str,
) -> dict[int, str]
Return an integer-id to label-name mapping for a dataset.
Source code in lib/laygen/src/laygen/common/labels.py
192 193 194 | |
label2id_for_dataset ¶
label2id_for_dataset(
dataset_name: DatasetName | str,
) -> dict[str, int]
Return a label-name to integer-id mapping for a dataset.
Source code in lib/laygen/src/laygen/common/labels.py
197 198 199 | |
max_elements_for_dataset ¶
max_elements_for_dataset(
dataset_name: DatasetName | str,
) -> int
Return the shared maximum element count for a dataset.
Source code in lib/laygen/src/laygen/common/labels.py
202 203 204 | |
layout_keys ¶
Shared key names for Hugging Face layout sample extraction.
model_card ¶
Model-card builders shared by converted layout model packages.
ModelCardMetadataKey ¶
Bases: StrEnum
YAML metadata keys emitted by generated Hub model cards.
Source code in lib/laygen/src/laygen/common/model_card.py
16 17 18 19 20 21 22 23 24 25 | |
ModelCardMetadata ¶
Bases: TypedDict
Structured metadata passed to ModelCardData.
Source code in lib/laygen/src/laygen/common/model_card.py
33 34 35 36 37 38 39 40 41 42 | |
ParityMetricKey ¶
Bases: StrEnum
Column keys used in generated parity metric rows.
Source code in lib/laygen/src/laygen/common/model_card.py
45 46 47 48 49 50 51 52 | |
ParityMetric
dataclass
¶
Reference-parity metric row included in generated model cards.
Attributes:
| Name | Type | Description |
|---|---|---|
dataset |
str
|
Dataset or checkpoint name. |
tokenizer_exact |
str
|
Exact-match ratio for tokenizer round-trips. |
deterministic_exact |
str
|
Exact-match ratio for deterministic samples. |
logits_max_abs |
float
|
Maximum absolute denoiser-logit difference. |
logits_max_rel |
float
|
Maximum relative denoiser-logit difference. |
Source code in lib/laygen/src/laygen/common/model_card.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | |
ParityMetricRow ¶
Bases: TypedDict
Structured parity metric row accepted by model-card generation.
Source code in lib/laygen/src/laygen/common/model_card.py
77 78 79 80 81 82 83 84 | |
build_layout_model_card ¶
build_layout_model_card(
*,
model_id: str,
model_name: str,
dataset_ids: Sequence[str],
license: str,
library_name: str,
pipeline_tag: str,
tags: Sequence[str],
model_details: str,
intended_uses: str,
limitations: str,
how_to_use: str,
training_data: str,
parity_metrics: Sequence[ParityMetricInput],
citation_bibtex: str,
original_implementation_url: str,
model_summary: str | None = None,
developers: str | None = None,
model_type: str = "Layout generation model.",
base_model: str | None = None,
paper: str | None = None,
preprocessing: str | None = None,
training_regime: str | None = None,
testing_data: str | None = None,
testing_metrics: str | None = None,
results_summary: str | None = None,
model_specs: str | None = None,
compute_infrastructure: str | None = None,
hardware_requirements: str | None = None,
software: str | None = None,
citation_apa: str | None = None,
) -> ModelCard
Build a Hugging Face model card for a layout-generation checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_id
|
str
|
Hub model id displayed in the card title. |
required |
model_name
|
str
|
Human-readable model name. |
required |
dataset_ids
|
Sequence[str]
|
Hub dataset ids used by the checkpoint. |
required |
license
|
str
|
SPDX-style license id for YAML metadata. |
required |
library_name
|
str
|
Hub library name, such as |
required |
pipeline_tag
|
str
|
Hub task tag. |
required |
tags
|
Sequence[str]
|
Additional Hub tags. |
required |
model_details
|
str
|
User-facing model description. |
required |
intended_uses
|
str
|
Direct-use description. |
required |
limitations
|
str
|
Known limitations and risks. |
required |
how_to_use
|
str
|
Python snippet without surrounding fences. |
required |
training_data
|
str
|
Training-data description. |
required |
parity_metrics
|
Sequence[ParityMetricInput]
|
Parity table rows. |
required |
citation_bibtex
|
str
|
BibTeX citation without surrounding fences. |
required |
original_implementation_url
|
str
|
URL for the upstream implementation. |
required |
model_summary
|
str | None
|
Short model summary for the card header. |
None
|
developers
|
str | None
|
Original developer attribution. |
None
|
model_type
|
str
|
User-facing model family/type. |
'Layout generation model.'
|
base_model
|
str | None
|
Base-model or conversion-relationship statement. |
None
|
paper
|
str | None
|
Paper URL. |
None
|
preprocessing
|
str | None
|
Preprocessing description. |
None
|
training_regime
|
str | None
|
Training-regime description. |
None
|
testing_data
|
str | None
|
Evaluation data or fixture description. |
None
|
testing_metrics
|
str | None
|
Evaluation metric description. |
None
|
results_summary
|
str | None
|
Summary of recorded parity results. |
None
|
model_specs
|
str | None
|
Architecture and objective summary. |
None
|
compute_infrastructure
|
str | None
|
Conversion/parity compute description. |
None
|
hardware_requirements
|
str | None
|
Runtime and parity hardware requirements. |
None
|
software
|
str | None
|
Runtime and parity software requirements. |
None
|
citation_apa
|
str | None
|
Optional APA-style citation. |
None
|
Returns:
| Type | Description |
|---|---|
ModelCard
|
Rendered |
ModelCard
|
metadata attached. |
Examples:
>>> card = layoutdm_model_card(dataset="rico25")
>>> card.data.to_dict()["library_name"]
'diffusers'
Source code in lib/laygen/src/laygen/common/model_card.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 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 | |
layoutdm_model_card ¶
layoutdm_model_card(
*,
dataset: DatasetName | str,
parity_metrics: Sequence[ParityMetricInput]
| None = None,
) -> ModelCard
Build the LayoutDM model card for a converted checkpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
DatasetName | str
|
LayoutDM dataset name, either |
required |
parity_metrics
|
Sequence[ParityMetricInput] | None
|
Optional parity rows. Defaults to the checked conversion metrics used by this package. |
None
|
Returns:
| Type | Description |
|---|---|
ModelCard
|
Validated model card for the requested LayoutDM checkpoint. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> card = layoutdm_model_card(dataset="publaynet")
>>> card.data.to_dict()["datasets"]
['creative-graphic-design/PubLayNet']
Source code in lib/laygen/src/laygen/common/model_card.py
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 | |
serialization ¶
Serialization helpers for shared layout-generation metadata.
DataclassInstance ¶
Bases: Protocol
Dataclass instance accepted by dataclasses.asdict.
Source code in lib/laygen/src/laygen/common/serialization.py
23 24 25 26 | |
sanitize_for_yaml ¶
sanitize_for_yaml(value: YamlInputValue) -> YamlValue
Convert enum-rich metadata into objects accepted by yaml.safe_dump.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
value
|
YamlInputValue
|
Metadata value that may contain |
required |
Returns:
| Type | Description |
|---|---|
YamlValue
|
A recursively sanitized value containing only YAML-safe scalar and |
YamlValue
|
container types. |
Examples:
>>> from laygen.common import DatasetName
>>> sanitize_for_yaml({"dataset": DatasetName.rico25})
{'dataset': 'rico25'}
Source code in lib/laygen/src/laygen/common/serialization.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 | |
testing ¶
Schema assertions and fixtures shared by layout-generation package tests.
ConfigAttributes ¶
Bases: Protocol
Attribute-backed config accepted by parity test helpers.
Source code in lib/laygen/src/laygen/common/testing.py
24 25 26 27 28 29 | |
__getattribute__ ¶
__getattribute__(name: str) -> ConfigValue
Return a constructor-compatible config field.
Source code in lib/laygen/src/laygen/common/testing.py
27 28 29 | |
LayoutOutputLike ¶
Bases: Protocol
Duck-typed layout output protocol used by shared test helpers.
Source code in lib/laygen/src/laygen/common/testing.py
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 | |
bbox
property
¶
bbox: (
Float[ndarray, "batch elements 4"]
| Float[Tensor, "batch elements 4"]
)
Layout boxes shaped (batch, elements, 4).
labels
property
¶
labels: (
Int[ndarray, "batch elements"]
| Int[Tensor, "batch elements"]
)
Layout labels shaped (batch, elements).
mask
property
¶
mask: (
Bool[ndarray, "batch elements"]
| Bool[Tensor, "batch elements"]
)
Valid-element mask shaped (batch, elements).
parity_require_enabled ¶
parity_require_enabled() -> bool
Return whether parity skips should fail.
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
|
Examples:
>>> parity_require_enabled() in {True, False}
True
Source code in lib/laygen/src/laygen/common/testing.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | |
skip_or_fail_vendor_parity ¶
skip_or_fail_vendor_parity(
reason: str,
*,
missing_paths: Sequence[str | PathLike[str]] = (),
regeneration_hint: str | None = None,
) -> NoReturn
Skip or fail a parity test when required assets are absent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reason
|
str
|
Human-readable reason the parity assertion cannot run. |
required |
missing_paths
|
Sequence[str | PathLike[str]]
|
Optional paths, cache entries, or environment-backed assets that were expected but absent. |
()
|
regeneration_hint
|
str | None
|
Optional command or instruction for regenerating the missing assets. |
None
|
Returns:
| Type | Description |
|---|---|
NoReturn
|
This helper never returns. It raises pytest's skip outcome when |
NoReturn
|
|
NoReturn
|
|
Raises:
| Type | Description |
|---|---|
Exception
|
When |
Exception
|
When |
Examples:
>>> callable(skip_or_fail_vendor_parity)
True
Source code in lib/laygen/src/laygen/common/testing.py
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 | |
assert_mask_valid ¶
assert_mask_valid(
mask: Bool[ndarray, "batch elements"]
| Bool[Tensor, "batch elements"],
) -> None
Assert that a valid-element mask has the public mask schema.
Source code in lib/laygen/src/laygen/common/testing.py
123 124 125 126 127 128 | |
assert_normalized_xywh ¶
assert_normalized_xywh(
bbox: Float[ndarray, "batch elements 4"]
| Float[Tensor, "batch elements 4"],
mask: Bool[ndarray, "batch elements"]
| Bool[Tensor, "batch elements"]
| None = None,
) -> None
Assert that boxes are normalized center xywh tensors.
Source code in lib/laygen/src/laygen/common/testing.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 | |
assert_layout_output_schema ¶
assert_layout_output_schema(
output: LayoutOutputLike,
*,
batch_size: int | None = None,
) -> None
Assert the shared layout output schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
LayoutOutputLike
|
Object with |
required |
batch_size
|
int | None
|
Optional expected batch size. |
None
|
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the object does not satisfy the shared schema. |
Source code in lib/laygen/src/laygen/common/testing.py
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 | |
assert_generator_reproducible ¶
assert_generator_reproducible(
callable_: Callable[..., LayoutOutputLike],
) -> None
Assert that a callable is reproducible with identical torch generators.
Source code in lib/laygen/src/laygen/common/testing.py
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
load_torch_checkpoint_state_dict ¶
load_torch_checkpoint_state_dict(
checkpoint: str | PathLike[str],
*,
state_dict_key: str | None = None,
map_location: str
| dict[str, str]
| "torch.device"
| None = None,
weights_only: bool | None = None,
) -> dict[str, Shaped[torch.Tensor, "..."]]
Load a PyTorch checkpoint and return its model state dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
checkpoint
|
str | PathLike[str]
|
Checkpoint path passed to :func: |
required |
state_dict_key
|
str | None
|
Optional key used by Lightning-style checkpoints. |
None
|
map_location
|
str | dict[str, str] | 'torch.device' | None
|
Device mapping passed to :func: |
None
|
weights_only
|
bool | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, Shaped[Tensor, '...']]
|
Mapping of checkpoint parameter names to tensors. |
Source code in lib/laygen/src/laygen/common/testing.py
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 | |
strip_torch_state_dict_prefix ¶
strip_torch_state_dict_prefix(
state_dict: Mapping[str, Shaped[Tensor, "..."]],
*,
strip_prefix: str,
include_prefix: str | None = None,
) -> OrderedDict[str, Shaped[torch.Tensor, "..."]]
Return a state dict with a wrapper prefix removed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dict
|
Mapping[str, Shaped[Tensor, '...']]
|
Source state dictionary. |
required |
strip_prefix
|
str
|
Prefix to remove from each emitted key. |
required |
include_prefix
|
str | None
|
Optional prefix filter. When set, only matching keys are emitted. |
None
|
Returns:
| Type | Description |
|---|---|
OrderedDict[str, Shaped[Tensor, '...']]
|
Ordered state dictionary with normalized keys. |
Source code in lib/laygen/src/laygen/common/testing.py
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | |
vendor_backbone_kwargs ¶
vendor_backbone_kwargs(
config: Mapping[str, ConfigValue] | ConfigAttributes,
fields: Sequence[str],
*,
aliases: Mapping[str, str] | None = None,
overrides: Mapping[str, ConfigValue] | None = None,
) -> dict[str, ConfigValue]
Build checkpoint-backbone constructor kwargs from a config object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Mapping[str, ConfigValue] | ConfigAttributes
|
Object or mapping that stores canonical package configuration. |
required |
fields
|
Sequence[str]
|
Constructor argument names to read in order. |
required |
aliases
|
Mapping[str, str] | None
|
Optional mapping from constructor argument name to config field name. |
None
|
overrides
|
Mapping[str, ConfigValue] | None
|
Optional explicit values that take precedence over |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, ConfigValue]
|
Ordered keyword arguments suitable for a checkpoint-backbone constructor. |
Source code in lib/laygen/src/laygen/common/testing.py
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 | |
install_jaxtyping_runtime_hook ¶
install_jaxtyping_runtime_hook(
modules: Sequence[str],
) -> AbstractContextManager[None]
Install the test-only jaxtyping runtime checker for target modules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
modules
|
Sequence[str]
|
Importable module or package names to hook before import. |
required |
Returns:
| Type | Description |
|---|---|
AbstractContextManager[None]
|
Context manager returned by :func: |
Examples:
>>> hook = install_jaxtyping_runtime_hook(["laygen.common.bbox"])
>>> hasattr(hook, "__enter__")
True
Source code in lib/laygen/src/laygen/common/testing.py
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 | |
tokenization ¶
Shared helpers for lightweight whitespace layout tokenizers.
WhitespaceTokenizerMixin ¶
Mixin for tokenizers backed by tokenizer-local id dictionaries.
Source code in lib/laygen/src/laygen/common/tokenization.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | |
get_vocab ¶
get_vocab() -> dict[str, int]
Return token-to-id mapping.
Source code in lib/laygen/src/laygen/common/tokenization.py
86 87 88 | |
convert_tokens_to_string ¶
convert_tokens_to_string(tokens: list[str]) -> str
Join layout tokens with spaces.
Source code in lib/laygen/src/laygen/common/tokenization.py
102 103 104 | |
build_token_maps ¶
build_token_maps(
*,
vocab_file: str | PathLike[str] | None,
tokens: Sequence[str] | None,
base_tokens: Sequence[str],
numeric_id_vocab: bool = False,
) -> tuple[dict[str, int], dict[int, str]]
Build token/id maps from a JSON vocabulary file or synthetic token list.
Source code in lib/laygen/src/laygen/common/tokenization.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | |
split_whitespace_tokens ¶
split_whitespace_tokens(text: str) -> list[str]
Split a layout token string on whitespace.
Source code in lib/laygen/src/laygen/common/tokenization.py
36 37 38 | |
convert_token_to_id ¶
convert_token_to_id(
token2id: dict[str, int], token: str, unk_token_id: int
) -> int
Convert a token to an id using a tokenizer-local unknown-token id.
Source code in lib/laygen/src/laygen/common/tokenization.py
41 42 43 | |
convert_id_to_token ¶
convert_id_to_token(
id2token: dict[int, str], index: int, unk_token: str
) -> str
Convert an id to a token using a tokenizer-local unknown token string.
Source code in lib/laygen/src/laygen/common/tokenization.py
46 47 48 | |
join_tokens ¶
join_tokens(tokens: Sequence[str]) -> str
Join already-tokenized layout tokens with spaces.
Source code in lib/laygen/src/laygen/common/tokenization.py
51 52 53 | |
save_json_vocabulary ¶
save_json_vocabulary(
*,
save_directory: str | PathLike[str],
filename: str,
data: dict[str, int] | dict[str, str],
filename_prefix: str | None = None,
) -> tuple[str]
Save tokenizer vocabulary JSON and return the generated path.
Source code in lib/laygen/src/laygen/common/tokenization.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | |
training ¶
Shared training-step helpers for layout generator Lightning modules.
ScalarLogger ¶
Bases: Protocol
Minimal scalar logging protocol implemented by Lightning modules.
Source code in lib/laygen/src/laygen/common/training.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | |
log ¶
log(
name: str,
value: Float[Tensor, ""],
*,
prog_bar: bool = False,
on_step: bool | None = None,
on_epoch: bool | None = None,
batch_size: int | None = None,
) -> None
Log a scalar training metric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Metric name. |
required |
value
|
Float[Tensor, '']
|
Scalar tensor value. |
required |
prog_bar
|
bool
|
Whether to show the value in the progress bar. |
False
|
on_step
|
bool | None
|
Whether to aggregate the value per step. |
None
|
on_epoch
|
bool | None
|
Whether to aggregate the value per epoch. |
None
|
batch_size
|
int | None
|
Batch size used by Lightning metric aggregation. |
None
|
Source code in lib/laygen/src/laygen/common/training.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | |
sum_loss_values ¶
sum_loss_values(
losses: Mapping[str, Float[Tensor, ""]],
) -> Float[torch.Tensor, ""]
Sum scalar loss values with the canonical training reduction.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
losses
|
Mapping[str, Float[Tensor, '']]
|
Mapping from metric names to scalar loss tensors. |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, '']
|
Scalar tensor containing the sum of all loss values. |
Examples:
>>> import torch
>>> sum_loss_values({"a": torch.tensor(1.0), "b": torch.tensor(2.0)})
tensor(3.)
Source code in lib/laygen/src/laygen/common/training.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
log_training_losses ¶
log_training_losses(
logger: ScalarLogger,
losses: Mapping[str, Float[Tensor, ""]],
total: Float[Tensor, ""],
*,
batch_size: int = 1,
) -> None
Log per-component and total training losses.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logger
|
ScalarLogger
|
Object exposing Lightning-compatible |
required |
losses
|
Mapping[str, Float[Tensor, '']]
|
Per-component scalar loss values. |
required |
total
|
Float[Tensor, '']
|
Total scalar training loss. |
required |
batch_size
|
int
|
Batch size used by Lightning metric aggregation. |
1
|
Returns:
| Type | Description |
|---|---|
None
|
None. |
Source code in lib/laygen/src/laygen/common/training.py
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 | |
finish_training_step ¶
finish_training_step(
logger: ScalarLogger,
losses: Mapping[str, Float[Tensor, ""]],
trace: Mapping[str, Shaped[Tensor, "..."]],
*,
batch_size: int = 1,
) -> tuple[
Float[torch.Tensor, ""],
dict[str, Shaped[torch.Tensor, "..."]],
]
Reduce losses, log training metrics, and append train_loss to a trace.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logger
|
ScalarLogger
|
Object exposing Lightning-compatible |
required |
losses
|
Mapping[str, Float[Tensor, '']]
|
Per-component scalar loss values. |
required |
trace
|
Mapping[str, Shaped[Tensor, '...']]
|
Training trace entries produced before the optimizer step. |
required |
batch_size
|
int
|
Batch size used by Lightning metric aggregation. |
1
|
Returns:
| Type | Description |
|---|---|
tuple[Float[Tensor, ''], dict[str, Shaped[Tensor, '...']]]
|
Total scalar loss and an updated detached trace mapping. |
Source code in lib/laygen/src/laygen/common/training.py
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | |
log_validation_loss ¶
log_validation_loss(
logger: ScalarLogger,
total: Float[Tensor, ""],
*,
batch_size: int = 1,
) -> None
Log the canonical validation loss metric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logger
|
ScalarLogger
|
Object exposing Lightning-compatible |
required |
total
|
Float[Tensor, '']
|
Scalar validation loss. |
required |
batch_size
|
int
|
Batch size used by Lightning metric aggregation. |
1
|
Returns:
| Type | Description |
|---|---|
None
|
None. |
Source code in lib/laygen/src/laygen/common/training.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 | |
vendor ¶
Vendor repository path helpers shared by parity scripts.
vendor_root ¶
vendor_root(
repo: str,
*,
marker: str | Path | None = None,
path: str | Path | None = None,
repo_root: Path | None = None,
cwd: Path | None = None,
) -> Path
Resolve an initialized vendor submodule checkout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo
|
str
|
Repository directory name under |
required |
marker
|
str | Path | None
|
Optional file that must exist inside the vendor checkout. |
None
|
path
|
str | Path | None
|
Optional user-supplied path. Defaults to |
None
|
repo_root
|
Path | None
|
Optional repository root override for tests. |
None
|
cwd
|
Path | None
|
Optional current working directory override for tests. |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
Resolved path to the vendor checkout. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the checkout or marker cannot be found. |
Examples:
>>> vendor_root("const-layout")
PosixPath('...')
Source code in lib/laygen/src/laygen/common/vendor.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | |
visualization ¶
Lightweight visualization helpers for generated layouts.
render_layout ¶
render_layout(
bbox: Float[Tensor, "elements 4"],
labels: Int[Tensor, "elements"],
mask: Bool[Tensor, "elements"],
id2label: dict[int, str],
*,
ax: Axes | None = None,
canvas_size: tuple[int, int] = (1, 1),
colors: Iterable[str] | None = None,
) -> Axes
Render one layout on a Matplotlib axis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
|
Float[Tensor, 'elements 4']
|
Normalized center |
required |
labels
|
Int[Tensor, 'elements']
|
Integer labels for one sample. |
required |
mask
|
Bool[Tensor, 'elements']
|
Boolean valid-element mask for one sample. |
required |
id2label
|
dict[int, str]
|
Mapping from integer ids to label names. |
required |
ax
|
Axes | None
|
Optional Matplotlib axis. A new axis is created when omitted. |
None
|
canvas_size
|
tuple[int, int]
|
Canvas size as |
(1, 1)
|
colors
|
Iterable[str] | None
|
Optional color cycle. |
None
|
Returns:
| Type | Description |
|---|---|
Axes
|
Axis containing rectangle patches and label text. |
Examples:
>>> import torch
>>> ax = render_layout(
... torch.zeros(1, 4),
... torch.zeros(1, dtype=torch.long),
... torch.ones(1, dtype=torch.bool),
... {0: "text"},
... )
>>> ax is not None
True
Source code in lib/laygen/src/laygen/common/visualization.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | |
modeling_outputs ¶
Canonical Transformers-compatible output types for layout generation.
This module is intentionally excluded from jaxtyping runtime import hooks because
Transformers ModelOutput dataclasses are backend-neutral containers. Static
annotations document the accepted NumPy/torch field shapes, while runtime shape
guarantees are provided by laygen.common.testing.assert_layout_output_schema.
LayoutGenerationOutput
dataclass
¶
Bases: ModelOutput
Canonical layout-generation output for Transformers-style APIs.
Attributes:
| Name | Type | Description |
|---|---|---|
bbox |
Float[ndarray, 'batch elements 4'] | Float[Tensor, 'batch elements 4']
|
Normalized center |
labels |
Int[ndarray, 'batch elements'] | Int[Tensor, 'batch elements']
|
Dataset-local integer labels with shape |
mask |
Bool[ndarray, 'batch elements'] | Bool[Tensor, 'batch elements']
|
Boolean valid-element mask with shape |
id2label |
dict[int, str]
|
Mapping from integer label ids to display names. |
sequences |
object | None
|
Optional raw token sequences. |
scores |
object | None
|
Optional per-token or per-element scores. |
trajectory |
object | None
|
Optional sampling trajectory. |
intermediates |
object | None
|
Optional model-specific debug or auxiliary data. |
Examples:
>>> import numpy as np
>>> output = LayoutGenerationOutput(
... bbox=np.zeros((1, 1, 4), dtype=np.float32),
... labels=np.zeros((1, 1), dtype=np.int64),
... mask=np.ones((1, 1), dtype=bool),
... id2label={0: "text"},
... )
>>> output["bbox"].shape
(1, 1, 4)
Source code in lib/laygen/src/laygen/modeling_outputs.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | |
nn ¶
Shared PyTorch neural-network helpers for layout generation models.
ActivationFn ¶
Bases: Protocol
Callable activation function for tensor-valued feed-forward blocks.
Source code in lib/laygen/src/laygen/nn/activations.py
31 32 33 34 35 36 37 38 39 | |
__call__ ¶
__call__(
input: Float[Tensor, ...],
) -> Float[torch.Tensor, ...]
Apply the activation to a tensor.
Source code in lib/laygen/src/laygen/nn/activations.py
35 36 37 38 39 | |
ActivationName ¶
Bases: StrEnum
Supported feed-forward activation names.
Origin
gelu2 is the VQ-Diffusion GELU2/QuickGELU branch used by the
LayoutDM, LACE, and LayoutFlow transformer utilities.
Source code in lib/laygen/src/laygen/nn/activations.py
18 19 20 21 22 23 24 25 26 27 28 | |
ElementPositionalEmbedding ¶
Bases: Module
Learned element and attribute positional embedding.
Origin
This learned element/attribute positional embedding is specific to CyberAgentAILab LayoutDM and is reused by Layout-Corrector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim_model
|
int
|
Embedding dimension. |
required |
max_token_length
|
int
|
Maximum flattened token sequence length. |
required |
n_attr_per_elem
|
int
|
Number of attributes per layout element. |
5
|
Source code in lib/laygen/src/laygen/nn/embeddings.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
no_decay_param_names
property
¶
no_decay_param_names: list[str]
Return parameter names that should skip weight decay.
__init__ ¶
__init__(
dim_model: int,
max_token_length: int,
n_attr_per_elem: int = 5,
) -> None
Initialize element and attribute embedding parameters.
Source code in lib/laygen/src/laygen/nn/embeddings.py
115 116 117 118 119 120 121 122 123 | |
forward ¶
forward(
h: Float[Tensor, "batch tokens channels"],
) -> Float[torch.Tensor, "batch tokens channels"]
Return positional embeddings matching hidden-state length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h
|
Float[Tensor, 'batch tokens channels']
|
Hidden states shaped |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'batch tokens channels']
|
Positional embedding tensor shaped like |
Source code in lib/laygen/src/laygen/nn/embeddings.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
SinusoidalPosEmb ¶
Bases: Module
Sinusoidal timestep or position embedding.
Origin
This is the VQ-Diffusion-style sinusoidal timestep embedding carried by
LayoutDM and LACE. The checkpoint operation order is preserved exactly
because LACE denoiser parity is bit-sensitive at rescale_steps=4000.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_steps
|
int
|
Maximum number of positions or timesteps. |
required |
dim
|
int
|
Embedding dimension. Odd dimensions keep the checkpoint truncation
behavior and return |
required |
rescale_steps
|
int
|
Rescaling constant used by the released checkpoints. |
4000
|
Source code in lib/laygen/src/laygen/nn/embeddings.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | |
__init__ ¶
__init__(
num_steps: int, dim: int, rescale_steps: int = 4000
) -> None
Initialize the embedding parameters.
Source code in lib/laygen/src/laygen/nn/embeddings.py
76 77 78 79 80 81 | |
forward ¶
forward(
x: Int[Tensor, "batch"],
) -> Float[torch.Tensor, "batch channels"]
Embed integer positions or timesteps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Int[Tensor, 'batch']
|
One-dimensional tensor of positions. |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'batch channels']
|
Sinusoidal embedding tensor. |
Source code in lib/laygen/src/laygen/nn/embeddings.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | |
TimestepEmbeddingType ¶
Bases: StrEnum
Supported timestep-conditioned normalization variants.
Origin
These names come from VQ-Diffusion-derived adaptive normalization modes used by the LayoutDM and LACE checkpoint backbones.
Source code in lib/laygen/src/laygen/nn/embeddings.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 | |
AdaInsNorm ¶
Bases: _AdaNorm
Adaptive instance normalization conditioned on diffusion timestep.
Origin
This module follows VQ-Diffusion AdaInsNorm as used by the LACE
checkpoint backbone; Diffusers has no key-compatible AdaInstanceNorm path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_embd
|
int
|
Hidden dimension. |
required |
max_timestep
|
int
|
Maximum diffusion timestep. |
required |
emb_type
|
TimestepEmbeddingType | str
|
Timestep embedding variant. |
adalayernorm_abs
|
Source code in lib/laygen/src/laygen/nn/norms.py
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__(
n_embd: int,
max_timestep: int,
emb_type: TimestepEmbeddingType
| str = TimestepEmbeddingType.adalayernorm_abs,
) -> None
Initialize adaptive instance normalization.
Source code in lib/laygen/src/laygen/nn/norms.py
89 90 91 92 93 94 95 96 97 | |
forward ¶
forward(
x: Float[Tensor, "batch tokens channels"],
timestep: Int[Tensor, "batch"],
) -> Float[torch.Tensor, "batch tokens channels"]
Apply timestep-conditioned instance normalization.
Source code in lib/laygen/src/laygen/nn/norms.py
99 100 101 102 103 104 105 106 107 108 109 110 | |
AdaLayerNorm ¶
Bases: _AdaNorm
Adaptive layer normalization conditioned on diffusion timestep.
Origin
This module follows VQ-Diffusion AdaLayerNorm and keeps the
submodule names used by LayoutDM, LACE, and Layout-Corrector checkpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_embd
|
int
|
Hidden dimension. |
required |
max_timestep
|
int
|
Maximum diffusion timestep. |
required |
emb_type
|
TimestepEmbeddingType | str
|
Timestep embedding variant. |
adalayernorm_abs
|
Source code in lib/laygen/src/laygen/nn/norms.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | |
__init__ ¶
__init__(
n_embd: int,
max_timestep: int,
emb_type: TimestepEmbeddingType
| str = TimestepEmbeddingType.adalayernorm_abs,
) -> None
Initialize adaptive layer normalization.
Source code in lib/laygen/src/laygen/nn/norms.py
55 56 57 58 59 60 61 62 63 | |
forward ¶
forward(
x: Float[Tensor, "batch tokens channels"],
timestep: Int[Tensor, "batch"],
) -> Float[torch.Tensor, "batch tokens channels"]
Apply timestep-conditioned layer normalization.
Source code in lib/laygen/src/laygen/nn/norms.py
65 66 67 68 69 70 71 72 73 | |
TimestepTransformerEncoder ¶
Bases: Module
Stack of cloned timestep transformer encoder layers.
Origin
This is the VQ-Diffusion-style cloned TransformerEncoder wrapper
used by LayoutDM and Layout-Corrector around the shared Block layer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoder_layer
|
TimestepTransformerEncoderLayer
|
Layer to clone for the stack. |
required |
num_layers
|
int
|
Number of cloned layers. |
required |
norm
|
Module | None
|
Optional final normalization module. |
None
|
Source code in lib/laygen/src/laygen/nn/blocks.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
__init__ ¶
__init__(
encoder_layer: TimestepTransformerEncoderLayer,
num_layers: int,
norm: Module | None = None,
) -> None
Initialize a transformer encoder stack.
Source code in lib/laygen/src/laygen/nn/blocks.py
155 156 157 158 159 160 161 162 163 164 165 | |
forward ¶
forward(
src: Float[Tensor, "batch tokens channels"],
mask: Bool[Tensor, "..."] | None = None,
src_key_padding_mask: Bool[Tensor, "batch tokens"]
| None = None,
timestep: Int[Tensor, "batch"] | None = None,
) -> Float[torch.Tensor, "batch tokens channels"]
Run hidden states through all encoder layers.
Source code in lib/laygen/src/laygen/nn/blocks.py
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
TimestepTransformerEncoderLayer ¶
Bases: Module
Transformer encoder block with optional adaptive normalization.
Origin
This class follows VQ-Diffusion Block rather than Diffusers
BasicTransformerBlock so checkpoint keys and adaptive norm call
conventions stay compatible with LayoutDM, LACE, and Layout-Corrector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d_model
|
int
|
Hidden dimension. |
512
|
nhead
|
int
|
Number of attention heads. |
8
|
dim_feedforward
|
int
|
Feed-forward hidden dimension. |
2048
|
dropout
|
float
|
Dropout probability. |
0.0
|
activation
|
ActivationName | str | ActivationFn
|
Feed-forward activation name or callable. |
relu
|
batch_first
|
bool
|
Whether inputs use |
True
|
norm_first
|
bool
|
Whether to use pre-norm residual blocks. |
True
|
diffusion_step
|
int
|
Maximum diffusion timestep. |
100
|
timestep_type
|
TimestepEmbeddingType | str | None
|
Timestep-conditioned normalization variant. |
adalayernorm
|
Source code in lib/laygen/src/laygen/nn/blocks.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | |
__init__ ¶
__init__(
d_model: int = 512,
nhead: int = 8,
dim_feedforward: int = 2048,
dropout: float = 0.0,
activation: ActivationName
| str
| ActivationFn = ActivationName.relu,
batch_first: bool = True,
norm_first: bool = True,
diffusion_step: int = 100,
timestep_type: TimestepEmbeddingType
| str
| None = TimestepEmbeddingType.adalayernorm,
) -> None
Initialize the transformer encoder block.
Source code in lib/laygen/src/laygen/nn/blocks.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 | |
forward ¶
forward(
src: Float[Tensor, "batch tokens channels"],
src_mask: Bool[Tensor, "..."] | None = None,
src_key_padding_mask: Bool[Tensor, "batch tokens"]
| None = None,
timestep: Int[Tensor, "batch"] | None = None,
) -> Float[torch.Tensor, "batch tokens channels"]
Apply self-attention and feed-forward layers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
Float[Tensor, 'batch tokens channels']
|
Input sequence. |
required |
src_mask
|
Bool[Tensor, '...'] | None
|
Optional attention mask. |
None
|
src_key_padding_mask
|
Bool[Tensor, 'batch tokens'] | None
|
Optional padding mask. |
None
|
timestep
|
Int[Tensor, 'batch'] | None
|
Diffusion timestep tensor for adaptive normalization. |
None
|
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'batch tokens channels']
|
Transformed sequence. |
Source code in lib/laygen/src/laygen/nn/blocks.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | |
get_activation ¶
get_activation(
name: ActivationName | str | ActivationFn,
) -> ActivationFn
Return the activation callable for a supported activation name.
Origin
The gelu2 branch resolves to Transformers ACT2FN["quick_gelu"],
which is formula-equivalent to VQ-Diffusion's GELU2 implementation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
ActivationName | str | ActivationFn
|
Activation enum, string value, or callable. |
required |
Returns:
| Type | Description |
|---|---|
ActivationFn
|
Activation callable. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the activation name is unsupported. |
Source code in lib/laygen/src/laygen/nn/activations.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 | |
normalize_activation ¶
normalize_activation(
name: ActivationName | str | ActivationFn,
) -> ActivationName | ActivationFn
Normalize an activation name while preserving custom callables.
Origin
The closed string set keeps the activation names used by VQ-Diffusion-derived LayoutDM, LACE, and LayoutFlow backbones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
ActivationName | str | ActivationFn
|
Activation enum, string value, or callable. |
required |
Returns:
| Type | Description |
|---|---|
ActivationName | ActivationFn
|
Canonical activation enum or the original callable. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the activation name is unsupported. |
Source code in lib/laygen/src/laygen/nn/activations.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 | |
normalize_timestep_embedding ¶
normalize_timestep_embedding(
timestep_type: TimestepEmbeddingType | str | None,
) -> TimestepEmbeddingType | None
Normalize a timestep embedding mode.
Origin
This normalizes the VQ-Diffusion-derived adaptive normalization mode names exposed by LayoutDM and LACE checkpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timestep_type
|
TimestepEmbeddingType | str | None
|
Embedding enum, string value, or |
required |
Returns:
| Type | Description |
|---|---|
TimestepEmbeddingType | None
|
Canonical embedding enum or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the embedding mode is unsupported. |
Source code in lib/laygen/src/laygen/nn/embeddings.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | |
clone_module_list ¶
clone_module_list(module: Module, n: int) -> nn.ModuleList
Return n deep-copied modules in a ModuleList.
Origin
This is the mechanical clone helper used by VQ-Diffusion-derived LayoutDM/LACE transformer stacks and by the LayoutFlow checkpoint backbone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
Module
|
Module to clone. |
required |
n
|
int
|
Number of clones. |
required |
Returns:
| Type | Description |
|---|---|
ModuleList
|
ModuleList containing independent deep copies. |
Source code in lib/laygen/src/laygen/nn/module_utils.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
activations ¶
Activation helpers shared by layout-generation transformer modules.
The gelu2 alias follows Microsoft VQ-Diffusion's GELU2/QuickGELU
activation used by the LayoutDM, LACE, and LayoutFlow checkpoint backbones.
ActivationName ¶
Bases: StrEnum
Supported feed-forward activation names.
Origin
gelu2 is the VQ-Diffusion GELU2/QuickGELU branch used by the
LayoutDM, LACE, and LayoutFlow transformer utilities.
Source code in lib/laygen/src/laygen/nn/activations.py
18 19 20 21 22 23 24 25 26 27 28 | |
ActivationFn ¶
Bases: Protocol
Callable activation function for tensor-valued feed-forward blocks.
Source code in lib/laygen/src/laygen/nn/activations.py
31 32 33 34 35 36 37 38 39 | |
__call__ ¶
__call__(
input: Float[Tensor, ...],
) -> Float[torch.Tensor, ...]
Apply the activation to a tensor.
Source code in lib/laygen/src/laygen/nn/activations.py
35 36 37 38 39 | |
normalize_activation ¶
normalize_activation(
name: ActivationName | str | ActivationFn,
) -> ActivationName | ActivationFn
Normalize an activation name while preserving custom callables.
Origin
The closed string set keeps the activation names used by VQ-Diffusion-derived LayoutDM, LACE, and LayoutFlow backbones.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
ActivationName | str | ActivationFn
|
Activation enum, string value, or callable. |
required |
Returns:
| Type | Description |
|---|---|
ActivationName | ActivationFn
|
Canonical activation enum or the original callable. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the activation name is unsupported. |
Source code in lib/laygen/src/laygen/nn/activations.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 | |
get_activation ¶
get_activation(
name: ActivationName | str | ActivationFn,
) -> ActivationFn
Return the activation callable for a supported activation name.
Origin
The gelu2 branch resolves to Transformers ACT2FN["quick_gelu"],
which is formula-equivalent to VQ-Diffusion's GELU2 implementation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
ActivationName | str | ActivationFn
|
Activation enum, string value, or callable. |
required |
Returns:
| Type | Description |
|---|---|
ActivationFn
|
Activation callable. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the activation name is unsupported. |
Source code in lib/laygen/src/laygen/nn/activations.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 | |
blocks ¶
Transformer encoder blocks shared by layout-generation models.
The timestep-aware encoder layer follows Microsoft VQ-Diffusion's
transformer_utils.Block structure as carried by LayoutDM, LACE, and
Layout-Corrector reference implementations.
TimestepTransformerEncoderLayer ¶
Bases: Module
Transformer encoder block with optional adaptive normalization.
Origin
This class follows VQ-Diffusion Block rather than Diffusers
BasicTransformerBlock so checkpoint keys and adaptive norm call
conventions stay compatible with LayoutDM, LACE, and Layout-Corrector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
d_model
|
int
|
Hidden dimension. |
512
|
nhead
|
int
|
Number of attention heads. |
8
|
dim_feedforward
|
int
|
Feed-forward hidden dimension. |
2048
|
dropout
|
float
|
Dropout probability. |
0.0
|
activation
|
ActivationName | str | ActivationFn
|
Feed-forward activation name or callable. |
relu
|
batch_first
|
bool
|
Whether inputs use |
True
|
norm_first
|
bool
|
Whether to use pre-norm residual blocks. |
True
|
diffusion_step
|
int
|
Maximum diffusion timestep. |
100
|
timestep_type
|
TimestepEmbeddingType | str | None
|
Timestep-conditioned normalization variant. |
adalayernorm
|
Source code in lib/laygen/src/laygen/nn/blocks.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | |
__init__ ¶
__init__(
d_model: int = 512,
nhead: int = 8,
dim_feedforward: int = 2048,
dropout: float = 0.0,
activation: ActivationName
| str
| ActivationFn = ActivationName.relu,
batch_first: bool = True,
norm_first: bool = True,
diffusion_step: int = 100,
timestep_type: TimestepEmbeddingType
| str
| None = TimestepEmbeddingType.adalayernorm,
) -> None
Initialize the transformer encoder block.
Source code in lib/laygen/src/laygen/nn/blocks.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 | |
forward ¶
forward(
src: Float[Tensor, "batch tokens channels"],
src_mask: Bool[Tensor, "..."] | None = None,
src_key_padding_mask: Bool[Tensor, "batch tokens"]
| None = None,
timestep: Int[Tensor, "batch"] | None = None,
) -> Float[torch.Tensor, "batch tokens channels"]
Apply self-attention and feed-forward layers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
src
|
Float[Tensor, 'batch tokens channels']
|
Input sequence. |
required |
src_mask
|
Bool[Tensor, '...'] | None
|
Optional attention mask. |
None
|
src_key_padding_mask
|
Bool[Tensor, 'batch tokens'] | None
|
Optional padding mask. |
None
|
timestep
|
Int[Tensor, 'batch'] | None
|
Diffusion timestep tensor for adaptive normalization. |
None
|
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'batch tokens channels']
|
Transformed sequence. |
Source code in lib/laygen/src/laygen/nn/blocks.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | |
TimestepTransformerEncoder ¶
Bases: Module
Stack of cloned timestep transformer encoder layers.
Origin
This is the VQ-Diffusion-style cloned TransformerEncoder wrapper
used by LayoutDM and Layout-Corrector around the shared Block layer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
encoder_layer
|
TimestepTransformerEncoderLayer
|
Layer to clone for the stack. |
required |
num_layers
|
int
|
Number of cloned layers. |
required |
norm
|
Module | None
|
Optional final normalization module. |
None
|
Source code in lib/laygen/src/laygen/nn/blocks.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
__init__ ¶
__init__(
encoder_layer: TimestepTransformerEncoderLayer,
num_layers: int,
norm: Module | None = None,
) -> None
Initialize a transformer encoder stack.
Source code in lib/laygen/src/laygen/nn/blocks.py
155 156 157 158 159 160 161 162 163 164 165 | |
forward ¶
forward(
src: Float[Tensor, "batch tokens channels"],
mask: Bool[Tensor, "..."] | None = None,
src_key_padding_mask: Bool[Tensor, "batch tokens"]
| None = None,
timestep: Int[Tensor, "batch"] | None = None,
) -> Float[torch.Tensor, "batch tokens channels"]
Run hidden states through all encoder layers.
Source code in lib/laygen/src/laygen/nn/blocks.py
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 | |
embeddings ¶
Embedding modules shared by layout-generation models.
SinusoidalPosEmb follows the VQ-Diffusion-derived timestep embedding used
by the LayoutDM and LACE checkpoint backbones. ElementPositionalEmbedding is a
LayoutDM-specific element/attribute position embedding.
TimestepEmbeddingType ¶
Bases: StrEnum
Supported timestep-conditioned normalization variants.
Origin
These names come from VQ-Diffusion-derived adaptive normalization modes used by the LayoutDM and LACE checkpoint backbones.
Source code in lib/laygen/src/laygen/nn/embeddings.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 | |
SinusoidalPosEmb ¶
Bases: Module
Sinusoidal timestep or position embedding.
Origin
This is the VQ-Diffusion-style sinusoidal timestep embedding carried by
LayoutDM and LACE. The checkpoint operation order is preserved exactly
because LACE denoiser parity is bit-sensitive at rescale_steps=4000.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_steps
|
int
|
Maximum number of positions or timesteps. |
required |
dim
|
int
|
Embedding dimension. Odd dimensions keep the checkpoint truncation
behavior and return |
required |
rescale_steps
|
int
|
Rescaling constant used by the released checkpoints. |
4000
|
Source code in lib/laygen/src/laygen/nn/embeddings.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | |
__init__ ¶
__init__(
num_steps: int, dim: int, rescale_steps: int = 4000
) -> None
Initialize the embedding parameters.
Source code in lib/laygen/src/laygen/nn/embeddings.py
76 77 78 79 80 81 | |
forward ¶
forward(
x: Int[Tensor, "batch"],
) -> Float[torch.Tensor, "batch channels"]
Embed integer positions or timesteps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Int[Tensor, 'batch']
|
One-dimensional tensor of positions. |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'batch channels']
|
Sinusoidal embedding tensor. |
Source code in lib/laygen/src/laygen/nn/embeddings.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | |
ElementPositionalEmbedding ¶
Bases: Module
Learned element and attribute positional embedding.
Origin
This learned element/attribute positional embedding is specific to CyberAgentAILab LayoutDM and is reused by Layout-Corrector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dim_model
|
int
|
Embedding dimension. |
required |
max_token_length
|
int
|
Maximum flattened token sequence length. |
required |
n_attr_per_elem
|
int
|
Number of attributes per layout element. |
5
|
Source code in lib/laygen/src/laygen/nn/embeddings.py
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
no_decay_param_names
property
¶
no_decay_param_names: list[str]
Return parameter names that should skip weight decay.
__init__ ¶
__init__(
dim_model: int,
max_token_length: int,
n_attr_per_elem: int = 5,
) -> None
Initialize element and attribute embedding parameters.
Source code in lib/laygen/src/laygen/nn/embeddings.py
115 116 117 118 119 120 121 122 123 | |
forward ¶
forward(
h: Float[Tensor, "batch tokens channels"],
) -> Float[torch.Tensor, "batch tokens channels"]
Return positional embeddings matching hidden-state length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
h
|
Float[Tensor, 'batch tokens channels']
|
Hidden states shaped |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'batch tokens channels']
|
Positional embedding tensor shaped like |
Source code in lib/laygen/src/laygen/nn/embeddings.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 | |
normalize_timestep_embedding ¶
normalize_timestep_embedding(
timestep_type: TimestepEmbeddingType | str | None,
) -> TimestepEmbeddingType | None
Normalize a timestep embedding mode.
Origin
This normalizes the VQ-Diffusion-derived adaptive normalization mode names exposed by LayoutDM and LACE checkpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timestep_type
|
TimestepEmbeddingType | str | None
|
Embedding enum, string value, or |
required |
Returns:
| Type | Description |
|---|---|
TimestepEmbeddingType | None
|
Canonical embedding enum or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the embedding mode is unsupported. |
Source code in lib/laygen/src/laygen/nn/embeddings.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | |
module_utils ¶
Small module-construction helpers.
clone_module_list is the deep-copy ModuleList helper used by the
VQ-Diffusion-derived LayoutDM/LACE blocks and the LayoutFlow checkpoint backbone.
clone_module_list ¶
clone_module_list(module: Module, n: int) -> nn.ModuleList
Return n deep-copied modules in a ModuleList.
Origin
This is the mechanical clone helper used by VQ-Diffusion-derived LayoutDM/LACE transformer stacks and by the LayoutFlow checkpoint backbone.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
module
|
Module
|
Module to clone. |
required |
n
|
int
|
Number of clones. |
required |
Returns:
| Type | Description |
|---|---|
ModuleList
|
ModuleList containing independent deep copies. |
Source code in lib/laygen/src/laygen/nn/module_utils.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
norms ¶
Adaptive normalization layers shared by layout-generation models.
These adaptive normalization layers follow Microsoft VQ-Diffusion's
AdaLayerNorm/AdaInsNorm utilities used by the LayoutDM and LACE
checkpoint backbones.
AdaLayerNorm ¶
Bases: _AdaNorm
Adaptive layer normalization conditioned on diffusion timestep.
Origin
This module follows VQ-Diffusion AdaLayerNorm and keeps the
submodule names used by LayoutDM, LACE, and Layout-Corrector checkpoints.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_embd
|
int
|
Hidden dimension. |
required |
max_timestep
|
int
|
Maximum diffusion timestep. |
required |
emb_type
|
TimestepEmbeddingType | str
|
Timestep embedding variant. |
adalayernorm_abs
|
Source code in lib/laygen/src/laygen/nn/norms.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | |
__init__ ¶
__init__(
n_embd: int,
max_timestep: int,
emb_type: TimestepEmbeddingType
| str = TimestepEmbeddingType.adalayernorm_abs,
) -> None
Initialize adaptive layer normalization.
Source code in lib/laygen/src/laygen/nn/norms.py
55 56 57 58 59 60 61 62 63 | |
forward ¶
forward(
x: Float[Tensor, "batch tokens channels"],
timestep: Int[Tensor, "batch"],
) -> Float[torch.Tensor, "batch tokens channels"]
Apply timestep-conditioned layer normalization.
Source code in lib/laygen/src/laygen/nn/norms.py
65 66 67 68 69 70 71 72 73 | |
AdaInsNorm ¶
Bases: _AdaNorm
Adaptive instance normalization conditioned on diffusion timestep.
Origin
This module follows VQ-Diffusion AdaInsNorm as used by the LACE
checkpoint backbone; Diffusers has no key-compatible AdaInstanceNorm path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_embd
|
int
|
Hidden dimension. |
required |
max_timestep
|
int
|
Maximum diffusion timestep. |
required |
emb_type
|
TimestepEmbeddingType | str
|
Timestep embedding variant. |
adalayernorm_abs
|
Source code in lib/laygen/src/laygen/nn/norms.py
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__(
n_embd: int,
max_timestep: int,
emb_type: TimestepEmbeddingType
| str = TimestepEmbeddingType.adalayernorm_abs,
) -> None
Initialize adaptive instance normalization.
Source code in lib/laygen/src/laygen/nn/norms.py
89 90 91 92 93 94 95 96 97 | |
forward ¶
forward(
x: Float[Tensor, "batch tokens channels"],
timestep: Int[Tensor, "batch"],
) -> Float[torch.Tensor, "batch tokens channels"]
Apply timestep-conditioned instance normalization.
Source code in lib/laygen/src/laygen/nn/norms.py
99 100 101 102 103 104 105 106 107 108 109 110 | |
pipelines ¶
Pipeline base and output types for layout-generation packages.
LayoutGenerationOutput
dataclass
¶
Bases: ModelOutput
Canonical layout-generation output for Transformers-style APIs.
Attributes:
| Name | Type | Description |
|---|---|---|
bbox |
Float[ndarray, 'batch elements 4'] | Float[Tensor, 'batch elements 4']
|
Normalized center |
labels |
Int[ndarray, 'batch elements'] | Int[Tensor, 'batch elements']
|
Dataset-local integer labels with shape |
mask |
Bool[ndarray, 'batch elements'] | Bool[Tensor, 'batch elements']
|
Boolean valid-element mask with shape |
id2label |
dict[int, str]
|
Mapping from integer label ids to display names. |
sequences |
object | None
|
Optional raw token sequences. |
scores |
object | None
|
Optional per-token or per-element scores. |
trajectory |
object | None
|
Optional sampling trajectory. |
intermediates |
object | None
|
Optional model-specific debug or auxiliary data. |
Examples:
>>> import numpy as np
>>> output = LayoutGenerationOutput(
... bbox=np.zeros((1, 1, 4), dtype=np.float32),
... labels=np.zeros((1, 1), dtype=np.int64),
... mask=np.ones((1, 1), dtype=bool),
... id2label={0: "text"},
... )
>>> output["bbox"].shape
(1, 1, 4)
Source code in lib/laygen/src/laygen/modeling_outputs.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | |
LayoutGenerationPipeline ¶
Bases: ABC
Base class for Transformers-side layout-generation pipelines.
Subclasses declare checkpoint components with component_specs, implement
_from_pretrained_components, and put generation orchestration in
__call__. The public __call__ contract is to return
laygen.modeling_outputs.LayoutGenerationOutput for layout-generation
outputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
PretrainedConfig
|
Root pipeline config, usually a |
required |
Examples:
>>> from transformers import PretrainedConfig
>>> class ToyPipeline(LayoutGenerationPipeline):
... config_class = PretrainedConfig
... @classmethod
... def _from_pretrained_components(cls, *, config, components):
... return cls(config)
... def __call__(self):
... import torch
... return LayoutGenerationOutput(
... bbox=torch.zeros(1, 1, 4),
... labels=torch.zeros(1, 1, dtype=torch.long),
... mask=torch.ones(1, 1, dtype=torch.bool),
... id2label={0: "text"},
... )
>>> isinstance(ToyPipeline(PretrainedConfig()).config, PretrainedConfig)
True
Source code in lib/laygen/src/laygen/pipelines/base.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 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 | |
__init__ ¶
__init__(config: PretrainedConfig) -> None
Initialize root config and runtime placement metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
PretrainedConfig
|
Root pipeline config. |
required |
Source code in lib/laygen/src/laygen/pipelines/base.py
249 250 251 252 253 254 255 256 257 | |
from_pretrained
classmethod
¶
from_pretrained(
pretrained_model_name_or_path: str | Path,
*,
local_files_only: bool = False,
config: PretrainedConfig | None = None,
components: Mapping[str, PipelineComponent]
| None = None,
) -> Self
Load a pipeline from a checkpoint root and declared subfolders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pretrained_model_name_or_path
|
str | Path
|
Checkpoint root. |
required |
local_files_only
|
bool
|
Whether to avoid network access. |
False
|
config
|
PretrainedConfig | None
|
Optional preloaded root config. |
None
|
components
|
Mapping[str, PipelineComponent] | None
|
Optional preloaded components keyed by spec name. |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
Loaded pipeline instance. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If a required component marker file is missing. |
TypeError
|
If |
Source code in lib/laygen/src/laygen/pipelines/base.py
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 | |
save_pretrained ¶
save_pretrained(
save_directory: str | Path,
*,
is_main_process: bool = True,
) -> None
Save root config and declared components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_directory
|
str | Path
|
Checkpoint root directory. |
required |
is_main_process
|
bool
|
Whether model-like components should perform main process writes. |
True
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If a component does not implement |
ValueError
|
If a required component attribute is missing. |
Source code in lib/laygen/src/laygen/pipelines/base.py
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 | |
to ¶
to(
device: str | device | None = None,
dtype: dtype | None = None,
) -> Self
Move movable components to a device and/or dtype.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | device | None
|
Target torch device. |
None
|
dtype
|
dtype | None
|
Target torch dtype. |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
This pipeline instance. |
Source code in lib/laygen/src/laygen/pipelines/base.py
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 | |
prepare_generator ¶
prepare_generator(
*,
generator: Generator | None = None,
seed: int | None = None,
device: str | device | None = None,
) -> torch.Generator | None
Apply generator-over-seed precedence for generation calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
generator
|
Generator | None
|
Explicit torch generator. When provided, |
None
|
seed
|
int | None
|
Integer seed used only when |
None
|
device
|
str | device | None
|
Optional device for a newly created generator. If omitted, the pipeline's current device is used. |
None
|
Returns:
| Type | Description |
|---|---|
Generator | None
|
The explicit generator, a seeded generator when a device is known, |
Generator | None
|
or |
Source code in lib/laygen/src/laygen/pipelines/base.py
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 | |
__call__
abstractmethod
¶
__call__() -> LayoutGenerationOutput
Generate a layout.
Returns:
| Type | Description |
|---|---|
LayoutGenerationOutput
|
Layout generation output in the canonical Transformers-style schema. |
Source code in lib/laygen/src/laygen/pipelines/base.py
494 495 496 497 498 499 500 | |
PipelineComponentSpec
dataclass
¶
Declarative loading and saving rule for one pipeline component.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attribute_name
|
str
|
Attribute on the pipeline instance. |
required |
loader
|
PipelineComponentLoader | None
|
Loader callable used by |
None
|
subfolder
|
str | None
|
Fixed subfolder under the checkpoint root. If omitted, the root itself is used. |
None
|
config_subfolder_attribute
|
str | None
|
Config attribute that stores the subfolder
name. This takes precedence over |
None
|
required
|
bool
|
Whether missing marker files or missing instance attributes are errors. |
True
|
marker_file
|
str | None
|
File used to detect whether an optional component exists.
Set to |
'config.json'
|
save_with_is_main_process
|
bool
|
Whether to pass |
True
|
Source code in lib/laygen/src/laygen/pipelines/base.py
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 | |
component_path ¶
component_path(
root: Path, config: PretrainedConfig
) -> Path
Resolve the component path under a checkpoint root.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root
|
Path
|
Checkpoint root directory. |
required |
config
|
PretrainedConfig
|
Root pipeline config. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Resolved root or subfolder path. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the configured subfolder attribute is not a string. |
Source code in lib/laygen/src/laygen/pipelines/base.py
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 | |
component_subfolder ¶
component_subfolder(config: PretrainedConfig) -> str | None
Resolve the component subfolder for Hub-backed loading.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
PretrainedConfig
|
Root pipeline config. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
Component subfolder or |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the configured subfolder attribute is not a string. |
Source code in lib/laygen/src/laygen/pipelines/base.py
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | |
model_processor_component_specs ¶
model_processor_component_specs(
*,
model_loader: PipelineComponentLoader,
processor_loader: PipelineComponentLoader,
) -> dict[str, PipelineComponentSpec]
Build standard model/processor component specs for simple pipelines.
Source code in lib/laygen/src/laygen/pipelines/base.py
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | |
base ¶
Shared base class for Transformers-side layout-generation pipelines.
transformers.Pipeline is optimized for registered single-model tasks using a
preprocess -> _forward -> postprocess contract. Layout-generation
packages in this workspace often compose processors, tokenizers, and multiple
standard Transformers models, while still loading from a single checkpoint root
with subfolders. LayoutGenerationPipeline is the Transformers-side analogue of
Diffusers' pipeline role: it owns root config metadata, component subfolder
loading and saving, device and dtype movement, and seed/generator precedence.
Subclasses keep the model-specific orchestration in __call__.
PipelineComponent ¶
Bases: Protocol
Loaded component; operation-specific capabilities are checked later.
Source code in lib/laygen/src/laygen/pipelines/base.py
27 28 29 | |
PipelineComponentLoader ¶
Bases: Protocol
Callable that loads one pipeline component from a checkpoint path.
Source code in lib/laygen/src/laygen/pipelines/base.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | |
__call__ ¶
__call__(
pretrained_model_name_or_path: str | Path,
*,
local_files_only: bool = False,
subfolder: str | None = None,
) -> PipelineComponent
Load a component.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pretrained_model_name_or_path
|
str | Path
|
Root checkpoint path or Hub repo id. |
required |
local_files_only
|
bool
|
Whether to avoid network access. |
False
|
subfolder
|
str | None
|
Optional component subfolder for Hub-backed loading. |
None
|
Returns:
| Type | Description |
|---|---|
PipelineComponent
|
Loaded component object. |
Source code in lib/laygen/src/laygen/pipelines/base.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | |
SavePretrainedWithMainProcess ¶
Bases: Protocol
Component protocol for model-like save_pretrained methods.
Source code in lib/laygen/src/laygen/pipelines/base.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | |
save_pretrained ¶
save_pretrained(
save_directory: str | Path,
*,
is_main_process: bool = True,
) -> None | tuple[str, ...]
Save a component and accept the common main-process flag.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_directory
|
str | Path
|
Directory to write. |
required |
is_main_process
|
bool
|
Whether this process should perform main writes. |
True
|
Returns:
| Type | Description |
|---|---|
None | tuple[str, ...]
|
Component-specific save result. |
Source code in lib/laygen/src/laygen/pipelines/base.py
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | |
SavePretrainedPlain ¶
Bases: Protocol
Component protocol for processor-like save_pretrained methods.
Source code in lib/laygen/src/laygen/pipelines/base.py
75 76 77 78 79 80 81 82 83 84 85 86 87 | |
save_pretrained ¶
save_pretrained(
save_directory: str | Path,
) -> None | tuple[str, ...]
Save a component.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_directory
|
str | Path
|
Directory to write. |
required |
Returns:
| Type | Description |
|---|---|
None | tuple[str, ...]
|
Component-specific save result. |
Source code in lib/laygen/src/laygen/pipelines/base.py
79 80 81 82 83 84 85 86 87 | |
TorchMovable ¶
Bases: Protocol
Component protocol for objects that can move device and dtype.
Source code in lib/laygen/src/laygen/pipelines/base.py
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | |
to ¶
to(
*,
device: device | None = None,
dtype: dtype | None = None,
) -> Self
Move a component.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
device | None
|
Target torch device. |
None
|
dtype
|
dtype | None
|
Target torch dtype. |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
Component-specific move result. |
Source code in lib/laygen/src/laygen/pipelines/base.py
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | |
PipelineComponentSpec
dataclass
¶
Declarative loading and saving rule for one pipeline component.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
attribute_name
|
str
|
Attribute on the pipeline instance. |
required |
loader
|
PipelineComponentLoader | None
|
Loader callable used by |
None
|
subfolder
|
str | None
|
Fixed subfolder under the checkpoint root. If omitted, the root itself is used. |
None
|
config_subfolder_attribute
|
str | None
|
Config attribute that stores the subfolder
name. This takes precedence over |
None
|
required
|
bool
|
Whether missing marker files or missing instance attributes are errors. |
True
|
marker_file
|
str | None
|
File used to detect whether an optional component exists.
Set to |
'config.json'
|
save_with_is_main_process
|
bool
|
Whether to pass |
True
|
Source code in lib/laygen/src/laygen/pipelines/base.py
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 | |
component_path ¶
component_path(
root: Path, config: PretrainedConfig
) -> Path
Resolve the component path under a checkpoint root.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root
|
Path
|
Checkpoint root directory. |
required |
config
|
PretrainedConfig
|
Root pipeline config. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Resolved root or subfolder path. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the configured subfolder attribute is not a string. |
Source code in lib/laygen/src/laygen/pipelines/base.py
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 | |
component_subfolder ¶
component_subfolder(config: PretrainedConfig) -> str | None
Resolve the component subfolder for Hub-backed loading.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
PretrainedConfig
|
Root pipeline config. |
required |
Returns:
| Type | Description |
|---|---|
str | None
|
Component subfolder or |
Raises:
| Type | Description |
|---|---|
TypeError
|
If the configured subfolder attribute is not a string. |
Source code in lib/laygen/src/laygen/pipelines/base.py
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | |
LayoutGenerationPipeline ¶
Bases: ABC
Base class for Transformers-side layout-generation pipelines.
Subclasses declare checkpoint components with component_specs, implement
_from_pretrained_components, and put generation orchestration in
__call__. The public __call__ contract is to return
laygen.modeling_outputs.LayoutGenerationOutput for layout-generation
outputs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
PretrainedConfig
|
Root pipeline config, usually a |
required |
Examples:
>>> from transformers import PretrainedConfig
>>> class ToyPipeline(LayoutGenerationPipeline):
... config_class = PretrainedConfig
... @classmethod
... def _from_pretrained_components(cls, *, config, components):
... return cls(config)
... def __call__(self):
... import torch
... return LayoutGenerationOutput(
... bbox=torch.zeros(1, 1, 4),
... labels=torch.zeros(1, 1, dtype=torch.long),
... mask=torch.ones(1, 1, dtype=torch.bool),
... id2label={0: "text"},
... )
>>> isinstance(ToyPipeline(PretrainedConfig()).config, PretrainedConfig)
True
Source code in lib/laygen/src/laygen/pipelines/base.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 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 | |
__init__ ¶
__init__(config: PretrainedConfig) -> None
Initialize root config and runtime placement metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
PretrainedConfig
|
Root pipeline config. |
required |
Source code in lib/laygen/src/laygen/pipelines/base.py
249 250 251 252 253 254 255 256 257 | |
from_pretrained
classmethod
¶
from_pretrained(
pretrained_model_name_or_path: str | Path,
*,
local_files_only: bool = False,
config: PretrainedConfig | None = None,
components: Mapping[str, PipelineComponent]
| None = None,
) -> Self
Load a pipeline from a checkpoint root and declared subfolders.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pretrained_model_name_or_path
|
str | Path
|
Checkpoint root. |
required |
local_files_only
|
bool
|
Whether to avoid network access. |
False
|
config
|
PretrainedConfig | None
|
Optional preloaded root config. |
None
|
components
|
Mapping[str, PipelineComponent] | None
|
Optional preloaded components keyed by spec name. |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
Loaded pipeline instance. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If a required component marker file is missing. |
TypeError
|
If |
Source code in lib/laygen/src/laygen/pipelines/base.py
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 | |
save_pretrained ¶
save_pretrained(
save_directory: str | Path,
*,
is_main_process: bool = True,
) -> None
Save root config and declared components.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
save_directory
|
str | Path
|
Checkpoint root directory. |
required |
is_main_process
|
bool
|
Whether model-like components should perform main process writes. |
True
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If a component does not implement |
ValueError
|
If a required component attribute is missing. |
Source code in lib/laygen/src/laygen/pipelines/base.py
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 | |
to ¶
to(
device: str | device | None = None,
dtype: dtype | None = None,
) -> Self
Move movable components to a device and/or dtype.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
str | device | None
|
Target torch device. |
None
|
dtype
|
dtype | None
|
Target torch dtype. |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
This pipeline instance. |
Source code in lib/laygen/src/laygen/pipelines/base.py
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 | |
prepare_generator ¶
prepare_generator(
*,
generator: Generator | None = None,
seed: int | None = None,
device: str | device | None = None,
) -> torch.Generator | None
Apply generator-over-seed precedence for generation calls.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
generator
|
Generator | None
|
Explicit torch generator. When provided, |
None
|
seed
|
int | None
|
Integer seed used only when |
None
|
device
|
str | device | None
|
Optional device for a newly created generator. If omitted, the pipeline's current device is used. |
None
|
Returns:
| Type | Description |
|---|---|
Generator | None
|
The explicit generator, a seeded generator when a device is known, |
Generator | None
|
or |
Source code in lib/laygen/src/laygen/pipelines/base.py
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 | |
__call__
abstractmethod
¶
__call__() -> LayoutGenerationOutput
Generate a layout.
Returns:
| Type | Description |
|---|---|
LayoutGenerationOutput
|
Layout generation output in the canonical Transformers-style schema. |
Source code in lib/laygen/src/laygen/pipelines/base.py
494 495 496 497 498 499 500 | |
model_processor_component_specs ¶
model_processor_component_specs(
*,
model_loader: PipelineComponentLoader,
processor_loader: PipelineComponentLoader,
) -> dict[str, PipelineComponentSpec]
Build standard model/processor component specs for simple pipelines.
Source code in lib/laygen/src/laygen/pipelines/base.py
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | |
pipeline_output ¶
Diffusers-compatible output types for layout generation pipelines.
LayoutGenerationOutput
dataclass
¶
Bases: BaseOutput
Layout-generation output for Diffusers pipelines.
Attributes:
| Name | Type | Description |
|---|---|---|
bbox |
Float[Tensor, 'batch elements 4']
|
Normalized center |
labels |
Int[Tensor, 'batch elements']
|
Dataset-local integer labels with shape |
mask |
Bool[Tensor, 'batch elements']
|
Boolean valid-element mask with shape |
id2label |
dict[int, str]
|
Mapping from integer label ids to display names. |
sequences |
object | None
|
Optional raw token sequences. |
scores |
object | None
|
Optional per-token or per-element scores. |
trajectory |
object | None
|
Optional sampling trajectory. |
intermediates |
object | None
|
Optional model-specific debug or auxiliary data. |
Examples:
>>> import torch
>>> output = LayoutGenerationOutput(
... bbox=torch.zeros(1, 1, 4),
... labels=torch.zeros(1, 1, dtype=torch.long),
... mask=torch.ones(1, 1, dtype=torch.bool),
... id2label={0: "text"},
... )
>>> output.to_tuple()[0].shape
torch.Size([1, 1, 4])
Source code in lib/laygen/src/laygen/pipelines/pipeline_output.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | |
schedulers ¶
Shared scheduler helpers for layout generation models.
BetaSchedule ¶
Bases: StrEnum
Supported DDPM beta schedules.
Origin
These schedule names mirror CompVis latent-diffusion
make_beta_schedule aliases used by the LACE scheduler.
Source code in lib/laygen/src/laygen/schedulers/continuous.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | |
DDIMDiscretization ¶
Bases: StrEnum
Supported DDIM timestep discretization methods.
Origin
These discretization names mirror CompVis latent-diffusion
make_ddim_timesteps modes used by the LACE scheduler.
Source code in lib/laygen/src/laygen/schedulers/continuous.py
50 51 52 53 54 55 56 57 58 59 60 | |
get_beta_schedule ¶
get_beta_schedule(
schedule: BetaSchedule | str = BetaSchedule.cosine,
num_timesteps: int = 1000,
start: float = 0.0001,
end: float = 0.02,
) -> Float[torch.Tensor, "timesteps"]
Create a beta schedule, delegating common schedules to Diffusers.
Origin
The public API follows CompVis latent-diffusion make_beta_schedule.
Common DDPM schedules delegate to Diffusers DDPMScheduler while
legacy LACE-only aliases remain custom for compatibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schedule
|
BetaSchedule | str
|
Schedule enum or string value. |
cosine
|
num_timesteps
|
int
|
Number of training timesteps. |
1000
|
start
|
float
|
Initial beta value for schedules that use a range. |
0.0001
|
end
|
float
|
Final beta value for schedules that use a range. |
0.02
|
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'timesteps']
|
One-dimensional beta tensor. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the schedule is unsupported. |
Source code in lib/laygen/src/laygen/schedulers/continuous.py
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | |
get_ddim_timesteps ¶
get_ddim_timesteps(
method: DDIMDiscretization | str,
num_ddim_timesteps: int,
num_ddpm_timesteps: int,
*,
steps_offset: int = 1,
) -> Int[np.ndarray, "ddim_timesteps"]
Create ascending reference-order DDIM timesteps.
Origin
The public API follows CompVis latent-diffusion make_ddim_timesteps.
The uniform branch adapts Diffusers DDIMScheduler back to LACE's
ascending one-indexed reference order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
DDIMDiscretization | str
|
Discretization enum or string value. |
required |
num_ddim_timesteps
|
int
|
Number of inference timesteps. |
required |
num_ddpm_timesteps
|
int
|
Number of training timesteps. |
required |
steps_offset
|
int
|
Diffusers timestep offset. LACE uses one-indexed
timesteps, so the default is |
1
|
Returns:
| Type | Description |
|---|---|
Int[ndarray, 'ddim_timesteps']
|
NumPy array of timesteps in ascending reference order. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the method is unsupported. |
Source code in lib/laygen/src/laygen/schedulers/continuous.py
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 | |
normalize_beta_schedule ¶
normalize_beta_schedule(
schedule: BetaSchedule | str,
) -> BetaSchedule
Normalize a beta schedule value.
Origin
This preserves the CompVis latent-diffusion schedule aliases exposed by the LACE checkpoint configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schedule
|
BetaSchedule | str
|
Schedule enum or string value. |
required |
Returns:
| Type | Description |
|---|---|
BetaSchedule
|
Canonical beta schedule enum. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the schedule is unsupported. |
Source code in lib/laygen/src/laygen/schedulers/continuous.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | |
normalize_ddim_discretization ¶
normalize_ddim_discretization(
method: DDIMDiscretization | str,
) -> DDIMDiscretization
Normalize a DDIM timestep discretization method.
Origin
This preserves the CompVis latent-diffusion DDIM discretization aliases exposed by the LACE checkpoint configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
DDIMDiscretization | str
|
Method enum or string value. |
required |
Returns:
| Type | Description |
|---|---|
DDIMDiscretization
|
Canonical DDIM discretization enum. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the method is unsupported. |
Source code in lib/laygen/src/laygen/schedulers/continuous.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | |
continuous ¶
Continuous diffusion scheduler adapters backed by Diffusers.
The beta/DDIM helper names follow CompVis latent-diffusion
ldm/modules/diffusionmodules/util.py utilities as used by the LACE
diffusion_utils.py. Common schedules are delegated to Diffusers schedulers.
BetaSchedule ¶
Bases: StrEnum
Supported DDPM beta schedules.
Origin
These schedule names mirror CompVis latent-diffusion
make_beta_schedule aliases used by the LACE scheduler.
Source code in lib/laygen/src/laygen/schedulers/continuous.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | |
LayoutDiffusionBetaSchedule ¶
Bases: StrEnum
LayoutDiffusion-specific beta schedules.
Source code in lib/laygen/src/laygen/schedulers/continuous.py
40 41 42 43 44 45 46 47 | |
DDIMDiscretization ¶
Bases: StrEnum
Supported DDIM timestep discretization methods.
Origin
These discretization names mirror CompVis latent-diffusion
make_ddim_timesteps modes used by the LACE scheduler.
Source code in lib/laygen/src/laygen/schedulers/continuous.py
50 51 52 53 54 55 56 57 58 59 60 | |
normalize_beta_schedule ¶
normalize_beta_schedule(
schedule: BetaSchedule | str,
) -> BetaSchedule
Normalize a beta schedule value.
Origin
This preserves the CompVis latent-diffusion schedule aliases exposed by the LACE checkpoint configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schedule
|
BetaSchedule | str
|
Schedule enum or string value. |
required |
Returns:
| Type | Description |
|---|---|
BetaSchedule
|
Canonical beta schedule enum. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the schedule is unsupported. |
Source code in lib/laygen/src/laygen/schedulers/continuous.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | |
normalize_layoutdiffusion_beta_schedule ¶
normalize_layoutdiffusion_beta_schedule(
schedule: LayoutDiffusionBetaSchedule | str,
) -> LayoutDiffusionBetaSchedule
Normalize a LayoutDiffusion-only beta schedule name.
Source code in lib/laygen/src/laygen/schedulers/continuous.py
87 88 89 90 91 92 93 94 95 96 97 98 | |
normalize_ddim_discretization ¶
normalize_ddim_discretization(
method: DDIMDiscretization | str,
) -> DDIMDiscretization
Normalize a DDIM timestep discretization method.
Origin
This preserves the CompVis latent-diffusion DDIM discretization aliases exposed by the LACE checkpoint configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
DDIMDiscretization | str
|
Method enum or string value. |
required |
Returns:
| Type | Description |
|---|---|
DDIMDiscretization
|
Canonical DDIM discretization enum. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the method is unsupported. |
Source code in lib/laygen/src/laygen/schedulers/continuous.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | |
get_layoutdiffusion_beta_schedule ¶
get_layoutdiffusion_beta_schedule(
schedule: LayoutDiffusionBetaSchedule | str,
num_timesteps: int,
) -> Float[torch.Tensor, "timesteps"]
Create LayoutDiffusion-specific beta schedules.
Origin
These formulas are copied narrowly from LayoutDiffusion's vendored
OpenAI improved_diffusion.gaussian_diffusion.get_named_beta_schedule
branches for names not exposed by Diffusers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schedule
|
LayoutDiffusionBetaSchedule | str
|
LayoutDiffusion schedule enum or string value. |
required |
num_timesteps
|
int
|
Number of diffusion timesteps. |
required |
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'timesteps']
|
Float64 beta tensor matching the reference NumPy formula. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> get_layoutdiffusion_beta_schedule("sqrt", 4).shape
torch.Size([4])
Source code in lib/laygen/src/laygen/schedulers/continuous.py
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 | |
get_beta_schedule ¶
get_beta_schedule(
schedule: BetaSchedule | str = BetaSchedule.cosine,
num_timesteps: int = 1000,
start: float = 0.0001,
end: float = 0.02,
) -> Float[torch.Tensor, "timesteps"]
Create a beta schedule, delegating common schedules to Diffusers.
Origin
The public API follows CompVis latent-diffusion make_beta_schedule.
Common DDPM schedules delegate to Diffusers DDPMScheduler while
legacy LACE-only aliases remain custom for compatibility.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schedule
|
BetaSchedule | str
|
Schedule enum or string value. |
cosine
|
num_timesteps
|
int
|
Number of training timesteps. |
1000
|
start
|
float
|
Initial beta value for schedules that use a range. |
0.0001
|
end
|
float
|
Final beta value for schedules that use a range. |
0.02
|
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'timesteps']
|
One-dimensional beta tensor. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the schedule is unsupported. |
Source code in lib/laygen/src/laygen/schedulers/continuous.py
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | |
get_layousyn_beta_schedule ¶
get_layousyn_beta_schedule(
schedule: Literal[
"linear", "squaredcos_cap_v2"
] = "linear",
num_timesteps: int = 100,
*,
alpha_scale: float = 1.0,
) -> Float[torch.Tensor, "timesteps"]
Create LayouSyn/OpenAI-style beta schedules.
Origin
This preserves the LayouSyn gaussian_diffusion.py formula exactly,
including the LayYourScene-specific
alpha_scale transform for both the linear and squared-cosine
schedules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
schedule
|
Literal['linear', 'squaredcos_cap_v2']
|
Schedule name. |
'linear'
|
num_timesteps
|
int
|
Number of diffusion timesteps. |
100
|
alpha_scale
|
float
|
Alpha-bar scaling factor. |
1.0
|
Returns:
| Type | Description |
|---|---|
Float[Tensor, 'timesteps']
|
One-dimensional beta tensor in float64 precision. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the schedule is unsupported. |
Source code in lib/laygen/src/laygen/schedulers/continuous.py
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 | |
get_ddim_timesteps ¶
get_ddim_timesteps(
method: DDIMDiscretization | str,
num_ddim_timesteps: int,
num_ddpm_timesteps: int,
*,
steps_offset: int = 1,
) -> Int[np.ndarray, "ddim_timesteps"]
Create ascending reference-order DDIM timesteps.
Origin
The public API follows CompVis latent-diffusion make_ddim_timesteps.
The uniform branch adapts Diffusers DDIMScheduler back to LACE's
ascending one-indexed reference order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
DDIMDiscretization | str
|
Discretization enum or string value. |
required |
num_ddim_timesteps
|
int
|
Number of inference timesteps. |
required |
num_ddpm_timesteps
|
int
|
Number of training timesteps. |
required |
steps_offset
|
int
|
Diffusers timestep offset. LACE uses one-indexed
timesteps, so the default is |
1
|
Returns:
| Type | Description |
|---|---|
Int[ndarray, 'ddim_timesteps']
|
NumPy array of timesteps in ascending reference order. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the method is unsupported. |
Source code in lib/laygen/src/laygen/schedulers/continuous.py
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 | |