This page contains the auto-generated API reference documentation.

Stable integration API

sequifier.api is the stable model boundary for sibling packages. It exposes the composable network, portable artifacts, explicit encode/decode and tracing types, canonical parameter naming, and parameter catalogs without exposing the training lifecycle.

Stable sibling-facing, model-level Sequifier API.

class sequifier.api.CaptureRequest(sites: 'tuple[str, ...]', detach: 'bool' = True, retain_grad: 'bool' = False, clone: 'bool' = False, positions: 'slice | Tensor | None' = None)[source]
clone: bool = False
detach: bool = True
positions: slice | Tensor | None = None
retain_grad: bool = False
sites: tuple[str, ...]
class sequifier.api.ComposableTransformerNetwork(*, backbone: Module, interfaces: dict[str, sequifier.model.network.ModelInterfaceModule], attention_mask_policy: Tensor, context_length: int)[source]

A shared backbone with explicitly selected named model interfaces.

property context_length: int
decode_representation(representation: Tensor, request: DecodeRequest = DecodeRequest(target_columns=None, positions=None, apply_output_transform=False, apply_final_norm=False), *, interface_name: str | None = None, trace: TraceContext | None = None) dict[str, Tensor][source]
property dim_model: int
encode(features: dict[str, Tensor], metadata: dict[str, Tensor], *, interface_name: str | None = None, trace: TraceContext | None = None) Tensor[source]
forward(features: dict[str, Tensor], metadata: dict[str, Tensor], *, interface_name: str | None = None, trace: TraceContext | None = None) ModelOutput[source]

Define the computation performed at every call.

Should be overridden by all subclasses.

Note

Although the recipe for forward pass needs to be defined within this function, one should call the Module instance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.

regularization_loss(interface_name: str | None = None) Tensor[source]

Return decoder regularization through an explicit model contract.

resolve_interface(interface_name: str | None) ModelInterfaceModule[source]
structural_metadata() dict[str, object][source]
trace(features: dict[str, Tensor], metadata: dict[str, Tensor], request: CaptureRequest, *, interface_name: str | None = None, interventions: tuple[InterventionBinding, ...] = ()) TracedModelOutput[source]
property trace_catalog: tuple[TraceSite, ...]
trace_catalog_for(interface_name: str | None = None) tuple[TraceSite, ...][source]
class sequifier.api.DecodeRequest(target_columns: 'tuple[str, ...] | None' = None, positions: 'slice | Tensor | None' = None, apply_output_transform: 'bool' = False, apply_final_norm: 'bool' = False)[source]
apply_final_norm: bool = False
apply_output_transform: bool = False
positions: slice | Tensor | None = None
target_columns: tuple[str, ...] | None = None
class sequifier.api.EncodeRequest(interface_name: 'str | None' = None)[source]
interface_name: str | None = None
class sequifier.api.EncodedOutput(representation: 'Tensor')[source]
representation: Tensor
class sequifier.api.Intervention(*args, **kwargs)[source]
transform(site: TraceSite, tensor: Tensor, context: ForwardContext) Tensor[source]
class sequifier.api.InterventionBinding(site: 'str', intervention: 'Intervention')[source]
intervention: Intervention
site: str
class sequifier.api.ModelArtifact(format_version: 'int', model_config: 'ModelExecutionConfig', model_state_dict: 'dict[str, Tensor]', metadata: 'ModelArtifactMetadata')[source]
format_version: int
classmethod from_state_dict(payload: Mapping[str, Any]) ModelArtifact[source]
metadata: ModelArtifactMetadata
model_config: ModelExecutionConfig
model_state_dict: dict[str, torch.Tensor]
state_dict() dict[str, Any][source]
validate() None[source]
class sequifier.api.ModelArtifactMetadata(trace_sites: 'tuple[str, ...]' = (), provenance: 'dict[str, Any]' = <factory>)[source]
provenance: dict[str, Any]
trace_sites: tuple[str, ...] = ()
class sequifier.api.ModelExecutionConfig(values: dict[str, Any])[source]

Serializable configuration required to reconstruct model execution.

classmethod from_training_config(config: Any) ModelExecutionConfig[source]
values: dict[str, Any]
class sequifier.api.ModelInterfaceModule(*, ingestion: Module, ingestion_adapter: Module, decoder: Module, decoder_input_width: int, decoding_support: int, prediction_length: int, target_columns: tuple[str, ...], target_column_types: dict[str, str])[source]

One named ingestion/adapter/decoder route around the shared backbone.

decode(representation: Tensor, request: DecodeRequest = DecodeRequest(target_columns=None, positions=None, apply_output_transform=False, apply_final_norm=False), *, trace: TraceContext | None = None) dict[str, Tensor][source]
decoder_input(representation: Tensor) Tensor[source]
ingest(features: dict[str, Tensor], metadata: dict[str, Tensor]) Tensor[source]
class sequifier.api.ModelOutput(logits: 'dict[str, Tensor]', prediction_positions: 'slice | Tensor')[source]
logits: dict[str, torch.Tensor]
prediction_positions: slice | Tensor
class sequifier.api.ParameterCatalog(model: Module)[source]
descriptors() tuple[sequifier.model.parameter_catalog.ParameterDescriptor, ...][source]
fingerprint() str[source]
parameter(parameter_id: str) Parameter[source]
select(*, component: str | None = None, semantic_group: str | None = None) tuple[sequifier.model.parameter_catalog.ParameterDescriptor, ...][source]
class sequifier.api.ParameterDescriptor(parameter_id: 'str', canonical_name: 'str', aliases: 'tuple[str, ...]', component: 'ParameterComponent', semantic_group: 'str', parameter_kind: 'ParameterKind', shape: 'tuple[int, ...]', dtype: 'torch.dtype', shared_parameter_id: 'str | None', depth_parameter: 'bool' = False, branch_path: 'tuple[str, ...]' = ())[source]
aliases: tuple[str, ...]
branch_path: tuple[str, ...] = ()
canonical_name: str
component: Literal['ingestion', 'backbone', 'decoder']
depth_parameter: bool = False
dtype: dtype
parameter_id: str
parameter_kind: Literal['weight', 'bias', 'other']
semantic_group: str
shape: tuple[int, ...]
shared_parameter_id: str | None
class sequifier.api.TraceSite(name: 'str', axes: 'tuple[str, ...]', width: 'int | None' = None)[source]
axes: tuple[str, ...]
name: str
width: int | None = None
class sequifier.api.TracedModelOutput(output: 'ModelOutput', captures: 'dict[str, Tensor]' = <factory>)[source]
captures: dict[str, torch.Tensor]
output: ModelOutput
sequifier.api.build_transformer_network(config: Any, *, device: device, initialize: bool = True, logger: Any | None = None) BuiltModel[source]

Build one shared backbone and every distinct named model interface.

