mstar.model.utils#

Functions

base_language(code)

en-US, en_us or EN -> en.

capture_ladder(key, value)

A capture ladder (token buckets or batch sizes) from model_kwargs: a 0, negative or repeated entry would go into the capture build, and an empty one would quietly mean the default.

check_kv_pools_fit(model, config, ...[, ...])

Refuse a max_concurrent_requests a resource the model builds cannot hold, as its spec's capacity_problem answers: the first problem raises.

check_loaded(module, loaded, what)

Raise unless loaded names every parameter of module: one built on meta and filled by a loader would otherwise serve uninitialized memory.

drop_stop_tokens(output, stop_token_ids, ...)

Drop the stop tokens that ended a text reply, unless the request sets ignore_eos.

fast_tokenizer_from_snapshot(source)

A fast tokenizer from tokenizer.json, which is version-independent, with the snapshot's chat template and the special tokens tokenizer_config.json declares.

kv_pages(tokens, page_size, requests)

Pages for requests sequences of tokens each, plus the sink page every KV cache keeps out of circulation.

load_generation_defaults(checkpoint_dir[, ...])

The sampling defaults checkpoint_dir/generation_config.json declares.

load_snapshot_tokenizer(model_path_hf[, ...])

The checkpoint's tokenizer, through AutoTokenizer or, where transformers 4.x cannot build the backend class a transformers-5 tokenizer_config.json names, fast_tokenizer_from_snapshot.

load_weights(state_dict, module[, prefix, ...])

load_weights_from_file(safetensors_file, modules)

load_weights_from_hf_shards(repo_dir, modules)

Load weights from a HuggingFace safetensors checkpoint.

process_weights_after_loading(root, device)

Finalize kernel layouts across a freshly loaded module tree: any submodule exposing process_weights_after_loading(device) gets it called (the attention layers build their absorbed w_kc/w_vc here).

read_fp8_block_quant_config(checkpoint_dir)

The Fp8BlockQuantConfig in checkpoint_dir/config.json, or None: no file, none declared, or unreadable (the weights then load as they are, bf16).

resolve_checkpoint(model_path_hf[, cache_dir])

A local checkpoint directory as given, a Hub id as its snapshot (fetched if not cached), None for no path.

warn_retired_ladder_env(name, setting)

Warn that the environment variable name, a capture ladder the serving config's prefill_token_buckets replaced, is set but no longer read; setting is the serving config entry that sets it.

Classes

ByteIdDetokenizer()

Token ids that are bytes, as a reduced model's byte tokenizer (tokenizer_mode: byte) makes them: an id is its low byte.

ByteLevelDetokenizer(tokenizer[, keep_special])

Byte-faithful per-token detokenization for byte-level BPE tokenizers (GPT-2 / Whisper / Qwen).

ByteLevelTextOutput()

Model.text_output for a model over a byte-level BPE tokenizer: each token's raw bytes with special tokens dropped, config.eos_token_ids ending a reply.

KeysAndConverter(keys, converter)

ModuleAndPrefix(module[, prefix, ...])

Operation(operation[, dim])

SentencePieceDetokenizer(tokenizer_json[, ...])

Per-token detokenization for SentencePiece-style vocabularies (▁ marks a word start, <0xNN> pieces are byte fallback), read from an HF tokenizer.json.

TextChunkDetokenizer(tokenizer)

One decode step's text chunk for a model that streams a token per step.

TextOutput(detokenizer[, stop_token_ids])

How a model's text output, token ids, becomes bytes: Model.text_output declares it, and Model.postprocess and Model.postprocess_inline derive their text paths from it.

WeightConverter(source_patterns, ...)

class mstar.model.utils.ByteIdDetokenizer[source]#

Bases: object

Token ids that are bytes, as a reduced model’s byte tokenizer (tokenizer_mode: byte) makes them: an id is its low byte.

static to_bytes(token_ids)[source]#
Parameters:

token_ids (list[int])

Return type:

bytes

static token_bytes(token_id)[source]#
Parameters:

token_id (int)

Return type:

bytes

class mstar.model.utils.ByteLevelDetokenizer(tokenizer, keep_special=False)[source]#

Bases: object

Byte-faithful per-token detokenization for byte-level BPE tokenizers (GPT-2 / Whisper / Qwen).

Streaming models emit one token per step to the client, so a multi-byte UTF-8 character split across tokens must be emitted as raw bytes and reassembled client-side — per-token tokenizer.decode would yield U+FFFD for each partial character.

