Browse documentation
aner.ml · Reference

Model API parameter index

Inspect model, training and evaluation signature families with every argument, default and constraint shared with editor help.

Released in Aner 0.0.5Aner 0.0.5 or newer

Use the model directory to choose a technique and machine learning for shared fitted workflows. This generated reference lists the supported model, training and evaluation signature families and explains every argument in each family. Generic Tensor arithmetic, tokenizer construction and unrelated module APIs remain in their owning references.

The current index contains 423 signature families and 902 parameter entries across 12 model and technique guides.

Signatures show implemented overload defaults using = value for reference. This notation does not add user defined default argument syntax or make an unsupported call valid. Receiver syntax omits the first model/value argument. Parameters marked required must be supplied to that family. Model specific guides explain validation, shapes, device support and lifecycle in context.

These pages describe the reviewed model API contracts. Dense dropout with v7 checkpoint continuation, NLP and its neural feed-forward/masked-pooling bridges require Aner 0.0.5 or newer. Other model families retain their own checkpoint formats and capability requirements. Runtime packages, optional backends and the VS Code 0.1.48 publication candidate have separate verification and publication records; see Downloads for actual availability.

Natural language processing

Read the model guide.

nlp.analyze(text: String, stop_words: List = List(), analyzer: String = "word", min_ngram: Int64 = 1, max_ngram: Int64 = 1, casefold: Bool = true, normalization: String = "nfc") -> List

Inspect the exact normalized lexical terms used by fitting and search. Terms are not reversible model token IDs. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time O(normalized scalars × ngram span + emitted bytes); returned space O(emitted term bytes), subject to work and List limits.

ArgumentTypeRequired or defaultMeaning and constraints
textStringRequiredUTF-8 text to analyze under the complete declared policy; original text is not mutated.
stop_wordsListList()Explicit List of Strings; omitted/empty List disables filtering. Word analyzer only. Entries pass through the same normalization and case folding and must each identify one word; removed before word ngrams.
analyzerString"word""word" uses Unicode 17 letter/number-led runs and following combining marks; punctuation splits words. "char" uses Unicode scalar values including spaces; it has no language specific segmentation.
min_ngramInt641Smallest included ngram length, from 1 through 5 and no larger than max_ngram.
max_ngramInt641Largest included ngram length, from min_ngram through 5. Word ngrams use spaces between retained words; character ngrams preserve scalar order.
casefoldBooltrueApply full default Unicode case folding after the declared normalization, followed by normalization again. This can change symbols and length; original document text is retained.
normalizationString"nfc"Explicit Unicode policy: "nfc" (canonical composition), "nfkc" (compatibility composition), or "none". NFKC can erase scientifically meaningful distinctions.

nlp.batch(corpus: TextCorpus, codec: Tokenizer, max_length: Int64, truncation: String = "error", bos: Bool = true, eos: Bool = true, pad_id: Int64 = -1) -> TokenBatch

Build right padded exact integer model IDs in corpus order with visible original lengths, truncation and source identity. Mask is detached CPU Float64 [batch,width]; an empty encoded row remains all padding. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time O(encoded tokens + batch×width); space O(batch×width + input provenance).

ArgumentTypeRequired or defaultMeaning and constraints
corpusTextCorpusRequiredImmutable ordered document snapshot with unique source IDs and an explicit partition role.
codecTokenizerRequiredExact native byte/BPE or imported tokenizer. IDs and context budgets use this codec, never whitespace estimates.
max_lengthInt64RequiredRequired exact padded sequence width from 1 through 4096. Batch rows×width must not exceed 1000000 native elements; List export has its separate 262144 value bound.
truncationString"error""error" rejects any overlength document. "right" keeps the literal token prefix and records truncation; a dropped EOS is not repaired.
bosBooltrueInsert codec BOS before width admission; contributes to original and retained lengths.
eosBooltrueInsert codec EOS before width admission; a right truncated prefix may omit it.
pad_idInt64-1−1 resolves to the codec PAD ID. A codec without PAD requires an explicit valid vocabulary ID; masks, not the ID value, identify padding.

nlp.batch_size(value: TokenBatch) -> Int64

Return document rows in this token batch. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTokenBatchRequiredImmutable native TokenBatch snapshot.

nlp.cols(value: TextFeatures) -> Int64

Return fitted vocabulary width. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextFeaturesRequiredImmutable native TextFeatures snapshot.

nlp.columns(value: TextFeatures) -> List

Return zero based column IDs, sorted within each CSR row. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextFeaturesRequiredImmutable native TextFeatures snapshot.

nlp.configuration(value: TextIndex) -> Dictionary

Return complete canonical analyzer and BM25 parameters including explicit stop words. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextIndexRequiredImmutable native TextIndex snapshot.

nlp.configuration(value: TextVectorizer) -> Dictionary

Return complete canonical analyzer and fitting options including explicit stop words. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextVectorizerRequiredImmutable native TextVectorizer snapshot.

nlp.context(value: TextMatches, codec: Tokenizer, max_tokens: Int64, separator: String = "\n\n") -> TextContext

Assemble ranked whole documents greedily under the exact tokenizer budget. Skip an oversized candidate and continue considering later smaller hits. Never truncate evidence or silently add instructions. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time O(sum of candidate assembly encoding work); space O(accepted text + retained source IDs).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextMatchesRequiredImmutable ranked positive score evidence hits retaining source identities, source positions and term level explanations.
codecTokenizerRequiredExact native byte/BPE or imported tokenizer. IDs and context budgets use this codec, never whitespace estimates.
max_tokensInt64RequiredRequired exact encoded token budget from 1 through 1000000. Counts the complete assembled text and separators; no BOS/EOS are inserted.
separatorString"\n\n"Literal separator between accepted whole evidence documents; its encoded effect counts in every admission check.

nlp.contributions(value: TextMatches, hit: Int64) -> List

Return each query term contribution to one hit, aligned with matches.terms(). The sum equals that hit score within floating point arithmetic. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and returned space O(unique query terms).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextMatchesRequiredImmutable ranked positive score evidence hits retaining source identities, source positions and term level explanations.
hitInt64RequiredZero based ranked hit index below matches.rows().

nlp.corpus(texts: List, ids: List, role: String = "training") -> TextCorpus

Snapshot 1..100000 documents and IDs without modifying source text. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and space O(input bytes + rows).

ArgumentTypeRequired or defaultMeaning and constraints
textsListRequiredRequired List of UTF-8 Strings in source row order. Empty text is retained; the corpus itself must be nonempty.
idsListRequiredRequired equally sized List of unique nonempty String IDs, at most 256 UTF-8 bytes per ID. IDs and text share the 4,000,000 byte corpus budget.
roleString"training"One of "training", "validation", "testing", or "inference". Roles are explicit scientific metadata, not automatic data splitting.

nlp.dense(value: TextFeatures, max_cells: Int64) -> Tensor

Materialize sparse features explicitly as a detached CPU Float64 matrix. Keep the sparse row IDs separately before fitting a Tensor only model. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and returned space O(rows × columns).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextFeaturesRequiredImmutable CPU Float64 compressed sparse row features, row IDs, transform provenance and out of vocabulary counts.
max_cellsInt64RequiredRequired explicit positive admission bound for rows×columns. The product must also fit the existing Tensor element budget; no automatic dense expansion occurs.

nlp.document_frequency(value: TextVectorizer) -> List

Return per column training document frequencies. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextVectorizerRequiredImmutable native TextVectorizer snapshot.

nlp.document_hashes(value: TextCorpus) -> List

Return raw document SHA256 values in corpus row order. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextCorpusRequiredImmutable native TextCorpus snapshot.

nlp.empty_rows(value: TextFeatures) -> List

Return zero based positions of rows with no retained nonzero feature, including stop word only and OOV only rows. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextFeaturesRequiredImmutable native TextFeatures snapshot.

nlp.fingerprint(value: TextContext) -> String

Return a versioned SHA256 identity covering the operation policy, ordered source identity and retained state. An identity is traceability evidence, not a privacy guarantee or authenticated signature. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time O(1); returned space O(1).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextContextRequiredImmutable native TextContext with its exact ordered provenance.

nlp.fingerprint(value: TextCorpus) -> String

Return a versioned SHA256 identity covering the operation policy, ordered source identity and retained state. An identity is traceability evidence, not a privacy guarantee or authenticated signature. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time O(1); returned space O(1).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextCorpusRequiredImmutable native TextCorpus with its exact ordered provenance.

nlp.fingerprint(value: TextFeatures) -> String

Return a versioned SHA256 identity covering the operation policy, ordered source identity and retained state. An identity is traceability evidence, not a privacy guarantee or authenticated signature. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time O(1); returned space O(1).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextFeaturesRequiredImmutable native TextFeatures with its exact ordered provenance.

nlp.fingerprint(value: TextIndex) -> String

Return a versioned SHA256 identity covering the operation policy, ordered source identity and retained state. An identity is traceability evidence, not a privacy guarantee or authenticated signature. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time O(1); returned space O(1).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextIndexRequiredImmutable native TextIndex with its exact ordered provenance.

nlp.fingerprint(value: TextMatches) -> String

Return a versioned SHA256 identity covering the operation policy, ordered source identity and retained state. An identity is traceability evidence, not a privacy guarantee or authenticated signature. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time O(1); returned space O(1).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextMatchesRequiredImmutable native TextMatches with its exact ordered provenance.

nlp.fingerprint(value: TextVectorizer) -> String

Return a versioned SHA256 identity covering the operation policy, ordered source identity and retained state. An identity is traceability evidence, not a privacy guarantee or authenticated signature. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time O(1); returned space O(1).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextVectorizerRequiredImmutable native TextVectorizer with its exact ordered provenance.

nlp.fingerprint(value: TokenBatch) -> String

Return a versioned SHA256 identity covering the operation policy, ordered source identity and retained state. An identity is traceability evidence, not a privacy guarantee or authenticated signature. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time O(1); returned space O(1).

ArgumentTypeRequired or defaultMeaning and constraints
valueTokenBatchRequiredImmutable native TokenBatch with its exact ordered provenance.

nlp.fitted_documents(value: TextVectorizer) -> Int64

Return the number of documents used for vocabulary and IDF fitting. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextVectorizerRequiredImmutable native TextVectorizer snapshot.

nlp.idf(value: TextVectorizer) -> List

Return per column smoothed training IDF values; retained for audit even when weighting does not use them. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextVectorizerRequiredImmutable native TextVectorizer snapshot.

nlp.ids(value: TextContext) -> List

Return only the IDs of accepted whole evidence documents. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextContextRequiredImmutable native TextContext snapshot.

nlp.ids(value: TextCorpus) -> List

Return source document IDs in corpus order. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextCorpusRequiredImmutable native TextCorpus snapshot.

nlp.ids(value: TextFeatures) -> List

Return unchanged transformed document IDs in sparse row order. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextFeaturesRequiredImmutable native TextFeatures snapshot.

nlp.ids(value: TextIndex) -> List

Return indexed document IDs in source row order. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextIndexRequiredImmutable native TextIndex snapshot.

nlp.ids(value: TextMatches) -> List

Return hit IDs in ranked order. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextMatchesRequiredImmutable native TextMatches snapshot.

nlp.index(memory: TextCorpus, stop_words: List = List(), k1: Float64 = 1.2, b: Float64 = 0.75, analyzer: String = "word", min_ngram: Int64 = 1, max_ngram: Int64 = 1, casefold: Bool = true, normalization: String = "nfc") -> TextIndex

Fit deterministic BM25 lexical memory. Scores use log(1+(N df+0.5)/(df+0.5)), one contribution per unique analyzed query term and explicit document lengths. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time O(analyzed terms + postings ordering); space O(rows + term postings + retained source bytes).

ArgumentTypeRequired or defaultMeaning and constraints
memoryTextCorpusRequiredTraining role immutable evidence corpus only. This is retrieval memory, independent of neural KV caches and model parameter fitting.
stop_wordsListList()Explicit List of Strings; omitted/empty List disables filtering. Word analyzer only. Entries pass through the same normalization and case folding and must each identify one word; removed before word ngrams.
k1Float641.2Finite BM25 term frequency saturation parameter in (0,1000].
bFloat640.75Finite document length normalization factor in [0,1]; zero disables length normalization.
analyzerString"word""word" uses Unicode 17 letter/number-led runs and following combining marks; punctuation splits words. "char" uses Unicode scalar values including spaces; it has no language specific segmentation.
min_ngramInt641Smallest included ngram length, from 1 through 5 and no larger than max_ngram.
max_ngramInt641Largest included ngram length, from min_ngram through 5. Word ngrams use spaces between retained words; character ngrams preserve scalar order.
casefoldBooltrueApply full default Unicode case folding after the declared normalization, followed by normalization again. This can change symbols and length; original document text is retained.
normalizationString"nfc"Explicit Unicode policy: "nfc" (canonical composition), "nfkc" (compatibility composition), or "none". NFKC can erase scientifically meaningful distinctions.

nlp.lengths(value: TokenBatch) -> List

Return retained nonpadding token lengths per source row. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTokenBatchRequiredImmutable native TokenBatch snapshot.

nlp.load_index(path: String) -> TextIndex

Validate bounded checksummed data and rebuild the exact fitted state from its retained source and policy. Checksum detects corruption; it does not authenticate an untrusted producer. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and space follow the corresponding deterministic fitting operation.

ArgumentTypeRequired or defaultMeaning and constraints
pathStringRequiredArtifact filesystem path. Save requires a new regular file destination in an existing directory; load validates the bounded canonical checksummed data.

nlp.load_vectorizer(path: String) -> TextVectorizer

Validate bounded checksummed data and rebuild the exact fitted state from its retained source and policy. Checksum detects corruption; it does not authenticate an untrusted producer. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and space follow the corresponding deterministic fitting operation.

ArgumentTypeRequired or defaultMeaning and constraints
pathStringRequiredArtifact filesystem path. Save requires a new regular file destination in an existing directory; load validates the bounded canonical checksummed data.

nlp.mask(value: TokenBatch) -> Tensor

Return detached CPU Float64 [batch,width] mask with one at retained real tokens and zero at padding. Transfer and cast explicitly to match model activations. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTokenBatchRequiredImmutable native TokenBatch snapshot.

nlp.nnz(value: TextFeatures) -> Int64

Return explicitly stored nonzero entries. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextFeaturesRequiredImmutable native TextFeatures snapshot.

nlp.oov(value: TextFeatures) -> List

Return analyzed term occurrences absent from the fitted vocabulary for each row. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextFeaturesRequiredImmutable native TextFeatures snapshot.

nlp.original_lengths(value: TokenBatch) -> List

Return encoded lengths after requested BOS/EOS and before right truncation. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTokenBatchRequiredImmutable native TokenBatch snapshot.

nlp.padding_id(value: TokenBatch) -> Int64

Return the resolved vocabulary padding ID. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTokenBatchRequiredImmutable native TokenBatch snapshot.

nlp.positions(value: TextMatches) -> List

Return original indexed source row positions in ranked order; these are not external IDs. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextMatchesRequiredImmutable native TextMatches snapshot.

nlp.role(value: TextCorpus) -> String

Return the declared partition role. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextCorpusRequiredImmutable native TextCorpus snapshot.

nlp.row_columns(value: TextFeatures, row: Int64) -> List

Export one CSR row as exact column IDs or aligned Float64 values without materializing the complete sparse arrays. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and returned space O(row nonzeros); language List limits still apply.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextFeaturesRequiredImmutable CPU Float64 compressed sparse row features, row IDs, transform provenance and out of vocabulary counts.
rowInt64RequiredZero based source or batch row inside the retained population.

nlp.row_ptr(value: TextFeatures) -> List

Return CSR row offsets of length rows+1, beginning at zero and ending at nnz. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextFeaturesRequiredImmutable native TextFeatures snapshot.

nlp.row_values(value: TextFeatures, row: Int64) -> List

Export one CSR row as exact column IDs or aligned Float64 values without materializing the complete sparse arrays. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and returned space O(row nonzeros); language List limits still apply.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextFeaturesRequiredImmutable CPU Float64 compressed sparse row features, row IDs, transform provenance and out of vocabulary counts.
rowInt64RequiredZero based source or batch row inside the retained population.

nlp.rows(value: TextCorpus) -> Int64

Return the retained document count. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextCorpusRequiredImmutable native TextCorpus snapshot.

nlp.rows(value: TextFeatures) -> Int64

Return sparse feature row count, including empty rows. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextFeaturesRequiredImmutable native TextFeatures snapshot.

nlp.rows(value: TextIndex) -> Int64

Return the indexed evidence population size. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextIndexRequiredImmutable native TextIndex snapshot.

nlp.rows(value: TextMatches) -> Int64

Return retained positive score hit count; zero is valid. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextMatchesRequiredImmutable native TextMatches snapshot.

nlp.save(value: TextIndex, path: String) -> Unit

Save canonical checksummed data including fitting/evidence text and source IDs. Refuse overwrite; artifacts can contain sensitive source material. No executable object deserialization occurs. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and artifact space O(retained source bytes + fitted metadata).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextIndexRequiredImmutable fitted TextIndex to persist.
pathStringRequiredArtifact filesystem path. Save requires a new regular file destination in an existing directory; load validates the bounded canonical checksummed data.

nlp.save(value: TextVectorizer, path: String) -> Unit

Save canonical checksummed data including fitting/evidence text and source IDs. Refuse overwrite; artifacts can contain sensitive source material. No executable object deserialization occurs. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and artifact space O(retained source bytes + fitted metadata).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextVectorizerRequiredImmutable fitted TextVectorizer to persist.
pathStringRequiredArtifact filesystem path. Save requires a new regular file destination in an existing directory; load validates the bounded canonical checksummed data.

nlp.scores(value: TextMatches) -> List

Return finite positive BM25 scores in ranked order. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextMatchesRequiredImmutable native TextMatches snapshot.

nlp.search(value: TextIndex, query: String, top_k: Int64 = 5) -> TextMatches

Rank positive score BM25 matches while retaining source row IDs, original text, source positions and per term contributions. No semantic embedding or external lookup is implied. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time O(query terms + scored postings + candidates log candidates); result space O(top_k × query terms + source hit text).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextIndexRequiredImmutable BM25 lexical memory with source text/IDs, analyzer policy and fitted document frequencies.
queryStringRequiredUTF-8 query analyzed by the fitted index policy; duplicate query terms count once. Empty or entirely unknown query terms yield zero hits.
top_kInt645Maximum number of positive score hits to retain, from 1 through 1000. Score ties use original source row order.

nlp.sequence_length(value: TokenBatch) -> Int64

Return exact configured padded width. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTokenBatchRequiredImmutable native TokenBatch snapshot.

nlp.skipped(value: TextContext) -> Int64

Return candidate hits skipped because their whole document assembly exceeded the token budget. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextContextRequiredImmutable native TextContext snapshot.

nlp.source_fingerprint(value: TokenBatch) -> String

Return originating TextCorpus fingerprint including its role, source IDs, raw text and order. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTokenBatchRequiredImmutable native TokenBatch snapshot.

nlp.source_ids(value: TokenBatch) -> List

Return source document IDs in batch row order. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTokenBatchRequiredImmutable native TokenBatch snapshot.

nlp.summary(value: TextContext) -> String

Return a bounded human readable summary of shape, policy and provenance. Original document content is not printed automatically. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and returned space O(summary metadata bytes).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextContextRequiredImmutable native TextContext with its exact ordered provenance.

nlp.summary(value: TextCorpus) -> String

Return a bounded human readable summary of shape, policy and provenance. Original document content is not printed automatically. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and returned space O(summary metadata bytes).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextCorpusRequiredImmutable native TextCorpus with its exact ordered provenance.

nlp.summary(value: TextFeatures) -> String

Return a bounded human readable summary of shape, policy and provenance. Original document content is not printed automatically. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and returned space O(summary metadata bytes).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextFeaturesRequiredImmutable native TextFeatures with its exact ordered provenance.

nlp.summary(value: TextIndex) -> String

Return a bounded human readable summary of shape, policy and provenance. Original document content is not printed automatically. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and returned space O(summary metadata bytes).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextIndexRequiredImmutable native TextIndex with its exact ordered provenance.

nlp.summary(value: TextMatches) -> String

Return a bounded human readable summary of shape, policy and provenance. Original document content is not printed automatically. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and returned space O(summary metadata bytes).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextMatchesRequiredImmutable native TextMatches with its exact ordered provenance.

nlp.summary(value: TextVectorizer) -> String

Return a bounded human readable summary of shape, policy and provenance. Original document content is not printed automatically. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and returned space O(summary metadata bytes).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextVectorizerRequiredImmutable native TextVectorizer with its exact ordered provenance.

nlp.summary(value: TokenBatch) -> String

Return a bounded human readable summary of shape, policy and provenance. Original document content is not printed automatically. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and returned space O(summary metadata bytes).

ArgumentTypeRequired or defaultMeaning and constraints
valueTokenBatchRequiredImmutable native TokenBatch with its exact ordered provenance.

nlp.terms(value: TextMatches) -> List

Return canonical unique analyzed query terms aligned with every contributions vector. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextMatchesRequiredImmutable native TextMatches snapshot.

nlp.text(value: TextContext) -> String

Return exact assembled evidence text, or empty text when no document fits. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextContextRequiredImmutable native TextContext snapshot.

nlp.texts(value: TextCorpus) -> List

Return original document texts without analyzer normalization. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextCorpusRequiredImmutable native TextCorpus snapshot.

nlp.texts(value: TextMatches) -> List

Return original hit document texts in ranked order. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextMatchesRequiredImmutable native TextMatches snapshot.

nlp.token_ids(value: TokenBatch, row: Int64) -> List

Export one exact padded token ID row of at most 4096 Int64 values without materializing the full batch List. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time and returned space O(sequence width).

ArgumentTypeRequired or defaultMeaning and constraints
valueTokenBatchRequiredImmutable fixed width exact Int64 token IDs, CPU Float64 padding mask, lengths, truncation flags and source identity.
rowInt64RequiredZero based source or batch row inside the retained population.

nlp.token_ids(value: TokenBatch) -> List

Return exact Int64 token IDs flattened in row major order, including padding. Large native batches may exceed the smaller List export bound; use row export. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTokenBatchRequiredImmutable native TokenBatch snapshot.

nlp.tokens(value: TextContext) -> Int64

Return exact encoded count of the assembled text under its retained codec, without BOS/EOS. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextContextRequiredImmutable native TextContext snapshot.

nlp.training_hashes(value: TextIndex) -> List

Return raw indexed document SHA256 values in source row order, including duplicate content hashes. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextIndexRequiredImmutable native TextIndex snapshot.

nlp.training_hashes(value: TextVectorizer) -> List

Return raw fitting document SHA256 values in fitting row order, including duplicate content hashes. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextVectorizerRequiredImmutable native TextVectorizer snapshot.

nlp.transform(value: TextVectorizer, corpus: TextCorpus) -> TextFeatures

Apply the unchanged fitted analyzer/vocabulary/IDF to an ordered corpus. Held out roles reject reused fitting IDs, raw content and policy-normalized/casefolded content overlap. Preserve IDs, OOV occurrence counts and zero rows. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time O(analyzed terms + row nonzeros log row nonzeros); space O(rows + nonzeros), capped at 2000000 native sparse entries.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextVectorizerRequiredFitted immutable vocabulary, weighting policy, training document frequencies and fitting provenance.
corpusTextCorpusRequiredImmutable ordered document snapshot with unique source IDs and an explicit partition role.

nlp.truncated(value: TokenBatch) -> List

Return one Bool per row; true means the original encoded length exceeded max_length. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTokenBatchRequiredImmutable native TokenBatch snapshot.

nlp.values(value: TextFeatures) -> List

Return finite CPU Float64 feature values aligned with columns. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextFeaturesRequiredImmutable native TextFeatures snapshot.

nlp.vectorizer(training: TextCorpus, stop_words: List = List(), weighting: String = "tfidf", analyzer: String = "word", min_ngram: Int64 = 1, max_ngram: Int64 = 1, min_df: Int64 = 1, max_df: Float64 = 1.0, max_features: Int64 = 20000, casefold: Bool = true, sublinear_tf: Bool = false, norm: String = "l2", normalization: String = "nfc") -> TextVectorizer

Fit a deterministic sparse lexical representation using only a training role corpus; reject an empty retained vocabulary. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Time O(analyzed terms + distinct terms log distinct terms); fitted space O(vocabulary + training provenance).