sequifier.api.canonical_parameter_name(name: str) str[source]

Remove compiler/distributed wrapper segments from one parameter name.

sequifier.api.canonicalize_state_dict(state_dict: Mapping[str, T]) dict[str, T][source]

Return a canonical state dict and reject ambiguous normalizations.

sequifier.api.load_model_artifact(path: str | Path, *, device: str = 'cpu', interface_name: str | None = None) tuple[Any, Any, sequifier.artifacts.model_artifact.ModelArtifact][source]

Load a portable artifact and return network, resolved config, and schema.

sequifier.api.load_weights_from_run_checkpoint(path: str | Path, *, device: str = 'cpu', interface_name: str | None = None) tuple[Any, Any, sequifier.artifacts.model_artifact.ModelArtifact][source]

Training integration API

Update-aware integrations use sequifier.training_api for optimization, step identity, directives, distributed strategies, and run state.

Stable update-aware primitives for training integrations.

class sequifier.training_api.DistributedDataParallelStrategy(rank: 'int' = 0, local_rank: 'int' = 0, world_size: 'int' = 1, device: 'torch.device' = device(type='cpu'), find_unused_parameters: 'bool' = False)[source]
barrier() None[source]
finalize() None[source]
find_unused_parameters: bool = False
gather_objects(value: Any) list[Any][source]
prepare_network(network: Module) PreparedNetwork[source]
class sequifier.training_api.DistributedStrategy(*args, **kwargs)[source]
barrier() None[source]
capture_model_state(network: Module) dict[str, torch.Tensor][source]
capture_optimizer_state(network: Module, optimizer: Optimizer) dict[str, Any][source]
device: device
finalize() None[source]
gather_objects(value: Any) list[Any][source]
local_rank: int
prepare_network(network: Module) PreparedNetwork[source]
prepare_optimizer_parameters(network: Module) Iterable[Parameter][source]
rank: int
restore_model_state(network: Module, state: dict[str, torch.Tensor]) None[source]
restore_optimizer_state(network: Module, optimizer: Optimizer, state: dict[str, Any]) None[source]
world_size: int
class sequifier.training_api.FullyShardedStrategy(rank: 'int' = 0, local_rank: 'int' = 0, world_size: 'int' = 1, device: 'torch.device' = device(type='cpu'), find_unused_parameters: 'bool' = False, cpu_offload: 'bool' = False, mixed_precision_dtype: 'torch.dtype | None' = None)[source]
capture_model_state(network: Module) dict[str, torch.Tensor][source]
capture_optimizer_state(network: Module, optimizer: Optimizer) dict[str, Any][source]
cpu_offload: bool = False
mixed_precision_dtype: dtype | None = None
prepare_network(network: Module) PreparedNetwork[source]
restore_model_state(network: Module, state: dict[str, torch.Tensor]) None[source]
restore_optimizer_state(network: Module, optimizer: Optimizer, state: dict[str, Any]) None[source]
class sequifier.training_api.LocalStrategy(rank: 'int' = 0, local_rank: 'int' = 0, world_size: 'int' = 1, device: 'torch.device' = device(type='cpu'))[source]
barrier() None[source]
capture_model_state(network: Module) dict[str, torch.Tensor][source]
capture_optimizer_state(network: Module, optimizer: Optimizer) dict[str, Any][source]
device: device = device(type='cpu')
finalize() None[source]
gather_objects(value: Any) list[Any][source]
local_rank: int = 0
prepare_network(network: Module) PreparedNetwork[source]
prepare_optimizer_parameters(network: Module) Iterable[Parameter][source]
rank: int = 0
restore_model_state(network: Module, state: dict[str, torch.Tensor]) None[source]
restore_optimizer_state(network: Module, optimizer: Optimizer, state: dict[str, Any]) None[source]
world_size: int = 1
class sequifier.training_api.OptimizationRuntime(optimizer: 'Optimizer', scheduler: 'Any', scaler: 'GradScaler', scheduler_policy: 'SchedulerPolicy', gradient_policy: 'GradientPolicy', optimizer_step: 'int' = 0, skip_next_scheduler_step: 'bool' = False)[source]
access(network: Module) TrainingAccess[source]
accumulate(loss: Any, identity: StepIdentity, integrations: IntegrationManager, network: Module) None[source]
capture_boundary_state() OptimizationBoundaryState[source]
complete_step(network: Module, identity: StepIdentity, integrations: IntegrationManager, policy: UpdatePolicy) StepResult[source]
classmethod create(training: Any, device: str, parameters: Iterable[Parameter] | list[dict[str, Any]], *, phase_epochs: int | None = None) OptimizationRuntime[source]
gradient_policy: GradientPolicy
load_non_optimizer_state(state: OptimizationState) None[source]
optimizer: Optimizer
optimizer_step: int = 0
restore_boundary_state(state: OptimizationBoundaryState) None[source]
scaler: GradScaler
scheduler: Any
scheduler_policy: SchedulerPolicy
skip_next_scheduler_step: bool = False
state_dict(optimizer_state: dict[str, Any] | None = None) OptimizationState[source]
step_scheduler() bool[source]
class sequifier.training_api.RunState(run_id: 'str' = <factory>, session_id: 'str' = <factory>, phase_index: 'int' = 0, phase_epoch: 'int' = 0, phase_epoch_complete: 'bool' = False, source_index: 'int' = 0, source_scheduler_state: 'dict[str, Any]' = <factory>, iterator_positions: 'dict[str, int]' = <factory>, epoch: 'int' = 0, batch: 'int' = 0, global_batch_step: 'int' = 0, optimizer_step: 'int' = 0, accumulation_index: 'int' = 0, best_validation_loss: 'float' = inf, epochs_without_improvement: 'int' = 0, best_model_state_dict: 'dict[str, Tensor] | None' = None, backbone_parent_revision_id: 'str | None' = None)[source]
accumulation_index: int = 0
backbone_parent_revision_id: str | None = None
batch: int = 0
best_model_state_dict: dict[str, torch.Tensor] | None = None
best_validation_loss: float = inf
epoch: int = 0
epochs_without_improvement: int = 0
classmethod from_state_dict(state: Mapping[str, Any]) RunState[source]
global_batch_step: int = 0
iterator_positions: dict[str, int]
optimizer_step: int = 0
phase_epoch: int = 0
phase_epoch_complete: bool = False
phase_index: int = 0
restore(snapshot: RunStateSnapshot) None[source]
run_id: str
session_id: str
snapshot() RunStateSnapshot[source]
source_index: int = 0
source_scheduler_state: dict[str, Any]
state_dict() dict[str, Any][source]
class sequifier.training_api.StepIdentity(epoch: 'int', batch: 'int', global_batch_step: 'int', optimizer_step: 'int', accumulation_index: 'int', accumulation_steps: 'int', rank: 'int', world_size: 'int')[source]
accumulation_index: int
accumulation_steps: int
batch: int
epoch: int
global_batch_step: int
optimizer_step: int
rank: int
world_size: int
class sequifier.training_api.StepResult(applied: 'bool', overflow: 'bool', stop_requested: 'bool')[source]
applied: bool
overflow: bool
stop_requested: bool
class sequifier.training_api.TrainingDirective(parameter_group_updates: 'dict[str, dict[str, Any]]' = <factory>, gradient_clip_norm: 'float | None' = None, skip_optimizer_step: 'bool' = False, stop_after_step: 'bool' = False, reason: 'str | None' = None, scheduler_state_updates: 'dict[str, Any]' = <factory>, disable_gradient_clipping: 'bool' = False, skip_scheduler_step: 'bool' = False)[source]
disable_gradient_clipping: bool = False
gradient_clip_norm: float | None = None
parameter_group_updates: dict[str, dict[str, Any]]
reason: str | None = None
scheduler_state_updates: dict[str, Any]
skip_optimizer_step: bool = False
skip_scheduler_step: bool = False
stop_after_step: bool = False

