Instructions to use tiny-random/hy4 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use tiny-random/hy4 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="tiny-random/hy4") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("tiny-random/hy4") model = AutoModelForMultimodalLM.from_pretrained("tiny-random/hy4", device_map="auto") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(processor.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use tiny-random/hy4 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "tiny-random/hy4" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "tiny-random/hy4", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker
docker model run hf.co/tiny-random/hy4
- SGLang
How to use tiny-random/hy4 with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "tiny-random/hy4" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "tiny-random/hy4", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "tiny-random/hy4" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "tiny-random/hy4", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }' - Docker Model Runner
How to use tiny-random/hy4 with Docker Model Runner:
docker model run hf.co/tiny-random/hy4
Upload folder using huggingface_hub
Browse filesFiles changed (12)
- .meta/create_model.pyAdded+178
- .meta/env.jsonAdded+37
- .meta/model.logAdded+283
- LICENSEAdded+245
- README.mdAdded+138
- chat_template.jinjaAdded+355
- config.jsonAdded+320
- generation_config.jsonAdded+10
- model.safetensorsAdded+3
- processor_config.jsonAdded+75
- tokenizer.jsonAdded
- tokenizer_config.jsonAdded+28
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178def create_model(source_model_id: str, source_revision: str, save_folder: str) -> str: import json from pathlib import Path
import torch from huggingface_hub import hf_hub_download from safetensors.torch import save_file from torch import nn from transformers import AutoConfig, HYV4VLForConditionalGeneration, set_seed from transformers.models.hy_v4_vl.modeling_hy_v4_vl import ( HYV4VLAttention, HYV4VLMLP, HYV4VLRMSNorm, )
folder = Path(save_folder) folder.mkdir(parents=True, exist_ok=True) assets = { "chat_template.jinja", "generation_config.json", "processor_config.json", "tokenizer.json", "tokenizer_config.json", "LICENSE", } for name in assets: (folder / name).write_bytes(Path(hf_hub_download(source_model_id, name, revision=source_revision)).read_bytes())
config = json.loads( Path(hf_hub_download(source_model_id, "config.json", revision=source_revision)).read_text(encoding="utf-8") ) text, vision = config["text_config"], config["vision_config"] layers = 10 # hidden_size 8 is the kernel floor: the tiny MoE uses `torch.nn.functional.grouped_mm`, # which raises "strides should be multiple of 16 bytes" for BF16 rows narrower than 8. text.update( hidden_size=8, num_hidden_layers=layers, num_attention_heads=8, q_lora_rank=64, kv_lora_rank=512, qk_nope_head_dim=32, qk_rope_head_dim=64, qk_head_dim=96, v_head_dim=32, intermediate_size=128, moe_intermediate_size=128, n_routed_experts=32, num_experts_per_tok=8, index_head_dim=128, index_n_heads=32, # One dense layer then MoE, exactly like the source's 1 + 77 split. mlp_layer_types=["dense"] + ["sparse"] * (layers - 1), layer_types=["deepseek_sparse_attention"] * layers, indexer_types=config["indexer_types"][:layers], ) vision.update( hidden_size=64, num_hidden_layers=4, num_attention_heads=2, intermediate_size=128, out_hidden_size=text["hidden_size"], ) # DFly2 target layers: one distinct backbone layer per draft layer. target_layers = [1, 3, 5, 7, 9] config["dfly_target_index_layer"] = list(target_layers) config["dfly_target_kv_layers"] = list(target_layers) (folder / "config.json").write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
set_seed(42) model = HYV4VLForConditionalGeneration._from_config(AutoConfig.from_pretrained(folder), dtype=torch.bfloat16)
# The Transformers class stops at the vision tower and language backbone; the # source checkpoint also carries the five-layer DFly2 parallel drafter. Each # draft layer is a dense MLA decoder that reuses a target layer's KV cache and # sparse top-k, so it owns no indexer and no iHC. class DraftLayer(nn.Module): def __init__(self, cfg): super().__init__() self.self_attn = HYV4VLAttention(cfg, layer_idx=0) self.self_attn.indexer = None self.self_attn.skip_topk = True self.mlp = HYV4VLMLP(cfg) self.input_layernorm = HYV4VLRMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps) self.post_attention_layernorm = HYV4VLRMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps)
class MtpFusion(nn.Module): def __init__(self, cfg): super().__init__() self.enorm = HYV4VLRMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps) self.hnorm = HYV4VLRMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps) self.eh_proj = nn.Linear(2 * cfg.hidden_size, cfg.hidden_size, bias=False) self.gate = nn.Parameter(torch.empty(cfg.hidden_size))
class HiddenCorrection(nn.Module): def __init__(self, cfg): super().__init__() width = cfg.hidden_size self.hidden_norm = HYV4VLRMSNorm(width, eps=cfg.rms_norm_eps) self.embed_norm = HYV4VLRMSNorm(width, eps=cfg.rms_norm_eps) self.gate_proj = nn.Linear(2 * width, width, bias=False) self.up_proj = nn.Linear(2 * width, width, bias=False) self.down_proj = nn.Linear(width, width, bias=False)
class Draft(nn.Module): def __init__(self, cfg, count): super().__init__() self.layers = nn.ModuleList([DraftLayer(cfg) for _ in range(count)]) self.mtp_fusion = MtpFusion(cfg) self.hidden_correction = HiddenCorrection(cfg) self.final_norm = HYV4VLRMSNorm(cfg.hidden_size, eps=cfg.rms_norm_eps) self.confidence_head = nn.Linear(cfg.hidden_size, 1)
text_config = model.config.text_config draft = Draft(text_config, model.config.dfly_num_hidden_layers) model.model.dfly_layers = draft with torch.no_grad(): for name, parameter in draft.named_parameters(): if name.endswith("norm.weight") or name.endswith("norm.bias"): parameter.fill_(1.0) elif name.endswith("bias"): parameter.zero_() else: parameter.normal_(mean=0.0, std=text_config.initializer_range)
def public_name(name: str) -> str: name = name.replace("model.language_model.", "model.") name = name.replace("model.vision_tower.", "vit.") for branch, node in (("attn_hc", "hc_attn_layer"), ("ffn_hc", "hc_mlp_layer")): for suffix in ("fn", "base", "scale"): name = name.replace(f".{branch}.{suffix}", f".{node}.hc_pre.hc_{suffix}") name = name.replace(".self_attn.sinks", ".self_attn.learnable_sink_param") name = name.replace(".self_attn.gate_proj", ".self_attn.linear_gate") for suffix in ("fn", "base", "scale"): name = name.replace(f".hc_head.hc_{suffix}", f".hc_head.hc_head_{suffix}") name = name.replace(".layer_norm1.", ".input_layernorm.") name = name.replace(".layer_norm2.", ".post_attention_layernorm.") name = name.replace(".mlp.fc1.", ".mlp.dense_h_to_4h.") name = name.replace(".mlp.fc2.", ".mlp.dense_4h_to_h.") name = name.replace(".patch_merger.before_rms.", ".perceive.norm.") name = name.replace(".patch_merger.proj_conv.", ".perceive.proj.0.") name = name.replace(".patch_merger.proj_out.", ".perceive.proj.2.") name = name.replace(".patch_merger.image_newline", ".perceive.image_newline") if name.startswith("model.dfly_layers."): name = name.replace("model.dfly_layers.layers.", "model.dfly_layers.") name = name.replace("model.dfly_layers.confidence_head.", "model.dfly_layers.confidence_head.proj.") return name
state = {} for name, value in model.state_dict().items(): public = public_name(name) # Source: backbone iHC, attention sinks and router correction bias are FP32; # the DFly2 sinks and any draft-layer tensors are BF16. backbone = not public.startswith("model.dfly_layers.") full_precision = backbone and public.endswith( ( ".hc_fn", ".hc_base", ".hc_scale", ".hc_head_fn", ".hc_head_base", ".hc_head_scale", ".learnable_sink_param", ".e_score_correction_bias", ) ) dtype = torch.float32 if full_precision else torch.bfloat16 state[public] = value.detach().to(dtype).cpu().contiguous() save_file(state, folder / "model.safetensors", metadata={"format": "pt"}) return str(model)
if __name__ == "__main__": create_model( source_model_id="tencent/Hy4", source_revision="c10c0de5b6f850703fb0a90e65d1c32b558b9167", save_folder="/tmp/hy4", )12345678910111213141516171819202122232425262728293031323334353637{ "source_model": { "name": "tencent/Hy4", "commit_id": "c10c0de5b6f850703fb0a90e65d1c32b558b9167" }, "environments": { "creation": { "python": "3.12.13", "packages": { "Pillow": "12.3.0", "huggingface_hub": "2.3.0", "numpy": "2.5.2", "safetensors": "0.8.0", "tokenizers": "0.23.3", "torch": "2.13.0+cu126", "transformers": "5.24.0.dev0" }, "cuda": "12.6" }, "transformers": { "python": "3.12.13", "packages": { "Pillow": "12.3.0", "huggingface_hub": "2.3.0", "numpy": "2.5.2", "safetensors": "0.8.0", "tokenizers": "0.23.3", "torch": "2.13.0+cu126", "transformers": "5.24.0.dev0" }, "cuda": "12.6", "hardware": { "gpu_model": "NVIDIA H20" } } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283HYV4VLForConditionalGeneration( (model): HYV4VLModel( (language_model): HYV4VLTextModel( (embed_tokens): Embedding(120832, 8, padding_idx=120002) (layers): ModuleList( (0): HYV4VLDecoderLayer( (self_attn): HYV4VLAttention( (q_a_proj): Linear(in_features=8, out_features=64, bias=False) (q_a_layernorm): HYV4VLRMSNorm((64,), eps=1e-05) (q_b_proj): Linear(in_features=64, out_features=768, bias=False) (kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False) (kv_a_layernorm): HYV4VLRMSNorm((512,), eps=1e-05) (kv_b_proj): Linear(in_features=512, out_features=512, bias=False) (o_proj): Linear(in_features=256, out_features=8, bias=False) (indexer): HYV4VLIndexer( (wq_b): Linear(in_features=64, out_features=4096, bias=False) (wk): Linear(in_features=8, out_features=128, bias=False) (k_norm): LayerNorm((128,), eps=1e-05, elementwise_affine=True, bias=True) (weights_proj): Linear(in_features=8, out_features=32, bias=False) ) (gate_proj): Linear(in_features=8, out_features=256, bias=False) ) (mlp): HYV4VLMLP( (gate_proj): Linear(in_features=8, out_features=128, bias=False) (up_proj): Linear(in_features=8, out_features=128, bias=False) (down_proj): Linear(in_features=128, out_features=8, bias=False) (act_fn): SiLUActivation() ) (input_layernorm): HYV4VLRMSNorm((8,), eps=1e-05) (post_attention_layernorm): HYV4VLRMSNorm((8,), eps=1e-05) (attn_hc): HYV4VLHyperConnection( (input_norm): HYV4VLUnweightedRMSNorm() ) (ffn_hc): HYV4VLHyperConnection( (input_norm): HYV4VLUnweightedRMSNorm() ) ) (1): HYV4VLDecoderLayer( (self_attn): HYV4VLAttention( (q_a_proj): Linear(in_features=8, out_features=64, bias=False) (q_a_layernorm): HYV4VLRMSNorm((64,), eps=1e-05) (q_b_proj): Linear(in_features=64, out_features=768, bias=False) (kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False) (kv_a_layernorm): HYV4VLRMSNorm((512,), eps=1e-05) (kv_b_proj): Linear(in_features=512, out_features=512, bias=False) (o_proj): Linear(in_features=256, out_features=8, bias=False) (indexer): HYV4VLIndexer( (wq_b): Linear(in_features=64, out_features=4096, bias=False) (wk): Linear(in_features=8, out_features=128, bias=False) (k_norm): LayerNorm((128,), eps=1e-05, elementwise_affine=True, bias=True) (weights_proj): Linear(in_features=8, out_features=32, bias=False) ) (gate_proj): Linear(in_features=8, out_features=256, bias=False) ) (mlp): HYV4VLMoE( (experts): HYV4VLExperts() (gate): HYV4VLTopkRouter() (shared_experts): HYV4VLMLP( (gate_proj): Linear(in_features=8, out_features=128, bias=False) (up_proj): Linear(in_features=8, out_features=128, bias=False) (down_proj): Linear(in_features=128, out_features=8, bias=False) (act_fn): SiLUActivation() ) ) (input_layernorm): HYV4VLRMSNorm((8,), eps=1e-05) (post_attention_layernorm): HYV4VLRMSNorm((8,), eps=1e-05) (attn_hc): HYV4VLHyperConnection( (input_norm): HYV4VLUnweightedRMSNorm() ) (ffn_hc): HYV4VLHyperConnection( (input_norm): HYV4VLUnweightedRMSNorm() ) ) (2-4): 3 x HYV4VLDecoderLayer( (self_attn): HYV4VLAttention( (q_a_proj): Linear(in_features=8, out_features=64, bias=False) (q_a_layernorm): HYV4VLRMSNorm((64,), eps=1e-05) (q_b_proj): Linear(in_features=64, out_features=768, bias=False) (kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False) (kv_a_layernorm): HYV4VLRMSNorm((512,), eps=1e-05) (kv_b_proj): Linear(in_features=512, out_features=512, bias=False) (o_proj): Linear(in_features=256, out_features=8, bias=False) (gate_proj): Linear(in_features=8, out_features=256, bias=False) ) (mlp): HYV4VLMoE( (experts): HYV4VLExperts() (gate): HYV4VLTopkRouter() (shared_experts): HYV4VLMLP( (gate_proj): Linear(in_features=8, out_features=128, bias=False) (up_proj): Linear(in_features=8, out_features=128, bias=False) (down_proj): Linear(in_features=128, out_features=8, bias=False) (act_fn): SiLUActivation() ) ) (input_layernorm): HYV4VLRMSNorm((8,), eps=1e-05) (post_attention_layernorm): HYV4VLRMSNorm((8,), eps=1e-05) (attn_hc): HYV4VLHyperConnection( (input_norm): HYV4VLUnweightedRMSNorm() ) (ffn_hc): HYV4VLHyperConnection( (input_norm): HYV4VLUnweightedRMSNorm() ) ) (5): HYV4VLDecoderLayer( (self_attn): HYV4VLAttention( (q_a_proj): Linear(in_features=8, out_features=64, bias=False) (q_a_layernorm): HYV4VLRMSNorm((64,), eps=1e-05) (q_b_proj): Linear(in_features=64, out_features=768, bias=False) (kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False) (kv_a_layernorm): HYV4VLRMSNorm((512,), eps=1e-05) (kv_b_proj): Linear(in_features=512, out_features=512, bias=False) (o_proj): Linear(in_features=256, out_features=8, bias=False) (indexer): HYV4VLIndexer( (wq_b): Linear(in_features=64, out_features=4096, bias=False) (wk): Linear(in_features=8, out_features=128, bias=False) (k_norm): LayerNorm((128,), eps=1e-05, elementwise_affine=True, bias=True) (weights_proj): Linear(in_features=8, out_features=32, bias=False) ) (gate_proj): Linear(in_features=8, out_features=256, bias=False) ) (mlp): HYV4VLMoE( (experts): HYV4VLExperts() (gate): HYV4VLTopkRouter() (shared_experts): HYV4VLMLP( (gate_proj): Linear(in_features=8, out_features=128, bias=False) (up_proj): Linear(in_features=8, out_features=128, bias=False) (down_proj): Linear(in_features=128, out_features=8, bias=False) (act_fn): SiLUActivation() ) ) (input_layernorm): HYV4VLRMSNorm((8,), eps=1e-05) (post_attention_layernorm): HYV4VLRMSNorm((8,), eps=1e-05) (attn_hc): HYV4VLHyperConnection( (input_norm): HYV4VLUnweightedRMSNorm() ) (ffn_hc): HYV4VLHyperConnection( (input_norm): HYV4VLUnweightedRMSNorm() ) ) (6-8): 3 x HYV4VLDecoderLayer( (self_attn): HYV4VLAttention( (q_a_proj): Linear(in_features=8, out_features=64, bias=False) (q_a_layernorm): HYV4VLRMSNorm((64,), eps=1e-05) (q_b_proj): Linear(in_features=64, out_features=768, bias=False) (kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False) (kv_a_layernorm): HYV4VLRMSNorm((512,), eps=1e-05) (kv_b_proj): Linear(in_features=512, out_features=512, bias=False) (o_proj): Linear(in_features=256, out_features=8, bias=False) (gate_proj): Linear(in_features=8, out_features=256, bias=False) ) (mlp): HYV4VLMoE( (experts): HYV4VLExperts() (gate): HYV4VLTopkRouter() (shared_experts): HYV4VLMLP( (gate_proj): Linear(in_features=8, out_features=128, bias=False) (up_proj): Linear(in_features=8, out_features=128, bias=False) (down_proj): Linear(in_features=128, out_features=8, bias=False) (act_fn): SiLUActivation() ) ) (input_layernorm): HYV4VLRMSNorm((8,), eps=1e-05) (post_attention_layernorm): HYV4VLRMSNorm((8,), eps=1e-05) (attn_hc): HYV4VLHyperConnection( (input_norm): HYV4VLUnweightedRMSNorm() ) (ffn_hc): HYV4VLHyperConnection( (input_norm): HYV4VLUnweightedRMSNorm() ) ) (9): HYV4VLDecoderLayer( (self_attn): HYV4VLAttention( (q_a_proj): Linear(in_features=8, out_features=64, bias=False) (q_a_layernorm): HYV4VLRMSNorm((64,), eps=1e-05) (q_b_proj): Linear(in_features=64, out_features=768, bias=False) (kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False) (kv_a_layernorm): HYV4VLRMSNorm((512,), eps=1e-05) (kv_b_proj): Linear(in_features=512, out_features=512, bias=False) (o_proj): Linear(in_features=256, out_features=8, bias=False) (indexer): HYV4VLIndexer( (wq_b): Linear(in_features=64, out_features=4096, bias=False) (wk): Linear(in_features=8, out_features=128, bias=False) (k_norm): LayerNorm((128,), eps=1e-05, elementwise_affine=True, bias=True) (weights_proj): Linear(in_features=8, out_features=32, bias=False) ) (gate_proj): Linear(in_features=8, out_features=256, bias=False) ) (mlp): HYV4VLMoE( (experts): HYV4VLExperts() (gate): HYV4VLTopkRouter() (shared_experts): HYV4VLMLP( (gate_proj): Linear(in_features=8, out_features=128, bias=False) (up_proj): Linear(in_features=8, out_features=128, bias=False) (down_proj): Linear(in_features=128, out_features=8, bias=False) (act_fn): SiLUActivation() ) ) (input_layernorm): HYV4VLRMSNorm((8,), eps=1e-05) (post_attention_layernorm): HYV4VLRMSNorm((8,), eps=1e-05) (attn_hc): HYV4VLHyperConnection( (input_norm): HYV4VLUnweightedRMSNorm() ) (ffn_hc): HYV4VLHyperConnection( (input_norm): HYV4VLUnweightedRMSNorm() ) ) ) (norm): HYV4VLRMSNorm((8,), eps=1e-05) (rotary_emb): HYV4VLRotaryEmbedding() (hc_head): HYV4VLHyperHead( (input_norm): HYV4VLUnweightedRMSNorm() ) ) (vision_tower): HYV4VLVisionModel( (embeddings): HYV4VLVisionPatchEmbed( (patch_embedding): Conv2d(3, 64, kernel_size=(16, 16), stride=(16, 16)) (position_embedding): Embedding(16385, 64) ) (layers): ModuleList( (0-3): 4 x HYV4VLVisionBlock( (layer_norm1): LayerNorm((64,), eps=1e-05, elementwise_affine=True, bias=True) (self_attn): HYV4VLVisionAttention( (q_proj): Linear(in_features=64, out_features=64, bias=True) (k_proj): Linear(in_features=64, out_features=64, bias=True) (v_proj): Linear(in_features=64, out_features=64, bias=True) (o_proj): Linear(in_features=64, out_features=64, bias=True) ) (layer_norm2): LayerNorm((64,), eps=1e-05, elementwise_affine=True, bias=True) (mlp): HYV4VLVisionMLP( (activation_fn): GELUActivation() (fc1): Linear(in_features=64, out_features=128, bias=True) (fc2): Linear(in_features=128, out_features=64, bias=True) ) ) ) (patch_merger): HYV4VLVisionPatchMerger( (proj_conv): Conv2d(64, 256, kernel_size=(2, 2), stride=(2, 2)) (proj_act): GELUActivation() (proj_out): Conv2d(256, 8, kernel_size=(1, 1), stride=(1, 1)) (before_rms): HYV4VLRMSNorm((64,), eps=1e-05) ) ) (dfly_layers): Draft( (layers): ModuleList( (0-4): 5 x DraftLayer( (self_attn): HYV4VLAttention( (q_a_proj): Linear(in_features=8, out_features=64, bias=False) (q_a_layernorm): HYV4VLRMSNorm((64,), eps=1e-05) (q_b_proj): Linear(in_features=64, out_features=768, bias=False) (kv_a_proj_with_mqa): Linear(in_features=8, out_features=576, bias=False) (kv_a_layernorm): HYV4VLRMSNorm((512,), eps=1e-05) (kv_b_proj): Linear(in_features=512, out_features=512, bias=False) (o_proj): Linear(in_features=256, out_features=8, bias=False) (indexer): None (gate_proj): Linear(in_features=8, out_features=256, bias=False) ) (mlp): HYV4VLMLP( (gate_proj): Linear(in_features=8, out_features=128, bias=False) (up_proj): Linear(in_features=8, out_features=128, bias=False) (down_proj): Linear(in_features=128, out_features=8, bias=False) (act_fn): SiLUActivation() ) (input_layernorm): HYV4VLRMSNorm((8,), eps=1e-05) (post_attention_layernorm): HYV4VLRMSNorm((8,), eps=1e-05) ) ) (mtp_fusion): MtpFusion( (enorm): HYV4VLRMSNorm((8,), eps=1e-05) (hnorm): HYV4VLRMSNorm((8,), eps=1e-05) (eh_proj): Linear(in_features=16, out_features=8, bias=False) ) (hidden_correction): HiddenCorrection( (hidden_norm): HYV4VLRMSNorm((8,), eps=1e-05) (embed_norm): HYV4VLRMSNorm((8,), eps=1e-05) (gate_proj): Linear(in_features=16, out_features=8, bias=False) (up_proj): Linear(in_features=16, out_features=8, bias=False) (down_proj): Linear(in_features=8, out_features=8, bias=False) ) (final_norm): HYV4VLRMSNorm((8,), eps=1e-05) (confidence_head): Linear(in_features=8, out_features=1, bias=True) ) ) (lm_head): Linear(in_features=8, out_features=120832, bias=False))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245 Tencent Hy License, Version 1.0
This License is derived from the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0), with modifications, mainly the additional commercial terms for large Model-as-a-Service ("MaaS") businesses in Section 10. This License is not the Apache License, Version 2.0, and is not endorsed by or affiliated with the Apache Software Foundation.
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 10 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). For the avoidance of doubt, the Work includes the model weights, parameters, configuration files, inference and training code, and documentation made available by Licensor under this License.
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. For the avoidance of doubt, Derivative Works include any fine-tuned, quantized, distilled, merged, pruned, or otherwise modified versions of the model weights.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. Notwithstanding the foregoing, any license terms You provide for the Work or any Derivative Works must not remove, limit, or conflict with Section 10, and Section 10 shall continue to apply to every recipient of the Work or any Derivative Works.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
10. Additional Commercial Terms.
10.1 MaaS. "MaaS" means giving third parties remote access to model inference or fine-tuning (e.g., via API), allowing them to submit inputs or specify parameters or training data. This excludes (i) end-user products with model capabilities confined to specific features or workflows, without general-purpose model access, or (ii) merely relaying requests to an independently operated third-party model service.
10.2 Separate License Required. Notwithstanding Sections 2 and 3, and except as provided in Section 10.3, if You operate a MaaS business, You must obtain a separate written license to use the Work or any Derivative Works from Licensor (including by email), in either of the following cases:
(a) if Your aggregate worldwide gross revenue exceeds US$50 million (or the equivalent in other currencies) in any consecutive 12-month period, whether or not such revenue is derived from the Work or any Derivative Works, before using (or continuing to use) the Work or any Derivative Works; or
(b) before using the Work or any Derivative Works in or for any product or service provided by You that has more than 100 million monthly active users in any calendar month.
10.3 Internal Use. Section 10.2 does not apply to Your use of the Work or any Derivative Works solely for internal purposes, provided that neither the Work, any Derivative Works, nor their outputs are made available to third parties.
10.4 Contact. For licensing requests or questions, please contact
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Tencent Hy License to your work.
To apply this License to a Derivative Work, attach the following notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!)
Copyright [yyyy] [name of copyright owner]
Licensed under the Tencent Hy License, Version 1.0 (the "License"), which is based on the Apache License, Version 2.0, with additional commercial terms. You may not use this file except in compliance with the License. You may obtain a copy of the License in the LICENSE file distributed with this work.
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138---library_name: transformerspipeline_tag: image-text-to-textbase_model:- tencent/Hy4---
This is a randomly initialized tiny model based on [tencent/Hy4](https://huggingface.co/tencent/Hy4) for testing and debugging.
| Feature | Source | This repo ||---|---|---|| Checkpoint tensor elements | 774.40B BF16, 30.80M F32 | 10.04M BF16, 5.82K F32 || Safetensors weight files | 1.55 TB (245 files) | 20.14 MB (model.safetensors) || Architecture / input | HYV4-VL; text, image, video | Same || Vocabulary rows / tied embeddings | 120,832 / false | Same || Backbone layers / MLP layout | 78 / 1 dense + 77 MoE | 10 / 1 dense + MoE || Hidden width / dense MLP width | 6,144 / 18,432 | 8 / 128 || Routed experts / top-k / shared experts | 256 / 8 / 1 | 32 / 8 / 1 || Expert intermediate size | 2,048 | 128 || Q heads; non-RoPE / RoPE / V dimensions | 64; 192 / 64 / 256 | 8; 32 / 64 / 32 || Q / KV LoRA rank | 2,048 / 512 | 64 / 512 || Indexer heads / dimension / top-k | 32 / 128 / 2,048 | 32 / 128 / 2,048 || Indexer layer cadence | full at 0, 1, then every 4th layer | Same || Independent Hyper-Connections | 4 streams; gated pre-branches | Same || MLA gating / learned sinks / SwiGLU clamp | elementwise / enabled / 10 | Same || Vision layers / width / output width | 40 / 1,536 / 6,144 | 4 / 64 / 8 || DFly2 draft layers | 5 dense MLA layers, fusion and hidden correction | Same structure || Checkpoint precision | BF16; FP32 iHC, attention sinks and router correction bias | Same |
The pinned Transformers `hy_v4_vl` class stops at the vision tower and language backbone; the ten-layer tiny keeps the source DFly2 drafter in the checkpoint. The DFly2 drafter is not executed by the Transformers example. M-RoPE sections are 12/10/10 as in the source.
| File path | Size ||------|------|| model.safetensors | 20.1MB |
### Example usage
#### Transformers (✅ verified)
Hy4's Gated DSA with learned sinks has no optimized Transformers kernel, so the example uses eager attention. `hy_v4_vl` is not in a released Transformers version; install it with `pip install "transformers @ git+https://github.com/huggingface/transformers@439bba079891ecd766900e8ce80ee961b94ef132"` first.
```pythondef run_transformers(model_id: str): import numpy as np import torch from PIL import Image, ImageDraw from transformers import AutoModelForImageTextToText, AutoProcessor from transformers.video_utils import VideoMetadata
model_id = str(model_id) processor = AutoProcessor.from_pretrained(model_id) model = AutoModelForImageTextToText.from_pretrained( model_id, dtype=torch.bfloat16, device_map="cuda", attn_implementation="eager" ) image = Image.new("RGB", (128, 128), "white") ImageDraw.Draw(image).text((20, 20), "Hello", fill="black") frames = np.stack( [ np.asarray(Image.new("RGB", (64, 64), color)) for color in ((220, 30, 30), (30, 220, 30), (30, 30, 220), (220, 220, 30)) ] ) messages = [ { "role": "user", "content": [ {"type": "image", "image": image}, {"type": "video", "video": frames}, {"type": "text", "text": "Describe the image and the video."}, ], } ] inputs = processor.apply_chat_template( messages, tokenize=True, add_generation_prompt=True, return_dict=True, return_tensors="pt", do_sample_frames=False, video_metadata=[VideoMetadata(total_num_frames=4, fps=2, frames_indices=[0, 1, 2, 3])], ).to(model.device) mm = inputs["mm_token_type_ids"] with torch.no_grad(): logits = model(**inputs).logits assert torch.isfinite(logits).all() output = model.generate(**inputs, do_sample=False, max_new_tokens=10) assert int((mm == 1).sum()) > 0 and int((mm == 2).sum()) > 0 print(processor.decode(output[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True))
if __name__ == "__main__": run_transformers(model_id="tiny-random/hy4")```
#### SGLang (unverified)
Hy4-VL support is in SGLang PR #51672 (`git+https://github.com/sgl-project/sglang.git@a0804a2f99719f5666ed2018e5d00a75645de6a8#subdirectory=python`), not a released wheel; see the [Hy4 cookbook](https://docs.sglang.io/cookbook/autoregressive/Tencent/Hy4). Install it into a CUDA 13 stack (torch 2.14.1+cu130, flashinfer 0.7.4, `sgl-fa3`, `sgl-flash-mla`) and set `SGLANG_SKIP_SGL_KERNEL_VERSION_CHECK=1`; on an H20 (driver 535) prepend the extracted `cuda-compat-13` `libcuda.so.1` to `LD_LIBRARY_PATH` and `LIBRARY_PATH`.
```bashsglang serve --model-path tiny-random/hy4 --tp 1 \ --dtype bfloat16 --context-length 4096 \ --reasoning-parser auto --tool-call-parser auto \ --served-model-name hy4 --host 0.0.0.0 --port 30000```
Send OpenAI chat messages. Text is a plain string; images and videos are `image_url` / `video_url` content parts (a local path or base64 `data:` URI). A video is one URL whose target is a frame container; to reuse the same 4-frame clip the tiny tests use, pass an `mp4` or a video file.
```pythonfrom openai import OpenAI
client = OpenAI(base_url="http://localhost:30000/v1", api_key="EMPTY")
# Text + image + video in one user messagemessages = [ { "role": "user", "content": [ {"type": "image_url", "image_url": {"url": "path/to/image.jpg"}}, {"type": "video_url", "video_url": {"url": "path/to/clip.mp4"}}, {"type": "text", "text": "Describe the image and the video."}, ], }]resp = client.chat.completions.create(model="hy4", messages=messages, max_tokens=64)print(resp.choices[0].message.content)```
### Creating this repo
- Code: [.meta/create_model.py](.meta/create_model.py)- Model structure: [.meta/model.log](.meta/model.log)- Environment: [.meta/env.json](.meta/env.json)
### Change log
- 2026-11-20: Initial tiny Hy4 vision-language checkpoint.
*This repo is generated by DeepSeek-V4.1-Flash.*123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355{#- ----------‑‑‑ special token variables ‑‑‑---------- -#}{%- set HYTK = ':opensource' %}{%- set hy_start_token = '<|hy_start{}|>'.format(HYTK) %}{%- set hy_middle_token = '<|hy_middle{}|>'.format(HYTK) %}{%- set hy_end_token = '<|hy_end{}|>'.format(HYTK) %}{%- set image_start_token = '<|hy_image▁start{}|>'.format(HYTK) %}{%- set image_pad_token = '<|hy_image▁pad{}|>'.format(HYTK) %}{%- set image_end_token = '<|hy_image▁end{}|>'.format(HYTK) %}{%- set video_start_token = '<|hy_video▁start{}|>'.format(HYTK) %}{%- set video_pad_token = '<|hy_video▁pad{}|>'.format(HYTK) %}{%- set video_end_token = '<|hy_video▁end{}|>'.format(HYTK) %}{%- set think_begin_token = '<think{}>'.format(HYTK) %}{%- set think_end_token = '</think{}>'.format(HYTK) %}{%- set toolcalls_begin_token = '<tool_calls{}>'.format(HYTK) %}{%- set toolcalls_end_token = '</tool_calls{}>'.format(HYTK) %}{%- set toolcall_begin_token = '<tool_call{}>'.format(HYTK) %}{%- set toolcall_end_token = '</tool_call{}>'.format(HYTK) %}{%- set argkey_begin_token = '<arg_key{}>'.format(HYTK) %}{%- set argkey_end_token = '</arg_key{}>'.format(HYTK) %}{%- set argvalue_begin_token = '<arg_value{}>'.format(HYTK) %}{%- set argvalue_end_token = '</arg_value{}>'.format(HYTK) %}{%- set toolresponse_begin_token = '<tool_response{}>'.format(HYTK) %}{%- set toolresponse_end_token = '</tool_response{}>'.format(HYTK) %}{%- set reasoning_mode_token = '<|reasoning_mode{}|>'.format(HYTK) %}
{#- ----------‑‑‑ hyperparameters variables ‑‑‑---------- -#}{%- if not add_generation_prompt is defined %} {%- set add_generation_prompt = false %}{%- endif %}{%- if not preserved_thinking is defined %} {%- if not tools %} {%- set preserved_thinking = false %} {%- else %} {%- set preserved_thinking = true %} {%- endif %}{%- endif %}
{%- if not reasoning_effort is defined %} {%- set reasoning_effort = 'high' %}{%- elif reasoning_effort not in ['no_think', 'high'] %} {%- if reasoning_effort is none %} {{- raise_exception('reasoning_effort error : None, should be no_think/high') }} {%- else %} {{- raise_exception('reasoning_effort error : ' + reasoning_effort + ', should be no_think/high') }} {%- endif %}{%- endif %}
{%- if fallback_strategy is defined and fallback_strategy == 'reasoning_toolcall_retry' %} {%- set reasoning_effort = 'high' %} {%- set add_generation_prompt = false %}{%- endif %}{%- if not raw_last_assistant is defined %} {%- set raw_last_assistant = false %}{%- endif %}{%- if not add_vision_id is defined %} {%- set add_vision_id = false %}{%- endif %}{%- set image_count = namespace(value=0) %}{%- set video_count = namespace(value=0) %}
{%- macro tool_to_json(tool) -%} {%- set ns_tool = namespace(first=true) -%} {{- '{' -}} {%- for k, v in tool.items() -%} {%- if k != 'defer_loading' and k != 'strict' -%} {%- if not ns_tool.first -%}{{- ', ' -}}{%- endif -%} {%- set ns_tool.first = false -%} {{- '"' ~ k ~ '": ' ~ (v | tojson(ensure_ascii=False)) -}} {%- endif -%} {%- endfor -%} {{- '}' -}}{%- endmacro -%}
{%- macro render_content(content, do_vision_count=true, is_system_content=false) -%} {%- if content is string -%} {{- content -}} {%- elif content is iterable and content is not mapping -%} {%- for item in content -%} {%- if item is mapping and item.type == 'text' -%} {{- item.text -}} {%- elif item is mapping and ('image' in item or 'image_url' in item or item.type in ['image', 'image_url']) -%} {%- if is_system_content -%} {{- raise_exception('System message cannot contain images.') -}} {%- endif -%} {%- if do_vision_count -%} {%- set image_count.value = image_count.value + 1 -%} {%- endif -%} {%- if add_vision_id -%} {{- 'Picture ' ~ image_count.value ~ ': ' -}} {%- endif -%} {{- image_start_token ~ image_pad_token ~ image_end_token -}} {%- elif item is mapping and ('video' in item or 'video_url' in item or item.type in ['video', 'video_url']) -%} {%- if is_system_content -%} {{- raise_exception('System message cannot contain videos.') -}} {%- endif -%} {%- if do_vision_count -%} {%- set video_count.value = video_count.value + 1 -%} {%- endif -%} {%- if add_vision_id -%} {{- 'Video ' ~ video_count.value ~ ': ' -}} {%- endif -%} {{- video_start_token ~ video_pad_token ~ video_end_token -}} {%- elif item is string -%} {{- item -}} {%- else -%} {{- item | string -}} {%- endif -%} {%- endfor -%} {%- elif content is none -%} {{- '' -}} {%- else -%} {{- content | string -}} {%- endif -%}{%- endmacro -%}
{%- macro render_tools_prompt() -%} {{- '# Tools\n\nYou may call one or more functions to assist with the user query.' -}} {{- '\n\nYou are provided with function signatures within <tools></tools> XML tags:' -}} {{- '\n<tools>\n' -}} {%- set tool_ns = namespace(first=true) -%} {%- for tool in tools -%} {%- set t = tool['function'] if tool is mapping and 'function' in tool else tool -%} {%- if t.defer_loading is not defined or not t.defer_loading -%} {%- if not tool_ns.first -%}{{- '\n' -}}{%- endif -%} {%- set tool_ns.first = false -%} {{- tool_to_json(t) -}} {%- endif -%} {%- endfor -%} {{- '\n</tools>\n\n' -}} {{- 'For function call returns, you should first print ' ~ toolcalls_begin_token -}} {{- '\nFor each function call, you should return object like:\n' -}} {{- toolcall_begin_token ~ '{function-name}' -}} {{- argkey_begin_token ~ '{arg-key-1}' ~ argkey_end_token -}} {{- argvalue_begin_token ~ '{arg-value-1}' ~ argvalue_end_token -}} {{- argkey_begin_token ~ '{arg-key-2}' ~ argkey_end_token -}} {{- argvalue_begin_token ~ '{arg-value-2}' ~ argvalue_end_token -}} {{- '...' -}} {{- toolcall_end_token -}} {{- '\nAt the end of function call returns, you should print ' ~ toolcalls_end_token -}}{%- endmacro -%}
{#- adjacent tool_search_output parts share one <tools> block, so a tool search result has the same shape as the tools prompt -#}{%- macro render_tool_response(message) -%} {%- set content = message['content'] -%} {{- toolresponse_begin_token -}} {%- if content is string -%} {{- content -}} {%- elif content is iterable and content is not mapping -%} {%- set tools_ns = namespace(open=false) -%} {%- for item in content -%} {%- set is_search_output = item is mapping and item.type is defined and item.type == 'tool_search_output' -%} {%- if is_search_output and not tools_ns.open -%} {{- '<tools>\n' -}} {%- set tools_ns.open = true -%} {%- elif not is_search_output and tools_ns.open -%} {{- '</tools>' -}} {%- set tools_ns.open = false -%} {%- endif -%} {%- if is_search_output -%} {%- if item.tools is defined and item.tools is iterable -%} {%- for tool in item.tools -%} {%- set t = tool['function'] if tool is mapping and 'function' in tool else tool -%} {{- tool_to_json(t) ~ '\n' -}} {%- endfor -%} {%- endif -%} {%- elif item is mapping and item.output is defined -%} {{- render_content(item.output) -}} {%- else -%} {{- render_content([item]) -}} {%- endif -%} {%- endfor -%} {%- if tools_ns.open -%} {{- '</tools>' -}} {%- endif -%} {%- else -%} {{- render_content(content) -}} {%- endif -%} {{- toolresponse_end_token -}}{%- endmacro -%}
{#- consecutive tool messages are clustered into a single tool message whose content is the list of the original tool messages; the result is written to merged_ns.messages (a macro cannot return a list) -#}{%- set merged_ns = namespace(messages=[]) %}{%- macro merge_tool_responses(messages) -%} {%- set merge_ns = namespace(result=[], cluster=[]) -%} {%- for message in messages -%} {%- if message['role'] == 'tool' -%} {%- set merge_ns.cluster = merge_ns.cluster + [message] -%} {%- else -%} {%- if merge_ns.cluster -%} {%- set merge_ns.result = merge_ns.result + [{'role': 'tool', 'content': merge_ns.cluster}] -%} {%- set merge_ns.cluster = [] -%} {%- endif -%} {%- set merge_ns.result = merge_ns.result + [message] -%} {%- endif -%} {%- endfor -%} {%- if merge_ns.cluster -%} {%- set merge_ns.result = merge_ns.result + [{'role': 'tool', 'content': merge_ns.cluster}] -%} {%- endif -%} {%- set merged_ns.messages = merge_ns.result -%}{%- endmacro -%}
{#- render one tool cluster, reordered to follow the tool_call order of the preceding assistant turn; any missing / ambiguous id falls back to the original tool message order for the whole cluster -#}{%- macro render_tool_responses(tool_messages, tool_call_ids) -%} {%- set order_ns = namespace(ordered=[], matched=true) -%} {%- if tool_call_ids and tool_call_ids | length == tool_messages | length -%} {%- for tool_call_id in tool_call_ids -%} {%- set hit_ns = namespace(count=0, message=none) -%} {%- for tool_message in tool_messages -%} {%- set message_id = tool_message['tool_call_id'] if tool_message['tool_call_id'] is defined else tool_message['id'] -%} {%- if message_id is defined and message_id == tool_call_id -%} {%- set hit_ns.count = hit_ns.count + 1 -%} {%- set hit_ns.message = tool_message -%} {%- endif -%} {%- endfor -%} {%- if hit_ns.count == 1 -%} {%- set order_ns.ordered = order_ns.ordered + [hit_ns.message] -%} {%- else -%} {%- set order_ns.matched = false -%} {%- endif -%} {%- endfor -%} {%- else -%} {%- set order_ns.matched = false -%} {%- endif -%} {%- for tool_message in (order_ns.ordered if order_ns.matched else tool_messages) -%} {{- render_tool_response(tool_message) -}} {%- endfor -%}{%- endmacro -%}
{%- set _ = merge_tool_responses(messages) %}{%- set normed_messages = merged_ns.messages %}
{%- set ns = namespace(last_user_index=-1, has_leading_system=false) %}{%- if normed_messages and normed_messages[0].role == 'system' %} {%- set ns.has_leading_system = true %}{%- endif %}{%- for message in normed_messages %} {%- if message['role'] == 'user' %} {%- set ns.last_user_index = loop.index0 %} {%- endif %}{%- endfor %}
{#- no leading system: synthesize one for tools and/or reasoning_mode -#}{%- if not ns.has_leading_system %} {{- hy_start_token ~ 'system' ~ hy_middle_token -}} {%- if tools %} {{- render_tools_prompt() -}} {%- endif %} {{- reasoning_mode_token ~ 'reasoning_effort:' ~ reasoning_effort -}} {{- hy_end_token -}}{%- endif %}
{%- set last_ns = namespace(last_is_assistant=false) %}{%- set prev_ns = namespace(tool_call_ids=[]) %}{%- for message in normed_messages %} {%- if message['role'] == 'system' %} {{- hy_start_token ~ 'system' ~ hy_middle_token -}} {#- tools / reasoning_mode only attach to the leading system (messages[0]) -#} {%- if loop.first %} {%- if tools %} {{- render_tools_prompt() -}} {%- endif %} {%- set content = render_content(message['content']) -%} {%- if tools and content -%} {{- '\n\n' -}} {%- endif -%} {{- content -}} {{- reasoning_mode_token ~ 'reasoning_effort:' ~ reasoning_effort -}} {%- else %} {{- render_content(message['content']) -}} {%- endif %} {{- hy_end_token -}} {%- elif message['role'] == 'user' %} {{- hy_start_token ~ 'user' ~ hy_middle_token -}} {{- render_content(message['content']) -}} {{- hy_end_token -}} {%- elif message['role'] == 'assistant' %} {%- set content_body = render_content(message['content']) -%} {#- 'reasoning' takes precedence, fall back to 'reasoning_content' when it is empty -#} {%- set reasoning_text = '' %} {%- if message['reasoning'] is defined and message['reasoning'] is string and message['reasoning'] %} {%- set reasoning_text = message['reasoning'] %} {%- elif message['reasoning_content'] is defined and message['reasoning_content'] is string and message['reasoning_content'] %} {%- set reasoning_text = message['reasoning_content'] %} {%- endif %} {#- no_think overrides preserved_thinking: history is always emitted with empty think tags -#} {%- if reasoning_effort != 'no_think' and (preserved_thinking or loop.index0 > ns.last_user_index) and reasoning_text %} {%- set content = think_begin_token ~ reasoning_text ~ think_end_token ~ content_body %} {%- else %} {%- set content = think_begin_token ~ think_end_token ~ content_body %} {%- endif %} {{- hy_start_token ~ 'assistant' ~ hy_middle_token -}} {%- if message['tool_calls'] is defined and message['tool_calls'] %} {#- remember the tool_call ids of this turn to order the following tool responses; an incomplete id set means "do not reorder" -#} {%- set ids_ns = namespace(ids=[], complete=true) %} {%- for tool in message['tool_calls'] %} {%- set tool_call_id = tool['id'] if tool['id'] is defined and tool['id'] else tool['tool_call_id'] %} {%- if tool_call_id is defined and tool_call_id %} {%- set ids_ns.ids = ids_ns.ids + [tool_call_id] %} {%- else %} {%- set ids_ns.complete = false %} {%- endif %} {%- endfor %} {%- set prev_ns.tool_call_ids = ids_ns.ids if ids_ns.complete else [] %} {{- content -}} {{- toolcalls_begin_token -}} {%- for tool in message['tool_calls'] -%} {%- set func = tool['function'] if tool is mapping and 'function' in tool else tool -%} {%- set arguments = func['arguments'] -%} {{- toolcall_begin_token ~ func['name'] -}} {%- for key, value in arguments.items() -%} {{- argkey_begin_token ~ key ~ argkey_end_token -}} {%- if value is not string -%} {%- set value = value | tojson(ensure_ascii=False) -%} {%- endif -%} {{- argvalue_begin_token ~ value ~ argvalue_end_token -}} {%- endfor -%} {{- toolcall_end_token -}} {%- endfor -%} {{- toolcalls_end_token -}} {%- else %} {%- if loop.last and raw_last_assistant %} {{- content_body -}} {%- else %} {{- content -}} {%- endif %} {%- endif %} {#- continuation / prefill: last assistant is still open, do not close with hy_end -#} {%- if not (loop.last and raw_last_assistant) and not (loop.last and fallback_strategy is defined and fallback_strategy == 'reasoning_toolcall_retry') %} {{- hy_end_token -}} {%- endif %} {%- elif message['role'] == 'tool' %} {{- hy_start_token ~ 'tool' ~ hy_middle_token -}} {{- render_tool_responses(message['content'], prev_ns.tool_call_ids) -}} {{- hy_end_token -}} {%- else %} {{- hy_start_token ~ message['role'] ~ hy_middle_token -}} {{- render_content(message['content']) -}} {{- hy_end_token -}} {%- endif %} {%- if message['role'] != 'assistant' or not (message['tool_calls'] is defined and message['tool_calls']) %} {%- set prev_ns.tool_call_ids = [] %} {%- endif %} {%- if loop.last and message['role'] == 'assistant' %} {%- set last_ns.last_is_assistant = true %} {%- endif %}{%- endfor %}{%- if add_generation_prompt %} {%- if not last_ns.last_is_assistant %} {%- if reasoning_effort == 'no_think' %} {{- hy_start_token ~ 'assistant' ~ hy_middle_token ~ think_begin_token ~ think_end_token -}} {%- else %} {{- hy_start_token ~ 'assistant' ~ hy_middle_token ~ think_begin_token -}} {%- endif %} {%- endif %}{%- endif %}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320{ "architectures": [ "HYV4VLForConditionalGeneration" ], "attention_bias": false, "attention_dropout": 0.0, "bitwise_backward_align": false, "bos_token_id": 120000, "enable_ihc": true, "enable_lm_head_fp32": true, "eos_token_id": 120025, "first_k_dense_replace": 1, "gated_mla": true, "gating_type": "elementwise", "hc_eps": 1e-06, "hc_magnitude": 2.0, "hc_mult": 4, "head_dim": 64, "hidden_act": "silu", "hidden_size": 6144, "image_end_token_id": 120119, "image_newline_token_id": 120121, "image_start_token_id": 120118, "image_token_id": 120120, "index_head_dim": 128, "index_n_heads": 32, "index_topk": 2048, "indexer_types": [ "full", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full" ], "initializer_range": 0.006, "intermediate_size": 18432, "kv_lora_rank": 512, "learnable_sink": true, "learnable_sink_init": 0.0, "max_position_embeddings": 1048576, "model_type": "hy_v4_vl", "moe_intermediate_size": 2048, "n_group": 1, "n_routed_experts": 256, "n_shared_experts": 1, "norm_topk_prob": true, "num_attention_heads": 64, "num_experts_per_tok": 8, "num_hidden_layers": 78, "num_key_value_heads": 8, "num_nextn_predict_layers": 0, "pad_token_id": 120002, "q_lora_rank": 2048, "qk_head_dim": 256, "qk_nope_head_dim": 192, "qk_norm": true, "qk_rope_head_dim": 64, "rms_norm_eps": 1e-05, "rope_parameters": { "mrope_interleaved": true, "mrope_section": [ 12, 10, 10 ], "rope_theta": 10000000, "rope_type": "default" }, "routed_scaling_factor": 2.827, "swiglu_limit": 10.0, "text_config": { "architectures": [ "HYV4VLForConditionalGeneration" ], "attention_bias": false, "attention_dropout": 0.0, "bitwise_backward_align": false, "bos_token_id": 120000, "enable_ihc": true, "enable_lm_head_fp32": true, "eos_token_id": 120025, "first_k_dense_replace": 1, "gated_mla": true, "gating_type": "elementwise", "hc_eps": 1e-06, "hc_magnitude": 2.0, "hc_mult": 4, "head_dim": 64, "hidden_act": "silu", "hidden_size": 8, "image_newline_token_id": 120121, "index_head_dim": 128, "index_n_heads": 32, "index_topk": 2048, "indexer_types": [ "full", "full", "shared", "shared", "shared", "full", "shared", "shared", "shared", "full" ], "initializer_range": 0.006, "intermediate_size": 128, "kv_lora_rank": 512, "layer_types": [ "deepseek_sparse_attention", "deepseek_sparse_attention", "deepseek_sparse_attention", "deepseek_sparse_attention", "deepseek_sparse_attention", "deepseek_sparse_attention", "deepseek_sparse_attention", "deepseek_sparse_attention", "deepseek_sparse_attention", "deepseek_sparse_attention" ], "learnable_sink": true, "learnable_sink_init": 0.0, "max_position_embeddings": 1048576, "mlp_layer_types": [ "dense", "sparse", "sparse", "sparse", "sparse", "sparse", "sparse", "sparse", "sparse", "sparse" ], "model_type": "hy_v4", "moe_intermediate_size": 128, "n_group": 1, "n_routed_experts": 32, "n_shared_experts": 1, "norm_topk_prob": true, "num_attention_heads": 8, "num_experts_per_tok": 8, "num_hidden_layers": 10, "num_key_value_heads": 8, "num_nextn_predict_layers": 0, "pad_token_id": 120002, "q_lora_rank": 64, "qk_head_dim": 96, "qk_nope_head_dim": 32, "qk_norm": true, "qk_rope_head_dim": 64, "rms_norm_eps": 1e-05, "rope_parameters": { "mrope_interleaved": true, "mrope_section": [ 12, 10, 10 ], "rope_theta": 10000000, "rope_type": "default" }, "routed_scaling_factor": 2.827, "swiglu_limit": 10.0, "tie_word_embeddings": false, "topk_group": 1, "use_cache": true, "v_head_dim": 32, "video_token_id": 120124, "vocab_size": 120832 }, "tie_word_embeddings": false, "topk_group": 1, "transformers_version": "5.24.0", "v_head_dim": 256, "video_end_token_id": 120123, "video_start_token_id": 120122, "video_token_id": 120124, "vision_config": { "add_patchemb_bias": true, "anyres_vit_max_image_size": 2048, "attention_dropout": 0.0, "cat_extra_token": 0, "hidden_act": "gelu", "hidden_dropout": 0.0, "hidden_size": 64, "img_max_token_num": 4096, "intermediate_size": 128, "interpolate_mode": "bilinear", "learnable_mlp_pooling_size": 0, "max_image_size": 2048, "max_vit_seq_len": 16384, "min_image_size": 512, "model_type": "hy_v4_vl", "num_attention_heads": 2, "num_channels": 3, "num_hidden_layers": 4, "num_key_value_heads": 16, "out_hidden_size": 8, "patch_size": 16, "perceive_post_norm": false, "perceive_pre_norm": true, "projector_type": "rmsnorm_mlp_adapter", "remove_prenorm": true, "resize_resolution": 2048, "rms_norm_eps": 1e-05, "rope_2d_percent": 1.0, "rope_2d_theta": 10000.0, "spatial_merge_size": 2, "spatial_patch_size": 1, "temporal_patch_size": 1, "text_hidden_size": 6144, "video_max_image_size": 768, "video_min_image_size": 256, "video_spatial_compression": false, "video_temporal_compression": false, "vision_full_attention": false }, "vocab_size": 120832, "dtype": "bfloat16", "dfly_enable_ihc": false, "dfly_mtp_fusion": "slot0", "dfly_target_index_topk": 2048, "dfly_context_local_window": null, "dfly_enable_hidden_correction": true, "dfly_num_hidden_layers": 5, "dfly_mlp_type": "dense", "dfly_mask_token_id": 120009, "dfly_target_index_layer": [ 1, 3, 5, 7, 9 ], "dfly_target_kv_layers": [ 1, 3, 5, 7, 9 ], "dfly_attn_causal": true, "dfly_block_size": 7}12345678910{ "bos_token_id": 120000, "do_sample": true, "eos_token_id": 120025, "pad_token_id": 120002, "temperature": 0.9, "top_k": -1, "top_p": 1, "transformers_version": "5.24.0"}123version https://git-lfs.github.com/spec/v1oid sha256:993e2daed4b926b926d3f8c88f1694d63c780d99fea17d1864284d78d4f9af7esize 20144742123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475{ "image_processor": { "device": "cpu", "do_convert_rgb": true, "do_normalize": true, "do_rescale": true, "do_resize": true, "image_mean": [ 0.5, 0.5, 0.5 ], "image_processor_type": "HYV4VLImageProcessor", "image_std": [ 0.5, 0.5, 0.5 ], "max_frames": 1024, "max_pixels": 4194304, "merge_size": 2, "min_frames": 2, "min_pixels": 4096, "patch_size": 16, "resample": 1, "rescale_factor": 0.00392156862745098, "size": { "longest_edge": 4194304, "shortest_edge": 4096 }, "spatial_patch_size": 1, "temporal_patch_size": 1, "timestamp_token_per_frame": 6, "timestamp_token_reserve": 1000, "video_max_image_size": 1024 }, "processor_class": "HYV4VLProcessor", "video_processor": { "do_convert_rgb": true, "do_normalize": true, "do_rescale": true, "do_resize": true, "do_sample_frames": false, "fps": 2, "image_mean": [ 0.5, 0.5, 0.5 ], "image_std": [ 0.5, 0.5, 0.5 ], "max_frames": 1024, "max_pixels": 4194304, "merge_size": 2, "min_frames": 2, "min_pixels": 4096, "patch_size": 16, "resample": 1, "rescale_factor": 0.00392156862745098, "return_metadata": false, "size": { "longest_edge": 4194304, "shortest_edge": 4096 }, "spatial_patch_size": 1, "temporal_patch_size": 1, "timestamp_token_per_frame": 6, "timestamp_token_reserve": 1000, "video_max_image_size": 1024, "video_processor_type": "HYV4VLVideoProcessor" }}12345678910111213141516171819202122232425262728{ "backend": "tokenizers", "bos_token": "<|hy_start:opensource|>", "clean_up_tokenization_spaces": false, "eos_token": "<|hy_end:opensource|>", "image_end_token": "<|hy_image▁end:opensource|>", "image_newline_token": "<|hy_image▁newline:opensource|>", "image_start_token": "<|hy_image▁start:opensource|>", "image_token": "<|hy_image▁pad:opensource|>", "is_local": true, "local_files_only": false, "model_max_length": 1000000000000000019884624838656, "model_specific_special_tokens": { "image_end_token": "<|hy_image▁end:opensource|>", "image_newline_token": "<|hy_image▁newline:opensource|>", "image_start_token": "<|hy_image▁start:opensource|>", "image_token": "<|hy_image▁pad:opensource|>", "video_end_token": "<|hy_video▁end:opensource|>", "video_start_token": "<|hy_video▁start:opensource|>", "video_token": "<|hy_video▁pad:opensource|>" }, "pad_token": "<|hy_pad:opensource|>", "processor_class": "HYV4VLProcessor", "tokenizer_class": "TokenizersBackend", "video_end_token": "<|hy_video▁end:opensource|>", "video_start_token": "<|hy_video▁start:opensource|>", "video_token": "<|hy_video▁pad:opensource|>"}.meta/create_model.pyAdded+178
.meta/env.jsonAdded+37
.meta/model.logAdded+283
LICENSEAdded+245
README.mdAdded+138
chat_template.jinjaAdded+355
config.jsonAdded+320
generation_config.jsonAdded+10
model.safetensorsAdded+3
processor_config.jsonAdded+75
tokenizer.jsonAdded
tokenizer_config.jsonAdded+28