ArgumentTypeRequired or defaultMeaning and constraints
trainingTextCorpusRequiredTraining role documents only. Fit before validation or test transformation; fitting retains content hashes and IDs for overlap checks.
stop_wordsListList()Explicit List of Strings; omitted/empty List disables filtering. Word analyzer only. Entries pass through the same normalization and case folding and must each identify one word; removed before word ngrams.
weightingString"tfidf""count", "binary", or "tfidf". TF IDF uses smoothed IDF log((1+N)/(1+df))+1; binary records presence.
analyzerString"word""word" uses Unicode 17 letter/number-led runs and following combining marks; punctuation splits words. "char" uses Unicode scalar values including spaces; it has no language specific segmentation.
min_ngramInt641Smallest included ngram length, from 1 through 5 and no larger than max_ngram.
max_ngramInt641Largest included ngram length, from min_ngram through 5. Word ngrams use spaces between retained words; character ngrams preserve scalar order.
min_dfInt641Minimum number of training documents containing a retained term; integer count from 1 through training rows.
max_dfFloat641.0Maximum training document fraction containing a term, finite in (0,1]; terms require df/N <= max_df.
max_featuresInt6420000Vocabulary cap from 1 through 65536; candidates rank by corpus term count then lexical tie order, and retained columns have canonical lexical order.
casefoldBooltrueApply full default Unicode case folding after the declared normalization, followed by normalization again. This can change symbols and length; original document text is retained.
sublinear_tfBoolfalseReplace positive term count tf with 1+log(tf) before weighting. Incompatible with binary weighting; that combination fails.
normString"l2""l2" gives unit Euclidean norm, "l1" gives unit absolute sum, and "none" retains weighted magnitude. A zero row remains zero.
normalizationString"nfc"Explicit Unicode policy: "nfc" (canonical composition), "nfkc" (compatibility composition), or "none". NFKC can erase scientifically meaningful distinctions.

nlp.vocabulary(value: TextVectorizer) -> List

Return exact feature names in fitted column order. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no hidden global random stream. Scalar access is O(1); owned List/text exports take O(returned fields + bytes) time and space and obey language heap limits.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextVectorizerRequiredImmutable native TextVectorizer snapshot.

nn.feed_forward(input: Tensor, w_in: Tensor, b_in: Tensor, w_out: Tensor, b_out: Tensor) -> Tensor

Apply exact GELU((input × w_in)+b_in) × w_out+b_out to rank two through rank eight input, preserving leading dimensions and autograd. Normalization, dropout and residual addition remain explicit caller choices. Requires import aner.nn. Time O(leading_rows × (input_width×hidden_width+hidden_width×output_width)); graph space follows retained projections within native tensor/work limits.

ArgumentTypeRequired or defaultMeaning and constraints
inputTensorRequiredDifferentiable input on the same device and dtype as every supplied parameter.
w_inTensorRequiredTrainable or constant rank two [input_width,hidden_width] projection.
b_inTensorRequiredRank two [1,hidden_width] bias; no implicit broadcasting from another logical shape.
w_outTensorRequiredRank two [hidden_width,output_width] projection.
b_outTensorRequiredRank two [1,output_width] bias.

nn.masked_mean(input: Tensor, mask: Tensor) -> Tensor

Pool nonpadding tokens to [batch,width] with zero gradient at excluded positions. No causal restriction or attention weighting is added. Mask validation may inspect mask data; activation data remains on its execution backend. Requires import aner.nn. Time O(batch×time×width); graph space O(batch×time×width) within native tensor/work limits.

ArgumentTypeRequired or defaultMeaning and constraints
inputTensorRequiredDifferentiable input on the same device and dtype as every supplied parameter.
maskTensorRequiredDetached exact binary [batch,time] mask matching rank three input [batch,time,width], dtype and device. Every row must contain a real token; an all padding row fails.

POS and named entity tagging

Read the model guide.

nlp.accuracy(value: TaggingEvaluation) -> Float64

Return corpus token accuracy; zero total tokens yields the documented zero result. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar access is O(1); exported metric Lists are O(reported labels or entity types).

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggingEvaluationRequiredImmutable alignment checked POS/NER metric snapshot with prediction/gold identities.

nlp.annotate(value: TextTokens, labels: List, task: String) -> TaggedCorpus

Validate a complete source aligned gold annotation. Labels and spans participate in the annotated corpus fingerprint. NER types are ASCII identifiers of at most64bytes; nested/discontinuous entities are outside BIO2. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and space O(tokens + label bytes).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTokensRequiredExact source token snapshot that determines annotation row/token alignment.
labelsListRequiredNested Lists of String labels, one List per sequence and one label per token. Empty token rows require empty label Lists.
taskStringRequiredRequired task: pos admits the 17 Universal POS spellings; ner admits strict BIO2 O/B-TYPE/I-TYPE. Invalid I transitions fail without repair.

nlp.configuration(value: TextTagger) -> Dictionary

Return canonical cumulative epoch count, seed/shuffle, feature normalization/casefold and versioned learning/feature protocol metadata. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalars are O(1); List export follows returned fields/bytes and the explicit language heap budget.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.

nlp.confusion(value: TaggingEvaluation) -> List

Return positive token confusion Dictionaries with gold,predicted,count sorted lexically by label pair, including the correct diagonal; counts sum to token_count. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar access is O(1); exported metric Lists are O(reported labels or entity types).

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggingEvaluationRequiredImmutable alignment checked POS/NER metric snapshot with prediction/gold identities.

nlp.correct(value: TaggingEvaluation) -> Int64

Return exactly correct token labels. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar access is O(1); exported metric Lists are O(reported labels or entity types).

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggingEvaluationRequiredImmutable alignment checked POS/NER metric snapshot with prediction/gold identities.

nlp.entities(value: TaggedCorpus, row: Int64) -> List

Return NER entities as Dictionaries with id/type/text/row and half open token_start/token_end, byte_start/byte_end and scalar_start/scalar_end. Source text retains intervening whitespace; POS calls reject. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time O(row tokens + entity bytes); returned space O(entities + source slice bytes).

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggedCorpusRequiredImmutable aligned TaggedCorpus with its original token snapshot.
rowInt64RequiredZero based source sequence row within this snapshot. Empty source rows remain addressable.

nlp.entities(value: TextTagging, row: Int64) -> List

Return NER entities as Dictionaries with id/type/text/row and half open token_start/token_end, byte_start/byte_end and scalar_start/scalar_end. Source text retains intervening whitespace; POS calls reject. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time O(row tokens + entity bytes); returned space O(entities + source slice bytes).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggingRequiredImmutable aligned TextTagging with its original token snapshot.
rowInt64RequiredZero based source sequence row within this snapshot. Empty source rows remain addressable.

nlp.entity_metric(value: TaggingEvaluation) -> Dictionary

Return NER strict full span micro gold,predicted,correct,precision,recall,f1. A hit requires exact source row, type and complete span; POS calls reject. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar access is O(1); exported metric Lists are O(reported labels or entity types).

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggingEvaluationRequiredImmutable alignment checked POS/NER metric snapshot with prediction/gold identities.

nlp.entity_metrics(value: TaggingEvaluation) -> List

Return per type NER exact span Dictionaries with label,gold,predicted,correct,precision,recall,f1; undefined denominators produce zero. POS calls reject. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar access is O(1); exported metric Lists are O(reported labels or entity types).

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggingEvaluationRequiredImmutable alignment checked POS/NER metric snapshot with prediction/gold identities.

nlp.epochs(value: TextTagger) -> Int64

Return cumulative completed epochs; resumed epochs add to this value. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalars are O(1); List export follows returned fields/bytes and the explicit language heap budget.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.

nlp.evaluate_tagger(value: TextTagger, gold: TaggedCorpus) -> TaggingEvaluation

Predict and evaluate with the model bound held out overlap guard. Report exact token counts, per label metrics and strict full span NER metrics with source/model/gold provenance. Declared roles do not replace group/time partition design. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time follows decoding plus O(tokens + entities) metric counting.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.
goldTaggedCorpusRequiredTask matching gold annotation. Validation/testing reject fitted source IDs, raw source text and identical policy normalized token sequences; training/inference permits intentional reuse.

nlp.evaluate_tags(value: TextTagging, gold: TaggedCorpus) -> TaggingEvaluation

Evaluate a retained prediction without rerunning decoding. This path checks alignment but cannot infer independence from model fitting; use evaluate_tagger for the model bound held out guard. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time O(tokens log labels + entities log entities) with bounded metric maps/sets and span storage.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggingRequiredRetained model prediction, task and exact source token alignment.
goldTaggedCorpusRequiredReference annotation with the exact same token snapshot and task as the prediction.

nlp.examples_seen(value: TextTagger) -> Int64

Return cumulative nonempty training sequences processed, including correctly predicted examples. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalars are O(1); List export follows returned fields/bytes and the explicit language heap budget.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.

nlp.feature_names(value: TextTagger) -> List

Return canonical learned emission feature names for lexical/context/shape/affix scores. Reserved transition names are inspected separately. Full export obeys the smaller language heap bound. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalars are O(1); List export follows returned fields/bytes and the explicit language heap budget.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.

nlp.fingerprint(value: TaggedCorpus) -> String

Return a SHA256 identity covering this value protocol and retained state. Fingerprints provide identity, not authentication or anonymity. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. O(1) stored identity readout.

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggedCorpusRequiredImmutable TaggedCorpus with complete source, task and operation provenance.

nlp.fingerprint(value: TaggingEvaluation) -> String

Return a SHA256 identity covering this value protocol and retained state. Fingerprints provide identity, not authentication or anonymity. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. O(1) stored identity readout.

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggingEvaluationRequiredImmutable TaggingEvaluation with complete source, task and operation provenance.

nlp.fingerprint(value: TextTagger) -> String

Return a SHA256 identity covering this value protocol and retained state. Fingerprints provide identity, not authentication or anonymity. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. O(1) stored identity readout.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable TextTagger with complete source, task and operation provenance.

nlp.fingerprint(value: TextTagging) -> String

Return a SHA256 identity covering this value protocol and retained state. Fingerprints provide identity, not authentication or anonymity. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. O(1) stored identity readout.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggingRequiredImmutable TextTagging with complete source, task and operation provenance.

nlp.fingerprint(value: TextTokens) -> String

Return a SHA256 identity covering this value protocol and retained state. Fingerprints provide identity, not authentication or anonymity. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. O(1) stored identity readout.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTokensRequiredImmutable TextTokens with complete source, task and operation provenance.

nlp.fit_tagger(training: TaggedCorpus, epochs: Int64 = 5, seed: Int64 = 42, shuffle: Bool = true, normalization: String = "nfc", casefold: Bool = true) -> TextTagger

Fit a first order averaged structured perceptron with lexical/context/shape/affix features and exact Viterbi decoding. NER paths satisfy strict BIO2; POS predicts the observed UPOS subset. No pretrained weights or probability calibration are supplied. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time includes O(epochs × tokens × labels²) decoding; cells and work are explicitly bounded.

ArgumentTypeRequired or defaultMeaning and constraints
trainingTaggedCorpusRequiredTraining role source aligned annotation with exact per token String labels and a task of pos or ner. At least one token is required.
epochsInt645Complete fitting passes from1through1000, with at most1000cumulativeepochs; requested work tokens×labels×(labels+32)×epochs must fit100000000.
seedInt6442Seed for deterministic per epoch sequence shuffle. The schedule is indexed by cumulative epoch, so continuation does not restart it.
shuffleBooltrueTrue shuffles rows with the versioned seed/epoch protocol; false visits source row order. Empty rows retain provenance but do not advance the averaging clock.
normalizationString"nfc"Feature text normalization: none, nfc or nfkc. Normalization does not alter original token text or spans.
casefoldBooltrueApply full Unicode default casefold between feature normalization passes. Original orthographic shape features remain separately defined.

nlp.gold_fingerprint(value: TaggingEvaluation) -> String

Return the exact gold annotation identity used for metric computation. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar access is O(1); exported metric Lists are O(reported labels or entity types).

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggingEvaluationRequiredImmutable alignment checked POS/NER metric snapshot with prediction/gold identities.

nlp.ids(value: TaggedCorpus) -> List

Return original document IDs in retained sequence row order. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar readouts are O(1); List export is O(returned fields + bytes) and follows the language heap bound.

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggedCorpusRequiredImmutable source aligned TaggedCorpus; source row order, IDs and roles remain explicit.

nlp.ids(value: TextTagging) -> List

Return original document IDs in retained sequence row order. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar readouts are O(1); List export is O(returned fields + bytes) and follows the language heap bound.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggingRequiredImmutable source aligned TextTagging; source row order, IDs and roles remain explicit.

nlp.ids(value: TextTokens) -> List

Return original document IDs in retained sequence row order. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar readouts are O(1); List export is O(returned fields + bytes) and follows the language heap bound.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTokensRequiredImmutable source aligned TextTokens; source row order, IDs and roles remain explicit.

nlp.labels(value: TextTagger) -> List

Return the exact lexicographically ordered fitted output inventory; NER includes O and B/I closure for each observed type. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalars are O(1); List export follows returned fields/bytes and the explicit language heap budget.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.

nlp.load_tagger(path: String) -> TextTagger

Validate the bounded canonical checksummed checkpoint and restore exact current/averaged training state without running producer code or refitting from source text. Checksum is not an authenticated signature. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and space O(validated artifact bytes + fitted state).

ArgumentTypeRequired or defaultMeaning and constraints
pathStringRequiredLocal artifact path. Save requires a new file in an existing directory; load validates bounded canonical data and its checksum.

nlp.model_fingerprint(value: TextTagging) -> String

Return the complete model fingerprint used for this prediction; preserve it with the source token and output fingerprints. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. O(1) readout.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggingRequiredRetained prediction with exact model state provenance.

nlp.prediction_fingerprint(value: TaggingEvaluation) -> String

Return the exact retained prediction identity used for metric computation. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar access is O(1); exported metric Lists are O(reported labels or entity types).

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggingEvaluationRequiredImmutable alignment checked POS/NER metric snapshot with prediction/gold identities.

nlp.resume_tagger(value: TextTagger, training: TaggedCorpus, epochs: Int64) -> TextTagger

Continue current integer weights, lazy averaging totals/timestamps, cumulative epoch shuffle and counters. Preserve seed, shuffle and feature policy; checkpoint continuation reproduces an uninterrupted run under the same protocol. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and additional work follow the requested epochs; no silent optimizer or averaging reset.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.
trainingTaggedCorpusRequiredTraining role source aligned annotation with exact per token String labels and a task of pos or ner. At least one token is required.
epochsInt64RequiredRequired additional complete epochs. The exact annotated training fingerprint must match, including source rows/order/IDs, role, token boundaries and gold labels.

nlp.role(value: TaggedCorpus) -> String

Return the original corpus partition role, without inferring held out independence. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar readouts are O(1); List export is O(returned fields + bytes) and follows the language heap bound.

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggedCorpusRequiredImmutable source aligned TaggedCorpus; source row order, IDs and roles remain explicit.

nlp.role(value: TaggingEvaluation) -> String

Return the declared evaluated corpus role. A role alone does not establish independence from fitting. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar access is O(1); exported metric Lists are O(reported labels or entity types).

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggingEvaluationRequiredImmutable alignment checked POS/NER metric snapshot with prediction/gold identities.

nlp.role(value: TextTagging) -> String

Return the original corpus partition role, without inferring held out independence. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar readouts are O(1); List export is O(returned fields + bytes) and follows the language heap bound.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggingRequiredImmutable source aligned TextTagging; source row order, IDs and roles remain explicit.

nlp.role(value: TextTokens) -> String

Return the original corpus partition role, without inferring held out independence. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar readouts are O(1); List export is O(returned fields + bytes) and follows the language heap bound.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTokensRequiredImmutable source aligned TextTokens; source row order, IDs and roles remain explicit.

nlp.rows(value: TaggedCorpus) -> Int64

Return the original sequence row count, including empty rows. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar readouts are O(1); List export is O(returned fields + bytes) and follows the language heap bound.

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggedCorpusRequiredImmutable source aligned TaggedCorpus; source row order, IDs and roles remain explicit.

nlp.rows(value: TextTagging) -> Int64

Return the original sequence row count, including empty rows. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar readouts are O(1); List export is O(returned fields + bytes) and follows the language heap bound.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggingRequiredImmutable source aligned TextTagging; source row order, IDs and roles remain explicit.

nlp.rows(value: TextTokens) -> Int64

Return the original sequence row count, including empty rows. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar readouts are O(1); List export is O(returned fields + bytes) and follows the language heap bound.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTokensRequiredImmutable source aligned TextTokens; source row order, IDs and roles remain explicit.

nlp.save(value: TextTagger, path: String) -> Unit

Write a bounded exclusive data only checkpoint containing current integer weights, lazy averaging totals/timestamps, continuation counters and fitting provenance. Raw training text is excluded; learned lexical features and source IDs remain retained. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and artifact space O(fitted cells + feature/label/provenance bytes).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.
pathStringRequiredLocal artifact path. Save requires a new file in an existing directory; load validates bounded canonical data and its checksum.

nlp.scores(value: TextTagging) -> List

Return one finite uncalibrated complete sequence score per source row. Empty rows have the engine defined zero score; no token confidence or probability is implied. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and returned space O(rows).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggingRequiredAveraged weight predicted complete sequences, original token alignment and exact model identity.

nlp.source(value: TextTokens) -> TextCorpus

Return the original immutable corpus, preserving source IDs, raw UTF-8 text and declared role. No feature normalization is applied. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. O(1) shared immutable handle.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTokensRequiredImmutable original source token snapshot.

nlp.summary(value: TaggedCorpus) -> String

Return bounded shape/task/state provenance without automatically printing original source text or labels. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and returned space O(summary metadata bytes).

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggedCorpusRequiredImmutable TaggedCorpus with complete source, task and operation provenance.

nlp.summary(value: TaggingEvaluation) -> String

Return bounded shape/task/state provenance without automatically printing original source text or labels. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and returned space O(summary metadata bytes).

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggingEvaluationRequiredImmutable TaggingEvaluation with complete source, task and operation provenance.

nlp.summary(value: TextTagger) -> String

Return bounded shape/task/state provenance without automatically printing original source text or labels. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and returned space O(summary metadata bytes).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable TextTagger with complete source, task and operation provenance.

nlp.summary(value: TextTagging) -> String

Return bounded shape/task/state provenance without automatically printing original source text or labels. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and returned space O(summary metadata bytes).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggingRequiredImmutable TextTagging with complete source, task and operation provenance.

nlp.summary(value: TextTokens) -> String

Return bounded shape/task/state provenance without automatically printing original source text or labels. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and returned space O(summary metadata bytes).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTokensRequiredImmutable TextTokens with complete source, task and operation provenance.

nlp.tag(value: TextTagger, tokens: TextTokens) -> TextTagging

Reject held out fitted IDs/raw/normalized-token overlap and decode all sequences with averaged weights, preserving source tokens, IDs, model identity and uncalibrated complete sequence scores. Global equal score paths use the lexicographically smallest label index sequence; empty rows remain empty. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time O(tokens × labels²) plus features; bounded dynamic programming space.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.
tokensTextTokensRequiredOriginal source aligned token snapshot. Boundaries and text are never normalized or rewritten; prediction requires the fitted tokenization protocol.

nlp.tag_metrics(value: TaggingEvaluation) -> List

Return per label Dictionaries with label,gold,predicted,correct,precision,recall,f1. Undefined precision/recall/F1 denominators produce zero. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar access is O(1); exported metric Lists are O(reported labels or entity types).

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggingEvaluationRequiredImmutable alignment checked POS/NER metric snapshot with prediction/gold identities.

nlp.tag_score(value: TextTagger, tokens: TextTokens, row: Int64, labels: List, averaged: Bool = true) -> Float64

Score an explicitly supplied complete path with current or averaged linear weights. This is an uncalibrated sequence score, not a normalized probability or cross length confidence. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time O(sequence feature work + sequence length); bounded row feature and label path storage.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.
tokensTextTokensRequiredOriginal source aligned token snapshot. Boundaries and text are never normalized or rewritten; prediction requires the fitted tokenization protocol.
rowInt64RequiredZero based source sequence row within this snapshot. Empty source rows remain addressable.
labelsListRequiredOne valid complete String label path for this sequence, exactly matching its token count and fitted label inventory; NER must satisfy BIO2.
averagedBooltrueTrue selects lazily averaged inference weights; false inspects the current weights used for the next training sequence.

nlp.tagger_weights(value: TextTagger, feature: String, averaged: Bool = true) -> List

Inspect one learned feature as Float64 weights aligned to labels(). Weights are linear score components, not token probabilities. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and returned space O(label count).

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.
featureStringRequiredExact learned feature name from feature_names(). Reserved transition names are @BOS, @EOS and @T:. Unknown feature names fail.
averagedBooltrueTrue selects lazily averaged inference weights; false inspects the current weights used for the next training sequence.

nlp.tags(value: TaggedCorpus, row: Int64) -> List

Return one sequence of exact String labels aligned one for one to original source tokens. NER uses valid BIO2 and POS uses Universal POS spellings. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and returned space O(row token labels); language List limits apply.

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggedCorpusRequiredImmutable aligned TaggedCorpus with its original token snapshot.
rowInt64RequiredZero based source sequence row within this snapshot. Empty source rows remain addressable.

nlp.tags(value: TextTagging, row: Int64) -> List

Return one sequence of exact String labels aligned one for one to original source tokens. NER uses valid BIO2 and POS uses Universal POS spellings. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and returned space O(row token labels); language List limits apply.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggingRequiredImmutable aligned TextTagging with its original token snapshot.
rowInt64RequiredZero based source sequence row within this snapshot. Empty source rows remain addressable.

nlp.task(value: TaggedCorpus) -> String

Return the declared task string pos or ner. The task determines label validation, legal transitions and metric interpretation. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. O(1) readout.

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggedCorpusRequiredImmutable task bearing TaggedCorpus with validated POS or NER semantics.

nlp.task(value: TaggingEvaluation) -> String

Return the declared task string pos or ner. The task determines label validation, legal transitions and metric interpretation. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. O(1) readout.

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggingEvaluationRequiredImmutable task bearing TaggingEvaluation with validated POS or NER semantics.

nlp.task(value: TextTagger) -> String

Return the declared task string pos or ner. The task determines label validation, legal transitions and metric interpretation. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. O(1) readout.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable task bearing TextTagger with validated POS or NER semantics.

nlp.task(value: TextTagging) -> String

Return the declared task string pos or ner. The task determines label validation, legal transitions and metric interpretation. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. O(1) readout.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggingRequiredImmutable task bearing TextTagging with validated POS or NER semantics.

nlp.token_count(value: TaggedCorpus) -> Int64

Return total source aligned tokens across retained sequences. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar readouts are O(1); List export is O(returned fields + bytes) and follows the language heap bound.

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggedCorpusRequiredImmutable source aligned TaggedCorpus; source row order, IDs and roles remain explicit.

nlp.token_count(value: TaggingEvaluation) -> Int64

Return the evaluated gold token count, including every row. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar access is O(1); exported metric Lists are O(reported labels or entity types).

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggingEvaluationRequiredImmutable alignment checked POS/NER metric snapshot with prediction/gold identities.

nlp.token_count(value: TextTagging) -> Int64

Return total source aligned tokens across retained sequences. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar readouts are O(1); List export is O(returned fields + bytes) and follows the language heap bound.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggingRequiredImmutable source aligned TextTagging; source row order, IDs and roles remain explicit.

nlp.token_count(value: TextTokens) -> Int64

Return total source aligned tokens across retained sequences. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalar readouts are O(1); List export is O(returned fields + bytes) and follows the language heap bound.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTokensRequiredImmutable source aligned TextTokens; source row order, IDs and roles remain explicit.

nlp.token_ends(value: TextTokens, row: Int64) -> List

Return original UTF-8 byte end offsets aligned to token_starts. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and returned space O(row tokens + exported text bytes), within row and heap bounds.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTokensRequiredImmutable source aligned token snapshot with exact original UTF-8 boundaries.
rowInt64RequiredZero based source sequence row within this snapshot. Empty source rows remain addressable.

nlp.token_scalar_ends(value: TextTokens, row: Int64) -> List

Return half open Unicode scalar ends suitable for String.slice. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and returned space O(row tokens + exported text bytes), within row and heap bounds.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTokensRequiredImmutable source aligned token snapshot with exact original UTF-8 boundaries.
rowInt64RequiredZero based source sequence row within this snapshot. Empty source rows remain addressable.

nlp.token_scalar_starts(value: TextTokens, row: Int64) -> List

Return Unicode scalar starts suitable for String.slice; these are not byte offsets. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and returned space O(row tokens + exported text bytes), within row and heap bounds.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTokensRequiredImmutable source aligned token snapshot with exact original UTF-8 boundaries.
rowInt64RequiredZero based source sequence row within this snapshot. Empty source rows remain addressable.

nlp.token_starts(value: TextTokens, row: Int64) -> List

Return zero based half open UTF-8 byte start offsets for one row. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and returned space O(row tokens + exported text bytes), within row and heap bounds.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTokensRequiredImmutable source aligned token snapshot with exact original UTF-8 boundaries.
rowInt64RequiredZero based source sequence row within this snapshot. Empty source rows remain addressable.

nlp.token_texts(value: TextTokens, row: Int64) -> List

Return exact original token Strings for one row. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and returned space O(row tokens + exported text bytes), within row and heap bounds.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTokensRequiredImmutable source aligned token snapshot with exact original UTF-8 boundaries.
rowInt64RequiredZero based source sequence row within this snapshot. Empty source rows remain addressable.

nlp.tokenize(corpus: TextCorpus, starts: List, ends: List) -> TextTokens