Preprocessing Config

class sequifier.config.preprocess_config.PreprocessorModel(*, depth_layouts: ~sequifier.config.depth_layout.DepthLayoutRegistryModel = <factory>, project_root: str, preprocessing_data_path: str, read_format: str = 'csv', write_format: str = 'parquet', merge_output: bool = True, allow_sequence_splitting: bool = False, selected_columns: list[str] | None = None, column_data_types: dict[str, str] | None = None, normalize_real_columns: bool = True, split_ratios: list[float], split_method: str = 'within_sequence', window_length: int, max_target_offset: int = 1, window_strides: list[int] | None = None, max_rows: int | None = None, seed: int = 1010, n_cores: int | None = None, batches_per_file: int = 1024, process_by_file: bool = True, continue_preprocessing: bool = False, window_placement: str = 'distribute', use_precomputed_maps: list[str] | None = None, metadata_config_path: str | None = None, mask_column: str | None = None)[source]

Top-level preprocessing config.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

Training Config

Canonical Sequifier training configuration and resolution.

The concise singleton authoring surface is normalized to the canonical named schema before validation. This module intentionally contains no migration adapter for the historical flat single-dataset YAML schema. Runtime consumers select a dataset, part, or model interface explicitly.

class sequifier.config.train_config.DatasetTrainingSpecModel(*, model_interface: str, parts: dict[str, sequifier.config.train_config.DatasetPartSpecModel], criterion: dict[str, str], class_weights: dict[str, list[float]] | None = None, loss_weights: dict[str, float] | None = None, class_share_log_columns: list[str] = <factory>, freeze: ~sequifier.config.train_config.DatasetFreezingSpecModel = <factory>)[source]
model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class sequifier.config.train_config.GlobalTrainingSpecModel(*, read_format: ~typing.Literal['csv', 'parquet', 'pt'] = 'parquet', training_objective: str, context_length: int, target_offset: int = 1, window_stride: int | None = None, inference_batch_size: int, batch_size: int, accumulation_steps: int | None = None, learning_rate: float, optimizer: ~sequifier.config.components.ComponentSpec = <factory>, scheduler: ~sequifier.config.components.ComponentSpec = <factory>, scheduler_step_on: ~typing.Literal['epoch', 'batch'] = 'epoch', reset_optimization_on_phase: bool = True, gradient_clip: float | None = None, bert_spec: ~sequifier.config.components.BERTSpecModel | None = None, next_occurrence_config: ~sequifier.config.components.NextOccurrenceConfigModel | None = None, device_max_concat_length: int = 12, log_interval: int = 10, early_stopping_epochs: int | None = None, save_interval_epochs: int = 1, save_latest_interval_minutes: float | None = None, save_interval_minutes: float | None = None, save_interval_batches: int | None = None, save_interval_val_loss: bool = True, calculate_validation_loss_on_initialization: bool = True, resume: ~sequifier.config.components.ResumeConfig | None = None, enforce_determinism: bool = False, distributed: bool = False, load_full_data_to_ram: bool = True, max_ram_gb: int | float = 16, world_size: int = 1, num_workers: int = 0, backend: str = 'nccl', layer_type_dtypes: dict[str, str] | None = None, layer_autocast: bool = False, data_parallelism: ~typing.Literal['ddp', 'fsdp'] | None = None, fsdp_cpu_offload: bool | None = None, torch_compile: ~typing.Literal['outer', 'inner', 'none'] = 'outer', float32_matmul_precision: ~typing.Literal['highest', 'high', 'medium'] = 'highest')[source]

Run-wide data, optimization, precision, and distribution settings.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class sequifier.config.train_config.LoadedTrainConfig(config: 'SequifierConfig', resolved: 'ResolvedSequifierConfig', metadata: 'dict[str, DatasetMetadata]')[source]
class sequifier.config.train_config.ModelInterfaceSpecModel(*, input_columns: list[str], target_columns: list[str], categorical_decoder_special_tokens: dict[str, list[typing.Literal['unknown', 'other', 'mask']]] = <factory>, feature_layout: ~sequifier.config.components.FeatureLayoutRegistryModel | None = None, ingestion: ~sequifier.config.components.EmbeddingIngestionConfig | ~sequifier.config.components.PassthroughIngestionConfig | ~sequifier.config.components.FeaturePoolIngestionConfig | ~sequifier.config.components.GroupedIngestionConfig | ~sequifier.config.components.SiameseIngestionConfig | ~sequifier.config.components.TemporalConvIngestionConfig | ~sequifier.config.components.StructuredIngestionConfig | ~sequifier.config.components.DepthTransformerIngestionConfig | ~sequifier.config.components.CompositeIngestionConfig, decoder: ~sequifier.config.components.LinearDecoderComponentConfig | ~sequifier.config.components.MLPDecoderComponentConfig | ~sequifier.config.components.CompositeDecoderComponentConfig)[source]

Architecture and selected-column contract for one named model route.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class sequifier.config.train_config.ModelSpecModel(*, backbone: BackboneComponentConfig, interfaces: dict[str, sequifier.config.train_config.ModelInterfaceSpecModel])[source]

One shared backbone and one or more named interfaces.

property decoder: LinearDecoderComponentConfig | MLPDecoderComponentConfig | CompositeDecoderComponentConfig

Single-interface compatibility view for low-level builders.

property ingestion: EmbeddingIngestionConfig | PassthroughIngestionConfig | FeaturePoolIngestionConfig | GroupedIngestionConfig | SiameseIngestionConfig | TemporalConvIngestionConfig | StructuredIngestionConfig | DepthTransformerIngestionConfig | CompositeIngestionConfig

