|
Mila
Deep Neural Network Library
|
Public Types | |
| using | Base = Model<TDeviceType, TPrecision> |
| Public Types inherited from Mila::Dnn::Model< TDeviceType, TPrecision > | |
| using | NetworkType = Network<TDeviceType, TPrecision> |
Public Member Functions | |
| LanguageModel (const LanguageModel &)=delete | |
| LanguageModel (LanguageModel &&)=default | |
| GenerateStatus | generate (std::span< const int32_t > prompt_tokens, const std::function< void(int32_t)> &on_token, const GenerateParams ¶ms={}, std::stop_token stop={}) |
| Generate tokens from a prompt, streaming each through on_token. | |
| LanguageModel & | operator= (const LanguageModel &)=delete |
| LanguageModel & | operator= (LanguageModel &&)=default |
| void | savePretrained (const std::filesystem::path &path) const |
| Write this model's live weights as a safetensors artifact. | |
| void | seedSampler (uint64_t seed) |
| Seed the sampler's RNG for reproducible generation. | |
| Public Member Functions inherited from Mila::Dnn::Model< TDeviceType, TPrecision > | |
| Model (const Model &)=delete | |
| Model (Model &&)=default | |
| DeviceId | getDeviceId () const noexcept |
| The device this model runs on. | |
| MemoryStats | getMemoryStats () const |
| Current memory allocation breakdown for this model. | |
| RuntimeMode | getRuntimeMode () const noexcept |
| The runtime mode this model was constructed for. | |
| std::size_t | getScratchHighWaterBytes () const |
| Context-owned scratch device memory, in bytes, at its high-water mark. | |
| bool | isEval () const noexcept |
| True if this model is currently in eval sub-state. | |
| bool | isInferenceMode () const noexcept |
| True if this model was constructed for inference. | |
| bool | isTrainingMode () const noexcept |
| True if this model was constructed for training. | |
| Model & | operator= (const Model &)=delete |
| Model & | operator= (Model &&)=default |
| void | setEval (bool eval) |
| Toggle eval sub-state for this model. | |
| virtual std::string | toString () const =0 |
| Human-readable summary of this model's configuration. | |
| void | train () |
| Run the training loop for this model. | |
Protected Types | |
| using | MR = typename DeviceTypeTraits<TDeviceType>::memory_resource |
| using | TensorType = Tensor<TPrecision, MR> |
| using | TokenTensor = Tensor<TensorDataType::INT32, MR> |
Protected Member Functions | |
| LanguageModel (std::unique_ptr< LanguageNetwork< TDeviceType, TPrecision > > network, RuntimeMode runtime_mode, Serialization::PretrainedMetadata source_metadata={}, WeightQuantization weight_quantization=WeightQuantization::None) | |
| int32_t | awaitSampledToken () |
| Block until the last enqueueSampleNext()'s token id is host-visible. | |
| void | enqueueSampleNext (const TensorType &logits, TokenTensor &token_out, const SamplingParams ¶ms) |
| Enqueue a sampling step without waiting for the host readback. | |
| virtual int32_t | eosToken () const noexcept=0 |
| virtual float | finalLogitSoftcap () const noexcept |
| Optional final-logit softcap the sampler applies (0 disables). | |
| const LanguageNetwork< TDeviceType, TPrecision > & | getLanguageNetwork () const noexcept |
| LanguageNetwork< TDeviceType, TPrecision > & | getLanguageNetwork () noexcept |
| virtual dim_t | maxSequenceLength () const noexcept=0 |
| virtual GenerateStatus | onGenerating (std::span< const int32_t > prompt_tokens, const std::function< void(int32_t)> &on_token, const GenerateParams ¶ms, std::stop_token stop)=0 |
| Prefill + decode implementation hook. | |
| int32_t | sampleNext (const TensorType &logits, TokenTensor &token_out, const SamplingParams ¶ms) |
| Sample the next token from a logits row on the device. | |
| virtual std::unordered_set< int32_t > | stopTokens () const |
| virtual dim_t | vocabSize () const noexcept=0 |
| Protected Member Functions inherited from Mila::Dnn::Model< TDeviceType, TPrecision > | |
| Model (std::unique_ptr< NetworkType > network, RuntimeMode runtime_mode) | |
| Construct with a fully built network and runtime mode. | |
| virtual void | onTraining ()=0 |
| Training loop hook – derived class owns the implementation. | |
Protected Attributes | |
| Serialization::PretrainedMetadata | source_metadata_ |
| The loaded artifact's metadata, carried so savePretrained can write it back verbatim. | |
| WeightQuantization | weight_quantization_ { WeightQuantization::None } |
| What the live weights are, not what the source file was. | |
| Protected Attributes inherited from Mila::Dnn::Model< TDeviceType, TPrecision > | |
| std::unique_ptr< NetworkType > | network_ |
| The owned Network instance. | |
|
inlineexplicitprotected |
| network | The transformer stack this model owns. |
| runtime_mode | Inference or Training, fixed for the model's lifetime. |
| source_metadata | The loaded artifact's metadata, written back verbatim by savePretrained so the result loads by the same path. |
| weight_quantization | What the live weights actually are, which is a load-time policy rather than a property of the source file. |
Both default, because a model reconstructed from a checkpoint has no pretrained provenance to carry; savePretrained refuses rather than writing an artifact that declares nothing.
|
inlineprotected |
Block until the last enqueueSampleNext()'s token id is host-visible.
Waits only for that sampling step – device work enqueued after it (the ahead-decoded forward) keeps running, which is what hides the per-token host gap.
|
inlineprotected |
Enqueue a sampling step without waiting for the host readback.
Decode-ahead half of the split sampleNext(): the token is written into token_out on the device (ready for the next decode step) and its id travels to the host asynchronously. awaitSampledToken() completes the pair. At most one enqueue may be outstanding.
|
protectedpure virtualnoexcept |
Implemented in Mila::Dnn::GptModel< TDeviceType, TPrecision >.
|
inlineprotectedvirtualnoexcept |
Optional final-logit softcap the sampler applies (0 disables).
Gemma overrides this with its 30.0 cap; other models leave it at 0.
|
inlinenodiscard |
Generate tokens from a prompt, streaming each through on_token.
Blocking, serial token generation: the model owns the decode loop (it owns the KV cache and the device stream) and pushes every generated token (EOS excluded) to on_token on the caller's thread until it stops. Returns why it stopped – the one outcome the caller cannot reconstruct from the token stream. Timing/throughput are the harness's to measure from the callback cadence; the model keeps no stopwatch. Callers that want asynchrony own the threading (e.g. the Python ModelWorker runs this on its own thread).
| prompt_tokens | Input token ids. |
| on_token | Per-token callback invoked on the caller's thread. |
| params | Per-call generation parameters (loop bound + sampling). |
| stop | Stop token for cooperative cancellation. |
|
protectedpure virtualnoexcept |
|
protectedpure virtual |
Prefill + decode implementation hook.
Derived classes own the full autoregressive generation loop. on_token must be called for every generated token except EOS. stop.stop_requested() must be checked on each decode step and generation must abort early when signalled, returning the GenerateStatus that reflects why the loop stopped.
| prompt_tokens | Input token ids. |
| on_token | Per-token callback. |
| params | Per-call generation parameters (loop bound + sampling). |
| stop | Stop token for cooperative cancellation. |
Implemented in Mila::Dnn::GemmaModel< TDeviceType, TPrecision >, Mila::Dnn::GptModel< TDeviceType, TPrecision >, and Mila::Dnn::LlamaModel< TDeviceType, TPrecision >.
|
inlineprotected |
Sample the next token from a logits row on the device.
Lazily constructs the model-owned TokenSampler on first use (the network is built and the execution context valid by the time generation runs), then samples from the final row of logits, writing the int32 token into token_out in place (ready for the next decode step) and returning the host value.
|
inline |
Write this model's live weights as a safetensors artifact.
The inverse of fromPretrained, and named for it: what this writes is what that reads. Weights go out as they currently sit on the device, so a model loaded under FP4 or FP8 produces a PRE-QUANTIZED artifact – packed storage plus its scale companions. That is the point of the operation: quantization is a load-time policy, so the quantized bytes exist nowhere until a model has been built with one.
The source artifact's metadata is written back verbatim, so the result loads by the same path that loaded the original and is readable by any safetensors reader without Mila.
Family-agnostic by construction: the tensor vocabulary comes from the network's own flat-save traversal, so a family is covered as soon as every composite that owns a parameter drives both halves of it. A composite that only recurses and silently drops its own tensors is the failure this cannot see – the export tool's source reconciliation is what catches that.
| path | Destination artifact path; parent directories are created. |
| std::runtime_error | if the model carries no pretrained provenance (it was reconstructed from a checkpoint), or if the file cannot be written. |
|
inline |
Seed the sampler's RNG for reproducible generation.
Reproducibility is a property of the RNG stream, not of a single call: seed once (before a run or a session), then the token stream is deterministic for a given prompt and model. Deliberately not a per-call GenerateParams field, so a caller cannot accidentally reset the stream on every call.
|
protectedpure virtualnoexcept |
|
protected |
The loaded artifact's metadata, carried so savePretrained can write it back verbatim.
Empty for a model reconstructed from a checkpoint, which savePretrained refuses.