Snapshot caller supplied source token boundaries without retokenization. At most 4096 tokens per row and 1000000 total; each token is at most 4096 UTF-8 bytes. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and space O(source bytes + token spans).

ArgumentTypeRequired or defaultMeaning and constraints
corpusTextCorpusRequiredImmutable ordered UTF-8 source rows, unique document IDs and explicit role. Each row is one tagging sequence.
startsListRequiredNested Lists of zero based half open original UTF-8 byte starts, one row per source sequence.
endsListRequiredMatching nested Lists of byte ends. Spans must be ordered, nonoverlapping, scalar aligned, contain no whitespace and cover every nonwhitespace source scalar.

nlp.tokenize(corpus: TextCorpus) -> TextTokens

Tokenize each original corpus row with the pinned Unicode 17 rule: letter/number-led runs retain following marks, whitespace is skipped and other punctuation/symbol scalars are separate. No sentence segmentation or normalization is implicit. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Time and space O(source bytes + tokens).

ArgumentTypeRequired or defaultMeaning and constraints
corpusTextCorpusRequiredImmutable ordered UTF-8 source rows, unique document IDs and explicit role. Each row is one tagging sequence.

nlp.tokenizer(value: TextTokens) -> String

Return the versioned source tokenization protocol. Automatic and explicitly supplied spans have distinct identities; no reversible neural codec is implied. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. O(1) protocol readout.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTokensRequiredOriginal token snapshot using automatic or explicit source boundaries.

nlp.tokens(value: TaggedCorpus) -> TextTokens

Return the exact original source token snapshot without normalization, token insertion or row reordering. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. O(1) shared immutable handle.

ArgumentTypeRequired or defaultMeaning and constraints
valueTaggedCorpusRequiredImmutable aligned TaggedCorpus with its original token snapshot.

nlp.tokens(value: TextTagging) -> TextTokens

Return the exact original source token snapshot without normalization, token insertion or row reordering. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. O(1) shared immutable handle.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggingRequiredImmutable aligned TextTagging with its original token snapshot.

nlp.tokens_seen(value: TextTagger) -> Int64

Return cumulative training tokens processed through all completed epochs. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalars are O(1); List export follows returned fields/bytes and the explicit language heap budget.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.

nlp.training_fingerprint(value: TextTagger) -> String

Return the exact annotated fitting identity, including token alignment, source IDs/order/role and gold labels. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalars are O(1); List export follows returned fields/bytes and the explicit language heap budget.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.

nlp.training_hashes(value: TextTagger) -> List

Return raw fitting document hashes in source row order. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalars are O(1); List export follows returned fields/bytes and the explicit language heap budget.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.

nlp.training_ids(value: TextTagger) -> List

Return fitting source IDs in training row order. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalars are O(1); List export follows returned fields/bytes and the explicit language heap budget.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.

nlp.training_tokenizer(value: TextTagger) -> String

Return the exact source tokenization protocol fitted by this model; automatic and explicit spans cannot be substituted at prediction. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalars are O(1); List export follows returned fields/bytes and the explicit language heap budget.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.

nlp.updates(value: TextTagger) -> Int64

Return mistaken sequences that triggered a structured update; this is not the averaging clock. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Scalars are O(1); List export follows returned fields/bytes and the explicit language heap budget.

ArgumentTypeRequired or defaultMeaning and constraints
valueTextTaggerRequiredImmutable trained contextual sequence tagger retaining current weights, averaging state, label order, fitted provenance and cumulative schedule.

nlp.upos_labels() -> List

List the 17 admissible Universal POS annotation spellings. A fitted model only predicts its observed training subset; this inventory does not perform automatic analysis. Requires import aner.nlp. Runtime: Aner 0.0.5 or newer. Immutable bounded CPU state; no model download or hidden random stream. Constant bounded output.

No arguments.

K nearest neighbor classification

Read the model guide.

ml.classes(model: KNNClassifier) -> Tensor

Return sorted distinct fitted class IDs as C × 1 detached CPU Float64 values; this is the predict_proba column mapping.

ArgumentTypeRequired or defaultMeaning and constraints
modelKNNClassifierRequiredRequired. Immutable fitted CPU Float64 KNN classifier retaining detached training features, labels and fitted row order; it does not own a standardizer.

ml.fit_knn(features: Tensor, labels: Tensor, k: Int64) -> KNNClassifier

Fit a uniform Euclidean KNN classifier using native CPU computation and detached Float64 fitting copies. No optimizer, automatic scaling, distance weighting or seed knob is involved; fitting preserves row order for exact distance ties.

ArgumentTypeRequired or defaultMeaning and constraints
featuresTensorRequiredRequired. Finite N × D feature Tensor; CPU fitting copies host values into detached Float64 state (Float32 retains its prior rounding; accelerators may synchronize/download). Fit any standardizer on training rows only; Tensor extraction does not retain Dataset roles or source identity.
labelsTensorRequiredRequired. N × 1 class IDs, exact integers in [0, 9007199254740991]. IDs may be noncontiguous; keep their meaning and fitted row order.
kInt64RequiredRequired. Number of uniformly weighted neighbors, 1..N; no default. Larger k averages more labels. Select k on validation rows, never the final test set. Equal distance neighbors use fitted row index; vote ties choose the smallest class ID.

ml.neighbor_distances(model: KNNClassifier, input: Tensor) -> Tensor

Return Q × k Euclidean distances, not squared distances, in the same order as neighbor_indices(). Training queries may include themselves.

ArgumentTypeRequired or defaultMeaning and constraints
modelKNNClassifierRequiredRequired. Immutable fitted CPU Float64 KNN classifier retaining detached training features, labels and fitted row order; it does not own a standardizer.
inputTensorRequiredRequired. Finite Q × D query Tensor (accelerator storage may synchronize/download for CPU computation) with the fitted feature count/order and the same explicit preprocessing. Prediction does not transform queries automatically.

ml.neighbor_indices(model: KNNClassifier, input: Tensor) -> Tensor

Return Q × k nearest first zero based fitted matrix row indices. Equal distances use fitted row order; map through saved dataset.row_ids yourself for source identities.

ArgumentTypeRequired or defaultMeaning and constraints
modelKNNClassifierRequiredRequired. Immutable fitted CPU Float64 KNN classifier retaining detached training features, labels and fitted row order; it does not own a standardizer.
inputTensorRequiredRequired. Finite Q × D query Tensor (accelerator storage may synchronize/download for CPU computation) with the fitted feature count/order and the same explicit preprocessing. Prediction does not transform queries automatically.

ml.predict(model: KNNClassifier, input: Tensor) -> Tensor

Return Q × 1 original fitted class IDs. Uniform vote ties choose the smallest class ID; probability column indices need not equal class IDs.

ArgumentTypeRequired or defaultMeaning and constraints
modelKNNClassifierRequiredRequired. Immutable fitted CPU Float64 KNN classifier retaining detached training features, labels and fitted row order; it does not own a standardizer.
inputTensorRequiredRequired. Finite Q × D query Tensor (accelerator storage may synchronize/download for CPU computation) with the fitted feature count/order and the same explicit preprocessing. Prediction does not transform queries automatically.

ml.predict_proba(model: KNNClassifier, input: Tensor) -> Tensor

Return Q × C neighbor vote fractions; columns follow sorted classes(). These fractions are not calibrated probability guarantees.

ArgumentTypeRequired or defaultMeaning and constraints
modelKNNClassifierRequiredRequired. Immutable fitted CPU Float64 KNN classifier retaining detached training features, labels and fitted row order; it does not own a standardizer.
inputTensorRequiredRequired. Finite Q × D query Tensor (accelerator storage may synchronize/download for CPU computation) with the fitted feature count/order and the same explicit preprocessing. Prediction does not transform queries automatically.

K means clustering

Read the model guide.

ml.centers(model: KMeansModel) -> Tensor

Return detached k × D fitted centers in cluster index order.

ArgumentTypeRequired or defaultMeaning and constraints
modelKMeansModelRequiredRequired. Immutable fitted CPU Float64 Lloyd K means model retaining centers and fitted row assignments; center indices are arbitrary cluster IDs.

ml.converged(model: KMeansModel) -> Bool

Return true when assignments were unchanged or largest absolute Euclidean center movement was <=tolerance; false when only the iteration cap stopped fitting.

ArgumentTypeRequired or defaultMeaning and constraints
modelKMeansModelRequiredRequired. Immutable fitted CPU Float64 Lloyd K means model retaining centers and fitted row assignments; center indices are arbitrary cluster IDs.

ml.fit_kmeans(features: Tensor, clusters: Int64, max_iterations: Int64, tolerance: Float64, seed: Int64) -> KMeansModel

Fit one seeded Lloyd K means run. Distinct fitting row indices initialize centers; empty clusters keep the previous center. No K means++ or automatic restarts.

ArgumentTypeRequired or defaultMeaning and constraints
featuresTensorRequiredRequired. Finite N × D feature Tensor; CPU fitting copies host values into detached Float64 state (Float32 retains its prior rounding; accelerators may synchronize/download). Fit any standardizer on training rows only; Tensor extraction does not retain Dataset roles or source identity.
clustersInt64RequiredRequired. Requested number k of centers, 1..N; no default. IDs are 0..k−1 and have no class label meaning. Duplicate coordinates may leave fewer than k occupied clusters.
max_iterationsInt64RequiredRequired. Lloyd update cap, 1..1000; no default. A capped run may return converged=false; final assignments and inertia are recomputed against the returned centers.
toleranceFloat64RequiredRequired. Finite absolute maximum Euclidean center movement, >=0; no default. Units follow the supplied feature representation. Zero still permits unchanged assignment stopping.
seedInt64RequiredRequired. Required signed Int64 initialization seed. SplitMix64 selects distinct fitted row indices with unbiased sampling; identical coordinates may still be selected. One run only: no K means++ or automatic restarts.

ml.inertia(model: KMeansModel) -> Float64

Return the sum of squared fitting row distances to final assigned centers. It depends on feature scale and k, and does not alone select a useful model.

ArgumentTypeRequired or defaultMeaning and constraints
modelKMeansModelRequiredRequired. Immutable fitted CPU Float64 Lloyd K means model retaining centers and fitted row assignments; center indices are arbitrary cluster IDs.

ml.iterations(model: KMeansModel) -> Int64

Return completed Lloyd updates, including a final update that met the convergence criterion.

ArgumentTypeRequired or defaultMeaning and constraints
modelKMeansModelRequiredRequired. Immutable fitted CPU Float64 Lloyd K means model retaining centers and fitted row assignments; center indices are arbitrary cluster IDs.

ml.labels(model: KMeansModel) -> Tensor

Return detached N × 1 assignments for fitted rows, recomputed against the returned final centers.

ArgumentTypeRequired or defaultMeaning and constraints
modelKMeansModelRequiredRequired. Immutable fitted CPU Float64 Lloyd K means model retaining centers and fitted row assignments; center indices are arbitrary cluster IDs.

ml.predict(model: KMeansModel, input: Tensor) -> Tensor

Return Q × 1 nearest center indices 0..k−1; distance ties choose the lowest cluster index. Cluster IDs are not class predictions.

ArgumentTypeRequired or defaultMeaning and constraints
modelKMeansModelRequiredRequired. Immutable fitted CPU Float64 Lloyd K means model retaining centers and fitted row assignments; center indices are arbitrary cluster IDs.
inputTensorRequiredRequired. Finite Q × D query Tensor (accelerator storage may synchronize/download for CPU computation) with the fitted feature count/order and the same explicit preprocessing. Prediction does not transform queries automatically.

Decision tree classification

Read the model guide.

ml.classes(model: DecisionTreeClassifier) -> Tensor

Return sorted fitted class IDs, defining the probability column mapping.

ArgumentTypeRequired or defaultMeaning and constraints
modelDecisionTreeClassifierRequiredRequired. Immutable fitted CPU Float64 numeric binary classification tree; preprocessing is explicit and returned probabilities follow sorted class IDs.

ml.depth(model: DecisionTreeClassifier) -> Int64

Return maximum fitted edge depth; a root only tree has depth zero.

ArgumentTypeRequired or defaultMeaning and constraints
modelDecisionTreeClassifierRequiredRequired. Immutable fitted CPU Float64 numeric binary classification tree; preprocessing is explicit and returned probabilities follow sorted class IDs.

ml.export_tree(model: DecisionTreeClassifier, path: String) -> Unit

Write a text, DOT or SVG visualization of the fitted tree to a .txt, .dot or .svg destination.

ArgumentTypeRequired or defaultMeaning and constraints
modelDecisionTreeClassifierRequiredRequired. Immutable fitted CPU Float64 numeric binary classification tree; preprocessing is explicit and returned probabilities follow sorted class IDs.
pathStringRequiredRequired. New .txt, .dot or .svg destination in an existing directory; existing paths are refused. SVG export is standalone and uses no external renderer.

ml.fit_tree(features: Tensor, labels: Tensor, criterion: String = "gini", max_depth: Int64 = 8, min_samples_split: Int64 = 2, min_samples_leaf: Int64 = 1) -> DecisionTreeClassifier

Fit an immutable CPU classification tree with numeric binary splits. Only strictly positive gain splits grow; majority ties choose the smallest class ID.

ArgumentTypeRequired or defaultMeaning and constraints
featuresTensorRequiredRequired. Finite N × D feature Tensor; CPU fitting copies host values into detached Float64 state (Float32 retains its prior rounding; accelerators may synchronize/download). Fit any standardizer on training rows only; Tensor extraction does not retain Dataset roles or source identity.
labelsTensorRequiredRequired. N × 1 class IDs, exact integers in [0, 9007199254740991]. IDs may be noncontiguous; keep their meaning and fitted row order.
criterionString"gini"Optional; defaults to "gini". Numeric binary split score: "gini", "entropy" (information gain), or "gain_ratio". These are criterion inspired trees, not complete historical CART/ID3/C4.5 implementations.
max_depthInt648Optional; defaults to 8. Maximum root to leaf edge depth, 1..64; root depth is 0. Smaller depth limits tree complexity; a dataset can still produce a root only tree.
min_samples_splitInt642Optional; defaults to 2. At least 2 fitting rows are needed to consider a node split. Increasing this threshold prevents small nodes from growing.
min_samples_leafInt641Optional; defaults to 1. At least 1 fitting row must reach each child. Increasing it limits tiny leaves; only positive gain splits grow.

ml.node_count(model: DecisionTreeClassifier) -> Int64

Return total internal nodes plus leaves in the fitted tree.

ArgumentTypeRequired or defaultMeaning and constraints
modelDecisionTreeClassifierRequiredRequired. Immutable fitted CPU Float64 numeric binary classification tree; preprocessing is explicit and returned probabilities follow sorted class IDs.

ml.predict(model: DecisionTreeClassifier, input: Tensor) -> Tensor

Predict each query row's class ID by traversing the fitted tree.

ArgumentTypeRequired or defaultMeaning and constraints
modelDecisionTreeClassifierRequiredRequired. Immutable fitted CPU Float64 numeric binary classification tree; preprocessing is explicit and returned probabilities follow sorted class IDs.
inputTensorRequiredRequired. Finite Q × D query Tensor (accelerator storage may synchronize/download for CPU computation) with the fitted feature count/order and the same explicit preprocessing. Prediction does not transform queries automatically.

ml.predict_proba(model: DecisionTreeClassifier, input: Tensor) -> Tensor

Return leaf class frequencies; probability columns follow sorted ml.classes(model). Frequencies are not calibrated confidence estimates.

ArgumentTypeRequired or defaultMeaning and constraints
modelDecisionTreeClassifierRequiredRequired. Immutable fitted CPU Float64 numeric binary classification tree; preprocessing is explicit and returned probabilities follow sorted class IDs.
inputTensorRequiredRequired. Finite Q × D query Tensor (accelerator storage may synchronize/download for CPU computation) with the fitted feature count/order and the same explicit preprocessing. Prediction does not transform queries automatically.

ml.tree_dot(model: DecisionTreeClassifier) -> String

Return Graphviz DOT source with explicit omitted branches beyond the display limit.

ArgumentTypeRequired or defaultMeaning and constraints
modelDecisionTreeClassifierRequiredRequired. Immutable fitted CPU Float64 numeric binary classification tree; preprocessing is explicit and returned probabilities follow sorted class IDs.

ml.tree_svg(model: DecisionTreeClassifier) -> String

Return a standalone SVG tree image without requiring Graphviz.

ArgumentTypeRequired or defaultMeaning and constraints
modelDecisionTreeClassifierRequiredRequired. Immutable fitted CPU Float64 numeric binary classification tree; preprocessing is explicit and returned probabilities follow sorted class IDs.

ml.tree_text(model: DecisionTreeClassifier) -> String

Describe branch tests and leaf predictions as text, marking branches omitted beyond the 127 node display limit.

ArgumentTypeRequired or defaultMeaning and constraints
modelDecisionTreeClassifierRequiredRequired. Immutable fitted CPU Float64 numeric binary classification tree; preprocessing is explicit and returned probabilities follow sorted class IDs.

Contextual preprocessing and linear regression

Read the model guide.

ml.align_inputs(self: ContextLinearModel, observations: AdaptiveFrame, columns: List) -> AdaptiveFrame

Explicitly map raw external numerical feature columns in fitted order, convert compatible declared units, and retain independent observation IDs. Extra fields are excluded; missing values and ambiguous/incompatible mappings fail. Alignment permits inference only, never fitting. For preprocessing align the first ledger, then apply every fitted stage exactly once. Time O(n p + p c); output space O(n p + N p + p).

ArgumentTypeRequired or defaultMeaning and constraints
selfContextLinearModelRequiredRecognized immutable native receiver; its retained scientific contract is validated.
observationsAdaptiveFrameRequiredExactly the stated native type; named argument and contract are checked.
columnsListRequiredExactly the stated native type; named argument and contract are checked.

ml.align_inputs(self: FeatureLedger, observations: AdaptiveFrame, columns: List) -> AdaptiveFrame

Explicitly map raw external numerical feature columns in fitted order, convert compatible declared units, and retain independent observation IDs. Extra fields are excluded; missing values and ambiguous/incompatible mappings fail. Alignment permits inference only, never fitting. For preprocessing align the first ledger, then apply every fitted stage exactly once. Time O(n p + p c); output space O(n p + N p + p).

ArgumentTypeRequired or defaultMeaning and constraints
selfFeatureLedgerRequiredRecognized immutable native receiver; its retained scientific contract is validated.
observationsAdaptiveFrameRequiredExactly the stated native type; named argument and contract are checked.
columnsListRequiredExactly the stated native type; named argument and contract are checked.

ml.center(self: FeatureLedger) -> Tensor

Copy fitted population centers for inspection into an ordinary CPU Float64 Tensor. Time O(p); output space O(p).

ArgumentTypeRequired or defaultMeaning and constraints
selfFeatureLedgerRequiredRecognized immutable native receiver; its retained scientific contract is validated.

ml.explain(self: ContextLinearModel) -> String

Describe retained native contracts, actual supported storage/backend, roles or source accounting without running a model or reconstructing lost context. Time O(n + p + h) worst case for descriptor traversal; output space O(n + p + h) bounded by native limits.

ArgumentTypeRequired or defaultMeaning and constraints
selfContextLinearModelRequiredRecognized immutable native receiver; its retained scientific contract is validated.

ml.explain(self: ContextPrediction) -> String

Describe retained native contracts, actual supported storage/backend, roles or source accounting without running a model or reconstructing lost context. Time O(n + p + h) worst case for descriptor traversal; output space O(n + p + h) bounded by native limits.

ArgumentTypeRequired or defaultMeaning and constraints
selfContextPredictionRequiredRecognized immutable native receiver; its retained scientific contract is validated.

ml.explain(self: FeatureLedger) -> String

Describe retained native contracts, actual supported storage/backend, roles or source accounting without running a model or reconstructing lost context. Time O(n + p + h) worst case for descriptor traversal; output space O(n + p + h) bounded by native limits.

ArgumentTypeRequired or defaultMeaning and constraints
selfFeatureLedgerRequiredRecognized immutable native receiver; its retained scientific contract is validated.

ml.fit_exploratory_standardizer(data: AdaptiveFrame) -> FeatureLedger

Fit unsplit exploratory statistics and retain every influencing row; later splitting cannot authorize those influences for strict training. Time O(n p + n log n + H); retained fitted space O(p + h), peak workspace O(n p + n + p + h).

ArgumentTypeRequired or defaultMeaning and constraints
dataAdaptiveFrameRequiredExactly the stated native type; named argument and contract are checked.

ml.fit_linear(training: ContextBatch) -> ContextLinearModel

Fit native CPU Float64 intercept least squares with checked two pass QR and exact fit authorization; deficient rank fails without hidden regularization. The resolved execution profile must be CPU Float64; conflicting GPU/Float32 requests raise R3501 E_BACKEND_UNSUPPORTED. Time O(n p squared + n log n + H); solver workspace O(n p + p squared + n + h).

ArgumentTypeRequired or defaultMeaning and constraints
trainingContextBatchRequiredExactly the stated native type; named argument and contract are checked.

ml.fit_standardizer(training: AdaptiveFrame) -> FeatureLedger

Fit population ddof=0 statistics only on the authorized training observations and transitive fit sources. Targets and identity/group roles are excluded; constant scale is one. Time O(n p + n log n + H); retained fitted space O(p + h), peak workspace O(n p + n + p + h).

ArgumentTypeRequired or defaultMeaning and constraints
trainingAdaptiveFrameRequiredExactly the stated native type; named argument and contract are checked.

ml.load_linear(path: String, training_anchor: ContextBatch) -> ContextLinearModel

Validate a bounded regression artifact against a live trusted contextual training batch and recomputed QR fit. The resolved execution profile must be CPU Float64; conflicting GPU/Float32 requests raise R3501 E_BACKEND_UNSUPPORTED. Time O(b + n p squared + n log n + H); additional space O(b + n p + p squared + h).

ArgumentTypeRequired or defaultMeaning and constraints
pathStringRequiredExactly the stated native type; named argument and contract are checked.
training_anchorContextBatchRequiredExactly the stated native type; named argument and contract are checked.

ml.load_standardizer(path: String, training_anchor: AdaptiveFrame) -> FeatureLedger

Validate a bounded artifact against a live trusted training anchor and recomputed parameters; bytes or display IDs never grant a fit scope. Time O(b + n p + n log n + H); additional space O(b + n p + n + p + h).

ArgumentTypeRequired or defaultMeaning and constraints
pathStringRequiredExactly the stated native type; named argument and contract are checked.
training_anchorAdaptiveFrameRequiredExactly the stated native type; named argument and contract are checked.

ml.predict(self: ContextLinearModel, samples: ContextBatch) -> ContextPrediction

Validate ordered feature meaning and exact experiment compatibility, then require the exact ordered preprocessing chain used by training and predict while retaining observation identity and target units. Raw, extra or differently ordered processing fails before output. Independent unlabeled observations require explicit align_inputs against the raw model or first fitted ledger; prediction retains external IDs and the fitted target unit. Missing targets are never fabricated. The resolved execution profile must be CPU Float64; conflicting GPU/Float32 requests raise R3501 E_BACKEND_UNSUPPORTED. Time O(n p + h); output space O(n + h).

ArgumentTypeRequired or defaultMeaning and constraints
selfContextLinearModelRequiredRecognized immutable native receiver; its retained scientific contract is validated.
samplesContextBatchRequiredExactly the stated native type; named argument and contract are checked.

ml.rmse(self: ContextPrediction, targets: ContextBatch) -> Float64

Compute numerical RMSE only for exactly aligned prediction/target observations and matching target meaning. Time O(n + h); auxiliary space O(1) after retained context validation.

ArgumentTypeRequired or defaultMeaning and constraints
selfContextPredictionRequiredRecognized immutable native receiver; its retained scientific contract is validated.
targetsContextBatchRequiredExactly the stated native type; named argument and contract are checked.

ml.row_id(self: ContextPrediction, index: Int64) -> Int64

Inspect the stated native value without granting a new scientific or fitting contract. Bounds and stored type are checked. Time O(1), plus scalar device synchronization when applicable; output and auxiliary space O(1).

ArgumentTypeRequired or defaultMeaning and constraints
selfContextPredictionRequiredRecognized immutable native receiver; its retained scientific contract is validated.
indexInt64RequiredExactly the stated native type; named argument and contract are checked.

ml.row_ids(self: ContextPrediction) -> List

Copy exact Int64 observation IDs in their current order into a managed List; large exports must use row_id(index). Time O(n); output space O(n), subject to managed value slot limits.

ArgumentTypeRequired or defaultMeaning and constraints
selfContextPredictionRequiredRecognized immutable native receiver; its retained scientific contract is validated.

ml.save(self: ContextLinearModel, path: String) -> Unit

Exclusively create a bounded versioned fitted artifact with integrity validation; existing files are not overwritten. Time O(b) for serialized bytes; temporary space O(b), capped at 1 MiB.

ArgumentTypeRequired or defaultMeaning and constraints
selfContextLinearModelRequiredRecognized immutable native receiver; its retained scientific contract is validated.
pathStringRequiredExactly the stated native type; named argument and contract are checked.