Single-interface compatibility view for low-level builders.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class sequifier.config.train_config.ResolvedSequifierConfig(*, project_root: str, model_name: str, device: str, seed: int, global_training: GlobalTrainingSpecModel, model: ModelSpecModel, dataset_training: dict[str, sequifier.config.train_config.ResolvedDatasetTrainingSpec], training_plan: list[sequifier.config.train_config.ResolvedTrainingPhase], evaluation_sources: list[sequifier.config.train_config.ResolvedTrainingSource], evaluation_monitor: EvaluationMonitorSpecModel | None, export_generative_model: bool, export_embedding_model: bool, embedding_layer_names: list[str], export_onnx: bool, export_pt: bool, export_with_dropout: bool = False)[source]

Runtime configuration after all dataset parts and interfaces resolve.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

validate_model_execution_plans()[source]

Compile each route while validation errors still retain Pydantic context.

class sequifier.config.train_config.SequifierConfig(*, project_root: str, model_name: str, device: str, seed: int = 1010, global_training: ~sequifier.config.train_config.GlobalTrainingSpecModel, model: ~sequifier.config.train_config.ModelSpecModel, dataset_training: dict[str, sequifier.config.train_config.DatasetTrainingSpecModel], training_plan: ~sequifier.config.train_config.TrainingPlanModel, evaluation: ~sequifier.config.train_config.EvaluationSpecModel | None = None, export_generative_model: bool = True, export_embedding_model: bool = False, embedding_layer_names: list[typing.Annotated[str, Strict(strict=True)]] = <factory>, export_onnx: bool = True, export_pt: bool = False, export_with_dropout: bool = False)[source]

Training configuration with singleton authoring normalization.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

sequifier.config.train_config.TrainModel

alias of ResolvedSequifierConfig

class sequifier.config.train_config.TrainingPlanModel(*, phases: list[sequifier.config.train_config.TrainingPhaseSpecModel])[source]
model_config: ClassVar[ConfigDict] = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

sequifier.config.train_config.resolve_sequifier_config(config: SequifierConfig, metadata: DatasetMetadata | dict[str, sequifier.config.metadata.DatasetMetadata], *, part_overrides: dict[str, dict[str, str]] | None = None) ResolvedSequifierConfig[source]

Resolve every dataset part, compatibility contract, and source.

Inference Config

class sequifier.config.infer_config.InferenceConfig(*, project_root: str, preprocessing_data_path: str | None = None, metadata_config_path: str | None = None, model_path: str | list[str], model_type: str, training_objective: str, data_path: str | None = None, training_config_path: str | None = None, dataset: str | None = None, part: str | None = None, model_interface: str | None = None, read_format: str = 'parquet', write_format: str = 'csv', input_columns: list[str] | None, target_columns: list[str], column_data_types: dict[str, str] | None = None, target_column_types: dict[str, str] | None = None, deterministic: bool = False, output_probabilities: bool = False, decode_categories: bool = True, seed: int = 1010, device: str, context_length: int, target_offset: int = 1, window_stride: int | None = None, prediction_length: int | None = None, inference_batch_size: int = 1, sample_from_distribution_columns: list[str] | None = None, infer_with_dropout: bool = False, autoregressive: bool = False, generation_steps: int | None = None)[source]

User-authored configuration for one inference run.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

sequifier.config.infer_config.InfererModel

alias of ResolvedInferenceConfig

class sequifier.config.infer_config.ResolvedInferenceConfig(*, project_root: str, preprocessing_data_path: str | None = None, metadata_config_path: str | None = None, model_path: str | list[str], model_type: str, training_objective: str, data_path: str, training_config_path: str | None = None, dataset: str | None = None, part: str | None = None, model_interface: str | None = None, read_format: str = 'parquet', write_format: str = 'csv', input_columns: list[str], target_columns: list[str], column_data_types: dict[str, str], target_column_types: dict[str, str], deterministic: bool = False, output_probabilities: bool = False, decode_categories: bool = True, seed: int = 1010, device: str, context_length: int, target_offset: int = 1, window_stride: int | None = None, prediction_length: int | None = None, inference_batch_size: int = 1, sample_from_distribution_columns: list[str] | None = None, infer_with_dropout: bool = False, autoregressive: bool = False, generation_steps: int | None = None, categorical_columns: list[str], real_columns: list[str], storage_layout: StoredWindowLayout, window_view: ModelWindowView, dataset_metadata: DatasetMetadata | None = None)[source]

Internal inference config after dataset metadata has been resolved.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

sequifier.config.infer_config.resolve_inference_config(config: InferenceConfig, metadata: DatasetMetadata) ResolvedInferenceConfig[source]

Return an inference config with all metadata-derived values populated.

Config Composition and Metadata

Composition helpers for user-authored configuration fragments.

sequifier.config.composition.deep_merge_config(base: Mapping[str, Any], override: Mapping[str, Any], *, atomic_paths: frozenset[tuple[str, ...]] = frozenset({('global_training', 'bert_spec', 'span_masking'), ('global_training', 'optimizer'), ('global_training', 'scheduler'), ('model', 'backbone')})) dict[str, Any][source]

Return a deep merge of two authored mappings.

Dictionaries merge recursively. Lists and scalar values are replaced, and an explicit None clears the inherited value. Neither input is mutated.

sequifier.config.composition.load_composed_yaml_config(config_path: str, *, atomic_paths: frozenset[tuple[str, ...]] = frozenset({('global_training', 'bert_spec', 'span_masking'), ('global_training', 'optimizer'), ('global_training', 'scheduler'), ('model', 'backbone')})) dict[str, Any][source]

Load one YAML config and its direct, complementary fragments.

Relative fragment paths are resolved against the entry config’s project_root. Fragments cannot include further fragments. Duplicate authored fields are rejected before the resulting mapping reaches the command-specific Pydantic model.

sequifier.config.composition.merge_complementary_config_fragments(fragments: Iterable[tuple[str, collections.abc.Mapping[str, Any]]], *, atomic_paths: frozenset[tuple[str, ...]] = frozenset({('global_training', 'bert_spec', 'span_masking'), ('global_training', 'optimizer'), ('global_training', 'scheduler'), ('model', 'backbone')})) dict[str, Any][source]

Merge sourced fragments while rejecting duplicate authored fields.

sequifier.config.composition.merge_config_fragments(fragments: Iterable[Mapping[str, Any]], *, atomic_paths: frozenset[tuple[str, ...]] = frozenset({('global_training', 'bert_spec', 'span_masking'), ('global_training', 'optimizer'), ('global_training', 'scheduler'), ('model', 'backbone')})) dict[str, Any][source]

Merge authored fragments in order, with later fragments taking priority.

Typed preprocessing metadata used during config resolution.