Special tokens are dropped, like skip_special_tokens, unless keep_special: then the joined bytes of any id sequence decode to what tokenizer.decode(ids) gives.

Parameters:

keep_special (bool)

static is_byte_level(tokenizer)[source]#

Whether to_bytes reproduces this tokenizer’s decode: a ByteLevel decoder (fast) or a GPT-2 byte map (slow), and no clean_up_tokenization_spaces rewrite.

Return type:

bool

to_bytes(token_ids)[source]#
Parameters:

token_ids (list[int])

Return type:

bytes

token_bytes(token_id)[source]#

to_bytes([token_id]), memoized: a decode step’s chunk is one token.

Parameters:

token_id (int)

Return type:

bytes

class mstar.model.utils.ByteLevelTextOutput[source]#

Bases: object

Model.text_output for a model over a byte-level BPE tokenizer: each token’s raw bytes with special tokens dropped, config.eos_token_ids ending a reply. Built on first use, as the host’s tokenizer may load lazily; a reduced model’s byte ids (_tokenizer_mode of "byte") never touch it.

text_output()[source]#
Return type:

TextOutput

class mstar.model.utils.KeysAndConverter(keys: set[str] = <factory>, converter: mstar.model.utils.WeightConverter | None = None)[source]#

Bases: object

Parameters:
append_key(key)[source]#
converter: WeightConverter | None = None#
keys: set[str]#
class mstar.model.utils.ModuleAndPrefix(module: torch.nn.modules.module.Module, prefix: str = None, enforce_missing_keys: bool = True)[source]#

Bases: object

Parameters:
enforce_missing_keys: bool = True#
module: Module#
prefix: str = None#
class mstar.model.utils.Operation(operation: str, dim: int = 0)[source]#

Bases: object

Parameters:
dim: int = 0#
operation: str#
class mstar.model.utils.SentencePieceDetokenizer(tokenizer_json, extra_skip_ids=frozenset())[source]#

Bases: object

Per-token detokenization for SentencePiece-style vocabularies (▁ marks a word start, <0xNN> pieces are byte fallback), read from an HF tokenizer.json. Same contract as ByteLevelDetokenizer: bytes per token, so a character split across byte pieces reassembles client-side.

Parameters:
to_bytes(token_ids)[source]#
Parameters:

token_ids (list[int])

Return type:

bytes

token_bytes(token_id)[source]#
Parameters:

token_id (int)

Return type:

bytes

class mstar.model.utils.TextChunkDetokenizer(tokenizer)[source]#

Bases: object

One decode step’s text chunk for a model that streams a token per step.

With a byte-level tokenizer the chunk is the tokens’ raw bytes, special tokens kept, so a character split across steps reassembles in the API server’s incremental decoder and the joined reply equals tokenizer.decode of all its ids. Any other tokenizer keeps the per-step decode.

to_bytes(token_ids)[source]#
Parameters:

token_ids (list[int])

Return type:

bytes

token_bytes(token_id)[source]#

to_bytes([token_id]), memoized.

Parameters:

token_id (int)

Return type:

bytes

tokenizer#
class mstar.model.utils.TextOutput(detokenizer, stop_token_ids=frozenset({}))[source]#

Bases: NamedTuple

How a model’s text output, token ids, becomes bytes: Model.text_output declares it, and Model.postprocess and Model.postprocess_inline derive their text paths from it.

Parameters:
detokenizer: ByteLevelDetokenizer | TextChunkDetokenizer | SentencePieceDetokenizer | ByteIdDetokenizer#

Alias for field number 0

stop_token_ids: Container[int]#

Alias for field number 1

class mstar.model.utils.WeightConverter(source_patterns: list[str], target_patterns: str, operations: list[mstar.model.utils.Operation])[source]#

Bases: object

Parameters:
operations: list[Operation]#
source_patterns: list[str]#
target_patterns: str#
mstar.model.utils.base_language(code)[source]#

en-US, en_us or EN -> en.

Parameters:

code (str)

Return type:

str

mstar.model.utils.capture_ladder(key, value)[source]#

A capture ladder (token buckets or batch sizes) from model_kwargs: a 0, negative or repeated entry would go into the capture build, and an empty one would quietly mean the default.

Parameters:

key (str)

Return type:

list[int]

mstar.model.utils.check_kv_pools_fit(model, config, config_path, log, request_layouts=None, loop_caps=None)[source]#

Refuse a max_concurrent_requests a resource the model builds cannot hold, as its spec’s capacity_problem answers: the first problem raises.