ml.save(self: FeatureLedger, path: String) -> Unit

Exclusively create a bounded versioned fitted artifact with integrity validation; existing files are not overwritten. Time O(b) for serialized bytes; temporary space O(b), capped at 1 MiB.

ArgumentTypeRequired or defaultMeaning and constraints
selfFeatureLedgerRequiredRecognized immutable native receiver; its retained scientific contract is validated.
pathStringRequiredExactly the stated native type; named argument and contract are checked.

ml.scale(self: FeatureLedger) -> Tensor

Copy fitted population scales for inspection into an ordinary CPU Float64 Tensor; constant features use one. Time O(p); output space O(p).

ArgumentTypeRequired or defaultMeaning and constraints
selfFeatureLedgerRequiredRecognized immutable native receiver; its retained scientific contract is validated.

ml.summary(self: ContextLinearModel) -> String

Describe retained native contracts, actual supported storage/backend, roles or source accounting without running a model or reconstructing lost context. Time O(n + p + h) worst case for descriptor traversal; output space O(n + p + h) bounded by native limits.

ArgumentTypeRequired or defaultMeaning and constraints
selfContextLinearModelRequiredRecognized immutable native receiver; its retained scientific contract is validated.

ml.summary(self: ContextPrediction) -> String

Describe retained native contracts, actual supported storage/backend, roles or source accounting without running a model or reconstructing lost context. Time O(n + p + h) worst case for descriptor traversal; output space O(n + p + h) bounded by native limits.

ArgumentTypeRequired or defaultMeaning and constraints
selfContextPredictionRequiredRecognized immutable native receiver; its retained scientific contract is validated.

ml.summary(self: FeatureLedger) -> String

Describe retained native contracts, actual supported storage/backend, roles or source accounting without running a model or reconstructing lost context. Time O(n + p + h) worst case for descriptor traversal; output space O(n + p + h) bounded by native limits.

ArgumentTypeRequired or defaultMeaning and constraints
selfFeatureLedgerRequiredRecognized immutable native receiver; its retained scientific contract is validated.

ml.transform(self: FeatureLedger, data: AdaptiveFrame) -> AdaptiveFrame

Apply the fixed ordered fitted statistics without changing population role or raw target; incompatible experiment scopes or applied preprocessing input chains fail. Applying this artifact to its own output fails; at most 64 ordered applied stages are retained. Time expected O(n p + h) with indexed values; output space O(n p + N p + h).

ArgumentTypeRequired or defaultMeaning and constraints
selfFeatureLedgerRequiredRecognized immutable native receiver; its retained scientific contract is validated.
dataAdaptiveFrameRequiredExactly the stated native type; named argument and contract are checked.

ml.unit(self: ContextPrediction) -> String

Inspect the stated native value without granting a new scientific or fitting contract. Bounds and stored type are checked. Time O(1), plus scalar device synchronization when applicable; output and auxiliary space O(1).

ArgumentTypeRequired or defaultMeaning and constraints
selfContextPredictionRequiredRecognized immutable native receiver; its retained scientific contract is validated.

ml.values(self: ContextPrediction) -> SemanticTensor

Return a shared SemanticTensor prediction view with observation and target meaning retained. Time O(n + h) descriptor construction; descriptor space O(n + h), sharing numeric storage.

ArgumentTypeRequired or defaultMeaning and constraints
selfContextPredictionRequiredRecognized immutable native receiver; its retained scientific contract is validated.

Dense neural models

Read the model guide.

ml.accuracy(report: EvaluationReport) -> Float64

Return the fraction correctly classified in an evaluation report.

ArgumentTypeRequired or defaultMeaning and constraints
reportEvaluationReportRequiredClassifier evaluation result.

ml.bias(model: FittedClassifier, layer: Int64) -> Tensor

Copy the trained bias of a zero based Dense layer into a detached Tensor with shape 1 × outputs.

ArgumentTypeRequired or defaultMeaning and constraints
modelFittedClassifierRequiredRequired. Immutable fitted Dense parameters, training fitted scaler, schema, numerical profile and continuation/provenance state.
layerInt64RequiredRequired. Zero based Dense layer index; ReLU/Tanh/Sigmoid/Dropout stages do not increment it. Weights have inputs × outputs shape and bias 1 × outputs.

ml.center(model: FittedClassifier) -> Tensor

Return fitted training feature means, or zeros when standardization was disabled.

ArgumentTypeRequired or defaultMeaning and constraints
modelFittedClassifierRequiredRequired. Immutable fitted Dense parameters, training fitted scaler, schema, numerical profile and continuation/provenance state.

ml.classifier(network: NeuralNetwork, standardize: Bool, loss: String = "cross_entropy", optimizer: String = "sgd") -> ClassifierPipeline

Build an immutable classifier plan from a network ending in Dense. standardize fits feature scaling on training rows only. loss defaults to "cross_entropy"; "mse" averages squared softmax probability errors against one hot targets over rows × classes.

ArgumentTypeRequired or defaultMeaning and constraints
networkNeuralNetworkRequiredRequired. Immutable NeuralNetwork ending in Dense raw logits; input/output widths must match Dataset features/classes.
standardizeBoolRequiredRequired. Required Bool. True fits mean/population-scale only on training rows and reuses that scaler for validation/prediction and warm starts. False leaves features unchanged.
lossString"cross_entropy"Optional; defaults to "cross_entropy". "cross_entropy" averages raw-logit/one-hot cross entropy over rows. "mse" averages squared error between softmax probabilities and one hot targets over rows × classes.
optimizerString"sgd"Optional; defaults to "sgd". "sgd" applies parameter−rate×gradient, without momentum/weight decay. "adam" uses beta1=0.9, beta2=0.999, epsilon=1e 8 and per update bias correction. Matching Adam warm starts restore moments and update count; changing optimizer explicitly resets them.

ml.dropout_seed(pipeline: ClassifierPipeline, seed: Int64) -> ClassifierPipeline

Return an immutable plan with an explicit dropout seed for both full batch and mini batch fitting. Streams advance by cumulative training update and layer. Omission automatically seeds a fresh active dropout fit and records its seed. Warm starts restore the saved seed and counter; a conflicting seed fails.

ArgumentTypeRequired or defaultMeaning and constraints
pipelineClassifierPipelineRequiredRequired. Immutable Dense classifier plan capturing topology, preprocessing, loss, optimizer and execution profile; fit returns an independent snapshot.
seedInt64RequiredRequired. Signed Int64 dropout replay seed, separate from initialization/shuffle. Set once per plan; omission acquires one OS seed for a fresh active dropout fit and records it. A conflicting warm start seed fails.

ml.evaluate(model: FittedClassifier, testing: Dataset) -> EvaluationReport

Evaluate a fitted classifier on a testing dataset using its fitted preprocessing and selected loss.

ArgumentTypeRequired or defaultMeaning and constraints
modelFittedClassifierRequiredRequired. Immutable fitted Dense parameters, training fitted scaler, schema, numerical profile and continuation/provenance state.
testingDatasetRequiredRequired. Held out Dataset with fitted schema. Mini batch evaluation checks source/group history; validation selected rows cannot be relabeled as a final test set.

ml.fit(pipeline: ClassifierPipeline, training: Dataset, config: TrainingConfig, execution: ParallelContext, progress: Bool = false) -> FittedClassifier

Fit eligible Dense models on an explicit strict local neural placement or configured neural replica context. Frozen global mini batches split by positive relative replica weights; Float64 host reduction produces one canonical CPU update in the selected dtype. Canonical parameters and optimizer state also use that dtype. Training roles, disjoint validation/groups and training only normalization remain audited. No model memory pooling or promised speedup. With e epochs, n rows, p parameters, batch b, activation width a and r replicas: numerical work O(e n p), coordinator reduction work O(e ceil(n/b) r p), working space O(r p + b a + b d), plus input staging, source/schedule storage, validation and evaluation. Optional progress observes the same updates.

ArgumentTypeRequired or defaultMeaning and constraints
pipelineClassifierPipelineRequiredRequired. Immutable Dense classifier plan capturing topology, preprocessing, loss, optimizer and execution profile; fit returns an independent snapshot.
trainingDatasetRequiredRequired. Training role or unspecified Dataset only; widths/schema must match the topology. Mini batch fitting checks cumulative training/preprocessing/validation membership before using rows.
configTrainingConfigRequiredRequired. Immutable TrainingConfig defining complete shuffled epochs, batch size, rate, shuffle seed, optional held out validation and final/best-epoch selection.
executionParallelContextRequiredRequired. Explicit strict nn.execution_context or enrolled parallel.cluster replicas. Gradients/loss are sample weighted Float64 host sums with one canonical CPU optimizer. Ordinary local worker contexts are not a neural device.
progressBoolfalseOptional; defaults to false. False by default. True prints bounded measured progress with epoch/loss phase, elapsed time, placement and approximate fixed budget ETA. It does not alter training or dropout masks.

ml.fit(pipeline: ClassifierPipeline, training: Dataset, config: TrainingConfig, progress: Bool = false) -> FittedClassifier

Fit fixed epoch mini batches with resolved precision/device and keyed optimizer state. Training roles and disjoint validation/groups are required; normalization fits training only. Validation evaluation occurs after epochs, with bounded progress/ETA observations. Source remains compact; working tensors are per batch. Time O(e×n×p+e×ceil(n/b)×p), working space O(b×activations+p), plus graph validation and validation passes.

ArgumentTypeRequired or defaultMeaning and constraints
pipelineClassifierPipelineRequiredRequired. Immutable Dense classifier plan capturing topology, preprocessing, loss, optimizer and execution profile; fit returns an independent snapshot.
trainingDatasetRequiredRequired. Training role or unspecified Dataset only; widths/schema must match the topology. Mini batch fitting checks cumulative training/preprocessing/validation membership before using rows.
configTrainingConfigRequiredRequired. Immutable TrainingConfig defining complete shuffled epochs, batch size, rate, shuffle seed, optional held out validation and final/best-epoch selection.
progressBoolfalseOptional; defaults to false. False by default. True prints bounded measured progress with epoch/loss phase, elapsed time, placement and approximate fixed budget ETA. It does not alter training or dropout masks.

ml.fit(pipeline: ClassifierPipeline, training: Dataset, epochs: Int64, rate: Float64, progress: Bool = false) -> FittedClassifier

Train with full batch SGD or Adam, one update per epoch, on the explicitly selected device. The plan resolves requested device and preserve/adapt/fast precision policy before training; CPU and CUDA support Float64/Float32, Metal/MPS Float32. Features, targets, parameters, gradients and Adam moments use the resolved precision after CPU Float64 preprocessing. Returns an immutable fitted model; scaling uses training rows only. For e epochs, b rows, parameter count p and activations a: numerical time O(e b p + e p), working space O(b a + p), plus reachable graph validation per stage. Adam adds two O(p) resident moment buffers. Optional progress records actual dtype/device/backend and at most 64 measurements; fixed horizon ETA begins after five epochs. Notebook output appears after the cell finishes.

ArgumentTypeRequired or defaultMeaning and constraints
pipelineClassifierPipelineRequiredRequired. Immutable Dense classifier plan capturing topology, preprocessing, loss, optimizer and execution profile; fit returns an independent snapshot.
trainingDatasetRequiredRequired. Training role or unspecified Dataset only; widths/schema must match the topology. Mini batch fitting checks cumulative training/preprocessing/validation membership before using rows.
epochsInt64RequiredRequired. Fixed full batch update count in 1..100000. For mini batches, use TrainingConfig; early stopping is not implied.
rateFloat64RequiredRequired. Finite positive learning rate, also representable as positive Float32 under a Float32 profile. The same rate is required to reproduce uninterrupted continuation.
progressBoolfalseOptional; defaults to false. False by default. True prints bounded measured progress with epoch/loss phase, elapsed time, placement and approximate fixed budget ETA. It does not alter training or dropout masks.

ml.initial_loss(model: FittedClassifier) -> Float64

Return the training loss before the first optimizer update, using the classifier loss policy.

ArgumentTypeRequired or defaultMeaning and constraints
modelFittedClassifierRequiredRequired. Immutable fitted Dense parameters, training fitted scaler, schema, numerical profile and continuation/provenance state.

ml.load_classifier(path: String) -> FittedClassifier

Load a validated versioned classifier checkpoint with its architecture, finite trained weights, preprocessing and class schema. Prediction and warm_start use the restored immutable model. Current checkpoints retain Adam moments and update count; version 1 checkpoints restore SGD.

ArgumentTypeRequired or defaultMeaning and constraints
pathStringRequiredRequired. Existing local checkpoint file of the matching model family; bounded validation occurs before reconstruction. Parameters are restored according to the selected supported load profile.

ml.loss(report: EvaluationReport) -> Float64

Return the evaluation loss chosen by ml.classifier: cross entropy averaged over rows, or MSE between softmax probabilities and one hot targets averaged over rows × classes.

ArgumentTypeRequired or defaultMeaning and constraints
reportEvaluationReportRequiredClassifier evaluation result.

ml.on(pipeline: ClassifierPipeline, device: String, precision: String, policy: String) -> ClassifierPipeline

Return an immutable classifier plan with explicit device, requested Float64/Float32 precision and preserve/adapt/fast policy. Preserve keeps precision; adapt lowers only when the selected backend cannot support it; fast intentionally uses Float32, with no speed guarantee. Resolve before training; summaries/checkpoints record requested and effective configuration. Parameters, gradients and Adam moments use effective precision. Time O(1) after bounded initialization; descriptor space O(1).

ArgumentTypeRequired or defaultMeaning and constraints
pipelineClassifierPipelineRequiredRequired. Immutable Dense classifier plan capturing topology, preprocessing, loss, optimizer and execution profile; fit returns an independent snapshot.
deviceStringRequiredRequired. Requested immutable profile: cpu, auto, or a compiled/available cuda/mps backend. Explicit unavailable accelerators fail; changing only device retains requested precision and policy.
precisionStringRequiredRequired. "Float64" or "Float32" request. CPU/CUDA support both; native MPS supports Float32. The policy determines any explicit precision adaptation.
policyStringRequiredRequired. "preserve" retains precision, including reported CPU Float64 fallback for MPS; "adapt" permits required Float32 conversion; "fast" requests Float32 without a speed guarantee.

ml.on(pipeline: ClassifierPipeline, device: String) -> ClassifierPipeline

Return an immutable classifier plan changing requested device while retaining its requested precision and preserve/adapt/fast policy. auto resolves available CUDA, then Metal/MPS, then CPU. An unavailable explicitly requested accelerator fails. Preserve on MPS with Float64 uses reported CPU Float64 fallback; adapt permits MPS Float32. Time O(1) after bounded device initialization; descriptor space O(1).

ArgumentTypeRequired or defaultMeaning and constraints
pipelineClassifierPipelineRequiredRequired. Immutable Dense classifier plan capturing topology, preprocessing, loss, optimizer and execution profile; fit returns an independent snapshot.
deviceStringRequiredRequired. Requested immutable profile: cpu, auto, or a compiled/available cuda/mps backend. Explicit unavailable accelerators fail; changing only device retains requested precision and policy.

ml.predict(model: FittedClassifier, input: Dataset) -> Tensor

Predict class labels or cluster IDs for each input row as an N × 1 tensor.

ArgumentTypeRequired or defaultMeaning and constraints
modelFittedClassifierRequiredRequired. Immutable fitted Dense parameters, training fitted scaler, schema, numerical profile and continuation/provenance state.
inputDatasetRequiredRequired. Dataset with the fitted feature/class schema and feature order. Stored training only preprocessing is reused; returned predictions are detached N × 1 IDs or N × C probabilities.

ml.probabilities(model: FittedClassifier, input: Dataset) -> Tensor

Return per class softmax probabilities for a fitted neural classifier on a dataset.

ArgumentTypeRequired or defaultMeaning and constraints
modelFittedClassifierRequiredRequired. Immutable fitted Dense parameters, training fitted scaler, schema, numerical profile and continuation/provenance state.
inputDatasetRequiredRequired. Dataset with the fitted feature/class schema and feature order. Stored training only preprocessing is reused; returned predictions are detached N × 1 IDs or N × C probabilities.

ml.row_ids(report: EvaluationReport) -> Tensor

Return the exact source row IDs and order used for evaluation.

ArgumentTypeRequired or defaultMeaning and constraints
reportEvaluationReportRequiredClassifier evaluation result.

ml.rows(report: EvaluationReport) -> Int64

Return the evaluated row count.

ArgumentTypeRequired or defaultMeaning and constraints
reportEvaluationReportRequiredClassifier evaluation result.

ml.save(model: FittedClassifier, path: String) -> Unit

Save a bounded versioned finite classifier checkpoint to a new file. An existing path is not overwritten; preprocessing, class schema, architecture, trained parameters, and Adam moments/update count are retained.

ArgumentTypeRequired or defaultMeaning and constraints
modelFittedClassifierRequiredRequired. Immutable fitted Dense parameters, training fitted scaler, schema, numerical profile and continuation/provenance state.
pathStringRequiredRequired. New checkpoint destination in an existing directory; existing files are refused. The owning model family’s versioned numerical/provenance state is saved, without executable source.

ml.scale(model: FittedClassifier) -> Tensor

Return fitted training feature scales, or ones when standardization was disabled.

ArgumentTypeRequired or defaultMeaning and constraints
modelFittedClassifierRequiredRequired. Immutable fitted Dense parameters, training fitted scaler, schema, numerical profile and continuation/provenance state.

ml.select_best(config: TrainingConfig, enabled: Bool) -> TrainingConfig

Choose whether fixed budget training returns the best validation snapshot. Selection uses validation, never official test; checkpoints record selection and optimizer/schedule continuation. O(1) configuration, additional O(p) selected parameter/state snapshot during fitting.

ArgumentTypeRequired or defaultMeaning and constraints
configTrainingConfigRequiredRequired. Immutable fixed epoch mini batch policy; setters return new configurations and never fit or mutate a model.
enabledBoolRequiredRequired. True selects the earliest epoch with lowest post epoch validation loss and requires attached validation. False retains the final epoch. The selected snapshot includes matching moments and dropout progress.

ml.summary(value: ClassifierPipeline) -> String

Describe the classifier topology, initialization, loss, optimizer and preprocessing policy before training.

ArgumentTypeRequired or defaultMeaning and constraints
valueClassifierPipelineRequiredRequired. Immutable Dense classifier plan capturing topology, preprocessing, loss, optimizer and execution profile; fit returns an independent snapshot.

ml.summary(value: EvaluationReport) -> String

Return a readable summary of a fitted classifier or evaluation report.

ArgumentTypeRequired or defaultMeaning and constraints
valueEvaluationReportRequiredClassifier evaluation result.

ml.summary(value: FittedClassifier) -> String

Return a readable summary of a fitted classifier or evaluation report.

ArgumentTypeRequired or defaultMeaning and constraints
valueFittedClassifierRequiredRequired. Immutable fitted Dense parameters, training fitted scaler, schema, numerical profile and continuation/provenance state.

ml.summary(value: NeuralNetwork) -> String

Describe the declared layer topology, seed and initialization; no training occurs.

ArgumentTypeRequired or defaultMeaning and constraints
valueNeuralNetworkRequiredRequired. Immutable Dense topology description; a builder returns a new description, and fitting does not mutate it.

ml.summary(value: TrainingConfig) -> String

Describe fixed epochs, mini batch size, seed, rate and validation/model-selection policy. Bounded descriptor output.

ArgumentTypeRequired or defaultMeaning and constraints
valueTrainingConfigRequiredRequired. Immutable fixed epoch mini batch policy; setters return new configurations and never fit or mutate a model.

ml.training(epochs: Int64, batch: Int64, rate: Float64, seed: Int64) -> TrainingConfig

Build immutable fixed epoch mini batch settings. Epoch schedule seed is seed+completedEpoch; fit uses exactly the Dataset.batches ordering. Source row order, dtype/device, seed, batch size and optimizer state must match for exact continuation. Construction O(1); training O(e×n×p+e×ceil(n/b)×p), numerical memory O(b×activations+p), plus graph validation.

ArgumentTypeRequired or defaultMeaning and constraints
epochsInt64RequiredRequired. Required complete epoch count, 1..100000. Training has a fixed horizon; best epoch selection does not stop the loop early.
batchInt64RequiredRequired. Required batch size, 1..1000000, subject to Tensor/work budgets. Every row is visited once per epoch, including the final partial batch.
rateFloat64RequiredRequired. Required finite positive learning rate; effective Float32 training also requires positive representability in Float32.
seedInt64RequiredRequired. Required signed Int64 shuffle seed; epoch e uses seed+completed_epoch with checked overflow. Continue with unchanged source order, batch size and seed.

ml.training_accuracy(model: FittedClassifier) -> Float64

Return the final training classification accuracy.

ArgumentTypeRequired or defaultMeaning and constraints
modelFittedClassifierRequiredRequired. Immutable fitted Dense parameters, training fitted scaler, schema, numerical profile and continuation/provenance state.

ml.training_loss(model: FittedClassifier) -> Float64

Return the final training loss using the classifier loss policy: row mean cross entropy or softmax probability MSE averaged over rows × classes.

ArgumentTypeRequired or defaultMeaning and constraints
modelFittedClassifierRequiredRequired. Immutable fitted Dense parameters, training fitted scaler, schema, numerical profile and continuation/provenance state.

ml.training_row_ids(model: FittedClassifier) -> Tensor

Return the exact source row IDs and order used to fit the classifier.

ArgumentTypeRequired or defaultMeaning and constraints
modelFittedClassifierRequiredRequired. Immutable fitted Dense parameters, training fitted scaler, schema, numerical profile and continuation/provenance state.

ml.training_seconds(model: FittedClassifier) -> Float64

Return measured wall clock seconds for the latest fit, including preprocessing and final metrics. Timing depends on the machine, backend and recording overhead; it is not a benchmark or a projected ETA. Time O(1); auxiliary space O(1).

ArgumentTypeRequired or defaultMeaning and constraints
modelFittedClassifierRequiredRequired. Immutable fitted Dense parameters, training fitted scaler, schema, numerical profile and continuation/provenance state.

ml.validation(config: TrainingConfig, data: Dataset) -> TrainingConfig

Attach protected validation rows to the training configuration. They are evaluated, never optimized or used to fit normalization; row/group leakage is rejected. O(1) immutable descriptor, audit cost at fit admission.

ArgumentTypeRequired or defaultMeaning and constraints
configTrainingConfigRequiredRequired. Immutable fixed epoch mini batch policy; setters return new configurations and never fit or mutate a model.
dataDatasetRequiredRequired. Validation/unspecified Dataset, disjoint from fitting rows/groups. It supplies held out post epoch metrics only and never gradients or scaler fitting.

ml.warm_start(pipeline: ClassifierPipeline, model: FittedClassifier) -> ClassifierPipeline

Return a classifier plan initialized from an immutable fitted model, retaining its preprocessing and class schema. Topology, loss and scaling policy must match. Fit continues on copied weights, with matching Adam moments and update count preserved; changing optimizer resets its state.

ArgumentTypeRequired or defaultMeaning and constraints
pipelineClassifierPipelineRequiredRequired. Immutable Dense classifier plan capturing topology, preprocessing, loss, optimizer and execution profile; fit returns an independent snapshot.
modelFittedClassifierRequiredRequired. Compatible immutable FittedClassifier to warm start. Topology, probabilities, loss, scaling policy and schema must match; original preprocessing and stochastic progress are retained.

ml.weights(model: FittedClassifier, layer: Int64) -> Tensor

Copy the trained weights of a zero based Dense layer into a detached Tensor with shape inputs × outputs.

ArgumentTypeRequired or defaultMeaning and constraints
modelFittedClassifierRequiredRequired. Immutable fitted Dense parameters, training fitted scaler, schema, numerical profile and continuation/provenance state.
layerInt64RequiredRequired. Zero based Dense layer index; ReLU/Tanh/Sigmoid/Dropout stages do not increment it. Weights have inputs × outputs shape and bias 1 × outputs.

nn.backward(loss: Tensor) -> Unit

Backpropagate from a 1 × 1 loss tensor and populate gradients for its differentiation graph.

ArgumentTypeRequired or defaultMeaning and constraints
lossTensorRequiredRequired. Connected differentiable scalar Tensor of logical size 1 × 1. Backward replaces reachable gradients; it does not accumulate across calls. Build a fresh graph after parameter updates.

nn.cross_entropy(logits: Tensor, targets: Tensor) -> Tensor

Return a differentiable 1 × 1 cross entropy loss, averaged over rows. Supply raw logits and matching constant, exactly one hot target rows.

ArgumentTypeRequired or defaultMeaning and constraints
logitsTensorRequiredRequired. Raw differentiable class score matrix N × C. Stable log sum exp cross entropy averages over rows; do not apply softmax first.
targetsTensorRequiredRequired. Constant exact one hot Tensor with the same N × C shape, dtype and device as logits.

nn.cross_entropy_ids(logits: Tensor, targets: List, ignore_index: Int64) -> Tensor

Stable integer target cross entropy averaged over nonignored positions; native CPU and supported Metal/CUDA sequence execution preserve logical shapes and explicit dtype/device.

