DataModule API¶
The text stage's data (Req 10; spec 4.3): two streams over every code and every task query.
One epoch reads every code once as an anchor and every task query once. StepDataset permutes
both streams per epoch from (seed, epoch) and cuts the two orders into the same S even chunks, so
step s reads code chunk s and query chunk s. Nothing is pre-drawn, and no step carries a candidate
pool: every candidate a term scores comes from the model's code cache.
NAICSDataModule builds the token cache, the task queries and the step dataset from the
validated bundle, and holds every code's token rows in codebook order for that cache. Its one
loader hands each step through whole (P12), and it has no validation loader: validation is the
outcome monitor (spec 4.4). TrainDatasetEpochCallback sets the epoch at each epoch start
(P27). stack_text_inputs batches the token rows of every encode.
NAICSDataModule
¶
Bases: LightningDataModule
The text stage's data: two streams over every code and every task query (Req 10; spec 4.3).
prepare_data builds the tokenization cache, or keeps one built from the same inputs.
setup builds the StepDataset once: every code's cached token rows in codebook order,
and the bundle's task queries, each tokenized once as a query: text with the cache's
tokenizer at its window. code_rows holds those rows for the model's code cache, which
encodes them at fit start and at each epoch's end.
The one loader is train_dataloader (P12). There is no validation loader, so Lightning
runs no validation loop: validation is the outcome monitor (spec 4.4). Construction reads
nothing; the bundle is loaded, and refused, in prepare_data and setup.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token_config
|
TokenizationConfig
|
The tokenization cache to build and read: the descriptions, the tokenizer,
the window and the file. |
required |
seed
|
int
|
The run's seed, from which each epoch's two permutations are drawn. |
required |
queries_per_step
|
int
|
The most task queries one step reads. |
DEFAULT_QUERIES_PER_STEP
|
supervision_manifest_path
|
Optional[str]
|
The bundle's manifest, read when no bundle is given. |
None
|
supervision_contract_version
|
str
|
The contract the manifest must carry. |
CONTRACT_VERSION
|
supervision_bundle
|
Optional[ValidatedSupervisionBundle]
|
The validated bundle, when the caller has loaded it. |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
code_rows
property
¶
Every code's token rows in codebook order, which the model's code cache encodes at fit start and at each epoch's end (spec 4.3): the rows the steps read their anchors from.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
Before |
prepare_data()
¶
Build the tokenization cache of the bundle's descriptions, or keep one built from the same inputs.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the bundle is refused. |
set_train_epoch(epoch)
¶
Make epoch the epoch the steps read: TrainDatasetEpochCallback calls it at each
epoch start.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
Before |
ValueError
|
If the epoch is negative. |
setup(stage=None)
¶
Build the step dataset from the bundle, once (spec 4.3); a later call keeps it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stage
|
Optional[str]
|
Lightning's stage. Every stage reads the same steps. |
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the tokenization cache is missing or was built from other inputs. |
ValueError
|
If the bundle is refused, the cache does not hold the codebook's codes
in order, or |
train_dataloader()
¶
The epoch's steps, one batch each, in step order (P12).
batch_size=None hands each step through whole, and shuffle=False keeps step order,
since the epoch's permutations are the order. With num_workers=0 every step is read
in the main process, whose dataset set_train_epoch reaches. The loader never reads
the trainer's epoch, which can be stale on a resume; TrainDatasetEpochCallback sets
it at each epoch start (P27).
Raises:
| Type | Description |
|---|---|
RuntimeError
|
Before |
StepDataset
¶
Bases: Dataset
The steps of one epoch over two streams: every code once as an anchor, and every task query once (Req 10; spec 4.3).
Each epoch permutes the codes and the queries (epoch_permutation, under the run's seed and
the epoch) and cuts both orders into the same S even chunks (even_chunks), with S from
steps_per_epoch: step s reads code chunk s and query chunk s. A step carries only its
anchors' token rows and its queries'. Every candidate a term scores comes from the model's
code cache, so no step carries a candidate pool.
The epoch comes only from set_epoch, which TrainDatasetEpochCallback calls at each
epoch start, and its two permutations are drawn at its first step and kept for the others.
set_epoch reaches only the main process's copy of the dataset, so the steps are read
there, as DataLoader(dataset, batch_size=None, shuffle=False, num_workers=0) reads them.
A step is a dict of two dicts:
codes:inputs, the anchors' token rows throughstack_text_inputs; andidsandlevels, int64 (A,).queries:inputs, the queries' token rows under the fieldquery;levels, int64 (Q,); andtargetsandnegatives, bool (Q, N) masks over the codes of each query's T and N.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code_rows
|
Sequence[Mapping[str, Any]]
|
Every code's token row, in codebook order, as the tokenization cache holds it. |
required |
code_levels
|
Sequence[int]
|
Every code's level, in codebook order. |
required |
queries
|
TokenizedQueries
|
The tokenized task queries. |
required |
n_codes
|
int
|
N, the number of codes. |
required |
seed
|
int
|
The run's seed. |
required |
queries_per_step
|
int
|
The most queries one step reads. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the code rows or levels are not one per code; if there is no task query, or there are more steps than codes, since every step needs at least one anchor; or if a query names a code id outside the codes, has no target, or has a target at another level. |
__getitem__(step)
¶
Step step of the current epoch: its anchors and its queries.
Raises:
| Type | Description |
|---|---|
IndexError
|
If the step is outside the epoch. |
RuntimeError
|
If no epoch has been set. |
__len__()
¶
S, the steps of an epoch.
set_epoch(epoch)
¶
Make epoch the epoch the steps read; its permutations are drawn at its first step.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the epoch is negative. |
TokenizedQueries
dataclass
¶
The task queries, each tokenized once as a query: text, with its level and code ids.
Built by tokenize_task_queries. Every field is in query order.
Attributes:
| Name | Type | Description |
|---|---|---|
texts |
Tuple[str, ...]
|
Each query's text. |
tokens |
Tuple[Dict[str, Any], ...]
|
Each query's |
levels |
Tuple[int, ...]
|
Each query's level. |
target_ids |
Tuple[Tuple[int, ...], ...]
|
The code ids of each query's targets, T. |
negative_ids |
Tuple[Tuple[int, ...], ...]
|
The code ids of each query's forced negatives, N. |
__len__()
¶
The number of queries.
TrainDatasetEpochCallback
¶
Bases: Callback
Set the step dataset's epoch to the trainer's at each epoch start (P27).
Register it on every Trainer that fits a NAICSDataModule: Lightning dispatches on_train_epoch_start to callbacks and the LightningModule, never to a LightningDataModule, and the step dataset refuses a step read before any epoch is set. Lightning never prefetches from a loader whose length it knows, so the epoch is set before the epoch's first step is read.
epoch_permutation(seed, epoch, n, stream)
¶
One stream's order in one epoch: a permutation of range(n) that depends only on the
arguments.
The CPU generator that draws it is seeded by the first eight bytes of the sha256 of
f'{seed}:{epoch}:{stream}', kept to 63 bits. So the order is the same in every process,
on every platform and after any history, and no global random state is read or moved.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
The run's seed. |
required |
epoch
|
int
|
The epoch, from 0. |
required |
n
|
int
|
The stream's length. |
required |
stream
|
str
|
|
required |
Returns:
| Type | Description |
|---|---|
Tensor
|
The permutation, a CPU int64 tensor of shape (n,). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the stream is neither, or the epoch or |
even_chunks(order, steps)
¶
Cut an order into exactly steps contiguous chunks whose sizes differ by at most one.
torch.tensor_split makes the first len(order) % steps chunks one longer than the rest.
torch.chunk is never used: it cuts chunks of ⌈len / steps⌉, so it can return fewer than
steps (2,125 codes over 87 steps give 85), which would leave steps with no chunk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order
|
Tensor
|
A one-dimensional order, such as an epoch's permutation. |
required |
steps
|
int
|
The number of chunks. |
required |
Returns:
| Type | Description |
|---|---|
List[Tensor]
|
The chunks, in order: views of |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
stack_text_inputs(embeddings, fields=CHANNELS)
¶
Stack token rows into one batch: per field, input_ids, attention_mask and a boolean
present of shape (B,).
Every code batch is built here (the training steps, the export and the HGCN feeder), and a query
batch too, under the field query. The encoder reads presence from present, never from
the attention mask.
Raises:
| Type | Description |
|---|---|
ValueError
|
If a row's field has no |
steps_per_epoch(n_queries, queries_per_step)
¶
S, the steps of one epoch: ⌈n_queries / queries_per_step⌉ (spec 4.3).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_queries
|
int
|
The task queries one epoch reads. |
required |
queries_per_step
|
int
|
The most queries one step reads. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The number of steps. Each reads one chunk of the queries and one of the codes. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
tokenize_task_queries(queries, tokenizer, max_length, code_ids)
¶
Tokenize every task query once, as a query: text, and name its codes by their ids.
A query is tokenized as ArmEncoder.encode_queries tokenizes a read's query texts: by
tokenize_field under the field query, padded and truncated to max_length.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
queries
|
Sequence[TaskQuery]
|
The task queries, as |
required |
tokenizer
|
Any
|
The backbone's tokenizer. |
required |
max_length
|
int
|
Tokens kept: the window the code channels are tokenized at. |
required |
code_ids
|
Mapping[str, int]
|
Each code's id, its row in the codebook. |
required |
Returns:
| Type | Description |
|---|---|
TokenizedQueries
|
The tokenized queries, in the order given. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a query names a code that has no code id. |