A request keeps its pages from prefill to its last token. Past a pool, a prefill batch is refused. With host pages (cpu_offload_pages) the worker offloads decoding requests to admit it, which costs far more than queueing would. Without them it retries until requests time out. So the cap’s requests at full length must fit each cache next to its sink page; the conductor queues the rest. Warnings go to the model’s log. request_layouts gives the Layout per array and label of the request the deployment is sized for, with its loops at loop_caps, and a pool it doesn’t name holds one stream of its max_seq_len.

Parameters:
Return type:

None

mstar.model.utils.check_loaded(module, loaded, what)[source]#

Raise unless loaded names every parameter of module: one built on meta and filled by a loader would otherwise serve uninitialized memory.

Parameters:
Return type:

None

mstar.model.utils.drop_stop_tokens(output, stop_token_ids, request_kwargs)[source]#

Drop the stop tokens that ended a text reply, unless the request sets ignore_eos.

A stop token ends the turn, not the reply: a client sends the reply back as an assistant message, whose template closes it. Under ignore_eos it ends nothing and stays, one chunk per token.

Parameters:
Return type:

list[int]

mstar.model.utils.fast_tokenizer_from_snapshot(source)[source]#

A fast tokenizer from tokenizer.json, which is version-independent, with the snapshot’s chat template and the special tokens tokenizer_config.json declares.

Parameters:

source (str)

mstar.model.utils.kv_pages(tokens, page_size, requests)[source]#

Pages for requests sequences of tokens each, plus the sink page every KV cache keeps out of circulation.

Parameters:
  • tokens (int)

  • page_size (int)

  • requests (int)

Return type:

int

mstar.model.utils.load_generation_defaults(checkpoint_dir, prefix='', stage='', switch_only=False)[source]#

The sampling defaults checkpoint_dir/generation_config.json declares.

Keys come back under mstar names (max_new_tokens -> max_output_tokens). prefix selects one stage’s keys in a multi-stage file ("talker_" reads talker_temperature) and stage prefixes the returned names ("code_predictor_"). do_sample: false is greedy: temperature 0. switch_only reads do_sample alone, for a file that is the backbone’s chat preset rather than the model’s own recipe. Returns {} when there is no file, so the caller’s own defaults apply.

Parameters:
Return type:

dict

mstar.model.utils.load_snapshot_tokenizer(model_path_hf, cache_dir=None)[source]#

The checkpoint’s tokenizer, through AutoTokenizer or, where transformers 4.x cannot build the backend class a transformers-5 tokenizer_config.json names, fast_tokenizer_from_snapshot.

Parameters:
  • model_path_hf (str)

  • cache_dir (str | None)

mstar.model.utils.load_weights(state_dict, module, prefix=None, enforce_missing_keys=True)[source]#
Parameters:
mstar.model.utils.load_weights_from_file(safetensors_file, modules, device='cpu')[source]#
Parameters:
mstar.model.utils.load_weights_from_hf_shards(repo_dir, modules, device='cpu', conv=None)[source]#

Load weights from a HuggingFace safetensors checkpoint.

Reads model.safetensors.index.json to find which shard each key lives in, then loads from each shard file. Checkpoints that ship a single unsharded model.safetensors (no index — e.g. whisper-large-v3) are handled by treating that one file as the whole weight map.

Parameters:
mstar.model.utils.process_weights_after_loading(root, device)[source]#

Finalize kernel layouts across a freshly loaded module tree: any submodule exposing process_weights_after_loading(device) gets it called (the attention layers build their absorbed w_kc/w_vc here).

Parameters:
Return type:

None

mstar.model.utils.read_fp8_block_quant_config(checkpoint_dir)[source]#

The Fp8BlockQuantConfig in checkpoint_dir/config.json, or None: no file, none declared, or unreadable (the weights then load as they are, bf16).

Parameters:

checkpoint_dir (str)

mstar.model.utils.resolve_checkpoint(model_path_hf, cache_dir=None)[source]#

A local checkpoint directory as given, a Hub id as its snapshot (fetched if not cached), None for no path.

Parameters:
  • model_path_hf (str | None)

  • cache_dir (str | None)

Return type:

str | None

mstar.model.utils.warn_retired_ladder_env(name, setting)[source]#

Warn that the environment variable name, a capture ladder the serving config’s prefill_token_buckets replaced, is set but no longer read; setting is the serving config entry that sets it.

Parameters:
Return type:

None