ArgumentTypeRequired or defaultMeaning and constraints
logitsTensorRequiredRequired. Raw differentiable class scores with classes on the final logical axis. Leading axes flatten into target positions; native CPU and supported sequence accelerators execute in the selected dtype.
targetsListRequiredRequired. List of exact Int64 class IDs, one per flattened leading logits position. Each ID is 0..classes−1 or exactly ignore_index; IDs never round through a floating point Tensor.
ignore_indexInt64RequiredRequired. Exact Int64 sentinel whose target positions contribute neither loss nor gradient. Average over nonignored positions only; a fully ignored batch is an error.

nn.dense(network: NeuralNetwork, inputs: Int64, outputs: Int64, initialization: String) -> NeuralNetwork

Append a Dense layer with deterministic seeded, Xavier uniform or He uniform initialization and zero bias. No training occurs. Widths must match adjacent stages. Appending copies s stage descriptors: time and output descriptor space O(s), with s capped at 32. Parameter allocation is deferred until fit.

ArgumentTypeRequired or defaultMeaning and constraints
networkNeuralNetworkRequiredRequired. Immutable Dense topology description; a builder returns a new description, and fitting does not mutate it.
inputsInt64RequiredRequired. Positive input width. Adjacent Dense widths must agree; the first width must equal dataset feature count. Tensor and total parameter budgets also apply.
outputsInt64RequiredRequired. Positive output width. Hidden layers choose their own width; the final Dense raw logit width must equal dataset class count.
initializationStringRequiredRequired. "seeded" gives uniform [-0.5,0.5), "xavier" uses ±sqrt(6/(inputs+outputs)), and "he" uses ±sqrt(6/inputs). Biases start at zero; explicit custom tensors use the separate overload.

nn.dense(network: NeuralNetwork, inputs: Int64, outputs: Int64, weights: Tensor, bias: Tensor) -> NeuralNetwork

Append a Dense layer using finite initial weights of shape inputs × outputs and bias of shape 1 × outputs. Inputs are copied and detached; later edits do not change the architecture.

ArgumentTypeRequired or defaultMeaning and constraints
networkNeuralNetworkRequiredRequired. Immutable Dense topology description; a builder returns a new description, and fitting does not mutate it.
inputsInt64RequiredRequired. Positive input width. Adjacent Dense widths must agree; the first width must equal dataset feature count. Tensor and total parameter budgets also apply.
outputsInt64RequiredRequired. Positive output width. Hidden layers choose their own width; the final Dense raw logit width must equal dataset class count.
weightsTensorRequiredRequired. Finite detached Tensor of exact shape inputs × outputs, copied into immutable initialization state. The custom overload has no initialization policy argument.
biasTensorRequiredRequired. Finite detached Tensor of exact shape 1 × outputs. Supplied weights/bias take precedence by choosing the custom overload.

nn.dense(network: NeuralNetwork, inputs: Int64, outputs: Int64) -> NeuralNetwork

Append a fully connected layer and return a new network. inputs must match the preceding stage width. For a classifier, first inputs must match feature count and final outputs must match class count.

ArgumentTypeRequired or defaultMeaning and constraints
networkNeuralNetworkRequiredRequired. Immutable Dense topology description; a builder returns a new description, and fitting does not mutate it.
inputsInt64RequiredRequired. Positive input width. Adjacent Dense widths must agree; the first width must equal dataset feature count. Tensor and total parameter budgets also apply.
outputsInt64RequiredRequired. Positive output width. Hidden layers choose their own width; the final Dense raw logit width must equal dataset class count.

nn.dropout(network: NeuralNetwork, probability: Float64) -> NeuralNetwork

Append training only elementwise inverted dropout. Finite probability in [0,1); 0.2 independently drops each activation with probability 20%, rather than selecting an exact count. Evaluation is identity. Control replay with the classifier dropout_seed; the initialization seed is separate.

ArgumentTypeRequired or defaultMeaning and constraints
networkNeuralNetworkRequiredRequired. Immutable Dense topology description; a builder returns a new description, and fitting does not mutate it.
probabilityFloat64RequiredRequired. Finite probability p in [0,1); 0 is identity. Each training activation is dropped with probability p, not an exact fixed fraction. Retained values/gradients scale by 1/(1−p). Validation and prediction disable it; the classifier plan owns its seed.

nn.dropout(value: Tensor, probability: Float64, seed: Int64, training: Bool) -> Tensor

Seeded inverted dropout with explicit train/eval state, independent of dev/prod. Probability is in [0,1). The same seed reproduces the same mask; change the seed between training calls. Native CPU, Metal and CUDA use the supported tensor precision.

ArgumentTypeRequired or defaultMeaning and constraints
valueTensorRequiredRequired. Input Tensor; the detached sampled mask preserves its logical shape, dtype and device, and backward reuses the same mask.
probabilityFloat64RequiredRequired. Finite p in [0,1); retained activations and gradients scale by 1/(1−p). p=0 is identity.
seedInt64RequiredRequired. Signed Int64 seed for this call local SplitMix64 stream. Repeating seed/probability/shape repeats the same mask; a custom training loop must deliberately advance its seed schedule.
trainingBoolRequiredRequired. Explicit model behavior. True applies the sampled mask; false returns the input. Dev/Prod recording does not change this flag.

nn.grad(value: Tensor) -> Tensor

Read the valid gradient from the most recent successful backward pass as a tensor.

ArgumentTypeRequired or defaultMeaning and constraints
valueTensorRequiredRequired. Tensor reachable from the most recent successful backward pass with a valid recorded gradient. Returns detached gradient values in the original logical shape, dtype and device; stale or missing gradients fail.

nn.mlp(inputs: Int64, hidden: List, outputs: Int64, seed: Int64) -> NeuralNetwork

Build an immutable Dense MLP with Xavier weights, zero biases, ReLU after each hidden Dense, and raw output logits. Hidden widths must be positive Int64 values, such as List(300,100). Dense seed is seed+layer. Time/descriptor space O(layers); parameter initialization occurs during fitting.

ArgumentTypeRequired or defaultMeaning and constraints
inputsInt64RequiredRequired. Positive input width. Adjacent Dense widths must agree; the first width must equal dataset feature count. Tensor and total parameter budgets also apply.
hiddenListRequiredRequired. List of positive Int64 hidden widths. nn.mlp builds Xavier Dense layers with ReLU between hidden layers and final raw logits; no hidden layer is implicit.
outputsInt64RequiredRequired. Positive output width. Hidden layers choose their own width; the final Dense raw logit width must equal dataset class count.
seedInt64RequiredRequired. Required signed Int64 base initialization seed. Dense layer i uses seed+i, checked for overflow; activation and dropout stages do not consume Dense indices.

nn.mse(prediction: Tensor, target: Tensor) -> Tensor

Return a differentiable 1 × 1 mean squared error tensor. Shapes must match; squared differences are averaged over all rows × columns. This function does not apply softmax.

ArgumentTypeRequired or defaultMeaning and constraints
predictionTensorRequiredRequired. Finite differentiable predicted Tensor. Mean squared error averages all cells without applying softmax.
targetTensorRequiredRequired. Tensor of the exact same logical shape, dtype and device as prediction; use detached observed targets.

nn.parameter(value: Tensor) -> Tensor

Create a trainable parameter leaf from tensor values. Use nn.backward before requesting gradients or applying nn.sgd.

ArgumentTypeRequired or defaultMeaning and constraints
valueTensorRequiredRequired. Finite Tensor copied into an independent trainable leaf while preserving logical shape, dtype and device. User classes do not register parameters automatically.

nn.random(rows: Int64, cols: Int64, seed: Int64, scale: Float64) -> Tensor

Create a deterministic rows × cols tensor with uniform values in [-scale, scale).

ArgumentTypeRequired or defaultMeaning and constraints
rowsInt64RequiredRequired. Positive row count; rows×cols must fit the native Tensor element limit.
colsInt64RequiredRequired. Positive column count; rows×cols must fit the native Tensor element limit.
seedInt64RequiredRequired. Signed Int64 call local SplitMix64 seed, converted to its UInt64 bit pattern. Repeating seed and shape restarts the same stream; unrelated calls do not advance it.
scaleFloat64RequiredRequired. Finite nonnegative amplitude; values lie in [-scale,scale). Zero returns zeros; the positive endpoint is excluded, subject to representable value rounding.

nn.relu(value: NeuralNetwork) -> NeuralNetwork

Append a relu activation stage and return a new network.

ArgumentTypeRequired or defaultMeaning and constraints
valueNeuralNetworkRequiredRequired. Immutable Dense topology description; a builder returns a new description, and fitting does not mutate it.

nn.sequential(seed: Int64) -> NeuralNetwork

Create an empty immutable sequential network with a deterministic initialization seed. Append Dense and activation stages before creating a classifier.

ArgumentTypeRequired or defaultMeaning and constraints
seedInt64RequiredRequired. Required signed Int64 base initialization seed. Dense layer i uses seed+i, checked for overflow; activation and dropout stages do not consume Dense indices.

nn.sigmoid(value: NeuralNetwork) -> NeuralNetwork

Append a sigmoid activation stage and return a new network.

ArgumentTypeRequired or defaultMeaning and constraints
valueNeuralNetworkRequiredRequired. Immutable Dense topology description; a builder returns a new description, and fitting does not mutate it.

nn.summary(network: NeuralNetwork) -> String

Describe a network topology, deterministic initialization seed, and explicit initial parameter policy; no training occurs.

ArgumentTypeRequired or defaultMeaning and constraints
networkNeuralNetworkRequiredRequired. Immutable Dense topology description; a builder returns a new description, and fitting does not mutate it.

nn.tanh(value: NeuralNetwork) -> NeuralNetwork

Append a tanh activation stage and return a new network.

ArgumentTypeRequired or defaultMeaning and constraints
valueNeuralNetworkRequiredRequired. Immutable Dense topology description; a builder returns a new description, and fitting does not mutate it.

SGD and Adam

Read the model guide.

nn.clip_grad_norm(parameters: List, max_norm: Float64) -> Float64

Clip the global CPU parameter gradient norm after backward. Tied leaves are counted once; max_norm must be finite and positive. Return the original norm. All parameters are checked before gradients change.

ArgumentTypeRequired or defaultMeaning and constraints
parametersListRequiredRequired. Nonempty List of trainable Tensor leaves with valid gradients. Computes one global norm over distinct leaf identities (duplicate handles count once), then scales their gradients in place; parameter values are unchanged.
max_normFloat64RequiredRequired. Finite strictly positive maximum global gradient norm. Unlike trainer clip_norm=0, this primitive does not accept zero as a disable setting.

nn.optimizer(name: String, rate: Float64) -> Optimizer

Create keyed SGD or Adam state; rate must be finite and positive, representable in actual parameter precision. Adam beta1=.9, beta2=.999, epsilon=1e 8. Initialization O(1); resident moments allocate on first keyed update.

ArgumentTypeRequired or defaultMeaning and constraints
nameStringRequiredRequired. Required exact optimizer name "sgd" or "adam". Adam constants are beta1=0.9, beta2=0.999, epsilon=1e 8; no momentum SGD, scheduler or weight decay is configured here.
rateFloat64RequiredRequired. Required finite positive learning rate. Float32 updates also require a positive Float32 representable rate.

nn.reset(optimizer: Optimizer) -> Unit

Clear all keyed optimizer moments and counters. Existing parameters are unchanged. Time O(keys+p) for releasing retained state.

ArgumentTypeRequired or defaultMeaning and constraints
optimizerOptimizerRequiredRequired. Explicit keyed SGD/Adam state. Handle aliases share per key counters/moments; reset discards that history.

nn.sgd(parameter: Tensor, rate: Float64) -> Tensor

Return a new parameter with value − rate × gradient. The input must be a parameter leaf with a valid gradient from nn.backward. Assign the result back to your parameter for the next step. For p values, time O(p) and output space O(p); the returned leaf does not retain the prior forward graph.

ArgumentTypeRequired or defaultMeaning and constraints
parameterTensorRequiredRequired. Trainable parameter leaf with a valid gradient from the current nn.backward call. Returns a new leaf; assign the result back. No momentum, decay or Adam state is involved.
rateFloat64RequiredRequired. Finite strictly positive learning rate; effective Float32 requires positive representability in Float32. Invalid gradients/rates or nonfinite updates are rejected.

nn.summary(network: Optimizer) -> String

Describe the keyed optimizer algorithm, rate, registered slots, and update counts. Time/output O(keys).

ArgumentTypeRequired or defaultMeaning and constraints
networkOptimizerRequiredRequired. Explicit keyed SGD/Adam state. Handle aliases share per key counters/moments; reset discards that history.

nn.update(optimizer: Optimizer, parameter: Tensor, key: String) -> Tensor

Replace a parameter leaf using its valid gradient; retain the returned Tensor. Each stable nonempty key owns its own step and resident moments; shape, dtype and device must remain consistent. Aliases share optimizer state. Time O(p), additional state O(p); Adam keeps two moment buffers. Failed updates retain prior state.

ArgumentTypeRequired or defaultMeaning and constraints
optimizerOptimizerRequiredRequired. Explicit keyed SGD/Adam state. Handle aliases share per key counters/moments; reset discards that history.
parameterTensorRequiredRequired. Trainable Tensor leaf with a valid gradient from the current nn.backward call. Update returns a new leaf: assign it back; earlier snapshots remain unchanged.
keyStringRequiredRequired. Stable nonempty unique name for this parameter, at most 1024 UTF-8 bytes (not characters), with no NUL. Reuse it only for the same logical shape, dtype and device. Each key retains its own SGD/Adam update count and Adam moments; failed updates leave state unchanged.

Convolutional networks

Read the model guide.

nn.accuracy(model: CNNModel, images: Tensor, targets: Tensor) -> Float64

Measure CNN top 1 accuracy on supplied image and target tensors.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
imagesTensorRequiredRequired. Finite image Tensor with declared NCHW geometry. No automatic image decoding, resizing, normalization or augmentation is performed.
targetsTensorRequiredRequired. Exact zero based class IDs [N,1], or exact one hot targets [N,classes]. They must match image sample count and model class width.

nn.attempts(model: CNNModel) -> Int64

Return attempted optimizer steps, including skipped overflow steps.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.avg_pool2d(model: CNNModel, kernel: Int64 = 2, stride: Int64 = 2, padding: Int64 = 0) -> CNNModel

Apply the native CNN avg pool2d operation with explicit immutable model state and inferred shapes.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
kernelInt642Optional; defaults to 2. Positive square convolution or pool window. Kernel, padding, stride and dilation must produce positive inferred output extents.
strideInt642Optional; defaults to 2. Positive spatial step for a model builder. Model pooling defaults to 2; Tensor pooling has a different zero stride default meaning kernel size.
paddingInt640Optional; defaults to 0. Nonnegative symmetric spatial zero padding; it changes inferred output geometry.

nn.batch_norm(model: CNNModel) -> CNNModel

Apply the native CNN batch norm operation with explicit immutable model state and inferred shapes.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.budget(model: CNNModel, tensor_elements: Int64, graph_elements: Int64) -> CNNModel

Set conservative per call Tensor and differentiation graph element budgets, including convolution workspaces.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
tensor_elementsInt64RequiredRequired. Per-Tensor/workspace ceiling in 1..256000000 elements. Raising a limit does not allocate memory or guarantee available RAM/VRAM.
graph_elementsInt64RequiredRequired. Live graph element ceiling >=tensor_elements and <=2000000000; saved activations and temporary workspaces are also checked.

nn.cnn(channels: Int64, height: Int64, width: Int64, seed: Int64 = 42) -> CNNModel

Declare an immutable CNN with NCHW input geometry. Infer every later layer shape; parameters initialize lazily. Seed defaults to 42.

ArgumentTypeRequired or defaultMeaning and constraints
channelsInt64RequiredRequired. Positive input channel count for images shaped [batch,channels,height,width] (NCHW). Geometry is declared before lazy parameter allocation.
heightInt64RequiredRequired. Positive input image height; subsequent convolution/pooling shapes are checked from this geometry.
widthInt64RequiredRequired. Positive input image width; subsequent convolution/pooling shapes are checked from this geometry.
seedInt6442Optional; defaults to 42. Signed Int64 model initialization or fit shuffle seed, according to this call. Continuation retains model attempt/update and epoch schedule state; keep the fit seed stable for exact replay.

nn.conv2d(model: CNNModel, outputs: Int64, kernel: Int64 = 3, stride: Int64 = 1, padding: Int64 = 0, groups: Int64 = 1, dilation: Int64 = 1) -> CNNModel

Apply grouped or dilated NCHW convolution with OIHW weights, or append a shape inferred CNN convolution. Matching placement and precision are required.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
outputsInt64RequiredRequired. Positive output channels for conv2d, or output features for Dense. Grouped convolution requires input/output channels divisible by groups.
kernelInt643Optional; defaults to 3. Positive square convolution or pool window. Kernel, padding, stride and dilation must produce positive inferred output extents.
strideInt641Optional; defaults to 1. Positive spatial step for a model builder. Model pooling defaults to 2; Tensor pooling has a different zero stride default meaning kernel size.
paddingInt640Optional; defaults to 0. Nonnegative symmetric spatial zero padding; it changes inferred output geometry.
groupsInt641Optional; defaults to 1. Positive group count dividing both input and output channels; grouped/depthwise execution still obeys Tensor/work budgets.
dilationInt641Optional; defaults to 1. Positive kernel spacing factor; effective convolution extent is dilation×(kernel−1)+1.

nn.dense(model: CNNModel, outputs: Int64) -> CNNModel

Apply the native CNN dense operation with explicit immutable model state and inferred shapes.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
outputsInt64RequiredRequired. Positive output channels for conv2d, or output features for Dense. Grouped convolution requires input/output channels divisible by groups.

nn.device(model: CNNModel) -> String

Return the CNN actual selected device.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.diagram(model: CNNModel) -> String

Return the declared CNN architecture as Mermaid without running a forward pass.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.dropout(model: CNNModel, probability: Float64 = 0.5) -> CNNModel

Apply the native CNN dropout operation with explicit immutable model state and inferred shapes.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
probabilityFloat640.5Optional; defaults to 0.5. Finite inverted elementwise dropout probability in [0,1), default 0.5. Fit enables masks; prediction disables them. CNN model/attempt/layer/sample identity owns the random schedule.

nn.dtype(model: CNNModel) -> String

Return the CNN configured compute precision.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.fit(model: CNNModel, images: Tensor, targets: Tensor, epochs: Int64 = 1, batch: Int64 = 32, rate: Float64 = 0.001, seed: Int64 = 42, optimizer: String = "adam") -> CNNModel

Train CNN images using mini batch cross entropy and return an immutable fitted model. Compatible subsequent fits retain optimizer and shuffle state. Targets are zero based [N,1] class IDs or one hot [N,classes].

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
imagesTensorRequiredRequired. Finite image Tensor with declared NCHW geometry. No automatic image decoding, resizing, normalization or augmentation is performed.
targetsTensorRequiredRequired. Exact zero based class IDs [N,1], or exact one hot targets [N,classes]. They must match image sample count and model class width.
epochsInt641Optional; defaults to 1. Fixed complete training passes, 1..100000, subject to native work/update bounds; no automatic early stopping.
batchInt6432Optional; defaults to 32. Positive global mini batch size; partial final batches are retained and replica gradients are sample weighted.
rateFloat640.001Optional; defaults to 0.001. Finite strictly positive learning rate, compatible with effective dtype. Matching Adam continuation retains its bias correction counter and moments.
seedInt6442Optional; defaults to 42. Signed Int64 model initialization or fit shuffle seed, according to this call. Continuation retains model attempt/update and epoch schedule state; keep the fit seed stable for exact replay.
optimizerString"adam"Optional; defaults to "adam". Exact "adam" or "sgd". Matching Adam fits preserve moments/step; selecting a different optimizer is an explicit state reset.

nn.fit(model: CNNModel, images: Tensor, targets: Tensor, epochs: Int64, batch: Int64, rate: Float64, seed: Int64, optimizer: String, execution: ParallelContext) -> CNNModel

Train synchronous CNN replicas through an explicit aner.parallel execution context. Preserve one canonical optimizer update per global batch and reject non frozen BatchNorm running statistics.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
imagesTensorRequiredRequired. Finite image Tensor with declared NCHW geometry. No automatic image decoding, resizing, normalization or augmentation is performed.
targetsTensorRequiredRequired. Exact zero based class IDs [N,1], or exact one hot targets [N,classes]. They must match image sample count and model class width.
epochsInt64RequiredRequired. Fixed complete training passes, 1..100000, subject to native work/update bounds; no automatic early stopping.
batchInt64RequiredRequired. Positive global mini batch size; partial final batches are retained and replica gradients are sample weighted.
rateFloat64RequiredRequired. Finite strictly positive learning rate, compatible with effective dtype. Matching Adam continuation retains its bias correction counter and moments.
seedInt64RequiredRequired. Signed Int64 model initialization or fit shuffle seed, according to this call. Continuation retains model attempt/update and epoch schedule state; keep the fit seed stable for exact replay.
optimizerStringRequiredRequired. Exact "adam" or "sgd". Matching Adam fits preserve moments/step; selecting a different optimizer is an explicit state reset.
executionParallelContextRequiredRequired. Explicit local/cluster execution policy for supported CNN replicas. Placement/precision/collective compatibility is validated; no silent accelerator fallback.

nn.flatten(model: CNNModel) -> CNNModel

Apply the native CNN flatten operation with explicit immutable model state and inferred shapes.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.freeze_backbone(model: CNNModel, frozen: Bool = true) -> CNNModel

Freeze backbone parameters and BatchNorm running statistics for head only transfer learning.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
frozenBooltrueOptional; defaults to true. True freezes the selected backbone or BatchNorm state. Backbone freezing preserves feature parameters and BatchNorm buffers; this does not freeze the classifier head.

nn.freeze_batch_norm(model: CNNModel, frozen: Bool = true) -> CNNModel

Freeze BatchNorm running statistics while retaining trainable affine parameters. Explicitly required for replicated CNN batches.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
frozenBooltrueOptional; defaults to true. True freezes the selected backbone or BatchNorm state. Backbone freezing preserves feature parameters and BatchNorm buffers; this does not freeze the classifier head.

nn.gelu(model: CNNModel) -> CNNModel

Apply the native CNN gelu operation with explicit immutable model state and inferred shapes.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.global_pool(model: CNNModel) -> CNNModel

Apply the native CNN global pool operation with explicit immutable model state and inferred shapes.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.head(model: CNNModel, classes: Int64) -> CNNModel

Append global spatial pooling when needed, then a class projection with raw logits.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
classesInt64RequiredRequired. Positive classification output width. A head replaces/selects the class projection; predictions are zero based class IDs.

nn.last_loss(model: CNNModel) -> Float64

Return the most recently recorded native CNN training loss.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.load_cnn(path: String) -> CNNModel

Restore a native CNN checkpoint for portable inference or resumed training.

ArgumentTypeRequired or defaultMeaning and constraints
pathStringRequiredRequired. Existing local checkpoint file of the matching model family; bounded validation occurs before reconstruction. Parameters are restored according to the selected supported load profile.

nn.load_weights(model: CNNModel, path: String) -> CNNModel

Import exact topology compatible names and shapes from a local Safetensors file.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
pathStringRequiredRequired. Local file path. save exclusively creates a versioned CNN checkpoint; load_cnn reads one; load_weights imports topology compatible named Safetensors; read_images reads exact size raw NCHW data.

nn.logits(model: CNNModel, images: Tensor) -> Tensor

Run native CNN evaluation and return detached [N,classes] logits using saved BatchNorm statistics.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
imagesTensorRequiredRequired. Finite image Tensor with declared NCHW geometry. No automatic image decoding, resizing, normalization or augmentation is performed.

nn.loss_scale(model: CNNModel) -> Float64

Return the retained mixed precision loss scaling factor.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.max_pool2d(model: CNNModel, kernel: Int64 = 2, stride: Int64 = 2, padding: Int64 = 0) -> CNNModel

Apply the native CNN max pool2d operation with explicit immutable model state and inferred shapes.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
kernelInt642Optional; defaults to 2. Positive square convolution or pool window. Kernel, padding, stride and dilation must produce positive inferred output extents.
strideInt642Optional; defaults to 2. Positive spatial step for a model builder. Model pooling defaults to 2; Tensor pooling has a different zero stride default meaning kernel size.
paddingInt640Optional; defaults to 0. Nonnegative symmetric spatial zero padding; it changes inferred output geometry.

nn.on(model: CNNModel, device: String = "auto", precision: String = "Float32") -> CNNModel

Return a CNN with explicit device and precision. Auto selects an available native accelerator; unsupported requests fail with capability diagnostics.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
deviceString"auto"Optional; defaults to "auto". Strict available cpu, cuda, or mps placement; auto prefers CUDA, then MPS, then CPU. Unsupported devices fail explicitly.
precisionString"Float32"Optional; defaults to "Float32". Float32 or Float64 parameter storage. Native MPS requires Float32; CUDA AMP uses Float32 masters with explicit lower precision GEMM operands.

nn.parameter(model: CNNModel, name: String) -> Tensor