class sequifier.config.metadata.DatasetMetadata(*, depth_layouts: ~sequifier.config.depth_layout.DepthLayoutRegistryModel = <factory>, tensor_payload_version: int = 1, split_paths: list[str] = <factory>, column_data_types: dict[str, str] = <factory>, n_classes: dict[str, int] = <factory>, id_maps: dict[str, dict[str | int, int]] = <factory>, special_token_ids: dict[str, int] = <factory>, selected_columns_statistics: dict[str, dict[str, float]] = <factory>, normalize_real_columns: bool = True, window_length: int, max_target_offset: int = 1, stored_window_layout_version: int = 2, **extra_data: ~typing.Any)[source]

The stable subset of preprocessing metadata consumed by other commands.

model_config: ClassVar[ConfigDict] = {'extra': 'allow', 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

sequifier.config.metadata.extract_inline_metadata(values: dict[str, Any]) tuple[dict[str, Any], dict[str, Any] | None][source]

Split the historical skip_metadata representation into two mappings.

sequifier.config.metadata.load_dataset_metadata(path: str) DatasetMetadata[source]

Load and validate one preprocessing metadata JSON file.

Hyperparameter Search Config

Canonical hyperparameter-search configuration.

Hyperparameter search always starts from a canonical authored training config and applies recursive parameters. Historical self-contained search configs and flat-schema base configs are intentionally unsupported.

class sequifier.config.hyperparameter_search_config.CanonicalHyperparameterSearchConfig(*, base_config_path: str, parameters: dict[str, Any], project_root: str, name: str, method: Literal['bayesian', 'sample', 'grid'] = 'bayesian', global_seed: int | None = None, trials: int | None = None, prune_trials: bool = True, pruning_warmup_epochs: int | None = None, pruning_warmup_batches: int | None = None, model_config_write_path: str, evaluation_inference_config: str | None = None, evaluation_script: str | None = None, evaluation_metric_directions: list[Literal['minimize', 'maximize']] | None = None, evaluation_metrics: list[str] | None = None)[source]

Search controls and a recursive sampler over one canonical train config.

model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'forbid', 'populate_by_name': True, 'validate_by_alias': True, 'validate_by_name': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

model_post_init(context: Any, /) None

This function is meant to behave like a BaseModel method to initialize private attributes.

It takes context as an argument since that’s what pydantic-core passes when calling it.

Parameters:
  • self – The BaseModel instance.

  • context – The context.

sample_trial(trial: Any, run_index: int) SequifierConfig[source]

Sample and validate one concrete canonical authored training config.

Validate the representative candidate and finite-grid controls.

sequifier.config.hyperparameter_search_config.HyperparameterSearchConfig

alias of CanonicalHyperparameterSearchConfig

sequifier.config.hyperparameter_search_config.compile_canonical_hyperparameter_search_config(config_path: str, config_values: dict[str, Any], skip_metadata: bool) CanonicalHyperparameterSearchConfig[source]

Compile base-training plus recursive parameters into a canonical sampler.

sequifier.config.hyperparameter_search_config.load_hyperparameter_search_config(config_path: str, skip_metadata: bool) CanonicalHyperparameterSearchConfig[source]

Load a canonical base-config hyperparameter search.

Non-standard Optimizers

class sequifier.optimizers.ademamix.AdEMAMix(params={}, lr=0.001, betas=(0.9, 0.999, 0.9999), eps=1e-08, weight_decay=0, alpha=5.0, T_alpha_beta3=None)[source]

AdEMAMix optimizer.

step(closure=None)[source]

Run one optimizer step.

Internals

sequifier.sequifier.build_args_config(args: Any) dict[str, Any][source]

Build config overrides from parsed CLI args.

sequifier.sequifier.main() None[source]

Main function to run the Sequifier CLI.

sequifier.sequifier.setup_parser() ArgumentParser[source]

Build the sequifier CLI parser.

class sequifier.preprocess.Preprocessor(project_root: str, continue_preprocessing: bool, preprocessing_data_path: str, read_format: str, write_format: str, merge_output: bool, allow_sequence_splitting: bool, selected_columns: list[str] | None, split_ratios: list[float], window_length: int, window_strides: list[int], max_rows: int | None, seed: int, n_cores: int | None, batches_per_file: int, process_by_file: bool, window_placement: str, use_precomputed_maps: list[str] | None, metadata_config_path: str | None, max_target_offset: int = 1, mask_column: str | None = None, column_data_types: dict[str, str] | None = None, split_method: str = 'within_sequence', normalize_real_columns: bool = True, depth_layouts: dict | None = None)[source]

Stateful preprocessing pipeline for single-file or folder inputs.

__init__(project_root: str, continue_preprocessing: bool, preprocessing_data_path: str, read_format: str, write_format: str, merge_output: bool, allow_sequence_splitting: bool, selected_columns: list[str] | None, split_ratios: list[float], window_length: int, window_strides: list[int], max_rows: int | None, seed: int, n_cores: int | None, batches_per_file: int, process_by_file: bool, window_placement: str, use_precomputed_maps: list[str] | None, metadata_config_path: str | None, max_target_offset: int = 1, mask_column: str | None = None, column_data_types: dict[str, str] | None = None, split_method: str = 'within_sequence', normalize_real_columns: bool = True, depth_layouts: dict | None = None)[source]

Initialize and run preprocessing from validated config fields.

sequifier.preprocess.cast_columns_to_string(data: DataFrame) DataFrame[source]

Cast Polars column names to strings.

sequifier.preprocess.combine_maps(map1: dict[Union[str, int], int], map2: dict[Union[str, int], int]) dict[Union[str, int], int][source]

Merge maps and reassign user IDs after reserved tokens.

sequifier.preprocess.combine_multiprocessing_outputs(project_root: str, target_dir: str, n_splits: int, input_files: dict[int, list[str]], dataset_name: str, write_format: str, in_target_dir: bool = False, pre_split_str: str | None = None, post_split_str: str | None = None) None[source]

Combine per-split intermediate files.

sequifier.preprocess.combine_parquet_files(files: list[str], out_path: str) None[source]

Stream-concatenate Parquet files with the first file schema.

sequifier.preprocess.create_file_paths_for_multiple_files1(project_root: str, target_dir: str, n_splits: int, n_batches: int, process_id: int, file_index_str: str, dataset_name: str, write_format: str) dict[int, list[str]][source]

Return per-split temp paths for one multi-file shard.

sequifier.preprocess.create_file_paths_for_multiple_files2(project_root: str, target_dir: str, n_splits: int, n_processes: int, n_files: dict[int, int], dataset_name: str, write_format: str) dict[int, list[str]][source]

Return per-split intermediate paths for multi-file merge.

sequifier.preprocess.create_file_paths_for_single_file(project_root: str, target_dir: str, n_splits: int, n_batches: int, dataset_name: str, write_format: str) dict[int, list[str]][source]

Return per-split temp paths for one single-file run.

sequifier.preprocess.create_id_map(data: DataFrame, column: str) dict[Union[str, int], int][source]

Map sorted user values to IDs after reserved tokens.

sequifier.preprocess.delete_files(files: list[str] | dict[int, list[str]]) None[source]

Delete paths from a list or split-indexed dict.

sequifier.preprocess.extract_sequences(data: DataFrame, schema: Any, layout: StoredWindowLayout, stride_for_split: int, columns: list[str], window_placement: str) DataFrame[source]

Extract long-format windows from grouped sequences.

sequifier.preprocess.extract_subsequences(in_seq: dict[str, list], window_length: int, stride_for_split: int, columns: list[str], window_placement: str) tuple[dict[str, list[list[Union[float, int]]]], list[int], numpy.ndarray][source]

Extract padded windows plus left-pad lengths from one sequence.

sequifier.preprocess.get_batch_limits(data: DataFrame, n_batches: int, allow_sequence_splitting: bool) list[tuple[int, int]][source]

Split rows into batches without crossing sequenceId boundaries unless allowed.

sequifier.preprocess.get_combined_statistics(n1: int, mean1: float, std1: float, n2: int, mean2: float, std2: float) tuple[float, float][source]

Combine two mean/std summaries.

sequifier.preprocess.get_group_bounds(data_subset: DataFrame, split_ratios: list[float])[source]

Return per-split row bounds for one sequence.

sequifier.preprocess.get_subsequence_starts(in_context_length: int, window_length: int, stride_for_split: int, window_placement: str) ndarray[source]

Return window start indices for distribute/exact modes.

sequifier.preprocess.insert_top_folder(path: str, folder_name: str) str[source]

Insert folder_name before the basename.

sequifier.preprocess.load_precomputed_id_maps(project_root: str, data_columns: list[str] | None, required_maps: list[str] | None = None) dict[str, dict[Union[str, int], int]][source]

Load and validate precomputed ID maps.

sequifier.preprocess.preprocess(args: Any, args_config: dict[str, Any]) None[source]

Load preprocessing config and run preprocessing.

sequifier.preprocess.preprocess_batch(project_root: str, data_name_root: str, process_id: int, batch: DataFrame, schema: Any, split_paths: list[str], layout: StoredWindowLayout, window_strides: list[int], data_columns: list[str], col_types: dict[str, str], split_ratios: list[float], target_dir: str, write_format: str, batches_per_file: int, window_placement: str, merge_output: bool, split_method: str = 'within_sequence', seed: int = 1010, sequence_split_assignments: dict[int, int] | None = None) None[source]

Extract and write all split windows for one batch.

sequifier.preprocess.process_and_write_data_pt(data: DataFrame, window_length: int, path: str, column_data_types: dict[str, str])[source]

Write long-format sequences as packed PT tensors.

Training command composition and PT inference entry points.

class sequifier.train.LoadedInferenceModel(network: Any, config: Any, interface_name: str, embedding: bool)[source]

Execution metadata alongside the sole weight-owning network.

sequifier.train.load_inference_model(model_type: str, model_path: str, training_config_path: str | None, args_config: dict[str, Any], device: str, infer_with_dropout: bool) LoadedInferenceModel[source]

Load only the new portable-model or exact-run artifact formats.

sequifier.train.run_training(config: ResolvedSequifierConfig, *, integration_specs: tuple[sequifier.integration.specifications.IntegrationSpec, ...] = (), integration_instances: tuple[Any, ...] = (), semantic_optimizer_grouping: bool = False) None[source]

Launch canonical service-composed training locally or across workers.

sequifier.train.train_worker(local_rank: int, world_size: int, config: ResolvedSequifierConfig, global_rank: int, integration_specs: tuple[sequifier.integration.specifications.IntegrationSpec, ...] = (), integration_instances: tuple[Any, ...] = (), semantic_optimizer_grouping: bool = False) None[source]

Initialize one execution environment and run the composed runtime.

class sequifier.infer.Inferer(model_type: str, model_path: str, project_root: str, id_maps: dict[str, dict[str | int, int]] | None, selected_columns_statistics: dict[str, dict[str, float]], decode_categories: bool, categorical_columns: list[str], real_columns: list[str], input_columns: list[str] | None, target_columns: list[str], target_column_types: dict[str, str], sample_from_distribution_columns: list[str] | None, infer_with_dropout: bool, prediction_length: int, inference_batch_size: int, device: str, args_config: dict[str, Any], training_config_path: str | None, training_objective: str | None = None, normalize_real_columns: bool = True, target_decoder_ids: dict[str, list[int]] | None = None)[source]

Inference runtime for PT/ONNX sequifier models.

__init__(model_type: str, model_path: str, project_root: str, id_maps: dict[str, dict[str | int, int]] | None, selected_columns_statistics: dict[str, dict[str, float]], decode_categories: bool, categorical_columns: list[str], real_columns: list[str], input_columns: list[str] | None, target_columns: list[str], target_column_types: dict[str, str], sample_from_distribution_columns: list[str] | None, infer_with_dropout: bool, prediction_length: int, inference_batch_size: int, device: str, args_config: dict[str, Any], training_config_path: str | None, training_objective: str | None = None, normalize_real_columns: bool = True, target_decoder_ids: dict[str, list[int]] | None = None)[source]

Load a PT or ONNX backend and postprocessing state.

adjust_and_infer_embedding(x: dict[str, numpy.ndarray], size: int, metadata: dict[str, numpy.ndarray], column_data_types: dict[str, torch.dtype])[source]

Batch embedding inference across the active backend.

adjust_and_infer_generative(x: dict[str, numpy.ndarray], size: int, metadata: dict[str, numpy.ndarray], column_data_types: dict[str, torch.dtype])[source]

Batch generative inference across the active backend.

expand_to_batch_size(x: ndarray) ndarray[source]

Repeat leading samples until the ONNX batch size is met.

infer_embedding(x: dict[str, numpy.ndarray], metadata: dict[str, numpy.ndarray], column_data_types: dict[str, torch.dtype]) ndarray[source]

Return embeddings for a feature-array batch.

infer_generative(x: dict[str, numpy.ndarray] | None, metadata: dict[str, numpy.ndarray], probs: dict[str, numpy.ndarray] | None = None, return_probs: bool = False, column_data_types: dict[str, torch.dtype] | None = None) dict[str, numpy.ndarray][source]

Return target probabilities or decoded predictions.

infer_pure(x: dict[str, numpy.ndarray], metadata: dict[str, numpy.ndarray]) list[numpy.ndarray][source]

Run one ONNX batch and flatten sequence-major outputs.

invert_normalization(values: ndarray, target_column: str) ndarray[source]

Invert target-column Z-score normalization.

prepare_inference_batches(x: dict[str, numpy.ndarray], pad_to_batch_size: bool) list[dict[str, numpy.ndarray]][source]

Split feature arrays into backend-sized batches.

class sequifier.infer.WindowedInferenceBatch(inputs: dict[str, torch.Tensor], metadata: dict[str, torch.Tensor], sequence_ids: Tensor, subsequence_ids: Tensor, model_start_positions: Tensor, window_start_offsets: Tensor)[source]

Model-facing windows plus physical identities and adjusted starts.

sequifier.infer.apply_inference_column_types(data: DataFrame, config: ResolvedInferenceConfig) DataFrame[source]

Cast loaded long-format sequence values to the configured unified dtype.

sequifier.infer.apply_inference_tensor_types(sequences_dict: dict[str, torch.Tensor], column_data_types: dict[str, torch.dtype]) dict[str, torch.Tensor][source]

Cast loaded PT feature tensors to the configured per-column dtype.

sequifier.infer.calculate_item_positions(start_positions: ndarray, context_length: int, prediction_length: int, training_objective: str, target_offset: int = 1) ndarray[source]

Return flattened absolute item positions for inference outputs.

sequifier.infer.fill_number(number: int | float, max_length: int) str[source]

Left-pad a number for sortable string keys.

sequifier.infer.get_embeddings(config: Any, inferer: Inferer, data: DataFrame, column_data_types: dict[str, torch.dtype]) ndarray[source]

Infer embeddings from a Polars chunk.

sequifier.infer.get_embeddings_pt(config: Any, inferer: Inferer, data: dict[str, torch.Tensor], metadata: dict[str, torch.Tensor], column_data_types: dict[str, torch.dtype]) ndarray[source]

Infer embeddings from PT tensors.

sequifier.infer.get_probs_preds_autoregressive(config: Any, inferer: Inferer, data: DataFrame, column_data_types: dict[str, torch.dtype], context_length: int) tuple[Optional[dict[str, numpy.ndarray]], dict[str, numpy.ndarray], numpy.ndarray, numpy.ndarray, numpy.ndarray][source]

Infer autoregressive predictions with sequence IDs, positions, and mask.

sequifier.infer.get_probs_preds_from_df(config: Any, inferer: Inferer, data: DataFrame, column_data_types: dict[str, torch.dtype]) tuple[Optional[dict[str, numpy.ndarray]], dict[str, numpy.ndarray]][source]

Infer non-autoregressive predictions from a Polars chunk.

sequifier.infer.get_probs_preds_from_dict(config: Any, inferer: Inferer, data: dict[str, torch.Tensor], metadata: dict[str, torch.Tensor], column_data_types: dict[str, torch.dtype], total_steps: int = 1) tuple[Optional[dict[str, numpy.ndarray]], dict[str, numpy.ndarray]][source]

Infer PT predictions, flattened sample-major across autoregressive steps.

sequifier.infer.infer(args: Any, args_config: dict[str, Any]) None[source]

Load inference config and dispatch the worker.

sequifier.infer.infer_embedding(config: ResolvedInferenceConfig, inferer: Inferer, model_id: str, dataset: list[Any] | Iterator[Any], column_data_types: dict[str, torch.dtype]) None[source]

Write embeddings for each dataset chunk.

sequifier.infer.infer_generative(config: ResolvedInferenceConfig, inferer: Inferer, model_id: str, dataset: list[Any] | Iterator[Any], column_data_types: dict[str, torch.dtype])[source]

Write generative predictions/probabilities for each dataset chunk.

sequifier.infer.infer_worker(config: Any, args_config: dict[str, Any], id_maps: dict[str, dict[str | int, int]] | None, selected_columns_statistics: dict[str, dict[str, float]], percentage_limits: tuple[float, float] | None, normalize_real_columns: bool)[source]

Load data, instantiate models, and run the configured inference mode.

sequifier.infer.inference_output_path(project_root: str, write_format: str, artifact_type: str, model_id: str, data_id: int, target_column: str | None = None) str[source]

Return a canonical inference output path and create its directory.

sequifier.infer.load_onnx_target_decoder_ids(session: InferenceSession, target_columns: list[str], target_column_types: dict[str, str], model_type: str) dict[str, list[int]][source]

Load and validate categorical decoder-index mappings from ONNX metadata.

sequifier.infer.load_parquet_folder_dataset(data_path: str, start_pct: float, end_pct: float) Iterator[Any][source]

Yield a percentage slice of sorted top-level Parquet files.

sequifier.infer.load_pt_dataset(data_path: str, start_pct: float, end_pct: float) Iterator[Any][source]

Yield a percentage slice of sorted top-level PT files.

sequifier.infer.normalize(outs: dict[str, numpy.ndarray]) dict[str, numpy.ndarray][source]

Softmax logits by target column.

sequifier.infer.sample_with_cumsum(probs: ndarray, is_log_probs: bool = True) ndarray[source]

Sample class indices from log-probabilities or probabilities.

sequifier.infer.verify_variable_order(data: DataFrame) None[source]

Require sequenceId order and in-sequence subsequenceId order.

sequifier.make.make(args)[source]

Create a sequifier project scaffold.

Load config, create Optuna study, and optimize trials.

sequifier.hyperparameter_search.objective(trial: Trial, accepted_trials: int, config, run_config: Any = None) float | tuple[float, ...][source]

Run one Optuna trial through the CLI trainer and validation metrics.

sequifier.hyperparameter_search.set_pdeathsig()[source]

Ask Linux to SIGTERM children when this parent dies.

class sequifier.helpers.ModelWindowSamplingPlan(resolved_view: ResolvedWindowView, stride: int | None = None)[source]

Resolve logical model windows contained in one stored window.

build_masks(left_pad_lengths: Tensor, input_starts: Tensor) dict[str, torch.Tensor][source]

Build masks for model windows with different positions in storage.

property candidate_input_starts: Tensor

Return chronological starts, anchored to include the rightmost view.

first_eligible_start_indices(left_pad_lengths: Tensor) Tensor[source]

Return the first candidate with at least one valid target position.

gather(tensor: Tensor, stored_row_indices: Tensor, input_starts: Tensor, *, target: bool = False) Tensor[source]

Gather input or target windows without materializing all overlaps.

sample_counts(left_pad_lengths: Tensor) Tensor[source]

Return the number of usable logical samples in each stored row.

class sequifier.helpers.ModelWindowView(context_length: int, objective: str, target_offset: int)[source]
class sequifier.helpers.ResolvedWindowView(storage: sequifier.helpers.StoredWindowLayout, view: sequifier.helpers.ModelWindowView, required_width: int, input_slice: slice, target_slice: slice)[source]
build_masks(left_pad_lengths: Tensor) dict[str, torch.Tensor][source]

Build explicit input-attention and target-validity masks for this view.

class sequifier.helpers.StoredWindowLayout(window_length: int, max_target_offset: int, version: int)[source]
class sequifier.helpers.WindowSampleIndex(plan: ModelWindowSamplingPlan, left_pad_lengths: Tensor)[source]

Compact logical-index mapping for variable per-row window counts.

sequifier.helpers.assign_sequence_to_split(sequence_id: int, split_ratios: list[float], seed: int) int[source]

Deterministically assign one sequenceId to a split index.

sequifier.helpers.build_valid_mask(left_pad_lengths: Tensor, full_length: int, view_slice: slice) Tensor[source]

Boolean mask from left-padding metadata.

sequifier.helpers.configure_determinism(seed: int, strict: bool = False) None[source]

Enforces deterministic execution for reproducibility.

sequifier.helpers.configure_logger(project_root: str, model_name: str, rank: int | None = 0, *, dataset_names: tuple[str, ...] = (), rank_specific: bool = False)[source]

Configure canonical model/dataset operational log files.

sequifier.helpers.configured_window_stride(config: Any) int | None[source]

Read the optional stride from validated configs or legacy test doubles.

sequifier.helpers.construct_index_maps(id_maps: dict[str, dict[Union[str, int], int]] | None, target_columns_index_map: list[str], decode_categories: bool | None) dict[str, dict[int, Union[str, int]]][source]

Build index-to-ID maps, including reserved token labels.

sequifier.helpers.derive_target_column_types(target_columns: list[str], column_data_types: dict[str, str]) dict[str, str][source]

Derive categorical/real target kinds from configured physical dtypes.

sequifier.helpers.get_best_model_path(project_root: str, run_name: str, model_type: str, *, dataset_name: str | None = None, dataset_count: int = 1) tuple[str, int][source]

Return the highest-epoch canonical best-model path.

sequifier.helpers.get_last_training_batch_timedelta(model_name: str, rank: int, project_root: str = '.') float[source]

Return seconds between the last two structured train observations.

sequifier.helpers.get_left_pad_lengths_from_preprocessed_data(data: DataFrame) Tensor[source]

One leftPadLength per long-format subsequence.

sequifier.helpers.get_torch_dtype(dtype_str: str) dtype[source]

String-to-torch dtype mapping.

sequifier.helpers.metadata_config_path_from_preprocessing_data_path(preprocessing_data_path: str) str[source]

Return the metadata path generated for a preprocessing input path.

sequifier.helpers.normalize_path(path: str, project_root: str) str[source]

Return path rooted under project_root.

sequifier.helpers.numpy_storage_to_pytorch(data: DataFrame, column_data_types: dict[str, torch.dtype], all_columns: list[str], window_length: int, sort_rows: bool = True) tuple[dict[str, torch.Tensor], torch.Tensor][source]

Convert complete stored windows to tensors for virtual window sampling.

sequifier.helpers.numpy_to_pytorch(data: DataFrame, column_data_types: dict[str, torch.dtype], all_columns: list[str], resolved_view: ResolvedWindowView) tuple[dict[str, torch.Tensor], dict[str, torch.Tensor]][source]

Convert long-format Polars windows to tensors plus masks.

sequifier.helpers.read_data(path: str, read_format: str, columns: list[str] | None = None) DataFrame[source]

Read CSV/Parquet into Polars.

sequifier.helpers.resolve_unified_polars_numeric_dtype(column_data_types: dict[str, str]) Any[source]

Resolve one Polars dtype for long-format numeric sequence columns.

sequifier.helpers.subset_to_input_columns(data: DataFrame | LazyFrame, input_columns: list[str]) DataFrame | LazyFrame[source]

Keep long-format rows whose inputCol is selected.

sequifier.helpers.write_data(data: DataFrame, path: str, write_format: str, **kwargs) None[source]

Write Polars/Pandas data as CSV or Parquet.

class sequifier.io.yaml.TrainModelDumper(stream, default_style=None, default_flow_style=False, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None, sort_keys=True)[source]

YAML dumper for sequifier config objects.

increase_indent(flow=False, indentless=False)[source]

Indent block sequences.

sequifier.io.yaml.represent_numpy_float(dumper, data)[source]

Represent NumPy floats as YAML floats.

sequifier.io.yaml.represent_numpy_int(dumper, data)[source]

Represent NumPy integers as YAML integers.

sequifier.io.yaml.represent_sequifier_object(dumper, data)[source]

Represent sequifier config objects as plain YAML mappings.

class sequifier.io.sequifier_dataset_from_folder_pt.SequifierDatasetFromFolderPt(data_path: str, config: Any, shuffle: bool = True)[source]

Eager PT-folder dataset yielding rank/worker-aligned batches.

set_epoch(epoch: int)[source]

Set the shuffle epoch.

set_start_batch(start_batch: int)[source]

Set the first global batch to yield on the next iteration.

class sequifier.io.sequifier_dataset_from_folder_pt_lazy.SequifierDatasetFromFolderPtLazy(data_path: str, config: Any, shuffle: bool = True)[source]

Streams PT chunks into rank/worker-aligned batches.

set_epoch(epoch: int)[source]

Set the shuffle epoch.

set_start_batch(start_batch: int)[source]

Set the first global batch to yield on the next iteration.

class sequifier.io.sequifier_dataset_from_folder_parquet.SequifierDatasetFromFolderParquet(data_path: str, config: Any, shuffle: bool = True)[source]

Eager Parquet-folder dataset yielding rank/worker-aligned batches.

set_epoch(epoch: int)[source]

Set the shuffle epoch.

set_start_batch(start_batch: int)[source]

Set the first global batch to yield on the next iteration.

class sequifier.io.sequifier_dataset_from_folder_parquet_lazy.SequifierDatasetFromFolderParquetLazy(data_path: str, config: Any, shuffle: bool = True)[source]

Streams long-format Parquet chunks into rank/worker-aligned batches.

set_epoch(epoch: int)[source]

Set the shuffle epoch.

set_start_batch(start_batch: int)[source]

Set the first global batch to yield on the next iteration.

class sequifier.io.sequifier_dataset_from_file.SequifierDatasetFromFile(data_path: str, config: Any, shuffle: bool = True)[source]

Eager single-file dataset yielding pre-collated batches.

set_epoch(epoch: int)[source]

Set the shuffle epoch.

set_start_batch(start_batch: int)[source]

Set the first global batch to yield on the next iteration.

sequifier.io.window_sampling.build_window_batch(sequences: dict[str, torch.Tensor], input_columns: Sequence[str], target_columns: Sequence[str], sample_index: WindowSampleIndex, logical_indices: Tensor | list[int], sample_is_real: Sequence[bool] | Tensor | None = None, depth_valid_masks: dict[str, torch.Tensor] | None = None) SequifierBatch[source]

Gather one batch of virtual model windows from stored tensors.

sequifier.optimizers.optimizers.get_optimizer_class(optimizer_name: str) type[torch.optim.optimizer.Optimizer][source]

Resolve a custom, torch-optimizer, or torch optimizer class.

sequifier.optimizers.optimizers.get_scheduler_class(scheduler_name: str)[source]

Resolve a supported PyTorch learning-rate scheduler.