Text Generation
Transformers
Safetensors
llama
feature-extraction
conversational
custom_code
text-generation-inference
Run this model with HF Jobs
Run ByteDance-Seed/Stable-DiffCoder-8B-Instruct on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/ByteDance-Seed/Stable-DiffCoder-8B-Instruct. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/ByteDance-Seed/Stable-DiffCoder-8B-Instruct on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/ByteDance-Seed/Stable-DiffCoder-8B-Instruct. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/ByteDance-Seed/Stable-DiffCoder-8B-Instruct. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use ByteDance-Seed/Stable-DiffCoder-8B-Instruct with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use ByteDance-Seed/Stable-DiffCoder-8B-Instruct with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="ByteDance-Seed/Stable-DiffCoder-8B-Instruct", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoTokenizer, AutoModel tokenizer = AutoTokenizer.from_pretrained("ByteDance-Seed/Stable-DiffCoder-8B-Instruct", trust_remote_code=True) model = AutoModel.from_pretrained("ByteDance-Seed/Stable-DiffCoder-8B-Instruct", trust_remote_code=True, device_map="auto") messages = [ {"role": "user", "content": "Who are you?"}, ] inputs = tokenizer.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(tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use ByteDance-Seed/Stable-DiffCoder-8B-Instruct with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "ByteDance-Seed/Stable-DiffCoder-8B-Instruct" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "ByteDance-Seed/Stable-DiffCoder-8B-Instruct", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/ByteDance-Seed/Stable-DiffCoder-8B-Instruct
- SGLang
How to use ByteDance-Seed/Stable-DiffCoder-8B-Instruct 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 "ByteDance-Seed/Stable-DiffCoder-8B-Instruct" \ --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": "ByteDance-Seed/Stable-DiffCoder-8B-Instruct", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'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 "ByteDance-Seed/Stable-DiffCoder-8B-Instruct" \ --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": "ByteDance-Seed/Stable-DiffCoder-8B-Instruct", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use ByteDance-Seed/Stable-DiffCoder-8B-Instruct with Docker Model Runner:
docker model run hf.co/ByteDance-Seed/Stable-DiffCoder-8B-Instruct
Update to adapt transformers v5.3.0
#5
by Seas0 - opened
Files changed (5)
- README.md+3-3
- config.json+30-30
- generation_utils.pyDeleted-133
- modeling_seed_diffcoder.pyDeleted-30
- modeling_stable_diffcoder.pyAdded+259
51 unmodified lines52535455565758596082 unmodified lines14314414514651 unmodified lines| 👉 **Stable-DiffCoder-8B-Instruct** | 8K | 🤗 [Model](https://huggingface.co/ByteDance-Seed/Stable-DiffCoder-8B-Instruct) | Instruction-tuned for alignment with user intent. |## RequirementsYou need to install a specific version of `transformers` to adapt to the inference process:```bashpip install transformers==4.46.2```## Explanation of Inference Parameters- `steps`: Number of steps for diffusion generation82 unmodified linesprimaryClass={cs.CL},url={https://arxiv.org/abs/2601.15892},}```51 unmodified lines52535455565758596082 unmodified lines14314414514651 unmodified lines| 👉 **Stable-DiffCoder-8B-Instruct** | 8K | 🤗 [Model](https://huggingface.co/ByteDance-Seed/Stable-DiffCoder-8B-Instruct) | Instruction-tuned for alignment with user intent. |## RequirementsCurrent (v5.3.0) `transformers` is available for inference:```bashpip install transformers~=5.3.0```## Explanation of Inference Parameters- `steps`: Number of steps for diffusion generation82 unmodified linesprimaryClass={cs.CL},url={https://arxiv.org/abs/2601.15892},}```
12345678910111213141516171819202122232425262728293031{"architectures": ["LlamaForCausalLM"],"auto_map": {"AutoModelForCausalLM": "modeling_seed_diffcoder.SeedDiffcoderForCausalLM"},"attention_bias": false,"attention_dropout": 0.1,"bos_token_id": 0,"eos_token_id": 2,"hidden_act": "silu","hidden_size": 4096,"initializer_range": 0.009882118,"intermediate_size": 14336,"layer_norm_eps": null,"max_position_embeddings": 8192,"mlp_bias": false,"model_type": "llama","num_attention_heads": 32,"num_hidden_layers": 32,"num_key_value_heads": 8,"resid_pdrop": 0.1,"rms_norm_eps": 1e-06,"rope_theta": 500000.0,"tie_word_embeddings": false,"torch_dtype": "bfloat16","transformers_version": "4.46.2","use_cache": true,"vocab_size": 155136}12345678910111213141516171819202122232425262728293031{"architectures": ["StableDiffcoderForCausalLM"],"auto_map": {"AutoModelForCausalLM": "modeling_stable_diffcoder.StableDiffcoderForCausalLM"},"attention_bias": false,"attention_dropout": 0.1,"bos_token_id": 0,"eos_token_id": 2,"hidden_act": "silu","hidden_size": 4096,"initializer_range": 0.009882118,"intermediate_size": 14336,"layer_norm_eps": null,"max_position_embeddings": 8192,"mlp_bias": false,"model_type": "llama","num_attention_heads": 32,"num_hidden_layers": 32,"num_key_value_heads": 8,"resid_pdrop": 0.1,"rms_norm_eps": 1e-06,"rope_theta": 500000.0,"tie_word_embeddings": false,"torch_dtype": "bfloat16","transformers_version": "5.3.0","use_cache": true,"vocab_size": 155136}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133 # Copyright (c) 2026 ByteDance Ltd. and/or its affiliates # SPDX-License-Identifier: MIT
import torchimport numpy as npimport torch.nn.functional as F
from transformers import AutoTokenizer, AutoModel, AutoModelForCausalLMfrom transformers.cache_utils import DynamicCache
def add_gumbel_noise(logits, temperature): if temperature == 0: return logits logits = logits.to(torch.float64) noise = torch.rand_like(logits, dtype=torch.float64) gumbel_noise = (- torch.log(noise)) ** temperature return logits.exp() / gumbel_noise
def get_num_transfer_tokens(mask_index, steps): mask_num = mask_index.sum(dim=1, keepdim=True)
base = mask_num // steps remainder = mask_num % steps
num_transfer_tokens = torch.zeros(mask_num.size(0), steps, device=mask_index.device, dtype=torch.int64) + base
for i in range(mask_num.size(0)): num_transfer_tokens[i, :remainder[i]] += 1
return num_transfer_tokens
def make_block_causal_mask(seq_len, block_size=2, device=None, dtype=torch.bool): num_blocks = (seq_len + block_size - 1) // block_size block_mask = torch.tril(torch.ones((num_blocks, num_blocks), dtype=torch.bool, device=device)) local_block = torch.ones((block_size, block_size), dtype=torch.bool, device=device) mask = torch.kron(block_mask, local_block)[:seq_len, :seq_len]
attention_mask = mask.float() attention_mask.masked_fill_(~mask, float('-inf')) attention_mask = attention_mask.unsqueeze(0).unsqueeze(0).to(dtype) return attention_mask
@ torch.no_grad()def generate_block(model, prompt, steps=128, gen_length=128, block_length=128, temperature=0., remasking='low_confidence', tokenizer=None, mask_id=5, threshold=0.95, shift=False, eos_id=None): x = torch.full((1, prompt.shape[1] + gen_length), mask_id, dtype=torch.long).to(model.device) x[:, :prompt.shape[1]] = prompt.clone()
assert gen_length % block_length == 0 num_blocks = gen_length // block_length
assert steps % num_blocks == 0 steps = steps // num_blocks
prompt_len = prompt.shape[1] res_block = block_length - prompt_len % block_length every_block = [block_length for _ in range(num_blocks)] if res_block > 0: every_block = [res_block] + every_block every_block[-1] = block_length - res_block cum_block = [sum(every_block[:i+1]) for i in range(len(every_block))] num_block = len(cum_block)
block_diffusion_attention_mask = make_block_causal_mask(prompt.shape[1] + gen_length, block_length, model.device, dtype=torch.bfloat16) nfe = 0 final_flag = 0 prefill_length = prompt_len // block_length * block_length if prefill_length > 0: cur_attn_mask = block_diffusion_attention_mask[:, :, :prefill_length, :prefill_length] past_key_values = model(x[:, :prefill_length], attention_mask=cur_attn_mask, use_cache=True).past_key_values for num_block in range(num_blocks): current_block_start = prompt_len + cum_block[num_block - 1] if num_block > 0 else prefill_length current_block_end = prompt_len + cum_block[num_block]
block_mask_index = (x[:, current_block_start:current_block_end] == mask_id) num_transfer_tokens = get_num_transfer_tokens(block_mask_index, steps)
replace_position = torch.zeros_like(x, dtype=torch.bool) replace_position[:, current_block_start:current_block_end] = 1 i = 0 while True: nfe += 1 mask_index = (x[:, current_block_start:current_block_end] == mask_id) cur_attn_mask = block_diffusion_attention_mask[:, :, current_block_start:current_block_end, :current_block_end] output = model(x[:, current_block_start:current_block_end], attention_mask=block_diffusion_attention_mask[:, :, current_block_start:current_block_end, :current_block_end], past_key_values=past_key_values, use_cache=True, cache_position=replace_position.nonzero(as_tuple=True)[1]) logits = output.logits x0, transfer_index = get_transfer_index(logits, temperature, remasking, mask_index, x[:, current_block_start:current_block_end], num_transfer_tokens[:, i] if threshold is None else None, threshold, shift=False) x[:, current_block_start:current_block_end][transfer_index] = x0[transfer_index] if (x[:, current_block_start:current_block_end] == mask_id).sum() == 0: if eos_id is not None and (x[:, current_block_start:current_block_end] == eos_id).sum() > 0: final_flag = 1 x = x[:, :current_block_end] break past_key_values = model(x[:, current_block_start:current_block_end], attention_mask=block_diffusion_attention_mask[:, :, current_block_start:current_block_end, :current_block_end], past_key_values=past_key_values, use_cache=True, cache_position=replace_position.nonzero(as_tuple=True)[1]).past_key_values break if final_flag == 1: break i += 1 return x, nfe
def get_transfer_index(logits, temperature, remasking, mask_index, x, num_transfer_tokens, threshold=None, shift=False): logits_with_noise = add_gumbel_noise(logits, temperature=temperature) x0 = torch.argmax(logits_with_noise, dim=-1) # b, l if shift == True: x0 = torch.cat([x[:, :1], x0[:, :-1]], dim=-1) pad = torch.zeros_like(logits[:, :1]) logits = torch.cat([pad, logits[:, :-1]], dim=1) if remasking == 'low_confidence': p = F.softmax(logits.to(torch.float64), dim=-1) x0_p = torch.squeeze( torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1) # b, l elif remasking == 'random': x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device) else: raise NotImplementedError(remasking) x0 = torch.where(mask_index, x0, x) confidence = torch.where(mask_index, x0_p, -np.inf)
transfer_index = torch.zeros_like(x0, dtype=torch.bool, device=x0.device) if threshold is not None: num_transfer_tokens = mask_index.sum(dim=1, keepdim=True) for j in range(confidence.shape[0]): _, select_index = torch.topk(confidence[j], k=num_transfer_tokens[j]) transfer_index[j, select_index] = True if threshold is not None: for k in range(1, num_transfer_tokens[j]): if confidence[j, select_index[k]] < threshold: transfer_index[j, select_index[k]] = False return x0, transfer_index123456789101112131415161718192021222324252627282930 # Copyright (c) 2026 ByteDance Ltd. and/or its affiliates # SPDX-License-Identifier: MIT
from .generation_utils import generate_blockfrom transformers.models.llama.modeling_llama import LlamaForCausalLMfrom transformers.generation.utils import GenerationConfigimport torch
class SeedDiffcoderForCausalLM(LlamaForCausalLM): @torch.no_grad() def generate( self, input_ids=None, generation_config: GenerationConfig = None, **kwargs, ): if input_ids is None: raise ValueError("input_ids must be provided")
if generation_config is None: generation_config = self.generation_config
prompt = input_ids output_ids, nfe = generate_block( model=self, prompt=prompt, **kwargs, )
return output_ids123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259# Copyright (c) 2026 ByteDance Ltd. and/or its affiliates# SPDX-License-Identifier: MIT
import numpy as npimport torchfrom torch import nnimport torch.nn.functional as Ffrom transformers import AutoTokenizer, AutoModel, AutoModelForCausalLM, DynamicCachefrom transformers.models.llama.modeling_llama import LlamaForCausalLMfrom transformers.generation.utils import GenerationConfig
class StableDiffcoderForCausalLM(LlamaForCausalLM): def _get_num_transfer_tokens(self, mask_map, steps): # Only bs == 1 is supported for now mask_num = mask_map.sum().long().item()
base = mask_num // steps remainder = mask_num % steps
num_transfer_tokens = torch.full( (steps,), fill_value=base, device=mask_map.device, dtype=torch.long )
num_transfer_tokens[:remainder] += 1
return num_transfer_tokens
def _make_block_causal_mask( self, seq_len, block_size=2, device=None, dtype=torch.bfloat16 ): num_blocks = (seq_len + block_size - 1) // block_size block_mask = torch.tril( torch.ones((num_blocks, num_blocks), dtype=torch.bool, device=device) ) local_block = torch.ones( (block_size, block_size), dtype=torch.bool, device=device ) mask = block_mask.kron(local_block)[:seq_len, :seq_len]
attention_mask = mask.float() attention_mask.masked_fill_(~mask, -torch.inf) attention_mask = attention_mask.unsqueeze(0).unsqueeze(0).to(dtype) return attention_mask
def _get_transfer_index( self, logits, temperature, remasking, mask_index, x, num_transfer_token, threshold=None, shift=False, ): def add_gumbel_noise(logits, temperature): if temperature == 0: return logits logits = logits.to(torch.float64) noise = torch.rand_like(logits, dtype=torch.float64) gumbel_noise = (-torch.log(noise)) ** temperature return logits.exp() / gumbel_noise
logits_with_noise = add_gumbel_noise(logits, temperature=temperature) x0 = torch.argmax(logits_with_noise, dim=-1) # b, l if shift: x0 = torch.cat([x[:, :1], x0[:, :-1]], dim=-1) pad = torch.zeros_like(logits[:, :1]) logits = torch.cat([pad, logits[:, :-1]], dim=1) if remasking == "low_confidence": p = F.softmax(logits.to(torch.float64), dim=-1) x0_p = torch.squeeze( torch.gather(p, dim=-1, index=torch.unsqueeze(x0, -1)), -1 ) # b, l elif remasking == "random": x0_p = torch.rand((x0.shape[0], x0.shape[1]), device=x0.device) else: raise NotImplementedError(remasking)
x0 = torch.where(mask_index, x0, x) confidence = torch.where(mask_index, x0_p, -np.inf)
transfer_map = torch.zeros_like(x0, dtype=torch.bool, device=x0.device) if threshold is not None: num_transfer_token = mask_index.sum(dim=1, keepdim=True) _, select_index = torch.topk(confidence[0], k=num_transfer_token) transfer_map[0, select_index] = True if threshold is not None: for k in range(1, num_transfer_token): if confidence[0, select_index[k]] < threshold: transfer_map[0, select_index[k]] = False return x0, transfer_map
@torch.no_grad() def generate_block( self, input_ids: torch.LongTensor, steps=128, gen_length=128, block_length=4, temperature=0.0, remasking="low_confidence", tokenizer=None, mask_id=5, threshold=0.95, shift=False, eos_id=None, ): x = torch.cat( [ input_ids, torch.full( (input_ids.shape[0], gen_length), mask_id, dtype=torch.long, device=input_ids.device, ), ], dim=1, )
assert gen_length % block_length == 0, ( "gen_length must be divisible by block_length" ) gen_blocks = gen_length // block_length
assert steps % gen_blocks == 0, ( "steps must be divisible by the number of generation blocks" ) steps = steps // gen_blocks
assert x.shape[0] == 1, ( "Only batch size of 1 is supported for block-wise generation currently." )
prompt_length = input_ids.shape[1] gen_block_list = [block_length for _ in range(gen_blocks)]
res_block = block_length - (prompt_length % block_length) if res_block > 0: gen_block_list = [res_block] + gen_block_list gen_block_list[-1] = block_length - res_block gen_blocks += 1 cum_block = [sum(gen_block_list[: i + 1]) for i in range(len(gen_block_list))]
block_diffusion_attention_mask = self._make_block_causal_mask( prompt_length + gen_length, block_length, self.device, dtype=torch.bfloat16, )
past_key_values = DynamicCache()
nfe = 0 final_flag = False prefill_length = prompt_length // block_length * block_length if prefill_length > 0: cur_attn_mask = block_diffusion_attention_mask[ ..., :prefill_length, :prefill_length ] self( x[:, :prefill_length], past_key_values=past_key_values, attention_mask=cur_attn_mask, use_cache=True, ).past_key_values
for block_id, block_size in enumerate(gen_block_list): block_start = ( prompt_length + cum_block[block_id - 1] if block_id > 0 else prefill_length ) block_end = prompt_length + cum_block[block_id]
block_mask_map = x[:, block_start:block_end] == mask_id num_transfer_tokens = self._get_num_transfer_tokens(block_mask_map, steps)
replace_position = torch.zeros_like(x, dtype=torch.bool) replace_position[:, block_start:block_end] = True
for token_count in num_transfer_tokens: if token_count: nfe += 1 mask_map = x[:, block_start:block_end] == mask_id attention_mask = block_diffusion_attention_mask[ ..., block_start:block_end, :block_end ] output = self( x[:, block_start:block_end], attention_mask=attention_mask, past_key_values=past_key_values, use_cache=True, cache_position=replace_position.nonzero(as_tuple=True)[1], ) logits = output.logits
past_key_values.crop(block_start)
x0, transfer_map = self._get_transfer_index( logits, temperature, remasking, mask_map, x[:, block_start:block_end], token_count if threshold is None else None, threshold, shift=False, ) x[:, block_start:block_end][transfer_map] = x0[transfer_map]
if (x[:, block_start:block_end] == mask_id).sum() == 0: if ( eos_id is not None and (x[:, block_start:block_end] == eos_id).sum() > 0 ): final_flag = True x = x[:, :block_end] eos_pos = (x == eos_id).nonzero(as_tuple=True)[1][0].item() x[0, eos_pos:] = eos_id break nfe += 1 self( x[:, block_start:block_end], attention_mask=block_diffusion_attention_mask[ ..., block_start:block_end, :block_end ], past_key_values=past_key_values, use_cache=True, cache_position=replace_position.nonzero(as_tuple=True)[1], ) break
if final_flag: break
return x, nfe
@torch.no_grad() def generate( self, input_ids=None, generation_config: GenerationConfig = None, **kwargs, ): if input_ids is None: raise ValueError("input_ids must be provided")
if generation_config is None: generation_config = self.generation_config
output_ids, nfe = self.generate_block( input_ids=input_ids, **kwargs, )
return output_idsREADME.md+3-3
config.json+30-30
generation_utils.pyDeleted-133
modeling_seed_diffcoder.pyDeleted-30
modeling_stable_diffcoder.pyAdded+259