Return an independent detached named CNN parameter for inspection.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
nameStringRequiredRequired. Exact parameter name returned by model.parameter_names(); inspection returns a detached Tensor.

nn.parameter_count(model: CNNModel) -> Int64

Return the architecture parameter count without allocating weights.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.parameter_names(model: CNNModel) -> List

List exact named parameters for local weight import and inspection.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.performance(model: CNNModel, amp: String = "off", matmul: String = "strict", collectives: String = "auto") -> CNNModel

Declare explicit CUDA compute and collective policies without allocating weights. AMP uses Float32 parameter/storage with fp16 or bf16 GEMM compute; strict/tf32 controls Float32 GEMM. Unsupported execution fails rather than changing backend. Collective choices are auto, nccl or mpi.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
ampString"off"Optional; defaults to "off". CUDA GEMM policy: "off", "fp16" or "bf16". AMP retains Float32 parameters/moments and validates backend support; fp16 uses retained loss scaling and can skip overflow updates.
matmulString"strict"Optional; defaults to "strict". "strict" or "tf32" Float32 CUDA GEMM compute when AMP is off. This is an explicit numerical policy choice, not a storage dtype.
collectivesString"auto"Optional; defaults to "auto". "auto", "nccl" or "mpi" collective policy for compatible native execution; an unavailable explicitly selected backend fails.

nn.performance_summary(model: CNNModel) -> String

Describe the requested CNN compute/collective policies, loss scaling and optimizer attempt counters.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.predict(model: CNNModel, images: Tensor) -> Tensor

Run CNN evaluation and return zero based predicted class IDs.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
imagesTensorRequiredRequired. Finite image Tensor with declared NCHW geometry. No automatic image decoding, resizing, normalization or augmentation is performed.

nn.prepare(model: CNNModel) -> CNNModel

Initialize a lazy CNN once and return an immutable resident model. Use for repeated inference before training; fitted or loaded models already retain initialized weights.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.probabilities(model: CNNModel, images: Tensor) -> Tensor

Run CNN evaluation and return detached class probabilities.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
imagesTensorRequiredRequired. Finite image Tensor with declared NCHW geometry. No automatic image decoding, resizing, normalization or augmentation is performed.

nn.read_images(model: CNNModel, path: String, samples: Int64) -> Tensor

Read exact size raw little endian NCHW Float32 or Float64 image data under this model's input geometry, precision and Tensor budget. No decoding, resizing, normalization or augmentation occurs.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
pathStringRequiredRequired. Existing exact size raw little endian Float32/Float64 NCHW payload, with model dtype and exactly samples×channels×height×width values. No PNG/JPEG decoding, resizing or normalization.
samplesInt64RequiredRequired. Positive number of raw NCHW samples expected by read_images; exact file size must match geometry and model dtype.

nn.relu(model: CNNModel) -> CNNModel

Apply the native CNN relu operation with explicit immutable model state and inferred shapes.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.save(model: CNNModel, path: String) -> Unit

Exclusively create a versioned native CNN checkpoint preserving architecture, trained parameters, BatchNorm buffers, optimizer and shuffle state.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.
pathStringRequiredRequired. New checkpoint destination in an existing directory; existing files are refused. The owning model family’s versioned numerical/provenance state is saved, without executable source.

nn.skipped_updates(model: CNNModel) -> Int64

Return skipped optimizer updates caused by nonfinite mixed precision gradients.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.summary(model: CNNModel) -> String

Describe CNN topology, parameter count, execution policy and retained training state.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.updates(model: CNNModel) -> Int64

Return the number of optimizer updates retained by this immutable CNN snapshot.

ArgumentTypeRequired or defaultMeaning and constraints
modelCNNModelRequiredRequired. Immutable native CNN topology or resident trained snapshot with NCHW geometry, normalization buffers and optimizer/attempt counters.

nn.vision(architecture: String, classes: Int64 = 1000, seed: Int64 = 42) -> CNNModel

Build a native model zoo architecture with a custom class count. Local weight import is explicit; construction downloads nothing.

ArgumentTypeRequired or defaultMeaning and constraints
architectureStringRequiredRequired. Exact supported model zoo name/alias from nn.architectures(). Construction is local and lazy; no pretrained weights or dataset are downloaded.
classesInt641000Optional; defaults to 1000. Positive classification output width. A head replaces/selects the class projection; predictions are zero based class IDs.
seedInt6442Optional; defaults to 42. Signed Int64 model initialization or fit shuffle seed, according to this call. Continuation retains model attempt/update and epoch schedule state; keep the fit seed stable for exact replay.

Recurrent networks

Read the model guide.

nn.attempts(model: RecurrentModel) -> Int64

Return attempted training updates, including mixed precision overflow skips; this counter is distinct from successful updates().

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.

nn.awd_lstm(vocabulary: Int64, embedding: Int64, hidden: Int64, layers: Int64 = 3, seed: Int64 = 42) -> RecurrentModel

Build a tied embedding vocabulary LSTM with locked dropout and recurrent DropConnect. This architecture does not automate the paper optimizer recipe.

ArgumentTypeRequired or defaultMeaning and constraints
vocabularyInt64RequiredRequired. AWD LSTM vocabulary size 2..65536; input token IDs must be exact integers in [0,vocabulary). Output class IDs share that mapping.
embeddingInt64RequiredRequired. AWD LSTM embedding width 1..8192. Tied input/output embeddings require the native architecture’s matching final projection.
hiddenInt64RequiredRequired. Hidden memory width 1..4096. Wider memory increases per layer parameters and saved sequence workspace; total budgets still apply.
layersInt643Optional; defaults to 3. Stacked recurrent layers, 1..32. Standard RNN/LSTM/GRU/DeepAR default to 1; AWD LSTM defaults to 3. Bidirectionality doubles each standard layer’s directions.
seedInt6442Optional; defaults to 42. Signed Int64 initialization, fit shuffle or forecasting seed according to this call. Model attempts/layers/sample identities derive recurrent dropout streams; preserve fit settings and saved state for replay.

nn.budget(model: RecurrentModel, tensor_elements: Int64, graph_elements: Int64) -> RecurrentModel

Native recurrent operation with explicit immutable state, checked shapes, placement and precision.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.
tensor_elementsInt64RequiredRequired. Positive per-Tensor/workspace ceiling <=256000000; limits remain bounded and do not reserve memory.
graph_elementsInt64RequiredRequired. Live graph element ceiling >=tensor_elements and <=2000000000; sequence length and layer width can exhaust it.

nn.convlstm(channels: Int64, hidden: Int64, outputs: Int64 = 1, kernel: Int64 = 3, seed: Int64 = 42) -> RecurrentModel

Build spatial LSTM gates for [batch,time,channels,height,width] with channel shared peepholes.

ArgumentTypeRequired or defaultMeaning and constraints
channelsInt64RequiredRequired. ConvLSTM input channels, 1..65536; input is [batch,time,channels,height,width], not an ordinary feature matrix.
hiddenInt64RequiredRequired. Hidden memory width 1..4096. Wider memory increases per layer parameters and saved sequence workspace; total budgets still apply.
outputsInt641Optional; defaults to 1. Output width 1..65536. Classification tasks require at least two outputs; task selection determines last step versus per timestep shape.
kernelInt643Optional; defaults to 3. Odd ConvLSTM spatial kernel in 1..31; padded gates preserve spatial extents. Only declared supported geometry/cell combinations execute.
seedInt6442Optional; defaults to 42. Signed Int64 initialization, fit shuffle or forecasting seed according to this call. Model attempts/layers/sample identities derive recurrent dropout streams; preserve fit settings and saved state for replay.

nn.deepar(inputs: Int64, hidden: Int64, outputs: Int64 = 1, layers: Int64 = 1, seed: Int64 = 42) -> RecurrentModel

Build a Gaussian autoregressive LSTM. Pack causal lags and observed indicators with nn.deepar_inputs; pack training targets with nn.deepar_targets.

ArgumentTypeRequired or defaultMeaning and constraints
inputsInt64RequiredRequired. Input feature width 1..65536 for construction; inference/training Tensor uses [batch,time,features], or the matching advanced architecture layout. Padding lengths are separate explicit metadata.
hiddenInt64RequiredRequired. Hidden memory width 1..4096. Wider memory increases per layer parameters and saved sequence workspace; total budgets still apply.
outputsInt641Optional; defaults to 1. Output width 1..65536. Classification tasks require at least two outputs; task selection determines last step versus per timestep shape.
layersInt641Optional; defaults to 1. Stacked recurrent layers, 1..32. Standard RNN/LSTM/GRU/DeepAR default to 1; AWD LSTM defaults to 3. Bidirectionality doubles each standard layer’s directions.
seedInt6442Optional; defaults to 42. Signed Int64 initialization, fit shuffle or forecasting seed according to this call. Model attempts/layers/sample identities derive recurrent dropout streams; preserve fit settings and saved state for replay.

nn.device(model: RecurrentModel) -> String

Native recurrent operation with explicit immutable state, checked shapes, placement and precision.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.

nn.diagram(model: RecurrentModel) -> String

Native recurrent operation with explicit immutable state, checked shapes, placement and precision.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.

nn.dropout(model: RecurrentModel, probability: Float64) -> RecurrentModel

Configure locked training dropout between stacked recurrent layers; reuse a sample’s mask across timesteps. Prediction disables it. This is distinct from Dense elementwise dropout.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.
probabilityFloat64RequiredRequired. Finite probability in [0,1). Recurrent dropout locks a sample’s feature mask across timesteps and applies it between stacked layers; it is not Dense elementwise dropout at every timestep.

nn.dtype(model: RecurrentModel) -> String

Native recurrent operation with explicit immutable state, checked shapes, placement and precision.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.

nn.fit(model: RecurrentModel, inputs: Tensor, targets: Tensor, epochs: Int64 = 1, batch: Int64 = 32, rate: Float64 = 0.001, seed: Int64 = 42, optimizer: String = "adam", clip_norm: Float64 = 1.0, weight_decay: Float64 = 0.0, shuffle: Bool = true, lengths: List = List(), execution: ParallelContext = parallel.local()) -> RecurrentModel

Train an immutable recurrent snapshot with padding masks, global gradient clipping, Adam or SGD, deterministic shuffling and optional aner.parallel execution.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.
inputsTensorRequiredRequired. Input feature width 1..65536 for construction; inference/training Tensor uses [batch,time,features], or the matching advanced architecture layout. Padding lengths are separate explicit metadata.
targetsTensorRequiredRequired. Finite detached task shaped Tensor aligned with input batch/time axes. Classification uses exact class IDs; sequence objectives mask invalid padded timesteps.
epochsInt641Optional; defaults to 1. Fixed complete training passes in 1..100000. A returned immutable model retains compatible optimizer and shuffle continuation state.
batchInt6432Optional; defaults to 32. Positive batch count. For initial_state this fixes detached [batch,hidden] memories; for fit it is global batch size and retains a final partial batch.
rateFloat640.001Optional; defaults to 0.001. Finite positive learning rate representable in effective dtype; parameter updates occur only after valid supervised positions and gradients are checked.
seedInt6442Optional; defaults to 42. Signed Int64 initialization, fit shuffle or forecasting seed according to this call. Model attempts/layers/sample identities derive recurrent dropout streams; preserve fit settings and saved state for replay.
optimizerString"adam"Optional; defaults to "adam". Exact "adam" or "sgd". Matching Adam fits retain moments; switching optimizer resets its optimizer specific history explicitly.
clip_normFloat641.0Optional; defaults to 1.0. Finite nonnegative global parameter gradient norm limit; 0 disables clipping. Clipping acts before the optimizer update.
weight_decayFloat640.0Optional; defaults to 0.0. Finite nonnegative decoupled parameter decay, applied with the learning rate; rate×weight_decay must remain below one.
shuffleBooltrueOptional; defaults to true. True permutes whole samples per saved epoch schedule; it does not shuffle timesteps. fit_chunk processes one ordered batch with an explicit state boundary.
lengthsListList()Optional; defaults to List(). List of one exact Int64 length per sample, each in [1,time]. Empty List() means all timesteps valid. Right padded positions are masked; no automatic length inference.
executionParallelContextparallel.local()Optional; defaults to parallel.local(). Explicit supported parallel execution context; global normalization uses valid sample/timestep targets, including masking, before one canonical update.

nn.fit_chunk(model: RecurrentModel, inputs: Tensor, targets: Tensor, state: RecurrentState, rate: Float64 = 0.001, optimizer: String = "adam", clip_norm: Float64 = 1.0, lengths: List = List()) -> RecurrentModel

Train one whole ordered batch with an explicit detached state boundary for truncated BPTT. The returned immutable model retains final carry and matching optimizer state.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.
inputsTensorRequiredRequired. Input feature width 1..65536 for construction; inference/training Tensor uses [batch,time,features], or the matching advanced architecture layout. Padding lengths are separate explicit metadata.
targetsTensorRequiredRequired. Finite detached task shaped Tensor aligned with input batch/time axes. Classification uses exact class IDs; sequence objectives mask invalid padded timesteps.
stateRecurrentStateRequiredRequired. Detached RecurrentState compatible with cell, layer/direction count, batch, shape, dtype and device. step returns a new final state; fit_chunk cuts gradient history at this explicit boundary.
rateFloat640.001Optional; defaults to 0.001. Finite positive learning rate representable in effective dtype; parameter updates occur only after valid supervised positions and gradients are checked.
optimizerString"adam"Optional; defaults to "adam". Exact "adam" or "sgd". Matching Adam fits retain moments; switching optimizer resets its optimizer specific history explicitly.
clip_normFloat641.0Optional; defaults to 1.0. Finite nonnegative global parameter gradient norm limit; 0 disables clipping. Clipping acts before the optimizer update.
lengthsListList()Optional; defaults to List(). List of one exact Int64 length per sample, each in [1,time]. Empty List() means all timesteps valid. Right padded positions are masked; no automatic length inference.

nn.forecast(model: RecurrentModel, context: Tensor, last_target: Tensor, future_covariates: Tensor, samples: Int64 = 100, seed: Int64 = 42) -> Tensor

Sample Gaussian trajectories autoregressively using each sampled value as its next lag; returns [batch,samples,horizon,outputs].

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.
contextTensorRequiredRequired. DeepAR context Tensor with causal lag/observed/covariate feature layout. Future target values must not enter the context as known inputs.
last_targetTensorRequiredRequired. Last observed target per batch/output, used as the first autoregressive lag; each sampled prediction becomes the next lag.
future_covariatesTensorRequiredRequired. Known future covariates with batch/time alignment; their time extent defines the forecast horizon in this overload.
samplesInt64100Optional; defaults to 100. Positive number of Monte Carlo trajectories per series; this affects forecast workspace and sampling cost, not model fitting.
seedInt6442Optional; defaults to 42. Signed Int64 initialization, fit shuffle or forecasting seed according to this call. Model attempts/layers/sample identities derive recurrent dropout streams; preserve fit settings and saved state for replay.

nn.forecast(model: RecurrentModel, context: Tensor, last_target: Tensor, horizon: Int64, samples: Int64 = 100, seed: Int64 = 42) -> Tensor

Sample Gaussian trajectories autoregressively using each sampled value as its next lag; returns [batch,samples,horizon,outputs].

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.
contextTensorRequiredRequired. DeepAR context Tensor with causal lag/observed/covariate feature layout. Future target values must not enter the context as known inputs.
last_targetTensorRequiredRequired. Last observed target per batch/output, used as the first autoregressive lag; each sampled prediction becomes the next lag.
horizonInt64RequiredRequired. Positive number of autoregressive future steps. Forecast returns [batch,samples,horizon,outputs] and obeys native work budgets.
samplesInt64100Optional; defaults to 100. Positive number of Monte Carlo trajectories per series; this affects forecast workspace and sampling cost, not model fitting.
seedInt6442Optional; defaults to 42. Signed Int64 initialization, fit shuffle or forecasting seed according to this call. Model attempts/layers/sample identities derive recurrent dropout streams; preserve fit settings and saved state for replay.

nn.gru(inputs: Int64, hidden: Int64, outputs: Int64 = 1, layers: Int64 = 1, bidirectional: Bool = false, seed: Int64 = 42) -> RecurrentModel

Build a native batch first GRU with explicit reset/update gates and detached streaming state.

ArgumentTypeRequired or defaultMeaning and constraints
inputsInt64RequiredRequired. Input feature width 1..65536 for construction; inference/training Tensor uses [batch,time,features], or the matching advanced architecture layout. Padding lengths are separate explicit metadata.
hiddenInt64RequiredRequired. Hidden memory width 1..4096. Wider memory increases per layer parameters and saved sequence workspace; total budgets still apply.
outputsInt641Optional; defaults to 1. Output width 1..65536. Classification tasks require at least two outputs; task selection determines last step versus per timestep shape.
layersInt641Optional; defaults to 1. Stacked recurrent layers, 1..32. Standard RNN/LSTM/GRU/DeepAR default to 1; AWD LSTM defaults to 3. Bidirectionality doubles each standard layer’s directions.
bidirectionalBoolfalseOptional; defaults to false. False is causal forward recurrence. True adds a reverse direction and concatenates directional features; it uses future context and is unsuitable for causal streaming forecasts.
seedInt6442Optional; defaults to 42. Signed Int64 initialization, fit shuffle or forecasting seed according to this call. Model attempts/layers/sample identities derive recurrent dropout streams; preserve fit settings and saved state for replay.

nn.initial_state(model: RecurrentModel, batch: Int64) -> RecurrentState

Return zero detached per-layer/direction memories for a declared batch size; ConvLSTM spatial state is inferred by step(input).state().

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.
batchInt64RequiredRequired. Positive batch count. For initial_state this fixes detached [batch,hidden] memories; for fit it is global batch size and retains a final partial batch.

nn.last_loss(model: RecurrentModel) -> Float64

Return the latest retained finite measured recurrent training loss; this is not a held out validation score.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.

nn.load_recurrent(path: String) -> RecurrentModel

Native recurrent operation with explicit immutable state, checked shapes, placement and precision.

ArgumentTypeRequired or defaultMeaning and constraints
pathStringRequiredRequired. Existing local checkpoint file of the matching model family; bounded validation occurs before reconstruction. Parameters are restored according to the selected supported load profile.

nn.logits(model: RecurrentModel, inputs: Tensor, lengths: List = List()) -> Tensor

Return detached task shaped raw output values/scores with reset streaming state; classification probabilities are not applied automatically.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.
inputsTensorRequiredRequired. Input feature width 1..65536 for construction; inference/training Tensor uses [batch,time,features], or the matching advanced architecture layout. Padding lengths are separate explicit metadata.
lengthsListList()Optional; defaults to List(). List of one exact Int64 length per sample, each in [1,time]. Empty List() means all timesteps valid. Right padded positions are masked; no automatic length inference.

nn.loss_scale(model: RecurrentModel) -> Float64

Native recurrent operation with explicit immutable state, checked shapes, placement and precision.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.

nn.lstm(inputs: Int64, hidden: Int64, outputs: Int64 = 1, layers: Int64 = 1, bidirectional: Bool = false, seed: Int64 = 42) -> RecurrentModel

Build a native batch first LSTM with explicit detached streaming state and a positive forget bias.

ArgumentTypeRequired or defaultMeaning and constraints
inputsInt64RequiredRequired. Input feature width 1..65536 for construction; inference/training Tensor uses [batch,time,features], or the matching advanced architecture layout. Padding lengths are separate explicit metadata.
hiddenInt64RequiredRequired. Hidden memory width 1..4096. Wider memory increases per layer parameters and saved sequence workspace; total budgets still apply.
outputsInt641Optional; defaults to 1. Output width 1..65536. Classification tasks require at least two outputs; task selection determines last step versus per timestep shape.
layersInt641Optional; defaults to 1. Stacked recurrent layers, 1..32. Standard RNN/LSTM/GRU/DeepAR default to 1; AWD LSTM defaults to 3. Bidirectionality doubles each standard layer’s directions.
bidirectionalBoolfalseOptional; defaults to false. False is causal forward recurrence. True adds a reverse direction and concatenates directional features; it uses future context and is unsuitable for causal streaming forecasts.
seedInt6442Optional; defaults to 42. Signed Int64 initialization, fit shuffle or forecasting seed according to this call. Model attempts/layers/sample identities derive recurrent dropout streams; preserve fit settings and saved state for replay.

nn.on(model: RecurrentModel, device: String = "auto", precision: String = "Float32") -> RecurrentModel

Native recurrent operation with explicit immutable state, checked shapes, placement and precision.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.
deviceString"auto"Optional; defaults to "auto". Requested available cpu/cuda/mps backend, or auto. Native CUDA may fuse standard RNN/LSTM/GRU cells; unsupported requests fail.
precisionString"Float32"Optional; defaults to "Float32". Requested Float32 or Float64 parameter precision; MPS supports Float32. Preserve semantics do not silently narrow an unsupported request.

nn.parameter(model: RecurrentModel, name: String) -> Tensor

Return a detached copy of the named recurrent parameter; arbitrary automatic field registration is not performed.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.
nameStringRequiredRequired. Exact parameter name from parameter_names(); inspection returns detached values, without automatic parameter replacement.

nn.parameter_count(model: RecurrentModel) -> Int64

Native recurrent operation with explicit immutable state, checked shapes, placement and precision.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.

nn.parameter_names(model: RecurrentModel) -> List

Return exact registered recurrent parameter names for explicit detached inspection.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.

nn.performance(model: RecurrentModel, amp: String = "off", matmul: String = "strict", collectives: String = "auto") -> RecurrentModel

Declare CUDA GEMM AMP and strict/TF32 compute plus MPI/NCCL collective policy. Float32 master weights and moments are retained.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.
ampString"off"Optional; defaults to "off". Explicit CUDA GEMM policy "off", "fp16" or "bf16", with Float32 masters/moments. Unsupported backend/architecture combinations fail.
matmulString"strict"Optional; defaults to "strict". Explicit CUDA Float32 GEMM policy "strict" or "tf32"; it is separate from stored parameter precision.
collectivesString"auto"Optional; defaults to "auto". Native replica reduction policy "auto", "nccl" or "mpi"; explicit unavailable collectives are rejected.

nn.performance_summary(model: RecurrentModel) -> String

Native recurrent operation with explicit immutable state, checked shapes, placement and precision.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.

nn.predict(model: RecurrentModel, inputs: Tensor, lengths: List = List()) -> Tensor

Return detached task shaped regression values or argmax class IDs. Right padding is masked using explicit lengths; prediction starts with reset state.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.
inputsTensorRequiredRequired. Input feature width 1..65536 for construction; inference/training Tensor uses [batch,time,features], or the matching advanced architecture layout. Padding lengths are separate explicit metadata.
lengthsListList()Optional; defaults to List(). List of one exact Int64 length per sample, each in [1,time]. Empty List() means all timesteps valid. Right padded positions are masked; no automatic length inference.

nn.prepare(model: RecurrentModel) -> RecurrentModel

Initialize lazy recurrent parameters once without fitting; repeated inference can reuse the resident immutable model.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.

nn.reset_state(model: RecurrentModel) -> RecurrentModel

Return an immutable model with retained carry cleared; parameters and optimizer history remain intact.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.

nn.rnn(inputs: Int64, hidden: Int64, outputs: Int64 = 1, layers: Int64 = 1, bidirectional: Bool = false, seed: Int64 = 42) -> RecurrentModel

Build a native batch first tanh RNN with fused sequence input projection.

ArgumentTypeRequired or defaultMeaning and constraints
inputsInt64RequiredRequired. Input feature width 1..65536 for construction; inference/training Tensor uses [batch,time,features], or the matching advanced architecture layout. Padding lengths are separate explicit metadata.
hiddenInt64RequiredRequired. Hidden memory width 1..4096. Wider memory increases per layer parameters and saved sequence workspace; total budgets still apply.
outputsInt641Optional; defaults to 1. Output width 1..65536. Classification tasks require at least two outputs; task selection determines last step versus per timestep shape.
layersInt641Optional; defaults to 1. Stacked recurrent layers, 1..32. Standard RNN/LSTM/GRU/DeepAR default to 1; AWD LSTM defaults to 3. Bidirectionality doubles each standard layer’s directions.
bidirectionalBoolfalseOptional; defaults to false. False is causal forward recurrence. True adds a reverse direction and concatenates directional features; it uses future context and is unsuitable for causal streaming forecasts.
seedInt6442Optional; defaults to 42. Signed Int64 initialization, fit shuffle or forecasting seed according to this call. Model attempts/layers/sample identities derive recurrent dropout streams; preserve fit settings and saved state for replay.

nn.save(model: RecurrentModel, path: String) -> Unit

Save versioned weights, optimizer, precision policy, counters and retained state for continuation.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.
pathStringRequiredRequired. New checkpoint destination in an existing directory; existing files are refused. The owning model family’s versioned numerical/provenance state is saved, without executable source.

nn.skipped_updates(model: RecurrentModel) -> Int64

Return mixed precision overflow attempts that did not update model parameters.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.

nn.state(model: RecurrentModel) -> RecurrentState

Return detached retained or final recurrent state.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.

nn.state(result: RecurrentOutput) -> RecurrentState

Return detached retained or final recurrent state.

