EdgeIn-v3 / modeling_edgeinstant.py
chenjz24's picture
Upload folder using huggingface_hub
d81a465 verified
Raw History Blame Contribute Delete
33.9 kB
"""Audio-conditioned Thinker and native-token speech generation."""
from __future__ import annotations
from typing import Iterator
from contextlib import ExitStack, contextmanager, nullcontext
from dataclasses import dataclass
import torch
from torch import nn
from torch.nn.attention import SDPBackend, sdpa_kernel
from transformers import GenerationMixin, PreTrainedModel, Qwen3_5ForConditionalGeneration
from transformers.modeling_outputs import CausalLMOutputWithPast
from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import (
Qwen3OmniMoeAudioEncoder,
_get_feat_extract_output_lengths,
)
from .configuration_edgeinstant import EdgeInstantConfig
from .codec_edgeinstant import EdgeInstantCodecDecoder
from .inference_edgeinstant import EdgeInstantDecoderLayer
from .salmonn_qformer import EdgeInstantSalmonnQFormer
from .compact_native_clock import CompactNativeClockTalker
@dataclass
class EdgeInstantCausalLMOutputWithPast(CausalLMOutputWithPast):
loss_stats: dict[str, torch.Tensor] | None = None
@torch.no_grad()
def _answer_loss_statistics(raw_losses, weighted_losses, example_ids, is_eos,
negative, unlikelihood_losses, batch_size):
"""Detached per-example sums for positive CE and unscaled unlikelihood."""
def sum_by_example(values, selected=None):
indices = example_ids if selected is None else example_ids[selected]
values = values if selected is None else values[selected]
return values.new_zeros(batch_size).scatter_add_(0, indices, values)
positive = torch.ones_like(example_ids, dtype=torch.bool) if negative is None else ~negative
positive_eos = positive & is_eos
positive_non_eos = positive & ~is_eos
counts = torch.ones_like(example_ids)
ce_tokens = sum_by_example(counts, positive)
raw_ce_sum = sum_by_example(raw_losses, positive)
ul_tokens = (sum_by_example(counts, negative) if negative is not None
else counts.new_zeros(batch_size))
ul_loss_sum = weighted_losses.new_zeros(batch_size)
if unlikelihood_losses is not None:
ul_loss_sum.scatter_add_(0, example_ids[negative], unlikelihood_losses)
return {
"raw_ce_sum": raw_ce_sum,
"raw_ce_example_sum": raw_ce_sum / ce_tokens.clamp_min(1),
"ce_tokens": ce_tokens,
"positive_samples": ce_tokens.gt(0).long(),
"eos_ce_sum": sum_by_example(raw_losses, positive_eos),
"eos_tokens": sum_by_example(counts, positive_eos),
"non_eos_ce_sum": sum_by_example(raw_losses, positive_non_eos),
"non_eos_tokens": sum_by_example(counts, positive_non_eos),
"ul_loss_sum": ul_loss_sum,
"ul_loss_example_sum": ul_loss_sum / ul_tokens.clamp_min(1),
"ul_tokens": ul_tokens,
"weighted_loss_sum": sum_by_example(weighted_losses),
"num_samples": counts.new_ones(batch_size),
}
class EdgeInstantThinker(Qwen3_5ForConditionalGeneration):
"""Qwen3.5 with CUDA graph replay for cached recurrent decoding."""
_no_split_modules = ["Qwen3_5DecoderLayer", "EdgeInstantDecoderLayer", "Qwen3_5VisionBlock"]
def __init__(self, config):
super().__init__(config)
for index in range(len(self.model.language_model.layers)):
if config.text_config.layer_types[index] == "linear_attention":
self.model.language_model.layers[index] = EdgeInstantDecoderLayer(config.text_config, index)
class EdgeInstantAudioProjector(nn.Module):
def __init__(self, config: dict, hidden_size: int):
super().__init__()
self.hidden_size = hidden_size
self.mode = config.get("align_mode", "replace")
if self.mode == "residual" and int(config["output_size"]) != hidden_size:
raise ValueError("Residual audio projection requires audio_split=1 (output_size must equal Thinker hidden_size)")
self.out_norm = bool(config.get("audio_out_norm", False))
self.norm = nn.LayerNorm(int(config["norm_size"]))
middle = config.get("intermediate_size")
self.proj = nn.Linear(int(config["input_size"]), int(middle or config["output_size"]))
self.proj2 = nn.Linear(int(middle), int(config["output_size"])) if middle else None
self.gate = nn.Parameter(torch.zeros(()))
self.out_scale = nn.Parameter(torch.ones(()))
def forward(self, audio: torch.Tensor, pad_embedding: torch.Tensor) -> torch.Tensor:
shape = audio.shape
frames = audio.float().reshape(*shape[:-1], -1, self.norm.normalized_shape[0])
mapped = self.proj(self.norm(frames).reshape(shape))
if self.proj2 is not None:
mapped = self.proj2(nn.functional.gelu(mapped))
if self.mode == "residual":
return pad_embedding.to(mapped.dtype) + self.gate.clamp(0, 4) * mapped
if self.out_norm:
mapped = nn.functional.normalize(mapped, dim=-1, eps=1e-6) * self.hidden_size ** 0.5
return (mapped * self.out_scale).reshape(-1, self.hidden_size)
class EdgeInstantForConditionalGeneration(PreTrainedModel, GenerationMixin):
config_class = EdgeInstantConfig
base_model_prefix = "edgeinstant"
main_input_name = "input_ids"
_supports_sdpa = True
_keep_in_fp32_modules_strict = ["align", "audio_special"]
_no_split_modules = ["Qwen3OmniMoeAudioEncoder", "EdgeInstantAudioProjector", "EdgeInstantSalmonnQFormer", "EdgeInstantCodecDecoder"]
def __init__(self, config, *, thinker=None, audio_tower=None, align=None,
talker=None, codec=None, audio_special_delta=None):
super().__init__(config)
supplied = [component for component in (thinker, audio_tower, align, talker, codec) if component is not None]
self.thinker = thinker if thinker is not None else EdgeInstantThinker(config.thinker_config)
self.audio_tower = audio_tower if audio_tower is not None else Qwen3OmniMoeAudioEncoder(config.audio_config)
if config.audio_tap == "ln_post":
self.audio_tower.proj1 = nn.Identity()
self.audio_tower.act = nn.Identity()
self.audio_tower.proj2 = nn.Identity()
projector_class = (EdgeInstantSalmonnQFormer
if config.projector_config["align_mode"] == "salmonn_qformer"
else EdgeInstantAudioProjector)
self.align = align if align is not None else projector_class(
config.projector_config, config.thinker_config.text_config.hidden_size,
)
self.audio_special = nn.Embedding(len(config.audio_special_ids), config.thinker_config.text_config.hidden_size)
if audio_special_delta is not None:
self.audio_special.weight = nn.Parameter(audio_special_delta.detach().clone())
supplied.append(self.audio_special)
self.talker = talker if talker is not None else (
CompactNativeClockTalker.from_config(config.talker_config) if config.talker_config else None
)
if self.talker is not None:
self.talker.prepare_for_serialization()
self.codec = codec if codec is not None else (
EdgeInstantCodecDecoder(config.codec_config) if config.codec_config else None
)
self._tied_weights_keys = {
f"talker.{target}": f"talker.{source}"
for target, source in (self.talker.tied_weight_keys.items() if self.talker is not None else [])
}
for component in supplied:
for module in component.modules():
module._is_hf_initialized = True
self.post_init()
if config.audio_lora_config:
from peft import LoraConfig, get_peft_model
self.thinker = get_peft_model(self.thinker, LoraConfig(**config.audio_lora_config))
self.all_tied_weights_keys = self.get_expanded_tied_weights_keys(all_submodels=True)
def enable_audio_lora_routing(self):
"""Keep the current LoRA separate and apply it only to requests with audio."""
adapter = self.thinker.peft_config["default"]
self.config.audio_lora_config = {
"r": adapter.r, "lora_alpha": adapter.lora_alpha,
"lora_dropout": adapter.lora_dropout,
"target_modules": sorted(adapter.target_modules),
"bias": "none", "task_type": "CAUSAL_LM",
}
self.all_tied_weights_keys = self.get_expanded_tied_weights_keys(all_submodels=True)
def _audio_request_route(self, input_ids, input_features=None, audio_request=None, cache=None):
if not self.config.audio_lora_config:
return None
if audio_request is not None:
values = torch.as_tensor(audio_request, dtype=torch.bool).reshape(-1).tolist()
if len(values) == 1 and input_ids is not None:
values *= input_ids.shape[0]
return tuple(values)
previous = getattr(cache, "edgeinstant_audio_request", None)
if input_ids is None:
if previous is not None:
return previous
raise ValueError("Audio LoRA routing with inputs_embeds requires audio_request")
# The full conversation includes audio slots from earlier user turns.
values = tuple(input_ids.eq(self.config.audio_pad_id).any(-1).tolist())
if previous is not None:
values = tuple(current or prior for current, prior in zip(values, previous))
return values
@contextmanager
def _audio_lora_context(self, route, *, checkpointing=True):
if route is None or getattr(self, "_active_audio_lora_route", None) == route:
yield
return
from peft.tuners.lora.layer import LoraLayer
previous = getattr(self, "_active_audio_lora_route", None)
self._active_audio_lora_route = route
# A recurrent decode graph captures its adapter operations as well as weights.
if getattr(self, "_audio_lora_graph_route", None) != route:
for layer in self._base_thinker().model.language_model.layers:
if isinstance(layer, EdgeInstantDecoderLayer):
layer._decode_graph = None
self._audio_lora_graph_route = route
with ExitStack() as stack:
stack.callback(setattr, self, "_active_audio_lora_route", previous)
if not any(route):
stack.enter_context(self.thinker.disable_adapter())
elif not all(route):
names = ["default" if active else "__base__" for active in route]
# PEFT's per-row Python indices require ordinary cached decoding.
for layer in self._base_thinker().model.language_model.layers:
if isinstance(layer, EdgeInstantDecoderLayer):
stack.callback(setattr, layer, "_mixed_audio_lora_batch", layer._mixed_audio_lora_batch)
layer._mixed_audio_lora_batch = True
def select_rows(module, args, kwargs):
repeats = args[0].shape[0] // len(names)
kwargs["adapter_names"] = [name for name in names for _ in range(repeats)]
return args, kwargs
for module in self.thinker.modules():
if isinstance(module, LoraLayer):
handle = module.register_forward_pre_hook(select_rows, with_kwargs=True)
stack.callback(handle.remove)
if checkpointing and self.training:
for module in self.thinker.modules():
if not getattr(module, "gradient_checkpointing", False):
continue
original = module._gradient_checkpointing_func
def checkpoint(function, *args, _original=original, **kwargs):
def recompute(*values, **options):
with self._audio_lora_context(route, checkpointing=False):
return function(*values, **options)
return _original(recompute, *args, **kwargs)
module._gradient_checkpointing_func = checkpoint
stack.callback(setattr, module, "_gradient_checkpointing_func", original)
yield
def get_input_embeddings(self):
return self.thinker.get_input_embeddings()
def set_input_embeddings(self, embeddings):
self.thinker.set_input_embeddings(embeddings)
def get_output_embeddings(self):
return self.thinker.get_output_embeddings()
def _base_thinker(self):
return self.thinker.get_base_model() if hasattr(self.thinker, "get_base_model") else self.thinker
def encode_audio(self, input_features, feature_attention_mask=None, tower=None, feature_lengths=None):
"""Return packed audio encoder features before the trainable projector."""
from transformers.models.qwen3_omni_moe.modeling_qwen3_omni_moe import (
chunk_and_pad_features, get_audio_cu_seqlens, get_valid_indices,
)
from transformers.utils.generic import is_flash_attention_requested
tower = self.audio_tower if tower is None else tower
tower_weight = next(tower.parameters())
if feature_lengths is not None:
lengths = torch.as_tensor(feature_lengths, dtype=torch.long).cpu()
elif feature_attention_mask is not None:
lengths = feature_attention_mask.sum(-1).to(device="cpu", dtype=torch.long)
else:
lengths = torch.full((input_features.shape[0],), input_features.shape[-1], dtype=torch.long)
if bool((lengths <= 0).any()):
raise ValueError("Audio must contain at least one valid mel frame")
packed = torch.cat([row[:, :int(length)] for row, length in zip(input_features, lengths)], dim=-1)
packed = packed.to(device=tower_weight.device, dtype=tower_weight.dtype)
padded_feature, chunk_lengths = chunk_and_pad_features(packed, lengths, tower.n_window)
valid_indices = get_valid_indices(chunk_lengths).to(tower_weight.device)
cu_seqlens = get_audio_cu_seqlens(chunk_lengths, lengths, tower.n_window_infer, tower.n_window)
# SDPA/eager split each attention window in Python; keep their boundaries on the CPU.
if is_flash_attention_requested(tower.config):
cu_seqlens = cu_seqlens.to(tower_weight.device)
# Keep FP32 audio attention outside the Thinker's mixed precision context.
audio_precision = (torch.autocast(tower_weight.device.type, enabled=False)
if tower_weight.dtype == torch.float32 else nullcontext())
with audio_precision:
hidden = tower(
input_features=packed, feature_lens=lengths,
padded_feature=padded_feature, chunk_lengths=chunk_lengths,
valid_indices=valid_indices, cu_seqlens=cu_seqlens,
).last_hidden_state
return self.group_audio_features(hidden, lengths)
def group_audio_features(self, hidden, frame_lengths):
"""Apply per-recording frame stacking or pooling to packed encoder output."""
if self.config.audio_stack == 1 and self.config.audio_pool == 1:
return hidden
counts = _get_feat_extract_output_lengths(frame_lengths).tolist()
processed = []
for row in hidden.split(counts):
if self.config.audio_stack > 1:
padding = -len(row) % self.config.audio_stack
if padding:
row = torch.cat((row, row[-1:].expand(padding, -1)))
row = row.reshape(len(row) // self.config.audio_stack, -1)
elif self.config.audio_pool > 1:
row = torch.stack([chunk.mean(0) for chunk in row.split(self.config.audio_pool)])
processed.append(row)
return torch.cat(processed)
def pad_embedding(self):
"""Audio placeholder embedding including its learned special-token delta."""
embed = self.get_input_embeddings()
pad = embed.weight[self.config.audio_pad_id]
if self.config.audio_pad_id in self.config.audio_special_ids:
slot = self.config.audio_special_ids.index(self.config.audio_pad_id)
pad = pad + self.audio_special.weight[slot].to(pad)
return pad
def get_audio_features(self, input_features, feature_attention_mask, feature_lengths=None):
features = self.encode_audio(input_features, feature_attention_mask, feature_lengths=feature_lengths)
device = next(self.align.parameters()).device
if self.align.mode == "salmonn_qformer":
if feature_lengths is not None:
lengths = torch.as_tensor(feature_lengths, dtype=torch.long).cpu()
elif feature_attention_mask is not None:
lengths = feature_attention_mask.sum(-1).to(device="cpu", dtype=torch.long)
else:
lengths = torch.full((input_features.shape[0],), input_features.shape[-1], dtype=torch.long)
counts = _get_feat_extract_output_lengths(lengths)
stride = self.config.audio_stack if self.config.audio_stack > 1 else self.config.audio_pool
counts = (counts + stride - 1) // stride
return self.align.forward_packed(features.to(device), counts.tolist())
return self.align(features.to(device), self.pad_embedding().to(device))
def merge_audio_embeds(self, input_ids, input_features, feature_attention_mask, feature_lengths=None):
vectors = self.get_audio_features(input_features, feature_attention_mask, feature_lengths)
return self.merge_custom_audio(input_ids, vectors)
def merge_custom_audio(self, input_ids, audio_vectors):
"""Insert projected or diagnostic audio vectors in the model's audio slots."""
embedding = self.get_input_embeddings()
ids = input_ids.to(embedding.weight.device)
embeds = embedding(ids)
for slot, token_id in enumerate(self.config.audio_special_ids):
embeds = embeds + (ids == token_id).unsqueeze(-1) * self.audio_special.weight[slot].to(embeds)
vectors = audio_vectors.to(embeds)
mask = ids == self.config.audio_pad_id
if int(mask.sum()) != len(vectors):
raise ValueError(f"Audio slots {int(mask.sum())} do not match encoded vectors {len(vectors)}")
return embeds.masked_scatter(mask.unsqueeze(-1).expand_as(embeds), vectors)
def forward(self, input_ids=None, attention_mask=None, input_features=None,
feature_attention_mask=None, inputs_embeds=None, labels=None,
audio_feature_lengths=None, answer_loss_reduction=None,
eos_loss_weight=1.0, eos_loss_weights=None, unlikelihood_mask=None, unlikelihood_weight=1.0,
return_answer_hidden_states=False, return_loss_stats=False, audio_request=None, **kwargs):
route = self._audio_request_route(input_ids, input_features, audio_request, kwargs.get("past_key_values"))
with self._audio_lora_context(route):
output = self._forward(
input_ids=input_ids, attention_mask=attention_mask, input_features=input_features,
feature_attention_mask=feature_attention_mask, inputs_embeds=inputs_embeds, labels=labels,
audio_feature_lengths=audio_feature_lengths, answer_loss_reduction=answer_loss_reduction,
eos_loss_weight=eos_loss_weight, eos_loss_weights=eos_loss_weights,
unlikelihood_mask=unlikelihood_mask,
unlikelihood_weight=unlikelihood_weight, return_answer_hidden_states=return_answer_hidden_states,
return_loss_stats=return_loss_stats,
**kwargs,
)
cache = getattr(output, "past_key_values", None)
if route is not None and cache is not None:
cache.edgeinstant_audio_request = route
return output
def _forward(self, input_ids=None, attention_mask=None, input_features=None,
feature_attention_mask=None, inputs_embeds=None, labels=None,
audio_feature_lengths=None, answer_loss_reduction=None,
eos_loss_weight=1.0, eos_loss_weights=None, unlikelihood_mask=None, unlikelihood_weight=1.0,
return_answer_hidden_states=False, return_loss_stats=False, **kwargs):
if input_features is not None:
if input_ids is None or feature_attention_mask is None:
raise ValueError("Audio forward requires input_ids and feature_attention_mask")
cache = kwargs.get("past_key_values")
if cache is None or cache.get_seq_length() == 0:
self._base_thinker().model.rope_deltas = None
inputs_embeds = self.merge_audio_embeds(
input_ids, input_features, feature_attention_mask, audio_feature_lengths,
)
if kwargs.get("position_ids") is None and (
kwargs.get("image_grid_thw") is not None or kwargs.get("video_grid_thw") is not None
):
kwargs["position_ids"] = self._base_thinker().model.compute_3d_position_ids(
input_ids, inputs_embeds, attention_mask=attention_mask,
**{key: kwargs.get(key) for key in ("image_grid_thw", "video_grid_thw", "mm_token_type_ids")},
)
input_ids = None
if answer_loss_reduction is not None:
if labels is None or answer_loss_reduction not in {"token_sum", "example_sum", "hidden"}:
raise ValueError("Answer loss requires labels and token_sum or example_sum reduction")
# LoRA lives on the base model's decoder linears; the vocabulary projection
# only needs hidden states that predict a supervised answer token or EOS.
thinker = self._base_thinker()
outputs = thinker.model(input_ids=input_ids, inputs_embeds=inputs_embeds,
attention_mask=attention_mask, **kwargs)
targets = labels[:, 1:]
mask = targets.ne(-100)
hidden = outputs.last_hidden_state[:, :-1][mask]
if answer_loss_reduction == "hidden":
return CausalLMOutputWithPast(hidden_states=(hidden,))
logits = thinker.lm_head(hidden)
losses = nn.functional.cross_entropy(logits.float(), targets[mask], reduction="none")
raw_losses = losses.detach() if return_loss_stats else None
negative = unlikelihood_losses = None
if unlikelihood_mask is not None:
negative = unlikelihood_mask[:, 1:][mask].bool()
if negative.any():
negative_logits = logits[negative].float()
negative_ids = targets[mask][negative, None]
selected = negative_logits.gather(1, negative_ids).squeeze(1)
alternatives = negative_logits.scatter(1, negative_ids, -torch.inf).logsumexp(dim=1)
unlikelihood_losses = nn.functional.softplus(selected - alternatives)
losses = losses.index_put((negative,),
unlikelihood_losses * unlikelihood_weight)
eos_ids = self.config.eos_token_id
if isinstance(eos_ids, int):
eos_ids = [eos_ids]
is_eos = torch.isin(targets[mask], targets.new_tensor(eos_ids))
example_ids = mask.nonzero(as_tuple=True)[0]
eos_weights = (eos_loss_weights.to(losses)[example_ids]
if eos_loss_weights is not None else eos_loss_weight)
weights = torch.where(is_eos, eos_weights, 1.0)
losses = losses * weights
if answer_loss_reduction == "example_sum":
counts = weights.new_zeros(targets.shape[0]).scatter_add(0, example_ids, weights)
losses = losses / counts[example_ids]
loss_stats = (_answer_loss_statistics(
raw_losses, losses.detach(), example_ids, is_eos, negative,
unlikelihood_losses.detach() if unlikelihood_losses is not None else None,
targets.shape[0],
) if return_loss_stats else None)
return EdgeInstantCausalLMOutputWithPast(loss=losses.sum(),
hidden_states=(hidden,) if return_answer_hidden_states else None, loss_stats=loss_stats)
return self.thinker(input_ids=input_ids, inputs_embeds=inputs_embeds,
attention_mask=attention_mask, labels=labels, **kwargs)
@torch.no_grad()
@sdpa_kernel([SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION, SDPBackend.MATH])
def generate(self, input_ids=None, attention_mask=None, input_features=None,
feature_attention_mask=None, audio_request=None, **kwargs):
"""Generate text token IDs, including the supplied prompt as in HF causal LMs."""
self._base_thinker().model.rope_deltas = None
if input_features is not None:
kwargs["inputs_embeds"] = self.merge_audio_embeds(input_ids, input_features, feature_attention_mask)
self.thinker.generation_config = self.generation_config
kwargs.setdefault("eos_token_id", self.config.eos_token_id)
route = self._audio_request_route(input_ids, input_features, audio_request, kwargs.get("past_key_values"))
with self._audio_lora_context(route):
output = self.thinker.generate(input_ids=input_ids, attention_mask=attention_mask, **kwargs)
cache = getattr(output, "past_key_values", None)
if route is not None and cache is not None:
cache.edgeinstant_audio_request = route
return output
generate_text = generate
@torch.inference_mode()
def synthesize(self, token_ids, *, language="chinese", max_frames=1536, do_sample=False,
decode=True, **sampling):
"""Speak one sequence of native Thinker token IDs."""
if self.talker is None:
raise ValueError("The model package does not contain a Talker")
state = self.talker.new_state(language=language, max_frames=max_frames, do_sample=do_sample, **sampling)
for token in torch.as_tensor(token_ids).reshape(-1).tolist():
state.push_token(token)
state.end_input()
while not state.ended:
state.advance(max_new_frames=4)
codes = torch.stack(state.frames) if state.frames else torch.empty((0, 16), dtype=torch.long)
waveform = None
if decode:
if self.codec is None:
raise ValueError("The model package does not contain a codec decoder")
waveform = self.codec.decode(codes.unsqueeze(0))[0] if len(codes) else torch.empty(0)
return {"audio_codes": codes, "audio": waveform, "sampling_rate": self.config.output_sampling_rate,
"stop_reason": state.status.value}
@torch.inference_mode()
def generate_speech(self, input_ids=None, *, language="chinese", max_frames=1536,
audio_do_sample=False, **kwargs):
"""Generate one reply and its waveform; text generation accepts standard HF options."""
if input_ids is None or input_ids.shape[0] != 1:
raise ValueError("Speech generation accepts one conversation at a time")
sequences = self.generate(input_ids=input_ids, **kwargs)
if not isinstance(sequences, torch.Tensor):
sequences = sequences.sequences
reply = sequences[0, input_ids.shape[1]:]
special = set(self.config.thinker_special_ids)
public, thinking = [], False
for token in reply.tolist():
if token == self.config.think_start_id:
thinking = True
elif token == self.config.think_end_id:
thinking = False
elif not thinking and token not in special:
public.append(token)
result = self.synthesize(public, language=language, max_frames=max_frames, do_sample=audio_do_sample)
return {"sequences": sequences, "text_token_ids": torch.tensor(public), **result}
@torch.inference_mode()
def stream_generate(self, input_ids, attention_mask=None, input_features=None,
feature_attention_mask=None, *, language="chinese", max_new_tokens=512,
max_frames=1536, first_packet_frames=1, chunk_frames=4,
left_context_frames=50, audio_do_sample=False, cancelled=None,
audio_request=None) -> Iterator[dict]:
route = self._audio_request_route(input_ids, input_features, audio_request)
with self._audio_lora_context(route):
yield from self._stream_generate(
input_ids, attention_mask, input_features, feature_attention_mask,
language=language, max_new_tokens=max_new_tokens, max_frames=max_frames,
first_packet_frames=first_packet_frames, chunk_frames=chunk_frames,
left_context_frames=left_context_frames, audio_do_sample=audio_do_sample, cancelled=cancelled,
)
def _stream_generate(self, input_ids, attention_mask=None, input_features=None,
feature_attention_mask=None, *, language="chinese", max_new_tokens=512,
max_frames=1536, first_packet_frames=1, chunk_frames=4,
left_context_frames=50, audio_do_sample=False, cancelled=None) -> Iterator[dict]:
"""Yield native text tokens and continuous 24 kHz audio chunks for one reply."""
if self.talker is None:
raise ValueError("The model package does not contain a Talker")
if input_ids.shape[0] != 1:
raise ValueError("Streaming accepts one conversation at a time")
state = self.talker.new_state(language=language, max_frames=max_frames, do_sample=audio_do_sample)
self._base_thinker().model.rope_deltas = None
inputs_embeds = None
if input_features is not None:
inputs_embeds = self.merge_audio_embeds(input_ids, input_features, feature_attention_mask)
if attention_mask is None:
attention_mask = torch.ones_like(input_ids)
sequences = input_ids
sent = 0
special = set(self.config.thinker_special_ids)
eos = self.config.eos_token_id
eos = {eos} if isinstance(eos, int) else set(eos)
thinking = False
def packet():
nonlocal sent
if len(state.frames) == sent:
return None
start = max(0, sent - left_context_frames)
codes = torch.stack(state.frames[start:]).unsqueeze(0)
pcm = self.codec(codes)[0]
pcm = pcm[(sent - start) * self.codec.samples_per_frame:]
event = {"type": "audio", "audio": pcm.detach().cpu(), "sampling_rate": self.codec.sample_rate,
"sample_start": sent * self.codec.samples_per_frame,
"audio_codes": torch.stack(state.frames[sent:])}
sent = len(state.frames)
return event
if self.codec is None:
raise ValueError("The model package does not contain a codec decoder")
try:
inputs = self.thinker.prepare_inputs_for_generation(
sequences, inputs_embeds=inputs_embeds, attention_mask=attention_mask,
is_first_iteration=True, use_cache=True, logits_to_keep=1,
)
output = self.thinker(**inputs)
cache = output.past_key_values
reached_eos = False
for _ in range(max_new_tokens):
if cancelled is not None and cancelled.is_set():
return
token = output.logits[:, -1].argmax(-1)
token_id = int(token.item())
if token_id in eos:
reached_eos = True
break
if token_id == self.config.think_start_id:
thinking = True
elif token_id == self.config.think_end_id:
thinking = False
elif not thinking and token_id not in special:
yield {"type": "text", "token_id": token_id}
state.push_token(token_id)
state.advance(max_new_frames=first_packet_frames if sent == 0 else chunk_frames)
event = packet()
if event is not None:
yield event
if state.ended:
break
sequences = torch.cat((sequences, token[:, None]), dim=-1)
attention_mask = torch.cat((attention_mask, torch.ones_like(token[:, None])), dim=-1)
inputs = self.thinker.prepare_inputs_for_generation(
sequences, past_key_values=cache, attention_mask=attention_mask,
is_first_iteration=False, next_sequence_length=1, use_cache=True, logits_to_keep=1,
)
output = self.thinker(**inputs)
cache = output.past_key_values
if not state.ended:
if not reached_eos:
raise RuntimeError(f"Thinker did not reach EOS within {max_new_tokens} tokens")
state.end_input()
while not state.ended:
if cancelled is not None and cancelled.is_set():
return
state.advance(max_new_frames=chunk_frames)
event = packet()
if event is not None:
yield event
yield {"type": "done", "stop_reason": state.status.value, "samples": sent * self.codec.samples_per_frame}
finally:
state.cancel()