pixtreme.train.common
pixtreme-train provides pixtreme.train.common: model-independent training,
image and video data, GPU preprocessing, evaluation, checkpoints, and inference
weight export. Trainer modules register their networks and model-specific steps,
then combine these components through YAML or Python.
The pure Python wheel owns only pixtreme/train/common/ and its distribution
metadata. pixtreme owns
pixtreme/__init__.py; trainer modules own their own
pixtreme/train/<module>/ subtrees. They can share one Python environment.
Installation and execution requirements
Use Linux x86_64, including WSL2, with CPython 3.12 or later:
pip install pixtreme-train
# Also install the converter when exporting or calibrating inference weights:
pip install 'pixtreme-train[export]'
For a uv project, use uv add pixtreme-train or
uv add 'pixtreme-train[export]'.
The declared runtime dependencies are cupy-cuda13x[ctk]>=14.1,
docstring-parser>=0.16, NumPy, Pillow>=11, pixtreme>=2.35.0,
pixtreme-transport-ffmpeg>=0.10.0, pixtreme-transport-nvdec>=0.15.1,
pixtreme-transport-nvenc>=0.16.0, pixtreme-transport-video>=0.2.0,
pydantic>=2.9, PyYAML>=6, and
torch>=2.11. The export extra adds tensoracle[convert]>=2.7.0, and the
webui extra adds fastapi>=0.115 and uvicorn>=0.30.
| Operation | Execution conditions |
|---|---|
Read/write YAML, Option, plain, resolve_config |
PyYAML; resolving a data type or an imports module also loads that component's Python dependencies. Built-in image data resolution loads torch and pixtreme for types and color validation, without CUDA initialization or allocation. |
| Image preprocessing, standard training and evaluation, PSNR/SSIM/VMAF | NVIDIA GPU, compatible driver and CUDA-enabled pixtreme/torch. Current pixtreme wheels require CUDA 13.x, driver R580 or later, and compute capability 7.5 or later. The selected torch wheel and its CUDA runtime must also match the driver. |
| Video indexing and clip packet demux | pixtreme-transport-ffmpeg>=0.10.0, using its Python Demuxer and CPU VideoDecoder.receive_info() APIs. Indexing requires no GPU, and neither operation starts an external command. |
| Video source decoding | pixtreme-transport-nvdec for codec/format combinations supported by the selected GPU; otherwise pixtreme-transport-ffmpeg for software decoding and upload to GPU PixelBuffers. Both paths require a compatible NVIDIA GPU/driver for subsequent pixel processing. Inputs unsupported by both decoders are rejected before training or evaluation. |
Whole-video evaluation input (VideoStreamEvaluationDataset.stream) |
pixtreme-transport-video>=0.2.0, using its VideoEntrance to decode each video from its first frame with the decoder selected for that material (NVDEC or FFmpeg). Colour attributes that the bitstream does not declare come from the container's colour declaration. No external command is started. |
temporal_compression, encode_hevc |
pixtreme-transport-nvenc, HEVC NVENC support (NVENC API 13.0, driver R580 or later), and NVDEC support for the selected encoded format. Source and compressed LQ decoding use the same process. |
Compressed evaluation LQ export (stream(..., lq_path=...)) |
pixtreme-transport-video>=0.2.0, using its PacketWriter to write the NVENC access units to MP4 without re-encoding. No external command is started. |
export_weights, calibrate |
The export extra. Export restores weights on the CPU; calibration also requires the GPU evaluation conditions above. |
The library checks missing CUDA support and video codec capabilities before the
first update or evaluation. Codec diagnostics identify the material or selected
format and dimensions. Reading and validating configuration does not initialize
CUDA, allocate GPU memory, open source material, or start an encoder/decoder.
User-supplied imports modules must follow the same rule to preserve this property.
Video pixels stay on the GPU for conversion, resizing and temporal compression.
Compressed packets and bitstreams pass through host memory.
The run's environment.json records both pixtreme-transport-nvenc and
pixtreme-transport-nvdec package versions alongside pixtreme and torch.
Reading the reference comparisons below. The listed limits are assertion thresholds for the stated inputs and comparison conditions. GPU checks use the installation requirements above and the codec capabilities named in each comparison. CPU checks are identified explicitly. Compare runs with matching material, seed, device, driver, package versions and arithmetic settings; the throughput measurements below do not establish the environment of every correctness check.
The measured GPU reference environment for the x3/absolute resize,
independent color, EXR half, training precision, individual execution-option,
and calibration numerical comparisons below is Linux x86_64, CPython 3.13.7,
torch 2.14.1+cu132, CUDA 13.2, pixtreme 2.34.0, NumPy 2.5.4, and an
NVIDIA RTX A6000. The image comparisons also record driver 616.92 and CuPy
14.2.0. Their bounds apply to the stated inputs, algorithms and execution
environment.
For tensor comparisons, atol and rtol mean
abs(actual - reference) <= atol + rtol * abs(reference) element by element.
Where a table says float32 tolerance, the limits are atol=1e-5,
rtol=1.3e-6 (torch's float32 comparison defaults). Scalar tolerance means
abs(actual - reference) <= max(1e-12, 1e-6 * abs(reference)).
Exact means zero numerical error, with order, identifiers and other discrete
fields compared directly. These definitions also distinguish a numerical
reference from repeating the same operation to check reproducibility.
Train an image model
Save this module as my_trainer.py on Python's import path:
import torch
from pixtreme.train.common import register
@register("network", "tiny")
class Tiny(torch.nn.Module):
def __init__(self, *, channels: int = 3) -> None:
super().__init__()
self.body = torch.nn.Conv2d(channels, channels, 3, padding=1)
def forward(self, image: torch.Tensor) -> torch.Tensor:
return image + self.body(image)
Save the configuration as config.yaml, replacing the image directory with your
material directory:
imports: [my_trainer]
networks:
main: {type: tiny}
losses:
pixel: {type: l1, weight: 1.0}
optimizers:
main: {type: adamw, networks: [main], lr: 2.0e-4}
data:
train:
type: image_degradation
directory: /data/train
patch_size: 64
degradation:
name: identity
seed: 0
gt: {steps: [crop]}
lq: {steps: [crop]}
train:
iterations: 1000
seed: 0
device: cuda
checkpoint_interval: 500
batch_size: 8
prefetch_batches: 2
sample_threads: 1
supply_processes: 1
pixtreme-train train config.yaml --output runs/first
train(config, output, *, resume=None) runs the same operation from Python and
returns the last checkpoint path. The output must be a new directory. A run
writes config.yaml with resolved defaults, environment.json, numbered JSONL
segments under records/, a consolidated training.jsonl when the run
completes or stops on the first signal (not when it fails), and
checkpoint_XXXXXXXX.pt files. Updates record their loss/metrics and learning
rates. The default step also records grad_norm/main, the main network's total
L2 gradient norm before clipping. Model-specific steps use
grad_norm/<network name> for each network. Evaluations add reports under the
run directory.
Common configuration and training parts
Top-level keys are imports, networks, losses, optimizers, schedulers,
ema, step, data, train, and notes. Data-specific keys belong inside the
chosen data.train or data.evaluation.<name> entry. resolve_config(mapping)
checks these keys, asks each registered data type to validate its own entry, and
returns a new mapping with defaults. write_yaml(path, mapping) saves it.
The default step is {type: default}: one network named main, one optimizer,
and at least one weighted supervised loss. Built-in losses are l1, mse, and
charbonnier; optimizers are adam, adamw, and sgd. Their remaining keys are
passed to the selected component. schedulers.<optimizer-name> can select
{type: warmup_cosine, warmup: 100, minimum: 0.0}; the runner supplies the total
iteration count. ema: {decay: 0.999} enables averaged evaluation weights.
To decay from the initial learning rate without warmup, select
{type: warmup_cosine, warmup: 0, minimum: 0.2}. The coefficient starts at 1.0
before any update and reaches minimum after the total number of updates;
positive warmup lengths retain linear warmup followed by cosine decay.
The warmup length must be nonnegative and less than the total iteration count,
and minimum must be between 0 and 1, inclusive. Invalid settings are
rejected before training starts. The scheduler counts completed updates and
continues from the saved count when resuming a checkpoint.
train key |
Behavior/default |
|---|---|
iterations, device, checkpoint_interval |
Required. Iteration and checkpoint intervals are positive. |
seed |
Optional nonnegative integer. Omit the key to choose a random seed once when starting a new run; null is rejected. The actual seed is saved in config.yaml and each checkpoint's configuration. Reuse that saved configuration to repeat the run. |
precision |
bf16 by default, or fp32. Parameters and optimizer state remain float32. |
gradient_clip_norm |
null by default (no clipping), or a positive finite number. Limits the total L2 gradient norm before the optimizer update; records retain the norm before clipping. Invalid bounds are rejected before the first update. |
channels_last |
Boolean, default false; stores all networks' 4D weights and 4D tensor inputs in channels_last order, including EMA evaluation inputs. Shapes and values are unchanged. Video tensors with five or more dimensions keep their existing layout. |
cudnn_benchmark |
Boolean, default false; enables cuDNN convolution algorithm benchmarking during training and restores the caller's flag on success or failure. When false, the caller's flag is left alone. |
compile |
null by default, or a torch.compile mode: default, reduce-overhead, max-autotune, max-autotune-no-cudagraphs. Compiles each registered network's forward; checkpoint, EMA and exported weight names stay unchanged. Initial compilation takes time and may use additional memory. |
batch_size |
Positive integer, default 1. |
prefetch_batches |
Nonnegative integer, default 0; bounds queued, running and out-of-order batches together across all supply processes, including batches whose sample reads are pending. Zero creates only the batch being requested. Grouped video reads may also retain the unused tail of one clip, as described below. |
sample_threads |
Positive integer, default 1; builds samples in threads within a supply process, preserving sampler order. With prefetch, stateless data and standard video identity state can read across batches within the global bound. Mutable data finishes each batch before starting the next. Data-owned batch samplers remain sequential. |
supply_processes |
Positive integer, default 1. Distributes independent built-in image_degradation batches across this many processes. Custom data and video retain one process that owns their state, clip tails and sampler. This count may change on resume. |
supply_timeout |
Finite seconds greater than zero, integer or float, default 600. Bounds the wait for the next training batch or evaluation data element, and the time allowed to save after a supply timeout. Always enabled; null, zero and negative values are rejected. |
evaluation_interval |
Required and positive when data.evaluation is nonempty. |
register(kind, name)(component) and lookup(kind, name) support network,
loss, step, optimizer, scheduler, dataset, and degradation. Unknown
names report the available names. Extend TrainingStep, or DefaultStep for a
compatible supervised model, to own model-specific updates, state or evaluation.
Network classes and steps can implement check_config; steps can implement
check_resume. Steps can also override these optional, default no-op methods:
initialize(self)runs once after step construction for a fresh training call, before data is supplied or any update runs. Load initial model weights here and initialize any EMA or model-specific averaged weights together. Load tensors into the existing network objects so optimizer parameters stay attached. Resume callsload_state_dictinstead and never callsinitialize.check_resume_file(cls, path: Path) -> Noneis a classmethod called only on resume, after resolving the configuration and selecting its step, before reading or validating the common checkpoint format and before creating the output directory. It receives only the checkpoint'sPath; the trainer chooses how to read it. RaiseValueErrorto explain an unsupported model format and how to continue.train()propagates that error unchanged; the training command writes it to standard error and exits with code2. Returning normally continues the common format checks. Steps inheriting the default no-op retain those checks. Fresh training and network extraction do not call this method.check_checkpoint(cls, saved)is a classmethod receiving the complete, format-checked checkpoint, includingsaved["config"]andsaved["step"]. Validate model-specific records here and raiseValueErroridentifying the record and reason when they are missing or inconsistent. This method runs on resume before step construction and on network extraction, export and calibration before applying weights. It must not mutatesavedor construct training resources. Inference never constructs the training step or optimizer.
Move fresh-only weight file reads from constructors and check_config into
initialize. A resumed run can then continue after that initial file is removed;
the resolved configuration can keep its original path. Keep configuration shape
checks in check_config, comparisons between the saved and requested
configurations in check_resume(cls, saved_config, requested_config), and instance
state restoration in load_state_dict(self, state). Implement model record checks
once in check_checkpoint so resume and inference share the same interpretation.
TrainingStep.gradient_clip_norm defaults to None. The runner sets this
attribute from resolved train.gradient_clip_norm after construction and before
initialize or load_state_dict, preserving existing constructor signatures.
A model-specific step that performs its own optimizer updates should call
check_finite_gradients(network.parameters(), max_norm=self.gradient_clip_norm)
after backward, after undoing any loss scaling and finishing any gradient
accumulation, and before optimizer.step(). The helper returns the total L2 norm
before clipping as a scalar torch tensor. Add float(norm) as
grad_norm/<network name> in the step's returned record for each network.
The default step performs these operations automatically.
A custom dataset receives seed and device, resolves its own
configuration through an optional resolve_config method, and can provide paired
state_dict/load_state_dict methods and close for lifecycle management.
A dataset that assembles complete batches can implement
batch_sampler(generator, completed, *, batch_size). The runner passes the
resolved train.batch_size and the number of completed updates (0 for a new
run). The sampler yields indices for the dataset's __getitem__, whose result
is passed directly to the update without another collation. Random material
choices should use the supplied torch generator; derive sample numbers from
completed and batch_size so resuming continues from the completed batch.
Batch size remains in train; data.train.batch_size is rejected.
Existing batch_sampler(generator, completed) implementations keep their
two-argument call and batch behavior. To receive the shared size, add an explicit
batch_size parameter accepting a keyword (as above, or as a regular parameter).
Accepting only **kwargs does not opt in, and uninspectable callables retain the
two-argument call. Dataset factories and data types without a batch sampler
keep their existing inputs and behavior.
Training and in-training evaluation data are constructed and read in spawned
processes, including with sample_threads: 1 and prefetch_batches: 0.
Suppliers perform the existing GPU preprocessing, copy completed tensors into
reusable shared host buffers, and send those buffers with sample metadata and
state snapshots. The learner copies GPU tensors through its own pinned memory
and finishes H2D before updating the network. Returned pixels belong to the
learner and remain valid after a supplier exits. Shared host and pinned buffer
allocation is separate from admission: increasing supply_processes does not
multiply prefetch_batches. Zero prefetch creates only the requested batch.
Measured image training throughput. A benchmark compared two ways to supply training batches. One configuration ran GPU preprocessing and batch construction in the process training the network. The other ran that work in separate supply processes and delivered batches through shared host memory and pinned memory owned by the learner to the training GPU.
The measurement on 2026-11-28 used SPANv2 with 128 feature channels and 8 blocks,
x2, patch 192, batch 8 and bf16, with BHI LSDIR/DF2K 512x512 WebP images and
GPU JPEG q50 4:2:0 simulation. The host used an RTX A6000, driver 616.92, WSL2,
a Threadripper PRO 3995WX, CPU affinity 0-31, OMP_NUM_THREADS=32,
torch 2.14.1+cu132 and pixtreme 2.32.0. sample_threads: 2 and
prefetch_batches: 2 were held constant. All three execution options enabled
means channels_last: true, cudnn_benchmark: true and compile: default;
their disabled defaults are false, false and null.
Each setting with separate supply processes was measured in three paired comparisons with runs that supplied batches in the training process. The comparison rows combine nine such runs per execution setting. Every run used 50 warm-up updates followed by 250 timed updates. Updates/s shows the mean and observed range; batch wait, network update, startup and RSS sum are means across the listed number of runs.
| Batch supply | Execution options | Runs | Updates/s, mean (range) | Batch wait (ms) | Network update (ms) | Startup (s) | RSS sum (GiB) |
|---|---|---|---|---|---|---|---|
| In the training process | Disabled (defaults) | 9 | 15.13 (14.64–15.54) | 1.20 | 63.48 | 26.7 | 2.37 |
Separate, supply_processes: 1 |
Disabled (defaults) | 3 | 17.58 (17.26–17.80) | 1.89 | 54.04 | 27.8 | 3.11 |
Separate, supply_processes: 2 |
Disabled (defaults) | 3 | 17.63 (17.53–17.71) | 1.83 | 53.81 | 53.0 | 4.46 |
Separate, supply_processes: 3 |
Disabled (defaults) | 3 | 17.53 (17.34–17.75) | 1.66 | 54.26 | 78.9 | 5.80 |
| In the training process | All three enabled | 9 | 15.41 (14.94–15.72) | 5.74 | 57.73 | 33.1 | 2.76 |
Separate, supply_processes: 1 |
All three enabled | 3 | 18.34 (18.25–18.43) | 12.96 | 40.55 | 33.2 | 3.52 |
Separate, supply_processes: 2 |
All three enabled | 3 | 23.20 (23.03–23.46) | 1.63 | 40.39 | 58.8 | 4.87 |
Separate, supply_processes: 3 |
All three enabled | 3 | 23.29 (23.19–23.47) | 1.48 | 40.35 | 85.2 | 6.21 |
supply_processes: 1 is the default because adding suppliers with the default
network execution settings gave no throughput gain within the measured
variation. Each additional process added roughly 25 seconds to startup and
about 1.4 GiB to the RSS sum. With all three execution options enabled, two
suppliers increased throughput from about 18.3 to 23.2 updates/second. A third
supplier gave no further gain within the measured variation.
Updates/s covers the full training loop, batch wait measures time spent obtaining the next batch, and network update measures update work without that wait. The update timer starts after synchronizing batch readiness, includes forward, loss, backward, optimizer, scheduler and EMA work, and ends after synchronizing update completion.
Startup measures the time from train() to the first completed update,
including material checks, process startup and the first update, and depends
on filesystem and compilation caches. Timed throughput includes image
reading, preprocessing, host transport, GPU transfer, network updates,
optimizer and EMA work. Initial setup, warm-up, evaluation and checkpoint
writing are outside the throughput timer. RSS sums add resident memory across
the learner and suppliers, counting a shared memory page in each process
that maps it. The sum therefore differs from the host's physical memory
usage. Physical GPU memory peaks were not measured.
Training reference comparisons. The following CPU checks use float32 parameters and inputs. Scalar and float32 tolerances have the meanings given above; custom networks and steps supply their own mathematical references.
| Component | Reference and comparison conditions | Limit |
|---|---|---|
l1, mse |
Mean absolute/squared differences. Predictions [1, -2] against [0, 0] give 1.5 and 2.5. |
Scalar tolerance. |
charbonnier |
mean(sqrt((prediction-target)^2 + eps^2)), default eps=1e-12. The same pair with eps=2 gives (sqrt(5)+sqrt(8))/2; zero difference gives eps. |
Scalar tolerance; zero difference with default epsilon uses absolute error 1e-18. |
DefaultStep.step |
Scalar network prediction=weight*lq, initial weight 1, lq=1, gt=0, L1/MSE weights 2/3, SGD initial LR 0.2, warmup 2, total 6, EMA decay 0.75: first loss 5, gradient norm 8, update LR 0.1, new weight 0.2, EMA 0.8. |
Scalar tolerance. CPU bf16 configuration performs this update without CUDA autocast. |
sgd, adam, adamw |
Factories are the corresponding torch.optim.SGD, Adam, AdamW classes and pass through arguments (checked with LR 0.04, weight decay 0.2). CPU Linear network save/restore reproduces the next update for each optimizer. |
Arguments and restored state/next update exact. Separate three-update MSE comparisons against independently constructed torch optimizers check SGD and Adam parameters exactly. |
check_finite_gradients, gradient_clip_norm |
Gradients [3, -4, 12] have total L2 norm 13. Bound 5 reduces the norm to 5 and preserves direction; no bound or bound 20 preserves the gradients. A Linear network with gradient -9.5*[3,4,1] follows the corresponding clipped SGD update. |
Norms use scalar tolerance, direction and updated parameters use float32 tolerance; unclipped gradients are exact. |
update_ema |
Floating state follows decay*previous + (1-decay)*source; integer/bool state copies the source. Checks cover decay 0, 0.75, 1, parameters and buffers. |
Floating state uses float32 tolerance; nonfloating copies and restored EMA state are exact. |
warmup_cosine_factor, warmup_cosine |
For completed count c < warmup, coefficient (c+1)/warmup; thereafter minimum + (1-minimum)*(1+cos(pi*(c-warmup)/(total-warmup)))/2, ending at minimum. With warmup 0, total 6, minimum 0.2, counts 0..6 give approximately [1, .94641016, .8, .6, .4, .25358984, .2]. |
Scalar tolerance for coefficients and learning rates, including continuation after restoring the scheduler. |
Custom TrainingStep |
A CPU example updates discriminator then generator with SGD LR 0.1, giving weights D=0.4, G=0.988, while auxiliary weight 0.25 stays fixed. |
Scalar tolerance for analytical weights; restoring the next update is exact. |
The GPU precision reference uses the measured GPU reference environment
and an independently assembled torch update: the same initial float32
Linear(3, 4) weights and bias, a signed batch of three vectors,
0.4 * L1 + 1.3 * MSE, Adam (lr=0.007, betas=(0.8, 0.95), eps=1e-7),
and EMA decay 0.75. For bf16, only the reference forward uses CUDA bf16
autocast; predictions become float32 before loss and backward. For fp32,
the reference forward runs without autocast. Total and component losses use
the larger of absolute tolerance 1e-7 and relative tolerance 1e-6;
parameter gradients, updated parameters, Adam moments and EMA weights use
atol=1e-7, rtol=1e-6. Losses, parameters, gradients, optimizer state, EMA
and saved weights remain float32. All measured errors were zero; the bounds
allow float32 arithmetic rounding in this same-precision comparison. The
reference follows PyTorch AMP.
The execution-option reference uses a bias-free 3-to-3, 3x3 convolution,
8x8 RGB ramps from 0 to 0.25, GT=LQ*0.75, batch 2, seed 23, bf16,
MSE, Adam LR 2e-4, and 20 updates. Individual-option comparisons use EMA
decay 0.5 and the measured GPU reference environment. The eager
reference disables all three execution options and starts with cuDNN
benchmarking disabled. Each compared run enables only the option in its row:
| Individual execution option | Maximum measured absolute loss error versus eager |
|---|---|
channels_last: true |
1.87e-9 |
cudnn_benchmark: true |
0 |
compile: default |
0 |
compile: reduce-overhead |
0 |
compile: max-autotune |
0 |
compile: max-autotune-no-cudagraphs |
0 |
For each option, all 20 losses use absolute tolerance 1e-8 and relative
tolerance 0. Final training and EMA weights use atol=1e-7, rtol=1e-6;
weight shapes and names agree exactly. Measured training and EMA weights were
exact for all six options. The loss bound allows several float32 rounding
units around the measured losses near 0.02; weight bounds allow float32
rounding. These fixed input comparisons follow
PyTorch's numerical accuracy guidance;
other networks, inputs, GPUs and package versions can select different
algorithms and have different numerical errors. The four separate compile
comparisons run in the default test selection.
The joint execution-options comparison uses the same convolution reference,
with EMA decay 0.5 or no EMA. With channels_last, cudnn_benchmark and
compile: reduce-overhead enabled together, final loss differs from the
same-seed eager run by at most 5e-6; restored/exported weights are exact.
That joint limit describes this combination. The layout check independently
preserves 4D input values exactly and leaves 5D video layout unchanged; the
benchmark flag check restores its prior boolean value after training.
Suppliers import registration modules and construct the selected data factory
from configuration. Define data factories at module scope in importable Python
modules and include them in imports. Python callers that already imported the
registered factory's module can use that module as well. Function-local classes,
lambdas, interactive definitions, and sending constructed data objects with
native readers or locks are unsupported. A script's module-level registrations
also work: spawn reexecutes that script's top level as __mp_main__.
Registrations inside its if __name__ == "__main__": guard do not run in the
child. Runtime mutations of module globals (for example MODE) are not copied;
the child sees the values established by executing the module. Pass such
conditions through the data configuration or an explicit shared test/control
file instead.
A supplier inherits standard output and standard error, so print("READY", flush=True) is visible on the parent's stdout. Spawn replaces the supplier's
standard input with the null device: reading it returns EOF and cannot wait for
input sent to the learner. This applies to indexed reads and evaluation stream
generators alike. Tests controlling a stalled read must use a shared file/event
or another explicit communication channel. Guard Python script entry points
with if __name__ == "__main__": when calling train(); YAML/CLI users need no
entry-point changes. Keep module imports free of training launches and GPU
allocation. The subprocesses inherit CUDA_VISIBLE_DEVICES; allow memory for
one CUDA context and data resources per active supplier. They require writable
shared host memory (Linux /dev/shm) in addition to pinned host memory.
Only the unchanged built-in image type distributes independent jobs among several processes. Mutable custom data, data-owned batch samplers and videos keep one process owner. That owner advances material selection, sample numbers, clip progress and sampler RNG. The learner records only the snapshots attached to completed updates. Each video clip is decoded once and its unused patches stay with that owner across batch boundaries. A whole-video evaluation stream also stays with one owner, including LQ stream export.
In-training evaluation receives a proxy for the selected data object.
hasattr, getattr and callable checks expose the original data's attributes
and methods: an indexed data type does not acquire a stream method or an
explicit __iter__ method. Python's iteration through __getitem__ remains
available when the original data supports that sequence protocol. Data methods
are called in their owning process; extracting dataset.close does not
transfer a bound data instance. Picklable values, sample classes and batch
classes retain their types and attributes, including Mapping subclasses.
Opaque native attributes stay with their owner and expose their methods through
references.
The proxy is not an instance of the registered data class. Replace
isinstance(dataset, MyData) checks with the needed capability checks, such as
callable(getattr(dataset, "stream", None)), or select by the registered type in
context["datasets"][name]["type"]. Tensor values in returned objects and their
attributes all use the shared host and pinned-memory transport.
Initialize any
thread-local decoder state in the thread that performs the read. A custom
dataset used with sample_threads > 1 must support concurrent
__getitem__ calls, protect shared mutable state and derive random choices from
the seed and sample number. Its checkpoint state must be independent of sample
completion order. Datasets supplying batch_sampler continue to return complete
batches sequentially. Cross-batch reads are enabled only when the dataset has no
state_dict, or its state_dict is the standard VideoDataset implementation
(including subclasses that inherit it unchanged). Other datasets with
state_dict finish each batch before submitting the next, so their checkpoint
state excludes unused future samples. A sample failure retains its exception
type and adds the batch and sample numbers through the exception's __notes__;
the CLI prints those notes.
Describe components and configuration keys
Inspect registered components without starting training, allocating GPU resources, opening material files, or executing codecs:
pixtreme-train describe --import my_trainer > components.json
Repeat --import MODULE to load several registration modules. Python callers
use the same operation. The command sends module-import messages to standard
error so standard output contains just the JSON document:
from pixtreme.train.common import describe_components
metadata = describe_components(imports=["my_trainer"])
network = metadata["components"]["network"]["my_network"]
fields = network["schema"]["properties"]
Use the registered name from your trainer in place of my_network. Reading the
descriptions imports the framework's built-in components and the explicitly
requested modules, including their dependencies such as torch. It does not
discover or import other training repositories. Registrations already loaded in
the Python process also appear. A registration module and its schema provider
must themselves avoid starting training or allocating GPU resources at import
or description time.
The result contains these JSON-compatible entries:
| Entry | Contents |
|---|---|
imports |
Explicit module names passed to this call. Include these modules in the YAML's imports so another process can resolve the same names. |
components.<kind>.<name> |
description, source (declaration or signature), schema, injected, and unknown. Kinds are the same seven kinds accepted by register. |
configuration |
JSON Schema describing the common YAML envelope, defaults, training options, and references between named components. |
degradation_pipeline |
JSON Schema for the ordered GT/LQ pipeline, from the same declaration used by its validator. |
temporal_compression |
JSON Schema for temporal compression, from the same declaration used by its validator. |
configuration marks component selections with x-component-kind. For example,
networks.additionalProperties selects a network, and data.train selects a
dataset. Choose its registered type, then use that component's schema for
the remaining entry. JSON Schema $ref values are local to each returned
schema; retain its $defs when rendering nested fields. Degradation operation
schemas describe the parameters under the operation name, for example
{gaussian_blur: {sigma: 1.0}}, rather than a type entry.
Loss entries include weight (default 1.0), which the step uses outside the
loss factory. Optimizer entries include a required networks list referring to
configured network names. Scheduler entries use their optimizer's name as the
mapping key. injected names the arguments supplied by the framework, such as
optimizer parameters, the scheduler's optimizer and total update count,
dataset seed and device, and the step's networks, losses and common settings.
These arguments are excluded from the component's user-input schema.
Without an explicit declaration, the operation reads the factory's signature
(names, type annotations and defaults) and its Google, NumPy or reST argument
docstrings. Missing information remains explicit: unknown.keys is true when
the accepted keys cannot be enumerated, and unknown.fields maps field names to
missing type, description, or JSON-serializable default information.
Opaque **kwargs factories and custom degradation operations remain available;
additionalProperties: true permits their keys to be entered manually. A missing
description or type does not hide a component or require its author to add a
declaration.
A registered class, factory, or degradation operation can optionally expose
config_schema() with no arguments, returning an object JSON Schema for its
accepted YAML mapping. This declaration takes precedence over signature and
docstring extraction. It describes component options; the framework supplies
the selection and composition keys (type, loss weight, optimizer
networks). Built-in datasets and degradation operations return the same
declarations used for validation. Custom datasets should likewise return a
schema from the declaration used by their resolve_config method. The method
is optional and does not change registration or training for existing parts.
Descriptions guide configuration entry; they do not replace resolve_config
or component-specific checks. Conditions between fields may require additional
validation. In particular, leave train.seed absent to choose it once at run
start or reuse the checkpoint's seed on resume. There is no configuration
default for that key, and explicit null is invalid.
Build configuration in a browser
Install the optional WebUI dependencies and start the local configuration builder:
pip install 'pixtreme-train[webui]'
pixtreme-train webui --import my_trainer
Open http://127.0.0.1:7860. Repeat --import MODULE for additional registration
modules; --port PORT selects another port between 1 and 65535. The server binds
to 127.0.0.1. It loads the selected modules at startup and includes the same
module list in exported YAML. Restart with different --import arguments to
change that list. Without the extra, the command explains how to install it;
training and describe do not require these dependencies.
Use Add entry to name networks, losses, and optimizers. Select their registered
types, connect each optimizer's networks list to the network names, then choose
data.train and enter the training progress settings. For the default step, name
the single network main, add at least one loss, and use one optimizer. Enable an
optional key with its Include checkbox; leaving it unchecked omits the key.
The displayed defaults describe what resolution supplies when a key is omitted;
the form does not insert component constructor defaults. Leave train.seed
unchecked to preserve its omission rather than setting it to null.
The form handles nested objects, named mappings, arrays and fixed-length tuples,
enum and constant choices, anyOf/oneOf alternatives, and local JSON Pointer
$ref references. Select the choices or range alternative to enter sampled
values. For opaque component keys, use Add entry and enter the value as JSON.
Fields with unknown types, external or cyclic references, allOf, conditionals,
or pattern-based objects use a JSON value editor. External references are not
fetched. Edit configuration as JSON can replace the whole form for more
complex inputs. The form guides entry; the server remains responsible for
constraints and checks between fields.
Click Validate to check the configuration, or Export YAML to check it and
show the resulting YAML with resolved defaults. The Download config.yaml link
saves that YAML. Both operations use resolve_config, report its key locations
and reasons on failure, and preserve fields that resolution leaves absent. Save
the YAML and pass it to pixtreme-train train config.yaml --output runs/first.
The builder does not start training. Its HTML, CSS, and JavaScript ship in the
wheel and load without an external CDN, font, or script.
Python callers with the extra installed can use
pixtreme.train.common.webui.create_app(imports=["my_trainer"]). Its HTTP endpoints
are:
| Endpoint | Input and response |
|---|---|
GET /api/components |
No input. Returns the same JSON document as describe_components, including startup imports, component schemas, and the common configuration schema. |
POST /api/validate |
The configuration object as a JSON request body. Returns {"config": <resolved configuration>}. |
POST /api/yaml |
The same JSON body. Returns the resolved configuration as application/yaml, with attachment filename config.yaml. |
Both POST endpoints insert the startup imports when omitted. If an imports
key is supplied, it must exactly match the startup list. HTTP requests never load
other modules. Configuration errors return status 422 and
{"detail": "<resolver error, including its key location>"}. JSON syntax errors
use FastAPI's normal 422 response. These operations import component dependencies
but do not initialize training, allocate GPU resources, or execute codecs.
Image data and degradation
image_degradation requires patch_size, degradation, and exactly one of
paths or directory. Optional prefixes filter direct child filenames;
augment defaults to true. Supported image suffixes are PNG, JPEG, BMP, TIFF,
WebP and EXR. Training samples include CHW float32 gt/lq tensors, path,
and the global sample number; evaluation samples include the material index.
image_evaluation uses the same source and degradation description without
patch_size or augmentation. It uses full images, trimming the bottom and right
for degradation divisibility and ignoring crop markers. image_pair_evaluation
accepts pairs: [[input_path, reference_path], ...], scale (default 1),
optional input_color/reference_color declarations, and output_color
(default {colorspace: Rec.709, gamma: sRGB}). It checks paired dimensions and
uses the corresponding full region.
Each source color attribute is resolved from file metadata, the optional
source_color declaration, then the format default: sRGB/sRGB for raster images
and ACES2065-1/linear for EXR. Conflicting or uninterpretable declarations fail
before training. Preprocessing starts in ACES2065-1/linear on the GPU and passes
tensors to torch through DLPack.
DegradationPipeline.from_mapping(mapping) and load_pipeline(path) validate
named gt.steps and lq.steps; to_mapping() returns the resolved description.
Steps include color, resize, compression_artifacts, the registered blur and
noise operations, and a value-free crop marker. compression_artifacts models
intraframe compression through pixtreme; temporal HEVC belongs in the video data
configuration. compression_artifacts applies to the values it receives as they
are, without color conversion or clipping, so place a color step such as
{colorspace: Rec.709, gamma: sRGB} before it; otherwise the simulated codec
sees ACES2065-1/linear values, including values outside 0 to 1. A custom degradation operation supplies validate(parameters, location) and apply(frame, values, *, stream), with optional scale and unit
geometry attributes.
A numeric pair denotes an inclusive range; {"choices": [...]} selects disjoint
candidates, and string lists select names. All candidates are validated.
resize runs in linear light. A color step declares its colorspace and
gamma; a sequence without a final color step receives Rec.709/sRGB.
Training requires one crop marker in each branch; patch_size is the final GT
size, and crop/augmentation preserve correspondence with LQ. Random choices are
derived from the seed and global sample number, including with process and thread prefetch.
compression_artifacts keeps its JPEG behavior when codec is omitted or null.
JPEG quality defaults to 75; explicit quality and explicit quantization tables
are mutually exclusive. JPEG accepts block sizes 4, 8, and 16, with omission
or null selecting 8. Sizes 4 and 16 require tables. To select several sizes,
use block_size: {choices: [4, 8]} and
quantization_tables: {choices: [<two 4x4 tables>, <two 8x8 tables>]}, replacing
the placeholders with positive finite numeric arrays of shape (2,N,N).
The pipeline first draws the block size, then draws a table pair only from
candidates matching that size. Every block-size candidate needs at least one
matching pair. A null table candidate selects the standard tables for size 8.
Since pixtreme 2.36.0, the same step also accepts these intra-like simulation
controls. Numeric values support fixed values, inclusive ranges, and explicit
choices; codec and boolean values support fixed values and candidates.
| Key | Default | Accepted values and conditions |
|---|---|---|
codec |
null (JPEG) | h264 or hevc; requires qp |
qp |
null | Integer 0–51; required for either codec, null for JPEG |
chroma_qp_offset |
0 |
Integer -12–12; zero for JPEG |
aq_strength |
0 |
Finite nonnegative spatial QP adjustment strength; zero for JPEG |
adaptive_block_size |
true |
Boolean; ignored for JPEG |
deblocking |
true |
Boolean; ignored for JPEG |
deblocking_alpha_offset |
0 |
Integer -6–6 in div2 units; H.264 only |
deblocking_beta_offset |
0 |
Integer -6–6 in div2 units; H.264 or HEVC |
deblocking_tc_offset |
0 |
Integer -6–6 in div2 units; HEVC only |
For either codec, omit quality and quantization_tables or set them to null.
With adaptive block sizes, omit block_size or set it to null. With
adaptive_block_size: false, omission selects 8; H.264 accepts 4/8, and
HEVC accepts 4/8/16/32. Offsets unsupported by the selected codec must
be zero. For JPEG, QP must be null and all codec offsets and AQ strength must
be zero. Validation checks every selectable combination before training, so
mixing both codecs requires zero alpha and tC offsets. For example, insert this
YAML step into lq.steps:
- compression_artifacts:
codec: [h264, hevc]
qp: [18, 42]
chroma_qp_offset: [-3, 3]
aq_strength: [0.0, 1.0]
adaptive_block_size: true
deblocking: [false, true]
deblocking_beta_offset: [-2, 2]
These settings simulate I-frame-like quantization, spatial QP adjustment, transform-size selection and deblocking. They do not encode files or reproduce an encoder's decoded pictures; intra prediction and integer codec transforms are absent. The operation itself uses no randomness; the pipeline selects its values reproducibly once per sample or clip.
value_clipping is a data key, default codec_only: preserve negative and
above-one scene values except at codec boundaries. color_and_metrics also clips
after color steps and clips prediction/reference during standard evaluation.
Final color and clipping choices are saved in the configuration and checkpoint.
For direct use, DegradationPipeline.apply(frame, generator, *, patch_size=None, crop_seed=0, number=0, value_clipping="codec_only") accepts a GPU pixtreme Frame
with float32 RGB pixels, ACES2065-1 primaries and linear transfer, and returns
{"gt": Frame, "lq": Frame}. A Rec.709/sRGB Frame must be converted first;
changing its metadata alone does not convert its pixels.
ImageDegradationDataset(paths, pipeline, *, seed, patch_size, ...) and ImageEvaluationDataset(paths, pipeline, ...) wrap source
reading, color handling and tensor conversion.
ImagePairEvaluationDataset(pairs, *, scale=1, input_color=None, reference_color=None, output_color=None, device="cuda", value_clipping="codec_only", seed=None) wraps explicit input/reference pairs.
Image and degradation reference comparisons. These checks use float32 RGB on the GPU unless identified as CPU. Degradation-only references start and finish in ACES2065-1/linear unless another color is specified. Dimensions below are height x width; tensor shapes include the channel axis where shown.
| Operation | Reference and input conditions | Limit |
|---|---|---|
| Integer image samples | Written 16x16 PNG/TIFF codes divided by 255 or 65535, covering 8-bit RGB/gray and 16-bit gray/RGB, sRGB conversion round trip, patch 16, augmentation off. |
atol=2e-6, rtol=2e-5. |
| EXR samples | Float32 16x16 ACES2065-1/linear ramp from -0.2 to 1.8, compared with the values written, including when format defaults supply missing color metadata. |
Exact. Existing half-reader replay checks use a constant 1 image. |
| EXR half samples | Known CPU binary16 values expanded to float32, written as a lossless ZIP-compressed 16x16 ACES2065-1/linear EXR: signed zero, positive/negative subnormals (including 2^-24), smallest normals, fractions, adjacent-to-one values, and finite extrema +/-65504. |
Exact GT/LQ (atol=rtol=0); measured error zero. Finite half values are exactly representable in float32, so decoding adds no rounding. |
| Format readers | PNG, JPEG, BMP, TIFF, WebP and EXR constant images, 16/24 pixels per dimension, selected values 64/255 or 192/255; EXR uses float32, raster formats use 8-bit storage. |
atol=2e-6, rtol=2e-5 for these constants; repeated reads preserve values exactly. |
image_evaluation |
Known 27x37 PNG converted from sRGB to ACES linear, trimmed to 26x36; x2 LQ equals the 2x2 area average of GT. Crop markers do not cut a patch. | Float32 tolerance; repeating the evaluation number after unrelated training RNG draws is exact. |
image_pair_evaluation |
Prepared 8x12 input/16x24 reference PNGs, scale 2, declared ACES2065-1/linear; pixels compared with independently normalized codes over the full region. Nearest-neighbor x2 predictions use NumPy float64 MSE as the PSNR reference. |
Pixel atol=rtol=2e-6; PSNR absolute error 1e-4 dB. |
augment_images |
CPU integer tensors with different image dimensions; horizontal flip, then vertical flip, then transpose on the last two axes, all eight selections. | Exact values; original tensors unchanged. |
Pipeline crop |
48x48 coordinate ramps, GT patch 16 and LQ 8; an additional GT reduction gives patches 8/4. Corresponding LQ equals the area average of the selected GT region. |
Float32 tolerance; the same numbered sample reproduces exactly. |
apply_clip |
Three identical 32x40 frames, sampled blur sigma/compression quality/noise intensity, crop 16, seeds 19/23, sample 7; compare with applying the once-selected values to one frame. |
Exact pixels and final generator state. |
color with linear-light resize |
16x16 ACES linear grid containing -0.1/1.4; independently area-average the linear values and call public pixtreme.color.rgb_to_rgb, retaining each branch's final color. |
atol=rtol=1e-5 for this composed reference. |
value_clipping |
The float32 EXR values above are retained by codec_only; color_and_metrics matches torch.clamp(0,1) after color conversion and before evaluation. |
Pixels exact; evaluation metrics use scalar tolerance. |
| Registered degradation extensions | Identity custom operation with an amount drawn from [0.1,0.9], sample numbers 0, 7, 2**32; compare bulk processing with the single-sample call order and selected values. |
Calls, draws and returned sample pixels exact. The extension provides the reference for its own mathematics. |
Resize references. Each axis uses source pixel center
(output_index + 0.5) * input_size / output_size - 0.5 and replicated edges.
There is no separate antialias configuration key. The four filters use these
CPU numerical references:
resize.filter |
Numerical reference and antialias behavior |
|---|---|
area |
torch CPU interpolate(mode="area"): a 2x2 area average at x2, 3x3 at x3, and 2x3 for the absolute dimensions below. |
bilinear |
torch CPU interpolate(mode="bilinear", align_corners=False, antialias=False). |
bicubic |
Independent separable cubic kernel with a=-0.5, without antialias widening: for distance d=abs(x), 1.5*d^3-2.5*d^2+1 below 1, -0.5*d^3+2.5*d^2-4*d+2 below 2, otherwise zero. Normalize each output's weights. |
lanczos |
Antialiased Lanczos3 (lanczos3-aa); normalized separable weights sinc(d/s)*sinc(d/(3*s)) for abs(d)<3*s, zero elsewhere, with s=input_size/output_size on each shrinking axis. At x2, s=2 and support is abs(d)<6; sinc(x)=sin(pi*x)/(pi*x), sinc(0)=1. |
Cubic and Lanczos weights are normalized over the complete support before mapping samples onto replicated edges. All comparisons below use ACES2065-1/linear float32 RGB:
| Reduction | Input and conditions | Output | Limit for each filter |
|---|---|---|---|
| x2 | (3,14,18) ramp from -0.1 to 1.1 with a local +0.7 grid. |
(3,7,9) |
atol=rtol=3e-5. |
| x3 | (3,18,30) ramp, pixel-frequency checkerboard and corner impulses spanning -1 to 2. |
(3,6,10) |
atol=rtol=3e-5. |
Absolute height=9, width=10 |
The same 18x30 corpus, reduced by 2 vertically and 3 horizontally in both GT and LQ, keeping their ratio at 1. | (3,9,10) |
atol=rtol=3e-5. |
The x3 and absolute comparisons retain the x2 bound to allow float32
coefficient, accumulation and output rounding; their largest measured absolute
error was 3.90e-7.
With scale 1, all four choices preserve values exactly, checked on a
(3,24,32) ramp from -0.3 to 1.7. Reductions retain negative/above-one
values; linear-light conversion occurs before filtering and returns to the
input color afterward.
Color references. Independent NumPy float64 references derive RGB/XYZ matrices from
BT.709,
BT.2020 and
Academy AP0 coordinates.
ACES2065-1 uses the ACES white (0.32168, 0.33767); sRGB/Rec.709 and Rec.2020
use D65 (0.3127, 0.3290). Differing whites use
Bradford adaptation,
matching the public rgb_to_rgb default, without tone mapping.
The transfer references use the published
sRGB equations, BT.709 equations,
and ST 2084 PQ equations in BT.2100.
Negative sRGB/Rec.709 values continue the lower linear branch; upper values
continue the power branch. PQ applies its formula to the magnitude and restores
the sign, with linear values normalized to 10,000 cd/m². No clipping is added.
The corpus starts in ACES2065-1/linear and compares output in Rec.709/linear,
Rec.2020/linear, sRGB/sRGB, Rec.709/Rec.709 and Rec.2020/PQ. It also compares
sRGB/sRGB and Rec.709/Rec.709 intermediates followed by Rec.2020/linear, and a
Rec.2020/PQ intermediate followed by Rec.709/linear. Inputs contain neutral
values from -0.25 to 4, small signed values, transfer cut points and saturated
and mixed RGB values. References round each intermediate image to float32.
The bounds are atol=rtol=3e-5, except the PQ decode sequence uses
atol=3e-5, rtol=1e-4 because the steep inverse amplifies float32 signal
rounding. Measured maximum absolute errors were 9.54e-7 without PQ,
9.30e-6 for PQ encoding and 2.26e-4 for the PQ decode sequence.
BT.709's rounded constants leave a discontinuity: the two encoding equations
at linear 0.018 differ by about 2.5e-4. A component whose interval from the
previous to the next float32 value spans the float64 cut may return either
equation's result. The same rule applies to decoding at 4.5 * 0.018 = 0.081.
The result must match one candidate within the unchanged numerical bound.
Inputs at least two float32 ULPs away use only
their prescribed branch. The corpus checks both alternatives at the cut and
the single-branch restriction away from it.
Filter and noise references. Built-in filter steps are compared with the
same pixtreme.filter public operation on the same Frame and parameter values,
using atol=rtol=2e-6. These are integration comparisons. The common input is
24x32 float32 RGB with values in [0,1) and the following settings:
| Operation | Compared settings |
|---|---|
gaussian_blur |
sigma=1.1 |
box_blur, median_blur |
size=3 |
bilateral_blur |
sigma_space=1, sigma_value=0.1 |
directional_blur |
angle=20, length=2 |
lens_blur |
radius=2 |
spin_blur |
angle=2 |
zoom_blur |
amount=0.1 |
sharpen |
amount=0.3 |
unsharp_mask |
sigma=1, amount=0.3 |
difference_of_gaussians |
sigma1=0.8, sigma2=1.3 |
Separate signed-sharpening comparisons use a 16x16 float32 RGB ramp from
-0.1 to 1.1 in ACES2065-1/linear: sharpen(amount=-0.3) and
unsharp_mask(sigma=1, amount=-0.3) match their public pixtreme operations
with atol=rtol=2e-6.
compression_artifacts uses that same public-operation reference and tolerance
on 17x23 RGB values from -0.3 to 1.7, quality 83, depths 8/10/16,
with 4:4:4 BT.601/full or 4:2:0 BT.709/legal. Custom all-one quantization tables
for block sizes 4/8/16 use a separate 17x23 ramp from -0.1 to 1.4
and depth selected from [8,10,16] with seed 7, with the same tolerance.
H.264 and HEVC comparisons use 17x23 float32 RGB from -0.2 to 1.2, QP 37,
chroma offset -3, AQ strength 0.7, beta offset 2 and alpha/tC offset 1
for the applicable codec, with deblocking enabled. Both adaptive sizes and fixed
sizes (8 for H.264, 32 for HEVC) match direct pixtreme calls with absolute
tolerance 2e-6 and zero relative tolerance. Separate sampled-control comparisons
use seeds 2, 7, and 19 and verify the same choices for every frame in a clip.
The original input is unchanged. Noise steps compare
input + pixtreme.generate.<operation>(...) - 0.5, with the same
atol=rtol=2e-6: 16x24 RGB from -0.3 to 1.7, seed 2**32-1,
grain(intensity=0.2, size=1), fractal_noise(scale=3) or
turbulent_noise(scale=3).
Direct preprocessing with Frames
Given a GPU pixtreme Frame image and a validated pipeline, prepare its channels,
color and dtype explicitly. This also converts integer storage to float32 through
pixtreme's output-storage conversion:
import numpy as np
import torch
from pixtreme.color import rgb_to_rgb
from pixtreme.train.common import rgb_frame
stream = torch.cuda.current_stream(image.__dlpack_device__()[1])
rgb = rgb_frame(image)
rgb.wait(stream)
linear = rgb_to_rgb(
rgb,
output_colorspace="ACES2065-1",
output_gamma="linear",
dtype="float32",
stream=stream,
)
rgb.record_stream(stream, write=False)
result = pipeline.apply(linear, np.random.default_rng(0))
gt, lq = result["gt"], result["lq"]
For a training pipeline containing crop markers, also pass patch_size (the final
GT size), crop_seed and the global sample number to apply. The image datasets
perform source decoding and this input conversion for their callers.
Video data and temporal compression
Choose the registered data type video for training or video_evaluation for
ordered evaluation. Supply paths containing video files, saved VideoIndex
JSON files, or directories. Each directory contributes recursively collected
video files in path order, using video_paths below. This also applies to
video_stream_evaluation. These datasets produce TCHW float32 GPU clips. A model-specific
training/evaluation step must handle the temporal dimension and model state;
the default image step does not adapt a video model automatically.
video_paths(directory, *, prefixes=()) returns a list of Path objects. It
matches .mp4, .m4v, .mov, .mkv, .webm, .avi, .ts, .m2ts, .mts,
and .mxf without regard to suffix case. It excludes files and directories
whose names begin with . beneath the requested directory, and does not follow
directory symlinks. Optional prefixes select filenames at every depth.
An empty selection raises an error naming the directory and extension conditions
before updates or evaluation. Collection only checks paths and suffixes; it
requires no GPU or codec initialization. A collected file must still
pass the existing indexing and decoder capability checks.
from pixtreme.train.common import video_paths
sources = video_paths("videos") # Includes videos nested below this directory.
selected = video_paths("videos", prefixes=("training_",))
Each directory expands at its position in paths. Directory contributions
exclude files explicitly listed anywhere in paths and files already collected
from another directory, comparing resolved paths. Explicit files keep their
order and repetitions, including when they follow a directory. Explicit video
and index JSON inputs retain their existing behavior and are not restricted by
the directory suffix or hidden-entry rules. The resolved configuration records
the expanded file list. Resolving the original directory configuration again
discovers added files; resuming after additions, removals or source changes uses
the same configuration and data-state correspondence checks as explicit files.
For whole-video evaluation, choose video_stream_evaluation. The model's
evaluation step opens each material with with dataset.stream(material) as samples:.
It receives every selected display frame once, including a short final delivery.
The source decoder, encoder and LQ decoder stay in one stream for that material;
changing frames only changes delivery boundaries. Crop coordinates and
compression settings are drawn once per material from its seed and material index.
The stream decodes each video sequentially from the beginning. Frames before
the start of time_range are also decoded and then discarded. For a fixed
selected duration, evaluating a range later in the video takes longer because
more frames must be decoded before its start. This extra decoding before the
requested range does not apply when evaluating the entire video.
| Evaluation data key or operation | video_evaluation / VideoEvaluationDataset |
video_stream_evaluation / VideoStreamEvaluationDataset |
|---|---|---|
frames (default 1) |
Length of each independent clip; incomplete tails are dropped. | Maximum frames per delivery; the entire tail is returned, including materials shorter than frames. |
frame_step, time_range |
Select eligible complete clips. | Select display frames in the half-open time range, then take every frame_step frame starting at its first eligible frame. |
gop_aligned |
Every clip starts at a source keyframe. | Only the material's first selected frame is advanced to the first eligible source keyframe. |
crop_size, temporal_compression |
Draw a crop and codec settings per clip; each clip is an independent compressed stream. | Draw once per material; the crop, references, frame types and timing persist across deliveries. |
len(dataset) |
Number of complete clips. | Number of materials in paths. |
| Reading | dataset[clip_index], including repeated random access. |
with dataset.stream(material_index) as samples: followed by ordered iteration. Each context opens a fresh stream. |
Both evaluation types reject augmentation and scene mixing and support the RGB
and optional YCbCr LQ paths. Other keys keep the meanings in the video data table
below. The existing video_evaluation behavior and defaults are unchanged.
from pixtreme.train.common import VideoStreamEvaluationDataset
dataset = VideoStreamEvaluationDataset(
paths=["source.mov"],
frames=5,
seed=17,
device="cuda",
temporal_compression={"gop_length": 10, "frame_types": True},
)
try:
for material in range(len(dataset)):
with dataset.stream(material) as samples:
for sample in samples:
# TCHW CUDA tensors: sample["gt"] and sample["lq"].
# Reset the model on LQ I frames and accumulate metrics per frame.
prediction = evaluate_video_frames(sample)
finally:
dataset.close()
evaluate_video_frames represents the caller's model evaluation. The model's
TrainingStep.evaluate(..., context=...) opens the stream contexts, including
when this data type is selected under data.evaluation in YAML. The runner
unwinds that method on a training signal. Use each context and its iterator on
the same thread. Exiting the context, even after break or an exception,
releases its source, encoder and LQ decoder without reading the remainder.
GPU retention covers delivery buffers and codec delay; the source is decoded
as the consumer advances. Indexing, demux and compressed bytes pass through the
CPU; sources unsupported by NVDEC also use CPU software decoding and upload
each picture before GPU pixel processing. Delivered tensors remain valid after context exit.
Callers retain those tensors for as long as they need them.
Stream samples carry the same fields, color, exact pts/time_base, source
frame_numbers and float times as video clips. index identifies the material
and number counts deliveries within it. continuous and source-based reset
continue across delivery boundaries; a boundary alone does not reset the model.
When compression requests frame_types, frame_type describes the continuous
LQ stream (B=0, P=1, I=2). The evaluation step selects model resets and
metric aggregation. An empty selected range is diagnosed before evaluation.
The existing source format, GPU and codec capability requirements also apply
to this data type.
To save the compressed LQ used by one evaluation stream, pass an MP4 destination to the same context:
with dataset.stream(material, lq_path="evaluation/lq.mp4") as samples:
for sample in samples:
prediction = evaluate_video_frames(sample)
lq_path defaults to None. Export requires temporal_compression; it copies
the same HEVC access units sent to the evaluation decoder, without another
encode or any change to samples or metrics. Codec selection and chosen settings
remain in temporal_compression and sample["compression"]. This also supports
B frames and the RGB and YCbCr LQ paths.
The MP4's presentation time for display frame i is i / R, starting at zero,
where R is the chosen sample["compression"]["frame_rate"] rational. The
source's original pts, time_base and times remain in the samples. A frame
rate override, source time range or stride can therefore make the MP4's times
differ from the source's absolute times. Decoding timestamps come from the
NVENC access units in their coding order. The MP4 container also
declares the colour that the encoder declared in the HEVC stream.
Export writes the MP4 to a temporary file beside the destination through
pixtreme-transport-video's PacketWriter; decoded pictures remain on the GPU.
Allow disk space for the temporary MP4. The destination's parent directories are
created when needed. After the iterator is exhausted and the context exits
successfully, the completed MP4 atomically replaces the destination. A new
destination gets the permissions of an ordinary file created by the process; a
replaced destination keeps its permission bits. A break, unconsumed iterator or evaluation exception
discards the temporary export and preserves any previous destination. A mux or
file error also preserves the previous destination and raises an exception.
Use a separate destination for each material whose LQ you want to retain.
| Video data key | Default/meaning |
|---|---|
frames, scale, frame_step |
1, 1, 1; clip length, spatial reduction, and source-frame stride. |
time_range |
null, or [start, end] in seconds. |
gop_aligned |
false; constrain selected starts to GOP boundaries when enabled. |
scene_cut_probability |
0.0; mixing needs at least two frames and two distinct materials. Evaluation forbids mixing. |
crop_size |
null, or GT crop size divisible by scale, selected before LQ reduction and temporal compression; it is the final GT size unless patch_size is set. Clips can mix source dimensions when a common crop is set. |
augment |
false; evaluation requires false. Transpose must preserve batch dimensions. |
colorspace, gamma |
Rec.709, Rec.709; RGB color of GT and decoded LQ. With temporal_compression, the encoder input primaries/transfer and HEVC declaration come from the source, independently of these settings. |
temporal_compression |
null, or a HEVC settings mapping as below. |
lq_resize |
rgb; ycbcr selects source YCbCr reduction before encoder conversion and requires temporal_compression. Applies to training and evaluation. |
decode_retries |
2; nonnegative integer number of extra attempts after a source or LQ decoding failure, excluding the first attempt. 0 disables retries. Applies to all video data types. |
index_paths |
Optional mapping from expanded video file paths to index JSON destinations. Keys name individual videos, including directory-collected videos, using the spelling returned by video_paths; directory and saved-index JSON keys are rejected. Omit it to keep rebuilding video paths without saving indexes. Available for training and evaluation. |
patch_size |
Training only: null (return the entire prepared clip), or final GT patch size divisible by scale. Patches are cut after temporal compression. When set, it must fit crop_size and every source. |
patches_per_clip |
Training only: 1; positive integer number of consecutive samples from each decoded/compressed clip. Values above 1 require patch_size. Independent of train.batch_size; a clip's samples may span batches. |
Each decode retry discards incomplete output and uses a fresh decoder with the same material, time interval and encoded input. Warnings identify the material, time interval, retry number and cause; exhaustion returns the material and cause to the caller. Sample selection, crops, compression choices and augmentation do not change. Configuration, source I/O and encoding failures are not retried. Whole-video evaluation keeps samples already delivered, discards unfinished deliveries and skips the delivered prefix when decoding again. Compressed LQ access units are staged in a temporary file and replayed without encoding again; the file is closed on completion, failure or early exit. A decode call that never returns is handled by the training supply time limit, separately from retries.
To reuse indexes across starts, choose a destination for each video. The names
and directories belong to the caller; the foundation does not impose a cache
filename. Destination directories must already exist. For a source named
training.mov, set index_paths: {training.mov: .training.mov.index.json} in
its data entry, as in the training example below. Sources omitted from the
mapping are scanned without saving an index.
For paths: [videos], a collected source videos/training.mov can use
index_paths: {videos/training.mov: indexes/training.json}. A directory itself
cannot be a mapping key. Use the public video_paths("videos") to enumerate
sources when choosing destinations programmatically. Existing unknown-key and
saved-index JSON validation also applies to directory inputs.
Only new videos and videos with missing, unreadable, unsupported or mismatched indexes are inspected on the CPU with pixtreme-transport-ffmpeg. Correspondence uses the resolved source path, byte size, and modification time floored to whole seconds. Differences within the same second also remain accepted by subsequent reads and resume. Changing the path, size, whole-second modification time or indexed frame timing still prevents resuming with different material. Removed videos' caches are unused. Indexes are fully written and synced to a sibling temporary file before replacement. Save failures warn with the source, destination and reason, then continue with the freshly built in-memory index. An index destination must differ from its source video.
Direct callers use the same behavior through
VideoIndex.build(source, cache_path=destination). Without cache_path, build
always scans and does not save. VideoIndex.save(destination) also uses complete
file replacement, but reports save errors to its caller. VideoIndex.load(path)
loads a saved index without scanning and reports errors rather than rebuilding.
New JSON indexes use version 3. Packets have explicit zero-based decode-order
packet_index values; display frames refer to those values. They contain
transport timestamps (unknown packet PTS, DTS or duration remains unknown), codec
configuration, dimensions, pixel format and container colour declarations.
Only containers declaring Identity add container_matrix_coefficients: 0 to
the stream metadata, distinguishing Identity from an absent matrix without
adding a pixtreme matrix token. Other sources retain their existing saved JSON
and fingerprints; the index version remains 3.
Packets and configuration retain their native framing. Length-prefixed
H.264/HEVC payloads are converted to Annex B only when submitted to NVDEC.
No file offsets or container format names are stored. Python VideoFrame.position
is the decode-order packet number for v3; for a loaded v2 index it retains its
original file-offset meaning. All clip payloads, including v2 inputs, are read
with Demuxer. A seek is checked against the indexed decode-order packet prefix;
if the demuxer skipped that prefix, reading from the beginning recovers it.
Only the required prefix is submitted; draining supplies delayed pictures
without decoding future packets outside that range.
Existing version 2 JSON indexes remain readable and reusable, and saving them
preserves version 2 and both original fingerprints. Version 1 indexes lack
container color metadata and require rebuilding: pass the original video and
destination to build, or use video paths with index_paths. Passing an old
JSON file directly in paths reports its unsupported format. CPU inspection
checks every display picture's colour and interlace; HEVC checks its VUI and
picture-timing declarations, distinguishing undeclared colour from decoder defaults.
H.273 matrix 0 (Identity) declares RGB stored as G, B and R planes, without a
YCbCr matrix. These 4:4:4 videos are accepted. The bitstream's known matrix
takes precedence over the container; otherwise the container's matrix applies.
When the effective matrix is 0, subsampled or monochrome video is rejected
during indexing with the source path and reason.
For containers without packet PTS, known DTS supplies display times only after
CPU inspection proves that the entire picture sequence preserves decode order;
the frame's pts_source="dts" records this interpretation, while packet PTS
remains unknown. Reordered pictures or missing PTS and DTS are diagnosed.
Video data state remains version 1. Version 3 fingerprints are prefixed v3:
and hash the index version, resolved source path/size/whole-second modification
time, time base, stream codec/pixel format/dimensions/configuration, display frame
numbers/PTS/timestamp sources/types/random-access flags/packet references, decode-order packet
numbers/sizes/PTS/DTS/durations, and container colour. Original canonical and
exact-nanosecond v2 fingerprints keep their existing calculation. Keep the
original v2 caches to resume a checkpoint whose data state contains those
fingerprints. If a v2 cache is missing or rebuilt as v3, resume rejects the
fingerprint mismatch and explains how to restore the original v2 cache or
resume with pixtreme-train 0.13.x. Start a new run to use the rebuilt v3 index.
No index or checkpoint is silently reinterpreted as a different material.
crop_size keeps its existing meaning: it selects the GT region before LQ
reduction and temporal compression. patch_size selects a smaller region after
those operations, then applies each sample's augmentation to every field and
frame. A patch's coordinates and size must align with every field's pixel grid.
With patch_size: null and patches_per_clip: 1, pixels, sample records, and
random choices are unchanged.
To reduce source YCbCr without passing the LQ pixels through RGB, set
lq_resize: ycbcr in the video data entry and enable temporal_compression.
The reader preserves the source PixelBuffer's format, bit depth and color
declarations. On the GPU, pixtreme's from_pixel_buffer expands it to a float32
YCbCr Frame, transform.resize applies area reduction, and to_pixel_buffer
converts once to the encoder input. Source primaries, transfer, matrix, range
and chroma position govern unpacking. Source primaries and transfer also govern
the encoder input and its HEVC declaration; the compression settings select its
matrix, range and bit depth, with left chroma position. Chroma is interpolated while expanding subsampled source pixels to
a Frame. This route does not retain the source plane grids during reduction.
GT and decoded LQ remain RGB in the configured colorspace/gamma. Crops still
precede reduction; patches and augmentation still follow compression. The
default lq_resize: rgb converts to source RGB before reduction and compression;
conversion to the configured training color follows decode.
This option requires pixtreme's public from_pixel_buffer, transform.resize
and to_pixel_buffer interfaces; it is supported with pixtreme 2.27.5.
Supported version-two RGB checkpoints written before lq_resize was added
retain their implicit rgb meaning, for both training and evaluation data.
They can resume with the option omitted or explicitly set to rgb. Resume
compares data options through the registered data type's configuration resolver,
including the existing single-patch defaults. Changing between rgb and
ycbcr changes preprocessing and is rejected on resume; two otherwise matching
ycbcr configurations remain compatible. Checkpoint files and saved training
states are preserved during this comparison.
For example, to produce 16 separate GT 128 / LQ 64 samples from one prepared
512-pixel GT clip, merge these fields into your training configuration. This
example uses train.batch_size: 16; a smaller or nondivisible batch size works too:
train:
batch_size: 16
data:
train:
type: video
paths: [training.mov]
index_paths: {training.mov: .training.mov.index.json}
frames: 10
scale: 2
crop_size: 512
patch_size: 128
patches_per_clip: 16
augment: true
temporal_compression: {}
The 16 samples share material, frame timing, the source crop, and compression
settings. Patch positions and horizontal/vertical flips and transposition are
chosen per sample; patches may overlap. Sharing clips reduces material/time and
compression diversity within each batch. The source clip is decoded once and
LQ is compressed once per group. train.sample_threads runs different groups
concurrently, including groups from subsequent batches within
train.prefetch_batches; thread count and prefetch do not change sample choices. Numbered
sample n belongs to clip n // patches_per_clip and patch
n % patches_per_clip. The group's first material draw chooses its clip; the
runner consumes the other material draws too, preserving sampler progress.
The runner takes consecutive samples from this sequence to fill each batch,
retaining the rest of a clip for the following batch. For example, batch 16
with patches_per_clip: 32, or batch 10 with patches_per_clip: 20, splits
one clip across two batches. Batch 8 with patches_per_clip: 12 places the
next clip's boundary inside the second batch. Each clip is decoded and
compressed once during uninterrupted training.
The number of created or in-progress samples not yet delivered in a batch is
bounded by max(1, train.prefetch_batches) * train.batch_size + patches_per_clip - 1.
The extra patches_per_clip - 1 allows the unused tail of one clip; sample
threads, pending reads and retained patches are reclaimed on every exit.
Resume rebuilds the clip containing the first unused patch and any later
prefetched clips, skipping patches already used by completed updates. Inside
a clip, checkpoint rng.generators.sampler records the generator state before
that clip's first material draw; iteration * train.batch_size % patches_per_clip
identifies the used patch count. At a clip boundary, that generator state is
before the next clip's first draw. The checkpoint format and video data state
version are unchanged. Resume requires the same batch size and patch count.
When patch_size is set, sample records additionally contain clip_number,
patch_number, patch_crop (top, left, height, width in the prepared GT clip),
source_crops (one top/left/height/width source region per frame), and
augmentation (hflip, vflip, transpose, applied in that order after crop).
patch_crop uses coordinates before augmentation; source_crops locates the
prepared clip in the source frames. GT-to-LQ coordinates follow scale.
Direct VideoDataset[(number, material)] access with multiple patches uses
material as that clip's material; use the same material for its other patch
numbers. The runner groups these reads automatically. Evaluation data has no
patch_size or patches_per_clip option.
Samples carry paths, frame_numbers, times (float seconds), pts,
time_base (numerator/denominator pairs), per-frame reset flags, and
continuous, as well as gt/lq and the sample number. Exact source times are
Fraction(pts, 1) * Fraction(*time_base) for each frame. Evaluation also supplies
path, index, and color. Saved indices are checked against source identity;
changed source material requires rebuilding the index.
For example, set the video entry's temporal_compression to
{rate_control: cbr, bitrate: [300000, 700000], gop_length: 10, b_frames: 0}.
Settings are selected once per clip from the sample's generator; sample["compression"]
records the chosen settings. All selectable codec formats are checked before use.
Numeric settings accept a scalar, an inclusive range ([min, max] or
{range: [min, max]}), or discrete {choices: [...]}.
| Temporal compression key | Default/accepted values |
|---|---|
codec, gop_length, b_frames |
hevc, 10, 0. |
rate_control |
cbr, vbr, or constqp; default cbr. |
bitrate, max_bitrate, qp |
500000 bit/s, selected bitrate, 24; QP is used for constant-QP control. Every selected maximum bitrate must cover every bitrate candidate. |
references |
null: encoder default; otherwise an integer from 1 to 7, selecting the forward reference count (NVENC num_ref_l0, corresponding to x265's ref). |
vbv_buffer_size |
null: encoder default; otherwise an integer from 1 to 4294967295 bits, corresponding to FFmpeg's -bufsize. VBV initial delay stays at the encoder default. |
subsampling, bit_depth |
4:2:0 and 8; also 4:2:2/4:4:4 and 10 where both GPU codecs support them. Use choices for disjoint bit depths. |
matrix, range |
BT.709, legal; matrices also accept BT.601/BT.2020, ranges also accept full. |
frame_rate |
null: source average display rate divided by frame_step; a positive rational such as "30000/1001" overrides it. For one-frame sources, the rate is the reciprocal of the frame's packet duration in seconds, divided by frame_step. A missing or nonpositive duration requires an explicit rate. |
motion_vectors, residuals, frame_types |
false; request mv, residual, frame_type GPU fields. |
For a scene-mixed clip, the first material determines the frame rate. One compressed clip or whole-video stream also uses the resolved primaries and transfer of its first selected frame. Later frames with a different color are converted on the GPU to that color before encoding; a color change does not split the stream or reset its references. Known decoder declarations take precedence, missing declarations use the container color saved in the index, and remaining unknown attributes use pixtreme's conversion defaults. GT and decoded LQ are returned in the configured training color. An LQ MP4 export retains the same source-color HEVC stream used for evaluation.
Omitting references or vbv_buffer_size, or setting either to null, preserves
the encoder's defaults. choices must contain integers; it cannot mix null
with explicit values. Explicit 0 is rejected in configuration. In the sample's
compression record, 0 for either control means that the encoder default was
used; this numeric representation lets the runner collate samples into a batch.
resolve_config and select keep these defaults as None. With an explicit
reference count, the DPB holds that many forward references plus one backward
reference when B frames are enabled (num_ref_l1=1); without B frames the DPB
holds only the forward references. Reference capability is checked before use.
For settings similar to x265's ref=1 and a VBV buffer of twice the bitrate,
add this mapping inside the video data entry:
temporal_compression:
rate_control: cbr
bitrate: 500000
references: 1
vbv_buffer_size: 1000000
b_frames: 0
vbv_buffer_size is a fixed number of bits, not a multiplier of the selected
bitrate. If bitrate varies per clip, choose the buffer independently; this example
has a two-second buffer only at 500000 bit/s. NVENC and x265 need not produce the
same pixels or bitstream with similar controls.
Motion vectors are displacement fields; geometric
transforms adjust their direction and magnitude. Frame type codes are B=0,
P=1, I=2. transform_video_fields applies corresponding spatial transforms
to image, vector, scalar and frame fields.
Temporal compression enables NVDEC analysis only when motion_vectors or
residuals is requested. Pictures and frame types alone skip that work. Without
analysis, faulty_reference and missing_slices metadata are unavailable;
missing references and native decoder errors still raise RuntimeError.
This applies to clips encoded internally by temporal compression. Source video
readers also use the decoder's default mode without analysis.
Direct Python operations include VideoIndex.build(source, *, cache_path=None),
VideoIndex.save/load, VideoFrame,
ClipSampler/ClipSelection, VideoField/VideoSample,
VideoClipReader.read/close, and
VideoDataset/VideoEvaluationDataset/VideoStreamEvaluationDataset.
Source decoding is selected per material before the first sample is requested.
Supported codec, chroma layout, bit depth and dimensions use NVDEC on the selected
GPU. Other inputs, including ProRes, use the public
pixtreme.transport.ffmpeg Reader.
It decodes on the CPU and completes the upload into independently owned GPU
PixelBuffers before the usual RGB conversion, crop, resize and compression.
Display order, exact source PTS/time_base, effective bit depth and color
declarations are preserved. Index persistence, clip selection and resume checks
work identically for both paths. Temporal compression still encodes with NVENC
and decodes LQ with NVDEC, including when the source uses software decoding.
Identity-matrix sources use GBR PixelBuffers on either decoder path, preserving
their primaries, transfer and range. A container's YCbCr matrix does not apply
to GBR pictures. When neither the picture nor the container declares range,
GBR uses full range. Source RGB is converted to the configured training and
evaluation colorspace and gamma after decoding.
When only the container declares Identity, both decoders use that declaration
as a fallback and keep any known bitstream matrix, so 4:4:4 sources that NVDEC
does not decode, such as H.264 High 4:4:4, are read as RGB by the software
decoder.
The pixtreme.train.common.video logger emits an INFO record per material
with its path, selected decoder (nvdec or ffmpeg) and CPU stages. Enable
that logger to inspect the selection. Unsupported software formats, such as
planar 4:1:1, are diagnosed with the material path and FFmpeg's reason before
updates or evaluation. An NVDEC capability-query error or a failure while
NVDEC is running remains an error; neither switches that material to software.
Software decode errors use the same decode_retries limit as other source
decode errors, without changing sample selection. Source software decoding uses
the bundled FFmpeg libraries through Python, without an ffmpeg child process.
VideoClipReader.read_pictures(selection, *, decode_retries=0) returns source PixelBuffers in the
selection's display order, preserving their format, declarations and code bits.
The selection retains exact PTS/time_base correspondence. Each picture owns a
GPU copy, so it remains usable after another read or close(); callers release
the returned pictures when finished. Both methods retain bounded per-thread
NVDEC sessions; software readers are closed after each clip or stream context.
TemporalCompression.resolve_config validates settings without running codecs;
select(generator) returns scalar settings, validate(...) checks capabilities,
and apply(lq, generator, *, frame_rate, ...) returns fields and chosen settings.
Both read_pictures and TemporalCompression.apply accept decode_retries=0,
a nonnegative integer number of extra attempts after a decoding failure. The
default makes one attempt; passing 2 allows at most three attempts in total.
This differs from the video data types' configured default of two extra attempts.
Retries discard partial pictures or LQ fields and decode the same selection or
encoded bytes, keeping compression choices and the generator's subsequent state
unchanged. Source I/O, configuration and encoding errors are not retried.
Each retry emits a Python logging warning with the target, retry number/limit and cause, for example:
source /data/clip.mov time [1/3, 3/2]s: decode retry 1/2: <decoder reason>
read_pictures obtains the target from the selection's source paths and minimum
and maximum selected times for each path. video_decode_target(selection),
exported from pixtreme.train.common, returns that same description without the
source prefix, retaining exact rational seconds and material order. For LQ,
pass decode_target=f"LQ {video_decode_target(selection)}" to apply; its default
target is "LQ HEVC clip". After exhaustion, the source ValueError or LQ
RuntimeError includes the target and decoder reason, including when retries
are disabled. The private apply arguments _decode_retries and _decode_target
have been replaced by these public names.
TemporalCompression.close() releases every LQ decoder session retained by
apply, including sessions opened by other sample threads. It is safe before
the first apply and on repeated calls; a later apply opens a new session as
needed. A custom data type that owns this component forwards cleanup from its
own close() method:
from pixtreme.train.common import TemporalCompression
class CustomVideoData:
def __init__(self):
self.temporal_compression = TemporalCompression({"gop_length": 10})
def close(self):
self.temporal_compression.close()
Call the custom data type's close() when sample work finishes, including on
errors. VideoDataset.close() already closes its temporal compression component.
encode_hevc(lq, parameters, *, frame_rate, colorspace="Rec.709", gamma="Rec.709")
encodes a nonempty TCHW floating CUDA RGB tensor to Annex B HEVC bytes. Pass
settings from TemporalCompression(...).select(generator).
encode_hevc_pictures(pictures, parameters, *, frame_rate, scale=1, crops=None, colorspace="Rec.709", gamma="Rec.709") accepts a nonempty sequence of source
PixelBuffers on one GPU. scale is a positive integer divisor of the selected
dimensions. Optional crops has one (top, left, height, width) or None per
picture, in source luma coordinates; resulting dimensions must match. The call
expands YCbCr, crops and reduces it on the GPU, then uses the same NVENC
submission/drain/close loop as encode_hevc. TemporalCompression.apply also
accepts these pictures with scale and crops, returning decoded RGB fields
and selected settings through the same LQ decoder sessions. For example:
from pixtreme.train.common import video_decode_target
pictures = reader.read_pictures(selection, decode_retries=2)
fields, chosen = compression.apply(
pictures,
generator,
frame_rate=frame_rate,
scale=2,
colorspace="Rec.709",
gamma="Rec.709",
decode_retries=2,
decode_target=f"LQ {video_decode_target(selection)}",
)
decode_hevc(source, *, device=0, motion_vectors=False, residuals=False, frame_types=False) accepts HEVC bytes or a file path and returns DecodedLQFrame
objects in display order; device is the CUDA device index.
This standalone operation always enables analysis and raises RuntimeError for
missing or faulty references and missing slices, even when no byproducts are requested.
Call close() on a directly constructed video reader or dataset when finished.
The training runner closes data resources on completion, error and signal stop.
Readers reuse bounded per-thread decoder sessions; samples retain valid pixel
values after subsequent reads and after readers close.
Video reference comparisons. Software references use independently built
FFmpeg/ffprobe from FFmpeg-Builds (BtbN), source
n8.1.3-27-g8dca1586f4, static GPL 8.1 build,
autobuild-2026-10-31-12-59, Linux x86_64. The reference manifest, archive
and extracted programs are SHA256-verified before use. Index and sampler
checks run on the CPU; pixel checks use the GPU and the selected codec support
listed in the installation table.
| Operation | Reference and input conditions | Limit |
|---|---|---|
VideoIndex.build, seek |
libx265 MOV, 12 frames at 6 fps, 256x192, 4:4:4 10-bit, GOP 4, two B frames: display timestamps i/6, seek frame 6 to GOP start 4, frame 3 to 0; save/load preserves the index. |
Frame order, rational timestamps, seeks and JSON exact. |
ClipSampler |
One 12-frame/6 fps source, range [1/2,2), stride 2, GOP-aligned start, seed 34: selection [4,6,8], times [2/3,1,4/3]. Same-seed selections repeat. With two sources and six-frame clips over 300 draws, scene-cut probabilities 0/1 give 0/300 clips containing cuts; probability 0.35, seed 812, gives more than 70 and fewer than 140. |
Discrete selections/times exact. The count interval is a fixed-seed smoke check. |
| NVDEC RGB source reading | Software-decoded 4:4:4 10-bit YUV plus independently applied BT.709 legal-range matrix/transfer, 256x192 source, B-frame seek, Rec.709 encoded or linear output; x2 LQ is the source RGB's area average. | RGB absolute error 5e-5, rtol=0. |
| Identity-matrix RGB source reading | Lossless H.264 High 4:4:4 and HEVC RExt, 8/10-bit, 256x192, six frames; original RGB codes, independent inverse transfer and the public CPU primaries matrix, in Rec.709 or linear Rec.2020. Check indexed clips, x2 area-reduced LQ and whole-video evaluation. Unsignalled GBR range is also checked with real 8/10/12-bit GPU PixelBuffers. | RGB absolute error 2e-6, rtol=0; reference lossless decode code values exact. |
read_pictures ownership |
Eight 256x192 10-bit pictures, source display order/color/PTS; compare saved RGB conversions before and after another read and reader close. | Values and correspondence exact. |
| Software source decode | Independent FFmpeg decode of ProRes 4:2:2 10-bit and 4:4:4 12-bit, 512x384, 6 fps with a five-second PTS offset, compared with uploaded GPU integer planes. | Code values and rational PTS exact. |
VideoDataset |
Same numbered sample (5), three frames, x2, augmentation on/off; known coordinate pictures also check common crop 16 across mixed source dimensions and scenes. |
Replay pixels/metadata exact; independent coordinate RGB absolute error 5e-5, rtol=0. |
VideoEvaluationDataset |
Order checks use two 12-frame/6 fps sources, three-frame clips, stride 2, scale 1, crop 16, seed 91: frame groups (0,2,4) and (6,8,10) in material order, source timestamps and reset flags. A separate coordinate-picture comparison uses mixed 256x192/320x224 sources, stride 1, scale 2, crop 16, seed 127. |
Numbers/times exact; coordinate RGB absolute error 5e-5, rtol=0. |
| Whole-video streaming, source order | Uncompressed 12-frame/6 fps sources: delivery sizes 5/20 cover all 12 frames; size 3, range [1/6,1.7], stride 2 selects (1,3,5,7,9). |
Source numbers/times and continuity/reset flags exact, including the final short delivery. |
| Whole-video streaming, compression | A 61-frame 512x384/24 fps source, selected range [0,0.5], crop 384, scale 2, seed 17, RGB/YCbCr routes, GOP 7, B frames 2, references 2, QP 22: compare delivery sizes 5/7/20. The RGB size 20 case also compares LQ with one independent TemporalCompression.apply call on the uncompressed LQ. |
GT/LQ/vector/residual/frame-type fields, PTS and selected compression settings exact across delivery sizes; independent RGB LQ exact. |
| Multiple patches per clip | Independently apply recorded patch_crop and augmentation to one prepared clip's fields. Uncompressed patch 32 checks use scale 2, no source crop and 1/2 patches per clip. Compressed patch 64 checks use (patches,scale,crop)=(2,1,192) or (16,2,384), including GT/LQ/vector/residual fields. All use three-frame clips, augmentation and seed 91. Separate batch-boundary checks use patch 64, scale 1, crop 192, batch 4, and 3/8 patches per clip. |
Pixels match the independent field transforms exactly; shared timing/compression and clip/patch numbers are exact, including across batches. Sample n selects clip n//k, patch n%k. |
| Decode retries | Successful source-picture and RGB/YCbCr LQ comparisons use two extra attempts after injected partial-decode failures, with the fault-free decode as reference and the same selection or encoded bytes. Separate limits 0/1 check bounded exhaustion and target diagnostics. |
Successful retry pixels, fields, settings and subsequent RNG state exact; exhaustion makes exactly 1+decode_retries attempts. |
transform_video_fields |
Two-frame grids, GT 6x8 and LQ/vector/scalar 3x4, crop (0,2,4,4), both flips, transpose and scale 0.5. Image/scalar fields match independent slicing/flips/transposition/area averaging. Vector (1,3) becomes (-1.5,-0.5); frame values [5,8] retain their tensor. |
Image/scalar/vector values use float32 tolerance; frame-field object and values unchanged. |
encode_hevc RGB round trip |
Original moving RGB clip, 12 frames, tensor height 192/width 256, 25 fps, 4:4:4 10-bit, constant-QP rate control with QP 0, BT.709/legal or BT.601/full; NVENC encode followed by NVDEC decode and RGB conversion. |
RGB absolute error 0.025, rtol=0 for these settings. |
encode_hevc_pictures input |
Independently compose YCbCr expansion, crop/area reduction and one encoder-format conversion: three 384x512 Rec.2020/PQ BT.2020/full pictures, 8/10-bit, left/center siting, x2 to 192x256 P010 10-bit BT.709/legal/left. | Submitted encoder codes exact. |
TemporalCompression.apply |
Compare with uncompressed GT/LQ after crop and resize: 512x384/6 fps 4:4:4 10-bit source, three frames, GT crop 384, x2 LQ 192, constant-QP rate control with QP 0, seed 17, augmentation. |
GT exact; LQ mean squared error against the uncompressed LQ is below 1e-4. |
Temporal source color, lq_resize=rgb/ycbcr |
Independently compose encoder input in source Rec.2020/PQ and decode the same encoded bytes into requested Rec.709/Rec.709 or ACES linear output. Check training, clip evaluation and whole-video evaluation, uncropped or crop 384; YCbCr uses its own crop/area/format conversion reference. |
Encoder codes exact; GT/LQ absolute error 1e-6, rtol=0. |
decode_hevc |
Independently software-decode a libx265 12-frame 194x146 stream, 25 fps, 4:2:0 8-bit, BT.709/legal/left, GOP 10, QP 24, no B frames. Compare each displayed integer plane. |
Absolute error 1 code value, rtol=0; display order and color exact. |
motion_vectors, residuals |
Fields match the native NVDEC analysis output exactly. For a 12-frame 192x256 picture moving right by four pixels, GOP 12, QP 20, ROI y=40:100,x=48:140, backward motion has median x -4. Residual reference uses libx265 4:2:0 8-bit frames and one-channel float32 fields. |
Native fields exact; motion median x absolute error 1 pixel, rtol=0, median absolute y at most 1 pixel. |
Evaluation and inference weights
measure(index, reference, candidate) measures RGB float32 GPU Frames using
pixtreme PSNR and SSIM with data range 1.0. Both Frames must have matching
shape, color and device and dimensions of at least 11 pixels. It does not change
color, crop, normalize or clip. Use rgb_frame(frame) explicitly to obtain RGB
channels from a supported pixtreme Frame, then perform any required color or
dtype conversion yourself. FrameMetrics, MaterialMetrics and
EvaluationMetrics preserve per-frame results and aggregate by frame count;
json_metric represents positive infinity as "Infinity" for strict JSON and
rejects NaN/negative infinity.
Metric references and conditions. PSNR uses all RGB samples over the full
image: MSE = sum((reference-candidate)^2)/(height*width*3) and
PSNR = 10*log10(1/MSE). Identical finite images give positive infinity.
The direct pixtreme.metrics.psnr call returns the same score as measure.
Independent NumPy float64 MSE comparisons and an ACES linear 16x16 image with
values -0.2 to 1.8 shifted by 0.1 (PSNR 20 dB) use absolute error
1e-4 dB, including negative and above-one values without additional clipping.
SSIM uses pixtreme.metrics.ssim with a normalized 11x11 Gaussian window,
sigma 1.5, weighted population variance/covariance, C1=(0.01*1.0)^2 and
C2=(0.03*1.0)^2. Each RGB channel is evaluated independently; channel means
are spatially averaged over valid window centers, excluding the five-pixel
border on each side. Scalar SSIM applies no padded boundary windows. The
calculation is float32, retains the input color and scene values, and always
uses declared data_range=1.0. Direct public-API comparisons are exact in the
same-call case; repeated integration checks and identical-image SSIM 1 use
scalar tolerance. These conditions describe scalar ssim used by measure.
Aggregation checks use two frames with PSNR [10,30], SSIM [0.1,0.3] and
three with PSNR [30,60,90], SSIM [0.3,0.6,0.9]: PSNR sum 220, overall
mean 44, SSIM sum 2.2, mean 0.44. Each frame has one vote; CPU integer-valued
PSNR sums/means are exact, floating SSIM sums/means use scalar tolerance.
For rgb_frame, RGB input values are exact. A 16x16 Rec.709/sRGB RGB ramp
from 0.1 to 0.9 converted to BT.709 YCbCr and back matches its original RGB
with atol=rtol=2e-6. frame_from_tensor copies contiguous/noncontiguous
(3,16,20) float32 tensors from -0.25 to 1.5, in Rec.709/sRGB or ACES
linear, exactly, including tensors requiring gradients.
Use frame_from_tensor(values, color) from pixtreme.train.common to pass a
network output to the common metrics. values must be a CUDA torch.float32
RGB tensor with shape (3, height, width) and positive dimensions. Contiguous
tensors and noncontiguous CHW views are accepted; split batches and video clips
into individual images before calling. color must specify colorspace
(primaries) and gamma (transfer) using pixtreme's supported color names. The
function copies the values on the same GPU without changing color, normalizing,
or clipping, including values outside [0, 1]. CPU tensors, other dtypes,
incompatible shapes and missing or unsupported color names raise ValueError.
Network outputs with requires_grad=True are accepted. The evaluation copy
does not track gradients; the original tensor's autograd state is preserved.
from pixtreme.train.common import frame_from_tensor, measure
color = {"colorspace": "Rec.709", "gamma": "sRGB"}
# reference and prediction are CHW float32 CUDA tensors produced on the current stream.
reference_frame = frame_from_tensor(reference, color)
prediction_frame = frame_from_tensor(prediction, color)
metrics = measure(0, reference_frame, prediction_frame)
The copy uses the current torch stream for the tensor's device and keeps
temporary tensor storage alive until the copy completes, including storage
borrowed through DLPack. The function waits for the copy to finish before
returning the Frame. When another stream
produces the tensor, order it with torch.cuda.current_stream(values.device).wait_stream(producer)
before calling. The returned Frame owns its pixels independently of later
source writes ordered after the copy. The default evaluation step uses the
same operation. Noise degradation and color clipping with
value_clipping="color_and_metrics" also wait for their tensor-to-Frame copies.
Callers using the private _frames._from_tensor should import
frame_from_tensor from pixtreme.train.common; the private name remains an
alias to the same implementation. rgb_frame continues to accept Frames.
measure requires a CUDA device and stream; CPU-only tests that substitute
Frames and metrics must substitute measure itself.
evaluate_material(path, references, candidates, *, conditions, correspondence, video=False) adds provenance through EvaluationConditions (region,
preprocessing, network, weights, precision, colorspace, gamma, normalization,
value_clipping, and data_range=1.0) and FrameCorrespondence (reference and
candidate indices and optional times in seconds). Video requires strictly
increasing indices and finite increasing times on both timelines, even for
one frame; timeline offsets can differ. Callers prepare corresponding RGB Frames
before evaluation. measure_vmaf(..., conditions=..., correspondence=..., model="vmaf_v0.6.1") returns VmafMetrics using pixtreme's VMAF implementation
(minimum dimensions 33 pixels). write_evaluation(path, result) atomically writes
a complete strict-JSON report.
VMAF accepts matching RGB float32 GPU Frames, width and height at least 33,
in strictly increasing frame order with paired reference/candidate times.
The public API converts both inputs to Rec.709 primaries and the Rec.709 camera
OETF without tone mapping. It forms single-channel 10-bit luma codes from
Y'=0.2126*R'+0.7152*G'+0.0722*B' using
floor(64+876*Y'+0.5) saturated to [0,1023], retaining nominal-range
overshoot within that storage range. This luma grid is the metric's pixel
representation; callers supply RGB Frames. Scores are returned in input order,
including the final frame, as CPU float64 values. The material sum and arithmetic
frame mean use every score once. metric_input, model and correspondence are
recorded with the result.
The API default is vmaf_v0.6.1. The existing reference comparison explicitly
selects vmaf_v0.6.1neg for two 48x48 Rec.709/sRGB pairs and compares every
score, sum and mean with a direct pixtreme.metrics.vmaf call using that same
model and inputs, with scalar tolerance. Compare results with matching model,
RGB color, luma quantization, dimensions and frame correspondence.
The runner passes context to TrainingStep.evaluate(datasets, output, *, context).
Direct calls must supply mappings networks (configuration by network name),
weights (checkpoint/version descriptions by network name) and datasets
(preprocessing descriptions by dataset name). Optional run and
completed_updates identify a training call. Overrides must accept this keyword
and record equivalent provenance. Standard evaluation prefers EMA when present,
runs in float32, and restores the network's previous training mode.
Standard evaluation reference checks use 16/24-pixel EXR images, ACES linear
GT containing 1.4/-0.2, fixed predictions such as 1.2, both clipping
policies, and the selected raw or EMA weights. They compare with direct public
PSNR/SSIM calls using scalar tolerance; analytical raw/EMA PSNR differences
use absolute error 1e-4 dB. Float32 evaluation is checked even inside an outer
bf16 autocast context, with the network's training mode restored afterward.
load_network(checkpoint, name="main", *, ema=True, device="cpu") restores a
named network in eval mode, preferring EMA and falling back to training weights
when that network has no EMA. Import the trainer's registration module first.
The checkpoint's configuration describes its data, colors and clipping policy.
The registered step's check_checkpoint validates model records first; rejected
records never become an inference network or a published weight artifact.
export_weights(checkpoint, output, *, name="main", ema=True, metadata, transform=None, inference_metadata=None) writes a new artifact directory containing weights.safetensors
and manifest.json, with source checkpoint SHA256, selected network/weights and
completed update count. The manifest's metadata must declare positive integer scale,
input_color and output_color (colorspace and gamma), normalization, and
value_clipping. Optional transform(state_dict) converts tensor names/values
before tensoracle writes safetensors. The artifact contains inference weights,
not optimizer, RNG or resumable training state.
Export and calibration deserialize the source checkpoint once and share that
validated content for weight selection and provenance. The SHA256 is computed
from the same open source file before deserialization.
Pass inference_metadata to put the trainer's string keys and string values
directly into weights.safetensors's __metadata__ header. An inference consumer
can then read these conventions from that file alone. This mapping is the source
for the header and is not copied into manifest.json; the existing structured
metadata argument continues to describe the manifest. The trainer chooses both
declarations and keeps any shared conventions consistent. Export does not infer
header fields from the checkpoint, convert values to strings, or compare header
fields with the manifest or saved model records.
For example, a trainer with cda-vsr-style inference conditions can declare its header's wire values explicitly:
from pixtreme.train.common import export_weights
from safetensors import safe_open
export_weights(
checkpoint,
artifact_directory,
metadata={
"scale": 2,
"input_color": {"colorspace": "Rec.709", "gamma": "sRGB"},
"output_color": {"colorspace": "Rec.709", "gamma": "sRGB"},
"normalization": "float32 scene values",
"value_clipping": "codec_only",
},
inference_metadata={"residual_unit": "normalized_rgb", "scale": "2", "gate": "true"},
)
with safe_open(artifact_directory / "weights.safetensors", framework="pt") as weights:
inference_conditions = weights.metadata()
The trainer's step can save residual_unit, scale, and gate in its model
record and validate that record in check_checkpoint. Export runs that check
before applying weights or calling transform; an incompatible record prevents
publication even when inference_metadata is valid. The trainer remains
responsible for choosing header values that describe the checked model.
Omitting inference_metadata or passing None preserves metadata-free weight
bytes; {} writes an empty header mapping. Tensoracle validates this argument:
non-string keys or values raise TypeError, and invalid UTF-8 or an oversized
header raises ValueError. Empty strings, Unicode, whitespace and embedded NUL
characters are preserved. Export propagates the converter's exception with
inference_metadata key context in its exception notes and publishes no partial
artifact.
calibrate(checkpoint, output, *, materials, preprocess, preprocessing, targets, infer_low_precision, metadata, ...) also writes scales, provenance, and
comparison.json comparing matched float32 and model-supplied low-precision
inference. CalibrationTarget(module, precision, input_scale, weight_scale, application, weight="weight") identifies a module input/weight, scale keys and
its inference operation. Precision is int8 or fp8 (e4m3fn), with one positive
float32 scale per tensor. preprocess(material) returns CHW GPU lq/gt, a
material path, and for video kind="video" plus FrameCorrespondence with both
times. Prepared samples stay on the GPU for comparison, so bound the material
set to available memory. The trainer owns both preprocessing and the callable
infer_low_precision(network, sample, scales); calibration does not build a
TensorRT engine.
Weight and calibration references. CPU load_network checks use a registered
scalar Scale network in a version 2 checkpoint: the selected raw/EMA weight and
its analytical float32 output are exact, including fallback when EMA is absent.
CPU export checks read safetensors through a separate reader and compare a
known conversion, gain = selected_weight * 2, exactly. Omitting header metadata
also preserves the bytes produced by the metadata-free safetensors writer.
The caller provides the mathematical reference for other transforms.
GPU calibration references use the measured GPU reference environment.
The scale reference independently takes the absolute maximum of module inputs
across the representative samples, or of the selected weight tensor. Each
saved scale is float32(max(absolute_maximum / maximum, 2**-126)), where
maximum is 127 for int8 and 448 for fp8 e4m3fn. The float32 smallest-normal
floor is this module's convention. The two-material Scale-network check uses
(3,16,16) materials with LQ values -2/1.5 and GT=LQ*0.6. Its nonzero
input and weight scales use scalar tolerance; saved float32 weights are exact.
Signed constant-input cases use [-3.25, 0.5] and weight -0.75, and all-zero
cases use zero inputs and weights, for both precisions. In these cases, saved
scalar float32 scales of shape (1,) match the reference after float32 rounding
with absolute and relative tolerance 0. All-zero inputs and all-zero weights
both produce exactly 1.1754943508222875e-38.
The calibration quality reference uses three RGB 16 x 16 float32 ramps
spanning -1.5 to 1.74609375, a known Scale-network weight 0.7, and
GT = 0.6 * LQ + 0.05, with Rec.709 primaries, sRGB transfer, data_range=1,
and value_clipping=codec_only. Two samples belong to one material and the
third to another. Independently prepared outputs use float32 multiplication
for the reference and input/weight quantization followed by multiplication for
the candidate. The INT8 comparison helper rounds to nearest, ties to even, and
clips to [-127, 127] before rescaling. TensorRT's
general INT8 formula
uses [-128, 127]. The FP8 comparison rounds through torch.float8_e4m3fn and
rescales; all scaled inputs and weights are within [-448, 448].
For each known output, PSNR is compared with -10 * log10(MSE) computed from
float64 sample differences, with absolute tolerance 1e-5 dB and relative
tolerance 0. SSIM is compared with a direct pixtreme.metrics.ssim call on
the same known output, with absolute tolerance 1e-6 and relative tolerance
0. These tolerances apply to each frame and each material/overall mean;
sums allow the frame count times the respective tolerance. The checks cover
both precisions and frame-weighted aggregation across the two materials.
Maximum measured PSNR error was 1.48e-6 dB and SSIM error was 0; the bounds
allow float32 metric arithmetic rounding. These bounds describe the accuracy
of recorded metrics for the known outputs. Comparisons record the matched
material, weights, times and precision. These checks establish no shared bound
on quality loss across models. Reused preprocessing buffers are checked against
the prepared inputs [2,1] so each material retains its own values.
Checkpoints, interruption and compatibility
Checkpoints use format version: 2, containing completed updates, network and EMA
weights, optimizer/scheduler state, model state, and committed data/sampler/RNG
state. read_checkpoint(path) validates this format; save_checkpoint and the
file helpers write_text/staging_directory publish complete artifacts atomically.
The following helpers are also public for custom training steps:
| Operation | Usage and behavior |
|---|---|
Option(name, parse, default, kinds, description, choices=(), repeat=False, required=False) |
yaml_value(value) validates accepted types, parses values, and applies choices; repeated options require lists. plain(value) converts paths and nested mappings/sequences to YAML-compatible values. |
save_checkpoint(path, payload, *, prefix=".checkpoint-") |
Atomically saves the caller's torch-compatible mapping; the caller assembles and validates its contents. read_checkpoint(path) checks a version 2 training checkpoint. |
write_text(path, text, *, prefix) |
Atomically writes UTF-8 text. with staging_directory(output, prefix=...) as temporary: publishes a new directory only after the block succeeds. |
rng_state(*, device=None, generators=None) / restore_rng_state(state, *, device=None, generators=None) |
Capture/restore Python, NumPy, torch CPU, optional CUDA and named torch generators; restoration validates all streams first. |
NumberedSampler(size, generator, *, start=0) |
Yields (global_sample_number, random_material_index) with replacement. sample_generator(seed, number) supplies that sample's NumPy generator. EndlessSampler(size, generator) draws uniform material indices with replacement from the supplied torch generator. |
image_paths(directory, *, prefixes=()) |
Lists supported direct child images in filename order, rejecting an empty selection. augment_images(images, *, hflip, vflip, transpose) applies matching spatial transforms to a mapping of tensors. |
video_paths(directory, *, prefixes=()) |
Recursively lists supported visible video files in path order, rejecting an empty selection. Prefixes select filenames at every depth. Directory inputs to video datasets use this collector; explicit files retain their order and repetitions. |
warmup_cosine_factor(completed, *, warmup, total, minimum) |
Returns the learning rate coefficient for completed updates. Set warmup=0 for cosine decay from 1.0 at zero updates to minimum at total; positive warmup lengths first increase the coefficient linearly. Requires 0 <= warmup < total and 0 <= minimum <= 1. |
update_ema(average, model, *, decay) |
Averages floating state and copies nonfloating state. check_finite_loss(loss, *, iteration) rejects nonfinite loss values. |
check_finite_gradients(parameters, *, max_norm=None) |
Rejects a nonfinite total gradient norm and returns the total L2 norm before clipping as a scalar torch tensor. With None, finite gradients remain unchanged; a positive finite max_norm clips their total L2 norm before the optimizer update. The existing check_finite_gradients(parameters) call remains valid. |
release_gpu_memory(device) |
Returns unused torch and CuPy allocator blocks for a CUDA device. |
training_signals() |
Context manager exposing the first interruption to the training loop and escalating a second signal. worker_signals(worker_id) configures a DataLoader worker; stop_loader_workers(iterator) requests shutdown, waits up to five seconds and reaps survivors. |
pixtreme-train train config.yaml --output runs/continued --resume runs/first/checkpoint_00000500.pt
Resume permits changes to train.iterations (must exceed completed updates),
train.device, train.sample_threads, train.supply_processes, train.supply_timeout, train.channels_last,
train.cudnn_benchmark, train.compile, and notes. Other settings must match the
saved configuration, including data sources, degradation, color, batch size and
prefetch depth. Version 2 checkpoints lacking supply_timeout use 600 seconds;
those lacking sample_threads or supply_processes use 1; missing
network execution options mean channels_last: false, cudnn_benchmark: false,
and compile: null. Checkpoints lacking gradient_clip_norm use null (no
clipping). The gradient bound must match when resuming. Network execution options
may change on resume in either direction without converting checkpoint weights.
Model steps may further restrict resumption. The next sample follows the last completed
update; unused prefetched samples are regenerated.
Version 2 also records supply_rng, the Python, NumPy, torch and CUDA RNG
snapshot attached to the last completed supply batch. A checkpoint without this
optional field initializes supply from its existing rng; its sampler state
continues through rng.generators.sampler. New runs using the same configuration
resume supply RNG independently from learning RNG, excluding unused prefetch.
A custom data type using global RNGs uses one sample thread; concurrent sample
threads require sample-number-derived or explicitly managed independent RNGs.
Custom data that relied on sharing global RNG consumption with stochastic
updates must move to sample-number-derived randomness or its own RNG saved by
state_dict. Resuming an older checkpoint splits those formerly shared global
streams; their old interleaving is not reproduced. Number-derived built-in image
and video choices retain their existing meaning.
An omitted train.seed on resume uses the seed saved in the checkpoint and does
not choose a new one. An explicitly supplied seed must match the saved value.
The same sources, configuration, environment and seed reproduce material/sample selection and preprocessing random choices. Bitwise identity of model updates across GPUs, library versions or arithmetic modes is not promised. Codecs can also depend on hardware/driver behavior; compare numerical outputs under matched conditions and a tolerance suitable for the operation.
Reproduction references. sample_generator(seed, number) is compared with
the same NumPy default_rng/SeedSequence implementation (PCG64) in another
process for (seed,number)=(17,35), using 32 integer draws. A separate
same-process non-aliasing check compares 16-draw sequences for the pairs
(2**32,0), (0,1), (1,2**32) and (1,0), requiring each pair's sequence
to differ from the others. These checks use matching NumPy and bit-generator
implementations. NumberedSampler(size=5, start=21, seed=83)
is compared with consecutive draws from an independent same-seed CPU
torch.Generator using torch.randint; after 35 draws, restoring state
reproduces 15 more draws exactly. EndlessSampler(size=3, seed=17) checks
50 such draws and 50 after restoring state. A separate size 1 check requires
all 20 draws to be zero. These references require the same torch version.
rng_state/restore_rng_state compare the next Python, NumPy, torch CPU,
optional CUDA and named-generator draws with those immediately after the
saved snapshot, including cached Gaussian state, exactly on the same versions
and devices. A CPU checkpoint payload with float32 weights [0.25,0.75]
is compared after loading with float32 tolerance; failed publication preserves
the previous file bytes exactly.
For matched-environment small-network image/video runs and CPU custom data,
resume is compared with an uninterrupted run: network, optimizer, scheduler,
EMA/model state, data state, next RNG draws and consumed sample order are exact
(tensor atol=rtol=0). Image supply with one/two processes, prefetch 0/2
and batch 2 compares float32 pixel bits and metadata exactly with sequential
GPU reads, including sample numbers beyond 2**32, for identity/JPEG pipelines
with augmentation. Separate bulk/single-read comparisons cover variable
geometry, color and noise choices; small-image training compares exact
step/RNG/data state across prefetch 0/2, sample threads 1/3 and resume.
The CPU mutable-data check requests three processes and checks one supply
owner per training call and exact step/RNG/data continuation after resuming.
Custom complete-batch delivery checks use batch sizes 1/3 without a second
collation. A separate resume check uses batch size 3, prefetch 0/2 and
three sample threads, resumes from two completed updates and compares the
step/RNG/data continuation exactly. Supply-timeout resume uses the corresponding
fault-free run as its reference and checks the same exact step/data/RNG
continuation. These checks
separate random-choice reproduction from the cross-environment numerical limits
described above.
The first SIGINT/SIGTERM stops new batch production, finishes an in-progress update, and saves the last completed state. No checkpoint is written before the first completed update or when no update has advanced since the last checkpoint.
An interrupted evaluation does not become a successful report. A second signal
exits without waiting for saving. The first signal also consolidates
training.jsonl in the same format as normal completion, containing only
completed updates and completed evaluations. Before the first completed update,
the file is empty. Incomplete updates are excluded, and an interrupted
evaluation contributes no evaluation values or report. A second signal skips
this consolidation when it has not started and can interrupt it in progress.
If training batch supply or evaluation data supply does not return within
train.supply_timeout seconds, the command stops learning and exits with code
75 (temporary failure; restart may succeed). The wait starts when the learner
requests the next batch, even when prefetch is disabled. Evaluation bounds each
indexed read, iteration and entry/exit/iteration of a dataset's stream() context;
evaluation calculations and hooks stay on the learning thread. Evaluation data
runs in its supplier at float32. Completion of the host and GPU copies orders
each result before the learner uses it. After each evaluation, both processes
release evaluation data and samples to the torch/CuPy allocators. A later
evaluation reconstructs its data from the same configuration.
Process startup and data validation precede per-batch waits and are bounded by
max(60, train.supply_timeout) seconds per supplier. Startup time is separate
from the wait for an already initialized supplier's next batch.
The command writes the normal training.jsonl containing completed updates,
discards partial evaluation metrics, and saves the last completed update unless
it was already saved. Before update one, it writes no checkpoint. Saving after
a supply timeout has the same time limit; if saving also stalls, the command
exits without publishing an incomplete checkpoint. It reports the dataset,
reason, saved checkpoint (or that none was saved), and how to continue on stderr.
The command flushes its output and completed records and exits without waiting
for unfinished native calls. Continue with a new output directory, for example:
pixtreme-train train config.yaml --output runs/retry --resume runs/first/checkpoint_00000500.pt
If no checkpoint was saved, retry from an earlier checkpoint, or restart the run.
Python callers of train() receive SupplyTimeoutError, a RuntimeError
exported from pixtreme.train.common. Its target names the batch or evaluation
dataset, reason describes the expired wait, and checkpoint is a Path to the
saved or reused checkpoint, or None when none is available. After catching this
exception, end the process and start a new process using --resume; do not
continue training in that process, because the CUDA state may be unusable.
Shutdown bounds its process joins and terminates a supplier that does not return. Unfinished native calls do not prevent the caller's process from exiting.
Migration of video temporal-compression color
Video data now encodes temporal-compression LQ in the source's primaries and
transfer, then converts the decoded RGB to colorspace / gamma. Configurations
whose training color differs from the source color receive different LQ values
and may produce different evaluation metrics. Start a new training run when
changing to this degradation order. There is no setting to retain encoding in
the training color. When source and training colors match, LQ pixels, compressed
streams and metrics are unchanged. Direct TemporalCompression.apply,
encode_hevc and encode_hevc_pictures calls retain their existing meaning:
their color arguments describe the frames supplied by the caller.
Migration from 0.3.x
Use the following replacements when updating trainer modules and configurations:
| 0.3.x usage | Current usage |
|---|---|
data.train.batch_size, data.train.prefetch_batches or num_workers |
Move batch size and prefetch depth to train.batch_size and train.prefetch_batches; use train.sample_threads for threads within a supplier and train.supply_processes for independent built-in image suppliers. |
Top-level degradation/evaluation_degradations; train.value_clipping |
Put each pipeline and value_clipping inside its data entry. Split the former {name, seed, steps} pipeline into {name, seed, gt: {steps}, lq: {steps}}; the example below shows training and named evaluations. |
data.evaluation: {type: image_evaluation, ...} |
Create one data.evaluation.<name> entry for the training pipeline and one for each former evaluation_degradations pipeline; explicitly give each entry its sources and degradation. |
data.train.region_size or ImageDegradationDataset(..., region_size=..., patch_size=...) |
Remove region_size from YAML and Python. Keep patch_size as the final GT size; place one crop marker in each training branch. |
NumPy input and one LQ ndarray returned by DegradationPipeline.apply |
Supply float32 RGB on the GPU in ACES2065-1/linear, as in the Frame example. The result is a mapping: use result["lq"] for the former LQ result and result["gt"] for its corresponding reference. |
torch tensor input to rgb_frame |
0.3.1 treated tensor values as Rec.709 primaries and Rec.709 transfer. Explicitly upload the CHW RGB CPU float tensor and construct a GPU Frame with pixtreme.io.from_tensor(..., layout="CHW", colorspace="Rec.709", gamma="Rec.709", channels="RGB"), as in the example below. Different color metadata changes metric values; rgb_frame prepares RGB channels without changing primaries or transfer. |
TrainingStep.evaluate(datasets, output) |
Accept *, context in overrides; direct calls supply network, weight and preprocessing descriptions. |
Implicit RGB conversion in measure |
Prepare matching RGB float32 Frames explicitly; call rgb_frame(frame) for channel conversion before measure. measure requires a CUDA device and stream; CPU-only tests that substitute Frames and metrics must substitute measure itself. |
encode steps selecting jpeg, prores_lt, h264 or hevc |
Replace the removed operation explicitly using the codec table below; moving encode into lq.steps still fails. |
VideoDataset sample times as Fractions |
Times are float seconds. Reconstruct exact times from each frame's pts and time_base. Video registry names are video and video_evaluation. |
| Weight export assumed available from the base install | Install pixtreme-train[export] and call export_weights with explicit inference metadata. |
A checkpoint with version: 1 from 0.3.x |
Resume and weight extraction reject it and identify pixtreme-train 0.3.x as its supported version. There is no conversion/import operation; retain a separate 0.3.x environment to use that checkpoint. Start a new run with the current configuration. |
Migrating tensor inputs to rgb_frame
Given a CHW RGB CPU float32 tensor, this preserves the tensor's values and the
Rec.709 primaries and transfer used by 0.3.1. Transfer host data to CUDA explicitly
before constructing the Frame:
import torch
from pixtreme.io import from_tensor
from pixtreme.train.common import rgb_frame
stream = torch.cuda.current_stream()
gpu_tensor = tensor.to("cuda")
gpu_tensor.record_stream(stream)
frame = from_tensor(
gpu_tensor,
layout="CHW",
colorspace="Rec.709",
gamma="Rec.709",
channels="RGB",
copy=True,
stream=stream,
)
rgb = rgb_frame(frame)
Setting gamma="sRGB" or different primaries describes a different signal and
can change PSNR and SSIM. Choose metadata that matches the values being measured.
Before: 0.3.1 image training and evaluation
This configuration uses the my_trainer module above. In 0.3.1 the runner applied
the single degradation.steps list to LQ, kept the original GT region, and cropped
the corresponding pair afterward. One evaluation source entry was reused for the
training pipeline (jpeg) and each additional evaluation pipeline (clean):
imports: [my_trainer]
networks:
main: {type: tiny}
losses:
pixel: {type: l1}
optimizers:
main: {type: adamw, networks: [main], lr: 2.0e-4}
degradation:
name: jpeg
seed: 0
steps:
- encode: {codec: jpeg, quality: 80, chroma: "4:2:0", bit_depth: 8}
evaluation_degradations:
- {name: clean, seed: 0, steps: []}
data:
train:
type: image_degradation
directory: /data/train
region_size: 128
patch_size: 64
batch_size: 8
num_workers: 2
evaluation: {type: image_evaluation, directory: /data/validation}
train:
iterations: 1000
seed: 0
device: cuda
checkpoint_interval: 500
evaluation_interval: 100
After: current image training and evaluation
Keep reference preparation in gt.steps and put the former LQ-only operations
in lq.steps. Each training branch needs one crop; place it after the LQ
operations to degrade the larger image before cropping, or before them to degrade
only the patch. The example chooses patch-only artifact simulation, so its context
and edge effects differ from the old region-then-crop JPEG operation. For a
resolution-reduction task, put the reduction in LQ and use a network with the
matching output scale; the GT patch_size determines the corresponding LQ size.
The YAML anchor reuses the training degradation for the named jpeg evaluation;
evaluation ignores its crop markers and uses the full corresponding image.
The clean evaluation explicitly gets its own pipeline. region_size is removed.
Old num_workers counted worker processes; sample_threads now selects threads
within each supply process. supply_processes selects independent built-in image suppliers, while prefetch_batches bounds batches across all suppliers
being prepared or queued. These are separate execution choices, not equivalent
worker-count settings.
imports: [my_trainer]
networks:
main: {type: tiny}
losses:
pixel: {type: l1}
optimizers:
main: {type: adamw, networks: [main], lr: 2.0e-4}
data:
train:
type: image_degradation
directory: /data/train
patch_size: 64
degradation: &jpeg
name: jpeg
seed: 0
gt: {steps: [crop]}
lq:
steps:
- crop
- color: {colorspace: Rec.709, gamma: sRGB}
- compression_artifacts:
quality: 80
subsampling: "4:2:0"
bit_depth: 8
matrix: BT.601
range: full
evaluation:
jpeg:
type: image_evaluation
directory: /data/validation
degradation: *jpeg
clean:
type: image_evaluation
directory: /data/validation
degradation:
name: clean
seed: 0
gt: {steps: []}
lq: {steps: []}
train:
iterations: 1000
seed: 0
device: cuda
checkpoint_interval: 500
evaluation_interval: 100
batch_size: 8
sample_threads: 2
prefetch_batches: 2
The old flat steps mapping and every old encode step are rejected. None of the
following substitutions promises the old encoder's pixels, quality scale or random
sequence. Source color handling, linear-light processing and crop context also
change the data; start a new run rather than resume a version 1 checkpoint.
Removed encode.codec |
Replacement and change in degradation meaning |
|---|---|
jpeg |
In lq.steps, use compression_artifacts with explicit quality, subsampling (formerly chroma), bit_depth, matrix and range. This GPU operation simulates compression artifacts; it does not run the former Pillow JPEG bitstream encode/decode and is not a pixel-exact substitute. |
prores_lt |
For image-only artifacts choose compression_artifacts and select its settings explicitly. There is no ProRes LT encoder or ProRes-quality equivalent in the standard degradation pipeline. |
h264 |
For image-only artifacts choose compression_artifacts. For a temporal encoding task, use video temporal_compression, which encodes HEVC; it changes codec and does not reproduce the former H.264 encoder or QP behavior. |
hevc |
For actual clip encoding choose video temporal_compression with NVENC/NVDEC and explicitly selected rate-control/GOP settings. This is clip-based hardware HEVC rather than the former FFmpeg still-image encode. For image-only simulated artifacts choose compression_artifacts. |
Version 2 training checkpoints and inference artifacts are distinct formats.
Inference artifacts cannot be used as resume checkpoints. The public API is
pixtreme.train.common and the documented registry contracts; private modules
and underscore-prefixed helpers are not compatibility interfaces.
License
MIT. See LICENSE.
Metadata
Release files for pixtreme-train 0.20.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pixtreme_train-0.20.0-py3-none-any.whl | Python 3 | none | any | Details for pixtreme_train-0.20.0-py3-none-any.whl |
Release files / pixtreme_train-0.20.0-py3-none-any.whl
| Download URL | pixtreme_train-0.20.0-py3-none-any.whl |
|---|---|
| Size | 202.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4559fb40b607ad9df1612da16eddb8ea6358b12c8e06ac7492f288f6591fd439
|
|
BLAKE2b-256 checksum How to use checksums |
57256e1d26baa1f131e6b5a427f66a22d8025cb71474e82a09684991e71dda90
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for pixtreme-train 0.20.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.