ArgumentTypeRequired or defaultMeaning and constraints
resultRecurrentOutputRequiredRequired. RecurrentOutput returned by step(): task shaped detached raw values plus detached final recurrent state. values() does not replace raw classification scores with argmax labels.

nn.step(model: RecurrentModel, inputs: Tensor, state: RecurrentState = default, lengths: List = List()) -> RecurrentOutput

Evaluate a sequence using explicit/retained detached state and return values plus a new detached final state; no gradient crosses this boundary.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.
inputsTensorRequiredRequired. Input feature width 1..65536 for construction; inference/training Tensor uses [batch,time,features], or the matching advanced architecture layout. Padding lengths are separate explicit metadata.
stateRecurrentStatedefaultOptional; defaults to default. Detached RecurrentState compatible with cell, layer/direction count, batch, shape, dtype and device. step returns a new final state; fit_chunk cuts gradient history at this explicit boundary.
lengthsListList()Optional; defaults to List(). List of one exact Int64 length per sample, each in [1,time]. Empty List() means all timesteps valid. Right padded positions are masked; no automatic length inference.

nn.summary(model: RecurrentModel) -> String

Native recurrent operation with explicit immutable state, checked shapes, placement and precision.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.

nn.task(model: RecurrentModel, task: String) -> RecurrentModel

Select regression, classification, sequence_regression or sequence_classification with an explicit output contract.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.
taskStringRequiredRequired. One of regression, classification, sequence_regression or sequence_classification. Advanced gaussian/spatial/tokens objectives require their matching DeepAR/ConvLSTM/AWD-LSTM architecture.

nn.updates(model: RecurrentModel) -> Int64

Return successful optimizer updates retained by the recurrent model.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.

nn.values(result: RecurrentOutput) -> Tensor

Return detached task shaped raw recurrent output values. Classification argmax belongs to predict(), not values().

ArgumentTypeRequired or defaultMeaning and constraints
resultRecurrentOutputRequiredRequired. RecurrentOutput returned by step(): task shaped detached raw values plus detached final recurrent state. values() does not replace raw classification scores with argmax labels.

nn.with_state(model: RecurrentModel, state: RecurrentState) -> RecurrentModel

Return a model carrying validated detached recurrent state; cell, layers, directions, batch, dtype and device must agree.

ArgumentTypeRequired or defaultMeaning and constraints
modelRecurrentModelRequiredRequired. Immutable recurrent topology or trained snapshot with task, layers, placement, optimizer/attempt counters and optional detached carry.
stateRecurrentStateRequiredRequired. Detached RecurrentState compatible with cell, layer/direction count, batch, shape, dtype and device. step returns a new final state; fit_chunk cuts gradient history at this explicit boundary.

nn.xlstm(inputs: Int64, hidden: Int64, outputs: Int64 = 1, variant: String = "slstm", layers: Int64 = 1, seed: Int64 = 42) -> RecurrentModel

Build stabilized scalar memory slstm or matrix memory mlstm cells. One memory head; no claim of reproducing the full paper block stack.

ArgumentTypeRequired or defaultMeaning and constraints
inputsInt64RequiredRequired. Input feature width 1..65536 for construction; inference/training Tensor uses [batch,time,features], or the matching advanced architecture layout. Padding lengths are separate explicit metadata.
hiddenInt64RequiredRequired. Hidden memory width 1..4096. Wider memory increases per layer parameters and saved sequence workspace; total budgets still apply.
outputsInt641Optional; defaults to 1. Output width 1..65536. Classification tasks require at least two outputs; task selection determines last step versus per timestep shape.
variantString"slstm"Optional; defaults to "slstm". Exact stabilized xLSTM memory kind "slstm" or "mlstm". These are bounded one head profiles, not the complete paper block stack.
layersInt641Optional; defaults to 1. Stacked recurrent layers, 1..32. Standard RNN/LSTM/GRU/DeepAR default to 1; AWD LSTM defaults to 3. Bidirectionality doubles each standard layer’s directions.
seedInt6442Optional; defaults to 42. Signed Int64 initialization, fit shuffle or forecasting seed according to this call. Model attempts/layers/sample identities derive recurrent dropout streams; preserve fit settings and saved state for replay.

Generative models

Read the model guide.

gen.averaged_parameter(model: ScientificModel, name: String) -> Tensor

Inspect detached inference EMA parameters on a trained EMA configured scientific model. The ordinary parameter getter retains raw optimizer weights; predict_noise(training:true) also uses the raw weights.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
nameStringRequiredRequired. Exact registered scientific parameter name from parameter_names(); averaged_parameter requires retained EMA state.

gen.baseline(model: LanguageModel) -> String

Describe the uniform token baseline using this model's actual tokenizer vocabulary.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.

gen.calibrate_diffusion(model: ScientificModel, training: ScientificData, samples_per_timestep: Int64, seed: Int64, ridge: Float64) -> ScientificModel

Fit a bounded affine epsilon residual correction and reverse covariance on independent forward noise folds from exact bound training records, sampling clean records independently with replacement. Preserves NN weights/optimizer; effective prediction and sampling use the correction while loss remains the raw NN objective.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
trainingScientificDataRequiredRequired. Exact bound training role ScientificData used by this scientific model. Calibration verifies content lineage; held out validation/test observations cannot become calibration inputs.
samples_per_timestepInt64RequiredRequired. Positive calibration draws per diffusion timestep; total regression/covariance work and table dimensions are checked before sampling.
seedInt64RequiredRequired. Signed Int64 initialization, training, calibration or sampling seed according to the operation. Saved training update/cursor state owns continued stochastic schedules.
ridgeFloat64RequiredRequired. Finite ridge coefficient in (0,1] for the bounded diffusion calibration system; it controls numerical regularization, not a guaranteed accuracy improvement.

gen.calibrate_diffusion_gaussian(model: ScientificModel, training: ScientificData) -> ScientificModel

Fit an explicit affine conditional Gaussian closure from bound clean training moments. Exact Gaussian DDPM score, reverse covariance and terminal prior bypass the nonlinear noisy field NN. Preserves raw NN weights/objective for resume; fitted moments and assumptions are checkpointed.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
trainingScientificDataRequiredRequired. Exact bound training role ScientificData used by this scientific model. Calibration verifies content lineage; held out validation/test observations cannot become calibration inputs.

gen.calibrate_diffusion_neural(model: ScientificModel, training: ScientificData, draws: Int64, seed: Int64, strength: Float64) -> ScientificModel

Blend the terminal covariance correction within the learned clean support. Strength must be finite in [0,1]: zero projects into clean support; one retains full moment matching. Smaller values regularize finite data variance correction while retaining mean correction and mass conservation. No general variance improvement guarantee.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
trainingScientificDataRequiredRequired. Exact bound training role ScientificData used by this scientific model. Calibration verifies content lineage; held out validation/test observations cannot become calibration inputs.
drawsInt64RequiredRequired. Positive seeded calibration draw count; calibration requires the model’s exact bound training data and native work limits.
seedInt64RequiredRequired. Signed Int64 initialization, training, calibration or sampling seed according to the operation. Saved training update/cursor state owns continued stochastic schedules.
strengthFloat64RequiredRequired. Finite calibration correction strength in [0,1]. It is a declared experiment setting; preserve it with the seed and calibration lineage.

gen.calibrate_diffusion_neural(model: ScientificModel, training: ScientificData, draws: Int64, seed: Int64) -> ScientificModel

Fit a terminal affine moment transport from bound training fields and independent generated probes. The neural denoiser remains active at every diffusion step; clean covariance support and the mass tangent constrain the transport. Draws repeat the complete training condition design. Calibrates first and second moments; nonlinear distribution shape remains learned by the neural chain.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
trainingScientificDataRequiredRequired. Exact bound training role ScientificData used by this scientific model. Calibration verifies content lineage; held out validation/test observations cannot become calibration inputs.
drawsInt64RequiredRequired. Positive seeded calibration draw count; calibration requires the model’s exact bound training data and native work limits.
seedInt64RequiredRequired. Signed Int64 initialization, training, calibration or sampling seed according to the operation. Saved training update/cursor state owns continued stochastic schedules.

gen.calibrate_diffusion_variance(model: ScientificModel, training: ScientificData, samples_per_timestep: Int64, seed: Int64) -> ScientificModel

Fit bounded reverse Gaussian covariance from frozen denoiser errors on the exact bound training data only; preserves weights and optimizer, stores seed/budget/provenance and is invalidated by further updates.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
trainingScientificDataRequiredRequired. Exact bound training role ScientificData used by this scientific model. Calibration verifies content lineage; held out validation/test observations cannot become calibration inputs.
samples_per_timestepInt64RequiredRequired. Positive calibration draws per diffusion timestep; total regression/covariance work and table dimensions are checked before sampling.
seedInt64RequiredRequired. Signed Int64 initialization, training, calibration or sampling seed according to the operation. Saved training update/cursor state owns continued stochastic schedules.

gen.decoder(codec: Tokenizer, context: Int64, width: Int64, heads: Int64, layers: Int64, seed: Int64, dropout: Float64) -> LanguageModel

Create a configurable pre norm decoder using the selected native execution profile with learned positions, multihead attention, GELU and tied embeddings. Optional dropout defaults to zero.

ArgumentTypeRequired or defaultMeaning and constraints
codecTokenizerRequiredRequired. Native Tokenizer with vocabulary size 259..65536 and stable special IDs. Training/evaluation corpora must use this tokenizer fingerprint.
contextInt64RequiredRequired. Maximum causal sequence length, 1..512. Input and generation context must fit attention/Tensor/work budgets.
widthInt64RequiredRequired. Decoder hidden width 2..256; must be divisible by heads. It controls embeddings, attention projection and feed forward parameters.
headsInt64RequiredRequired. Attention heads, 1..64, dividing width exactly; head width is width/heads.
layersInt64RequiredRequired. Decoder block count, 1..8; total parameters must remain <=1000000 and per call attention/work budgets also apply.
seedInt64RequiredRequired. Signed Int64 seed for initialization, training or sampling according to the operation. Training derives masks from saved update/layer identity; sampling owns a separate explicit stream.
dropoutFloat64RequiredRequired. Finite training only inverted dropout probability in [0,1); omitted constructor overload uses 0. Saved model and training update identities determine the mask sequence.

gen.decoder(codec: Tokenizer, context: Int64, width: Int64, heads: Int64, layers: Int64, seed: Int64) -> LanguageModel

Create a configurable pre norm decoder using the selected native execution profile with learned positions, multihead attention, GELU and tied embeddings. Optional dropout defaults to zero.

ArgumentTypeRequired or defaultMeaning and constraints
codecTokenizerRequiredRequired. Native Tokenizer with vocabulary size 259..65536 and stable special IDs. Training/evaluation corpora must use this tokenizer fingerprint.
contextInt64RequiredRequired. Maximum causal sequence length, 1..512. Input and generation context must fit attention/Tensor/work budgets.
widthInt64RequiredRequired. Decoder hidden width 2..256; must be divisible by heads. It controls embeddings, attention projection and feed forward parameters.
headsInt64RequiredRequired. Attention heads, 1..64, dividing width exactly; head width is width/heads.
layersInt64RequiredRequired. Decoder block count, 1..8; total parameters must remain <=1000000 and per call attention/work budgets also apply.
seedInt64RequiredRequired. Signed Int64 seed for initialization, training or sampling according to the operation. Training derives masks from saved update/layer identity; sampling owns a separate explicit stream.

gen.device(model: LanguageModel) -> String

Return the actual native parameter device.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.

gen.device(model: ScientificModel) -> String

Return actual native scientific parameter placement or precision.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.

gen.diffusion_covariance(model: ScientificModel) -> Tensor

Inspect detached CPU Float64 [steps,interior_sites,interior_sites] reverse covariance, including the mass tangent projection when constrained; bounded to 65 physical interior coordinates and one million elements.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.

gen.diffusion_model(rows: Int64, cols: Int64, condition_size: Int64, width: Int64, diffusion_steps: Int64, beta_start: Float64, beta_end: Float64, seed: Int64) -> ScientificModel

Create a conditional small field epsilon denoiser and DDPM schedule with hard zero Dirichlet boundaries.

ArgumentTypeRequired or defaultMeaning and constraints
rowsInt64RequiredRequired. Diffusion grid rows 3..64; rows×cols must remain <=4096 sites.
colsInt64RequiredRequired. Diffusion grid columns 3..64; rows×cols must remain <=4096 sites.
condition_sizeInt64RequiredRequired. Number of conditioning features, 1..256. Their order/normalization must match across fitting, calibration and sampling.
widthInt64RequiredRequired. Hidden network width 2..256; total parameters and native work/Tensor budgets still constrain valid shapes.
diffusion_stepsInt64RequiredRequired. Diffusion schedule length 2..1000; forward corruption/reverse sampling use the retained schedule.
beta_startFloat64RequiredRequired. Finite starting noise variance with 0 < beta_start <= beta_end <1; schedule coefficients must be representable in effective precision.
beta_endFloat64RequiredRequired. Finite ending noise variance with beta_start <= beta_end <1; it controls the end of the retained diffusion schedule.
seedInt64RequiredRequired. Signed Int64 initialization, training, calibration or sampling seed according to the operation. Saved training update/cursor state owns continued stochastic schedules.

gen.diffusion_variance(model: ScientificModel) -> Tensor

Return detached CPU Float64 [steps,1] mean effective reverse variances: posterior defaults or the trace of the fitted covariance divided by stochastic degrees of freedom.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.

gen.dtype(model: LanguageModel) -> String

Return the actual native parameter precision.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.

gen.dtype(model: ScientificModel) -> String

Return actual native scientific parameter placement or precision.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.

gen.fine_tune(model: LanguageModel, corpus: TokenCorpus, steps: Int64, batch: Int64, rate: Float64, seed: Int64, clip_norm: Float64, warmup_steps: Int64, weight_decay: Float64) -> LanguageModel

Fine tune with a fresh Adam optimizer and explicit clipping, warmup and decay policy; preserve prior document provenance.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
corpusTokenCorpusRequiredRequired. Tokenizer compatible TokenCorpus. train/fine_tune require training role; evaluation checks held out document lineage and tokenizer training overlap.
stepsInt64RequiredRequired. Positive additional optimizer updates; cumulative model steps must remain <=100000. resume restores saved corpus cursor, schedule and optimizer settings.
batchInt64RequiredRequired. Number of sequences per native call, 1..64. Training windows preserve corpus/document boundaries and memory preflight may reject smaller than limit shapes.
rateFloat64RequiredRequired. Finite positive Adam learning rate; unchanged settings and backend are needed for exact continuation.
seedInt64RequiredRequired. Signed Int64 seed for initialization, training or sampling according to the operation. Training derives masks from saved update/layer identity; sampling owns a separate explicit stream.
clip_normFloat64RequiredRequired. Finite nonnegative global gradient norm limit; 0 disables clipping. Default short train overload uses 1.0.
warmup_stepsInt64RequiredRequired. Integer warmup horizon 0..100000; 0 disables warmup. Default short train overload uses 0; scheduling uses retained cumulative updates.
weight_decayFloat64RequiredRequired. Finite nonnegative decoupled Adam weight decay with finite rate×weight_decay <1. Default short train overload uses 0.

gen.fine_tune(model: LanguageModel, corpus: TokenCorpus, steps: Int64, batch: Int64, rate: Float64, seed: Int64) -> LanguageModel

Start a fresh optimizer run on new training data, preserving weights, trainable selection and cumulative lineage. Resume continues the same run.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
corpusTokenCorpusRequiredRequired. Tokenizer compatible TokenCorpus. train/fine_tune require training role; evaluation checks held out document lineage and tokenizer training overlap.
stepsInt64RequiredRequired. Positive additional optimizer updates; cumulative model steps must remain <=100000. resume restores saved corpus cursor, schedule and optimizer settings.
batchInt64RequiredRequired. Number of sequences per native call, 1..64. Training windows preserve corpus/document boundaries and memory preflight may reject smaller than limit shapes.
rateFloat64RequiredRequired. Finite positive Adam learning rate; unchanged settings and backend are needed for exact continuation.
seedInt64RequiredRequired. Signed Int64 seed for initialization, training or sampling according to the operation. Training derives masks from saved update/layer identity; sampling owns a separate explicit stream.

gen.fingerprint(model: LanguageModel) -> String

Return a SHA256 identity covering complete model and continuation state.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.

gen.fingerprint(model: ScientificModel) -> String

Inspect bounded scientific state or its complete canonical SHA256 identity.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.

gen.freeze(model: LanguageModel, names: List) -> LanguageModel

Freeze exact registered names and begin a new run with reset optimizer/counters. Frozen tensors receive no gradients, updates or decay.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
namesListRequiredRequired. Nonempty List of unique exact parameter names selected from parameter_names(). Freeze/unfreeze returns a deliberate training configuration change.

gen.generate(model: LanguageModel, prompt: List, max_new_tokens: Int64, temperature: Float64, top_k: Int64, top_p: Float64, seed: Int64, use_cache: Bool = true) -> List

Return new Int64 IDs, including EOS on termination. Native inference prefills the prompt and reuses call local layer keys/values by default. Set use_cache=false to recompute prefixes. Identical sampling policy and strict context bound; cache state is never saved or shared between requests.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
promptListRequiredRequired. Nonempty List of exact vocabulary IDs within model context. Sampling returns prompt plus generated IDs and stops at EOS or the budget.
max_new_tokensInt64RequiredRequired. Positive generation budget: one Int64 or one exact positive Int64 per prompt in the List overload. Prompt plus usable generated context must fit the declared model context.
temperatureFloat64RequiredRequired. Finite temperature >=0. Zero uses greedy decoding; positive values rescale logits before top-k/top-p selection.
top_kInt64RequiredRequired. Integer 0..vocabulary size; 0 disables top k truncation. Otherwise only the k highest logit candidates remain before sampling.
top_pFloat64RequiredRequired. Finite nucleus probability in (0,1]; 1 disables nucleus truncation. Candidate ordering and logits are part of reproducibility.
seedInt64RequiredRequired. Signed Int64 seed for initialization, training or sampling according to the operation. Training derives masks from saved update/layer identity; sampling owns a separate explicit stream.
use_cacheBooltrueOptional; defaults to true. True reuses call local attention keys/values; false recomputes prefixes as a reference path. The cache is not a checkpoint and is released after the call.

gen.generate_batch(model: LanguageModel, prompts: List, max_new_tokens: Int64, temperature: Float64, top_k: Int64, top_p: Float64, seeds: List, use_cache: Bool = true, cuda_graph: Bool = false) -> List

Return one List of new Int64 IDs per prompt, in input order. Prompts are Lists of Int64; budgets are one per row or a shared Int64; seeds always contain one Int64 per row. Empty prompts use BOS; EOS and each output budget independently stop a row. CUDA cached execution packs active rows with shared weights; CPU/Metal use a portable reference. use_cache=false recomputes prefixes. cuda_graph=true requests bounded CUDA decode replay and requires cached CUDA execution; capture/setup remains part of each request and short decode windows may run eagerly. Strict row context and bounded aggregate KV/work apply.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
promptsListRequiredRequired. List of 1..64 nonempty token ID Lists, each within its context budget. Rows remain in input order.
max_new_tokensInt64RequiredRequired. Positive generation budget: one Int64 or one exact positive Int64 per prompt in the List overload. Prompt plus usable generated context must fit the declared model context.
temperatureFloat64RequiredRequired. Finite temperature >=0. Zero uses greedy decoding; positive values rescale logits before top-k/top-p selection.
top_kInt64RequiredRequired. Integer 0..vocabulary size; 0 disables top k truncation. Otherwise only the k highest logit candidates remain before sampling.
top_pFloat64RequiredRequired. Finite nucleus probability in (0,1]; 1 disables nucleus truncation. Candidate ordering and logits are part of reproducibility.
seedsListRequiredRequired. List of one exact signed Int64 generation seed per prompt, retained by row identity. Do not route seeds through floating point tensors.
use_cacheBooltrueOptional; defaults to true. True reuses call local attention keys/values; false recomputes prefixes as a reference path. The cache is not a checkpoint and is released after the call.
cuda_graphBoolfalseOptional; defaults to false. False by default. True requires use_cache=true with a CUDA model and requests bounded decode replay. CPU, Metal and uncached requests fail. Capture/setup remains part of each request.

gen.generate_batch(model: LanguageModel, prompts: List, max_new_tokens: List, temperature: Float64, top_k: Int64, top_p: Float64, seeds: List, use_cache: Bool = true, cuda_graph: Bool = false) -> List

Return one List of new Int64 IDs per prompt, in input order. Prompts are Lists of Int64; budgets are one per row or a shared Int64; seeds always contain one Int64 per row. Empty prompts use BOS; EOS and each output budget independently stop a row. CUDA cached execution packs active rows with shared weights; CPU/Metal use a portable reference. use_cache=false recomputes prefixes. cuda_graph=true requests bounded CUDA decode replay and requires cached CUDA execution; capture/setup remains part of each request and short decode windows may run eagerly. Strict row context and bounded aggregate KV/work apply.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
promptsListRequiredRequired. List of 1..64 nonempty token ID Lists, each within its context budget. Rows remain in input order.
max_new_tokensListRequiredRequired. Positive generation budget: one Int64 or one exact positive Int64 per prompt in the List overload. Prompt plus usable generated context must fit the declared model context.
temperatureFloat64RequiredRequired. Finite temperature >=0. Zero uses greedy decoding; positive values rescale logits before top-k/top-p selection.
top_kInt64RequiredRequired. Integer 0..vocabulary size; 0 disables top k truncation. Otherwise only the k highest logit candidates remain before sampling.
top_pFloat64RequiredRequired. Finite nucleus probability in (0,1]; 1 disables nucleus truncation. Candidate ordering and logits are part of reproducibility.
seedsListRequiredRequired. List of one exact signed Int64 generation seed per prompt, retained by row identity. Do not route seeds through floating point tensors.
use_cacheBooltrueOptional; defaults to true. True reuses call local attention keys/values; false recomputes prefixes as a reference path. The cache is not a checkpoint and is released after the call.
cuda_graphBoolfalseOptional; defaults to false. False by default. True requires use_cache=true with a CUDA model and requests bounded decode replay. CPU, Metal and uncached requests fail. Capture/setup remains part of each request.

gen.import_gpt2(directory: String, context: Int64) -> LanguageModel

Import the supported bounded GPT2LMHeadModel from local config.json, model.safetensors, vocab.json and merges.txt. Retain a declared position prefix; reject unsupported architecture variants.

ArgumentTypeRequired or defaultMeaning and constraints
directoryStringRequiredRequired. Existing local directory with supported GPT 2 metadata/tokenizer/weights; import performs no network download and validates exact supported architecture and tensor names.
contextInt64RequiredRequired. Maximum causal sequence length, 1..512. Input and generation context must fit attention/Tensor/work budgets.

gen.last_loss(model: LanguageModel) -> Float64

Return the final training batch loss evaluated before its parameter update.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.

gen.last_loss(model: ScientificModel) -> Float64

Return the last scientific training batch loss before its update.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.

gen.load(path: String, device: String) -> LanguageModel

Load complete native checkpoints directly onto a supported requested device. Exact resume requires recorded precision, backend and implementation.

ArgumentTypeRequired or defaultMeaning and constraints
pathStringRequiredRequired. Existing local checkpoint file of the matching model family; bounded validation occurs before reconstruction. Parameters are restored according to the selected supported load profile.
deviceStringRequiredRequired. Strict compiled/available cpu, mps or cuda backend. The complete sequence implementation must exist; unsupported requests do not silently fall back.

gen.load(path: String) -> LanguageModel

Load a validated bounded native checkpoint onto CPU using its saved precision; resume checks the saved CPU backend identity.

ArgumentTypeRequired or defaultMeaning and constraints
pathStringRequiredRequired. Existing local checkpoint file of the matching model family; bounded validation occurs before reconstruction. Parameters are restored according to the selected supported load profile.

gen.load_adapter(base: LanguageModel, path: String) -> LanguageModel

Attach a validated adapter to its exact matching native base. A full model checkpoint is required for exact optimizer resume.

ArgumentTypeRequired or defaultMeaning and constraints
baseLanguageModelRequiredRequired. Compatible unmerged base LanguageModel snapshot whose exact fingerprint must match the LoRA adapter.
pathStringRequiredRequired. Existing local checkpoint file of the matching model family; bounded validation occurs before reconstruction. Parameters are restored according to the selected supported load profile.

gen.load_scientific(path: String, device: String) -> ScientificModel

Load a validated bounded scientific checkpoint onto CPU or an explicitly supported device.

ArgumentTypeRequired or defaultMeaning and constraints
pathStringRequiredRequired. Existing local checkpoint file of the matching model family; bounded validation occurs before reconstruction. Parameters are restored according to the selected supported load profile.
deviceStringRequiredRequired. Strict compiled/available backend supporting the complete scientific operation; unsupported placement fails instead of silently falling back.

gen.load_scientific(path: String) -> ScientificModel

Load a validated bounded scientific checkpoint onto CPU or an explicitly supported device.

ArgumentTypeRequired or defaultMeaning and constraints
pathStringRequiredRequired. Existing local checkpoint file of the matching model family; bounded validation occurs before reconstruction. Parameters are restored according to the selected supported load profile.

gen.logits(model: LanguageModel, ids: List, batch: Int64, length: Int64, training: Bool) -> Tensor

Return native decoder logits; training=true exposes connected parameter gradients for custom objectives, false creates no gradient graph.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
idsListRequiredRequired. List of exact vocabulary Int64 IDs, count batch×length. Each sequence starts with a nonpadding token; IDs and tokenizer mapping must match the model.
batchInt64RequiredRequired. Number of sequences per native call, 1..64. Training windows preserve corpus/document boundaries and memory preflight may reject smaller than limit shapes.
lengthInt64RequiredRequired. Sequence length 1..model context; ids count must equal batch×length. It affects quadratic attention workspace.
trainingBoolRequiredRequired. Explicit forward/memory-estimate mode. True uses training dropout/graph requirements; false uses detached inference behavior. Dev/Prod recording does not choose this mode.

gen.lora(model: LanguageModel, targets: List, rank: Int64, alpha: Float64, seed: Int64) -> LanguageModel

Attach native LoRA factors to named block projections. Freeze the base; effective weight is W + (alpha/rank) A B, initially identical to the base.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
targetsListRequiredRequired. Nonempty exact parameter name List identifying supported projection weights for LoRA; use existing names rather than guessed wildcard patterns.
rankInt64RequiredRequired. Adapter rank in 1..64, also no larger than either selected projection dimension; smaller ranks train fewer adapter parameters, subject to native shape/budget checks.
alphaFloat64RequiredRequired. Finite LoRA scaling coefficient in (0,1000000]; effective adapter contribution uses alpha/rank.
seedInt64RequiredRequired. Signed Int64 seed for initialization, training or sampling according to the operation. Training derives masks from saved update/layer identity; sampling owns a separate explicit stream.

gen.loss(model: LanguageModel, corpus: TokenCorpus) -> Float64

Compute token weighted next token loss, scoring each document transition once. Reject overlap with training documents for held out roles.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
corpusTokenCorpusRequiredRequired. Tokenizer compatible TokenCorpus. train/fine_tune require training role; evaluation checks held out document lineage and tokenizer training overlap.

gen.loss(model: ScientificModel, corpus: ScientificData, seed: Int64) -> Float64

Evaluate teacher forced Gaussian NLL or explicit seed diffusion denoising loss on the declared partition.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
corpusScientificDataRequiredRequired. Training role ScientificData with matching model kind/geometry/conditions; fitting binds its content identity for later resume and calibration.
seedInt64RequiredRequired. Signed Int64 initialization, training, calibration or sampling seed according to the operation. Saved training update/cursor state owns continued stochastic schedules.

gen.loss(model: ScientificModel, corpus: ScientificData) -> Float64

Evaluate teacher forced Gaussian NLL or explicit seed diffusion denoising loss on the declared partition.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
corpusScientificDataRequiredRequired. Training role ScientificData with matching model kind/geometry/conditions; fitting binds its content identity for later resume and calibration.

gen.memory_estimate(model: LanguageModel, batch: Int64, length: Int64, training: Bool) -> Dictionary

Return conservative numeric buffer components, total_bytes, graph_elements, fits and reason. fits checks native tensor/work/graph limits, not physical RAM.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
batchInt64RequiredRequired. Number of sequences per native call, 1..64. Training windows preserve corpus/document boundaries and memory preflight may reject smaller than limit shapes.
lengthInt64RequiredRequired. Sequence length 1..model context; ids count must equal batch×length. It affects quadratic attention workspace.
trainingBoolRequiredRequired. Explicit forward/memory-estimate mode. True uses training dropout/graph requirements; false uses detached inference behavior. Dev/Prod recording does not choose this mode.

gen.memory_summary(model: LanguageModel, batch: Int64, length: Int64, training: Bool) -> String

Explain native weight/gradient/Adam/activation/attention/index/temporary estimates and checked limits.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
batchInt64RequiredRequired. Number of sequences per native call, 1..64. Training windows preserve corpus/document boundaries and memory preflight may reject smaller than limit shapes.
lengthInt64RequiredRequired. Sequence length 1..model context; ids count must equal batch×length. It affects quadratic attention workspace.
trainingBoolRequiredRequired. Explicit forward/memory-estimate mode. True uses training dropout/graph requirements; false uses detached inference behavior. Dev/Prod recording does not choose this mode.

gen.merge_lora(model: LanguageModel) -> LanguageModel

Merge adapter deltas into detached inference weights. Use fine_tune for an explicit new training run.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.

gen.parameter(model: LanguageModel, name: String) -> Tensor

Get a named parameter handle for inspection or custom objectives; frozen weights are detached constants. Tied embeddings have one registered identity.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
nameStringRequiredRequired. Exact parameter key returned by parameter_names(); values must match that parameter’s logical shape.

gen.parameter(model: ScientificModel, name: String) -> Tensor

Inspect a named native scientific parameter for custom objectives and gradient checks.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
nameStringRequiredRequired. Exact registered scientific parameter name from parameter_names(); averaged_parameter requires retained EMA state.

gen.parameter_names(model: LanguageModel) -> List

Native gen.parameter_names accessor; see the generative workflow reference for bounds and contracts.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.

gen.parameter_names(model: ScientificModel) -> List

List native scientific parameter identities.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.

gen.perplexity(model: LanguageModel, corpus: TokenCorpus) -> Float64

Native gen.perplexity accessor; see the generative workflow reference for bounds and contracts.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
corpusTokenCorpusRequiredRequired. Tokenizer compatible TokenCorpus. train/fine_tune require training role; evaluation checks held out document lineage and tokenizer training overlap.

gen.predict_noise(model: ScientificModel, noisy: Tensor, conditions: Tensor, timesteps: List, training: Bool) -> Tensor

Predict epsilon for per record diffusion timesteps 0..steps 1; preserve the native differentiation graph in training mode.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
noisyTensorRequiredRequired. Finite noisy field Tensor with the declared grid width; one matching timestep ID is supplied per row.
conditionsTensorRequiredRequired. Finite condition Tensor with the configured condition feature width and aligned sample order; condition meaning and training fitted transforms must be retained.
timestepsListRequiredRequired. List of exact Int64 diffusion step IDs, one per noisy field, within the model’s schedule.
trainingBoolRequiredRequired. Explicit forward/memory-estimate mode. True uses training graph requirements; false uses detached inference. It does not authorize fitting on held out ScientificData.

gen.predict_series(model: ScientificModel, history: Tensor, conditions: Tensor, training: Bool) -> Tensor

Predict next step conditional means; training=true exposes native parameter gradients.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
historyTensorRequiredRequired. Series look back 1..256 at construction, or a matching finite history Tensor during prediction. History determines the autoregressive model input width.
conditionsTensorRequiredRequired. Finite condition Tensor with the configured condition feature width and aligned sample order; condition meaning and training fitted transforms must be retained.
trainingBoolRequiredRequired. Explicit forward/memory-estimate mode. True uses training graph requirements; false uses detached inference. It does not authorize fitting on held out ScientificData.

gen.resume(model: LanguageModel, corpus: TokenCorpus, steps: Int64) -> LanguageModel

Continue the saved optimizer, dropout and data cursor using the identical training corpus and CPU backend.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
corpusTokenCorpusRequiredRequired. Tokenizer compatible TokenCorpus. train/fine_tune require training role; evaluation checks held out document lineage and tokenizer training overlap.
stepsInt64RequiredRequired. Positive additional optimizer updates; cumulative model steps must remain <=100000. resume restores saved corpus cursor, schedule and optimizer settings.

gen.resume(model: ScientificModel, corpus: ScientificData, steps: Int64) -> ScientificModel

Resume identical scientific data, optimizer policy, sampling streams, execution backend and implementation.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
corpusScientificDataRequiredRequired. Training role ScientificData with matching model kind/geometry/conditions; fitting binds its content identity for later resume and calibration.
stepsInt64RequiredRequired. Positive additional updates; cumulative scientific training steps must stay in 1..100000. resume reuses bound data and retained schedule/settings.

gen.sample_fields(model: ScientificModel, conditions: Tensor, seed: Int64) -> Tensor

Run seeded DDPM sampling with posterior or fitted full reverse covariance and zero Dirichlet edges. A sufficiently noisy terminal schedule is required.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
conditionsTensorRequiredRequired. Finite condition Tensor with the configured condition feature width and aligned sample order; condition meaning and training fitted transforms must be retained.
seedInt64RequiredRequired. Signed Int64 initialization, training, calibration or sampling seed according to the operation. Saved training update/cursor state owns continued stochastic schedules.

gen.sample_series(model: ScientificModel, conditions: Tensor, prefix: Tensor, new_steps: Int64, seed: Int64) -> Tensor

Generate native conditional Gaussian trajectories; returns only new steps, excluding the supplied lag prefix.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
conditionsTensorRequiredRequired. Finite condition Tensor with the configured condition feature width and aligned sample order; condition meaning and training fitted transforms must be retained.
prefixTensorRequiredRequired. Finite series prefix Tensor with at least the configured history length and the declared channel order; the model samples subsequent steps autoregressively.
new_stepsInt64RequiredRequired. Number of new autoregressive series steps in 1..4096, also subject to output Tensor and work budgets.
seedInt64RequiredRequired. Signed Int64 initialization, training, calibration or sampling seed according to the operation. Saved training update/cursor state owns continued stochastic schedules.

gen.save(model: LanguageModel, path: String) -> Unit

Atomically publish a new checksummed checkpoint with architecture, weights, Adam moments, tokenizer identity, lineage, cursor and random stream policy.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
pathStringRequiredRequired. New checkpoint destination in an existing directory; existing files are refused. The owning model family’s versioned numerical/provenance state is saved, without executable source.

gen.save(model: ScientificModel, path: String) -> Unit

Publish a checksummed scientific checkpoint including optimizer, data provenance and noise streams; destination must be new.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
pathStringRequiredRequired. New checkpoint destination in an existing directory; existing files are refused. The owning model family’s versioned numerical/provenance state is saved, without executable source.

gen.save_adapter(model: LanguageModel, path: String) -> Unit

Publish a new checksummed adapter artifact with factors, target shapes, scaling, tokenizer, lineage and exact base weight identity.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
pathStringRequiredRequired. New checkpoint destination in an existing directory; existing files are refused. The owning model family’s versioned numerical/provenance state is saved, without executable source.

gen.scientific_memory(model: ScientificModel, batch: Int64, training: Bool) -> Dictionary

Estimate scientific model numeric buffers and checked native resource admission for a training or prediction batch.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
batchInt64RequiredRequired. Positive scientific training or memory estimate batch size, subject to geometry/Tensor/work bounds.
trainingBoolRequiredRequired. Explicit forward/memory-estimate mode. True uses training graph requirements; false uses detached inference. It does not authorize fitting on held out ScientificData.

gen.series_model(channels: Int64, history: Int64, condition_size: Int64, width: Int64, innovation_sigma: Float64, seed: Int64) -> ScientificModel

Create a conditional native autoregressive MLP mean with explicit fixed Gaussian innovation scale.

ArgumentTypeRequired or defaultMeaning and constraints
channelsInt64RequiredRequired. Series channel count 1..64; targets/history preserve the declared channel order.
historyInt64RequiredRequired. Series look back 1..256 at construction, or a matching finite history Tensor during prediction. History determines the autoregressive model input width.
condition_sizeInt64RequiredRequired. Number of conditioning features, 1..256. Their order/normalization must match across fitting, calibration and sampling.
widthInt64RequiredRequired. Hidden network width 2..256; total parameters and native work/Tensor budgets still constrain valid shapes.
innovation_sigmaFloat64RequiredRequired. Fixed series Gaussian innovation standard deviation, finite and positive, <=1000000, with representable likelihood coefficient; it is not an estimated uncertainty guarantee.
seedInt64RequiredRequired. Signed Int64 initialization, training, calibration or sampling seed according to the operation. Saved training update/cursor state owns continued stochastic schedules.

gen.steps(model: LanguageModel) -> Int64

Native gen.steps accessor; see the generative workflow reference for bounds and contracts.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.

gen.steps(model: ScientificModel) -> Int64

Return scientific optimizer updates or scored training objective rows.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.

gen.summary(model: LanguageModel) -> String

Native gen.summary accessor; see the generative workflow reference for bounds and contracts.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.

gen.summary(model: ScientificModel) -> String

Inspect bounded scientific state or its complete canonical SHA256 identity.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.

gen.to(model: LanguageModel, device: String, dtype: String) -> LanguageModel

Explicitly transfer and/or convert a native model. A changed placement or precision starts a fresh optimizer run; matching requests retain state.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
deviceStringRequiredRequired. Strict compiled/available cpu, mps or cuda backend. The complete sequence implementation must exist; unsupported requests do not silently fall back.
dtypeStringRequiredRequired. Exact Float64 or Float32 storage/compute dtype supported on the requested backend; MPS supports Float32.

gen.to(model: ScientificModel, device: String, dtype: String) -> ScientificModel

Return a scientific model on the declared supported device/dtype while retaining model and optimizer provenance; an identical profile is an operation with no effect and does not reset training.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
deviceStringRequiredRequired. Strict compiled/available backend supporting the complete scientific operation; unsupported placement fails instead of silently falling back.
dtypeStringRequiredRequired. Exact Float64 or Float32 model storage/compute precision supported on the chosen backend.

gen.tokenizer(model: LanguageModel) -> Tokenizer

Recover the exact complete tokenizer stored in a model checkpoint.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.

gen.train(model: LanguageModel, corpus: TokenCorpus, steps: Int64, batch: Int64, rate: Float64, seed: Int64, clip_norm: Float64, warmup_steps: Int64, weight_decay: Float64) -> LanguageModel

Configure global gradient clipping (zero disables), linear warmup and decoupled matrix weight decay. Complete optimizer/data/schedule state is retained for exact resume.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
corpusTokenCorpusRequiredRequired. Tokenizer compatible TokenCorpus. train/fine_tune require training role; evaluation checks held out document lineage and tokenizer training overlap.
stepsInt64RequiredRequired. Positive additional optimizer updates; cumulative model steps must remain <=100000. resume restores saved corpus cursor, schedule and optimizer settings.
batchInt64RequiredRequired. Number of sequences per native call, 1..64. Training windows preserve corpus/document boundaries and memory preflight may reject smaller than limit shapes.
rateFloat64RequiredRequired. Finite positive Adam learning rate; unchanged settings and backend are needed for exact continuation.
seedInt64RequiredRequired. Signed Int64 seed for initialization, training or sampling according to the operation. Training derives masks from saved update/layer identity; sampling owns a separate explicit stream.
clip_normFloat64RequiredRequired. Finite nonnegative global gradient norm limit; 0 disables clipping. Default short train overload uses 1.0.
warmup_stepsInt64RequiredRequired. Integer warmup horizon 0..100000; 0 disables warmup. Default short train overload uses 0; scheduling uses retained cumulative updates.
weight_decayFloat64RequiredRequired. Finite nonnegative decoupled Adam weight decay with finite rate×weight_decay <1. Default short train overload uses 0.

gen.train(model: LanguageModel, corpus: TokenCorpus, steps: Int64, batch: Int64, rate: Float64, seed: Int64) -> LanguageModel

Return a newly trained model with Adam moments and deterministic document window schedule. Only training role data is accepted. Save all state with gen.save.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
corpusTokenCorpusRequiredRequired. Tokenizer compatible TokenCorpus. train/fine_tune require training role; evaluation checks held out document lineage and tokenizer training overlap.
stepsInt64RequiredRequired. Positive additional optimizer updates; cumulative model steps must remain <=100000. resume restores saved corpus cursor, schedule and optimizer settings.
batchInt64RequiredRequired. Number of sequences per native call, 1..64. Training windows preserve corpus/document boundaries and memory preflight may reject smaller than limit shapes.
rateFloat64RequiredRequired. Finite positive Adam learning rate; unchanged settings and backend are needed for exact continuation.
seedInt64RequiredRequired. Signed Int64 seed for initialization, training or sampling according to the operation. Training derives masks from saved update/layer identity; sampling owns a separate explicit stream.

gen.train(model: ScientificModel, corpus: ScientificData, steps: Int64, batch: Int64, rate: Float64, seed: Int64, clip_norm: Float64, warmup_steps: Int64, weight_decay: Float64) -> ScientificModel

Train native scientific objectives with deterministic data/noise streams and complete Adam continuation state.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
corpusScientificDataRequiredRequired. Training role ScientificData with matching model kind/geometry/conditions; fitting binds its content identity for later resume and calibration.
stepsInt64RequiredRequired. Positive additional updates; cumulative scientific training steps must stay in 1..100000. resume reuses bound data and retained schedule/settings.
batchInt64RequiredRequired. Positive scientific training or memory estimate batch size, subject to geometry/Tensor/work bounds.
rateFloat64RequiredRequired. Finite positive Adam learning rate representable in the selected native precision.
seedInt64RequiredRequired. Signed Int64 initialization, training, calibration or sampling seed according to the operation. Saved training update/cursor state owns continued stochastic schedules.
clip_normFloat64RequiredRequired. Finite nonnegative global gradient norm limit; 0 disables clipping. The short training overload uses its documented default.
warmup_stepsInt64RequiredRequired. Nonnegative warmup horizon within the native cumulative step bound; 0 disables warmup.
weight_decayFloat64RequiredRequired. Finite nonnegative decoupled Adam decay; rate×weight_decay must remain finite and below one.

gen.train(model: ScientificModel, corpus: ScientificData, steps: Int64, batch: Int64, rate: Float64, seed: Int64) -> ScientificModel

Train native scientific objectives with deterministic data/noise streams and complete Adam continuation state.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
corpusScientificDataRequiredRequired. Training role ScientificData with matching model kind/geometry/conditions; fitting binds its content identity for later resume and calibration.
stepsInt64RequiredRequired. Positive additional updates; cumulative scientific training steps must stay in 1..100000. resume reuses bound data and retained schedule/settings.
batchInt64RequiredRequired. Positive scientific training or memory estimate batch size, subject to geometry/Tensor/work bounds.
rateFloat64RequiredRequired. Finite positive Adam learning rate representable in the selected native precision.
seedInt64RequiredRequired. Signed Int64 initialization, training, calibration or sampling seed according to the operation. Saved training update/cursor state owns continued stochastic schedules.

gen.trainable_parameters(model: LanguageModel) -> List

List exact trainable parameter names, including active LoRA factors.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.

gen.trained_samples(model: ScientificModel) -> Int64

Return scientific optimizer updates or scored training objective rows.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.

gen.trained_tokens(model: LanguageModel) -> Int64

Native gen.trained_tokens accessor; see the generative workflow reference for bounds and contracts.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.

gen.unfreeze(model: LanguageModel, names: List) -> LanguageModel

Unfreeze exact registered names and begin a new run with reset optimizer/counters. Retain cumulative data provenance.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
namesListRequiredRequired. Nonempty List of unique exact parameter names selected from parameter_names(). Freeze/unfreeze returns a deliberate training configuration change.

gen.with_diffusion_ema(model: ScientificModel, decay: Float64) -> ScientificModel

Configure exponential parameter averaging before diffusion training. Native resident updates average post update weights; inference, generation, and calibration use the average, while optimizer weights and Adam state remain available for exact continuation. Decay must be finite in (0,1) and representable in model precision.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
decayFloat64RequiredRequired. Finite EMA decay strictly between 0 and 1 (also representable there in Float32). Configure before training; averaged weights are a distinct inspected state.

gen.with_diffusion_schedule_features(model: ScientificModel) -> ScientificModel

Configure native schedule aware time inputs before diffusion training: sqrt cumulative alpha, sqrt one minus alpha, and endpoint normalized log SNR. Uses the same three input slots and initialization as legacy fraction/sin/cos features; checkpoints preserve the choice.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.

gen.with_diffusion_sobolev_loss(model: ScientificModel, dx: Float64, dy: Float64, laplacian_weight: Float64) -> ScientificModel

Configure native derivative matching for an untrained diffusion model. A dimensionless Laplacian penalty matches the selected epsilon or velocity denoising errors; zero weight preserves its base loss. Mass and loss geometry must agree.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
dxFloat64RequiredRequired. Finite positive grid spacing along one spatial axis, used by the mass/Sobolev contract. Units must be consistent with the supplied field and conditions.
dyFloat64RequiredRequired. Finite positive grid spacing along the other spatial axis; no unit or coordinate conversion occurs automatically.
laplacian_weightFloat64RequiredRequired. Finite Sobolev Laplacian penalty in [0,1000]. It is part of the objective, not a post hoc evaluation metric.

gen.with_diffusion_velocity_prediction(model: ScientificModel, loss_weighting: String) -> ScientificModel

Select velocity prediction with explicit loss weighting: velocity uses uniform velocity error; epsilon scales velocity error by sqrt(cumulative alpha), retaining epsilon equivalent timestep weighting and native epsilon inference/calibration.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
loss_weightingStringRequiredRequired. Exact velocity training loss weighting "velocity" or "epsilon"; configure an untrained diffusion model.

gen.with_diffusion_velocity_prediction(model: ScientificModel) -> ScientificModel

Configure a native velocity target on an untrained diffusion model. Public predict_noise, covariance calibration and sampling continue to use epsilon; supports optional mass conservation and derivative matching.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.

gen.with_mass_constraint(model: ScientificModel, condition_index: Int64, scale: Float64, offset: Float64, dx: Float64, dy: Float64) -> ScientificModel

Configure an untrained diffusion model with total mass = scale * condition[index] + offset; train and sample in the zero Dirichlet fixed mass subspace.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
condition_indexInt64RequiredRequired. Zero based condition feature containing the declared mass target. Only an untrained diffusion model may add this explicit projection constraint.
scaleFloat64RequiredRequired. Finite mass target multiplier: target mass = scale×selected condition+offset. Coefficients must remain representable in effective precision.
offsetFloat64RequiredRequired. Finite additive mass target offset; together with scale and geometry it defines the explicit physical projection target.
dxFloat64RequiredRequired. Finite positive grid spacing along one spatial axis, used by the mass/Sobolev contract. Units must be consistent with the supplied field and conditions.
dyFloat64RequiredRequired. Finite positive grid spacing along the other spatial axis; no unit or coordinate conversion occurs automatically.

gen.with_parameter(model: LanguageModel, name: String, value: Tensor) -> LanguageModel

Replace a matching CPU Float64 initialization tensor before training; trained optimizer state is never silently reset.

ArgumentTypeRequired or defaultMeaning and constraints
modelLanguageModelRequiredRequired. Native causal decoder snapshot with its tokenizer, parameters, optimizer state, data lineage and deterministic update/sampling schedules.
nameStringRequiredRequired. Exact parameter key returned by parameter_names(); values must match that parameter’s logical shape.
valueTensorRequiredRequired. Finite detached replacement initialization Tensor with exact parameter shape, dtype and device. Replacing trained state is rejected.

gen.with_parameter(model: ScientificModel, name: String, value: Tensor) -> ScientificModel

Replace a shape/device/precision-matching scientific initialization before training.

ArgumentTypeRequired or defaultMeaning and constraints
modelScientificModelRequiredRequired. Native conditional series or field diffusion snapshot with geometry, conditions, parameters and bound training/calibration provenance.
nameStringRequiredRequired. Exact registered scientific parameter name from parameter_names(); averaged_parameter requires retained EMA state.
valueTensorRequiredRequired. Finite detached initialization Tensor matching the named parameter’s shape, dtype and device; editing already trained state is rejected.

Evaluation metrics

Read the model guide.

metrics.accuracy(predicted: Tensor, actual: Tensor) -> Float64

Return the fraction of matching labels from predicted and actual N × 1 tensors.

ArgumentTypeRequired or defaultMeaning and constraints
predictedTensorRequiredPredicted labels as an N × 1 tensor.
actualTensorRequiredTrue labels as an N × 1 tensor.

metrics.adjusted_rand_index(predicted: Tensor, actual: Tensor) -> Float64

Compare cluster assignments against actual labels with the adjusted Rand index. Inputs are matching N × 1 label tensors.

ArgumentTypeRequired or defaultMeaning and constraints
predictedTensorRequiredPredicted cluster IDs as an N × 1 tensor.
actualTensorRequiredReference labels as an N × 1 tensor.

metrics.confusion_matrix(predicted: Tensor, actual: Tensor, classes: Int64) -> Tensor

Count classification outcomes in a classes × classes matrix, with actual labels as rows and predicted labels as columns.

ArgumentTypeRequired or defaultMeaning and constraints
predictedTensorRequiredPredicted class IDs as an N × 1 tensor.
actualTensorRequiredTrue class IDs as an N × 1 tensor.
classesInt64RequiredNumber of classes; every class ID must be less than this value.

metrics.mean_squared_error(predicted: Tensor, actual: Tensor) -> Float64

Return mean squared error across all elements of two tensors with matching shapes as a Float64.

ArgumentTypeRequired or defaultMeaning and constraints
predictedTensorRequiredPredicted numeric values.
actualTensorRequiredActual values with the same tensor shape as predicted.
Aner documentation · Reference and guides