Stable-DiffCoder icon indicating copy to clipboard operation
Stable-DiffCoder copied to clipboard

[Bug] Empty output issues after upgrading from transformers v4.46.2 to v5.3.0

Open Natt1e opened this issue 8 months ago • 3 comments

Thanks for your amazing work for updating to adapt new transformers!

After upgrading transformers from v4.46.2 to v5.3.0 to adapt to the latest features, I encountered an issue where the model produces an empty response for certain prompts, while working correctly for writing quick sort algorithm.

# the version of my transformers is 5.3.0
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

device = 'cuda'
model = AutoModelForCausalLM.from_pretrained('model_path', trust_remote_code=True, torch_dtype=torch.bfloat16).to(device).eval()
tokenizer = AutoTokenizer.from_pretrained('model_path', trust_remote_code=True)

prompt = 'Write a hello world program'
# prompt = 'Write a quick sort algorithm.'
m = [{"role": "user", "content": prompt}, ]
prompt = tokenizer.apply_chat_template(m, add_generation_prompt=True, tokenize=False)
input_ids = tokenizer(prompt)['input_ids']
input_ids = torch.tensor(input_ids).to(device).unsqueeze(0)

out = model.generate(input_ids, steps=512, gen_length=512, block_length=4, temperature=0., remasking='low_confidence', tokenizer=tokenizer, shift=False, threshold=None, eos_id=tokenizer.eos_token_id)
print(tokenizer.decode(out[0][input_ids.shape[1]:], skip_special_tokens=True))

Observed Behavior:

Prompt A: "Write a quick sort algorithm." -> Success (Produces full, correct code).

Prompt B: "Write a hello world program." -> Empty response (Produces only <[end▁of▁sentence]>).

LiveCodeBench tasks: All tasks result in an empty response(Produces only <[end▁of▁sentence]>).

I am pretty sure that I have downloaded the newest model from hugging face, because the older version is not compatible with transformers v5.3.0(there is an exception).

This issue does not occur when I switch back to the older model and older version of transformers.

There is a minor typo in the README: the model path in the example code is hardcoded as an absolute path.

Natt1e avatar Mar 15 '26 05:03 Natt1e

I've dug into the code and successfully debugged this issue. The problem stems from a combination of how tokenizers (chat templates) interact with the block-wise generation logic, along with stricter DynamicCache requirements in transformers v5.3.0.

  1. The "Hello World" vs "Quick Sort" Mystery (Premature EOS Triggering)

The reason some prompts work while others fail purely depends on prompt_length % block_length. When using apply_chat_template, the prompt ends with <[end▁of▁sentence]>. If the length is not perfectly divisible, the first generation block will straddle both the end of the prompt and the newly generated tokens. The old code checked the entire block for eos_id. It instantly detected the EOS token from the prompt, falsely assumed generation was complete on step 1, and truncated the output, resulting in an empty string.

Fix: We need to restrict the eos_id check so it only scans the newly generated fraction of the block:

# Calculate where the actual generated tokens start in the current block
gen_start = max(block_start, prompt_length)

# Only check for eos_id in the freshly generated region
if (
    eos_id is not None
    and gen_start < block_end
    and (x[:, gen_start:block_end] == eos_id).sum() > 0
):
    final_flag = True
    x = x[:, :block_end]
    eos_pos = (x[:, gen_start:block_end] == eos_id).nonzero(as_tuple=True)[1][0].item() + gen_start
    x[0, eos_pos:] = eos_id
    break
  1. Strict DynamicCache Prefill in Transformers v5.3.0

In newer versions of transformers, initializing DynamicCache during the prefill phase strictly requires the cache_position tensor for correct RoPE (Rotary Position Embedding) computation. Leaving it out causes context degradation.

Fix: Explicitly pass cache_position during prefill:

if prefill_length > 0:
    cur_attn_mask = block_diffusion_attention_mask[..., :prefill_length, :prefill_length]
    cache_pos = torch.arange(prefill_length, device=x.device) # <-- Added
    self(
        x[:, :prefill_length],
        past_key_values=past_key_values,
        attention_mask=cur_attn_mask,
        use_cache=True,
        cache_position=cache_pos, # <-- Added
    )

After fix the bug above, I find another issue in the generate_block():

  1. PyTorch RuntimeError: cannot reshape tensor of 0 elements at Max Generation Length

Observed Behavior: When running long generations that reach the maximum gen_length without emitting an EOS token (often seen in certain LiveCodeBench tasks), the model occasionally crashes with a PyTorch RuntimeError: RuntimeError: cannot reshape tensor of 0 elements into shape [1, 0, -1, 128] because the unspecified dimension size -1 can be any value and is ambiguous

Root Cause Analysis: This bug is triggered strictly when prompt_length % block_length == 0. In generate_block(), there is a flaw in how the residual block (res_block) is calculated:

    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

If prompt_length is perfectly divisible by block_length (e.g., prompt_length % 4 == 0), res_block evaluates to 4. Since 4 > 0 is true, the code modifies the last block in gen_block_list to be block_length - res_block, which equals 0.

If the model manages to generate up to the very last block without triggering an early stop via eos_id, it will attempt to process this 0-length block. Slicing the tensor yields an empty sequence x[:, block_start:block_end] (shape [1, 0]). Passing an empty sequence into Llama's attention mechanism causes the q_proj(...).view(...) operation to crash due to ambiguous dimensions.

Fix: We need to correct the res_block logic so it only modifies the block list if there is an actual remainder.

Replace the original res_block logic with:

        # Only handle residual blocks if the prompt length is NOT cleanly divisible
        remainder = prompt_length % block_length
        if remainder != 0:
            res_block = block_length - remainder
            gen_block_list = [res_block] + gen_block_list
            gen_block_list[-1] = remainder
            gen_blocks += 1

Natt1e avatar Mar 15 '26 06:03 Natt1e

I have tested these fixes locally with transformers==5.3.0 and both "Hello world" and the LiveCodeBench tasks are now decoding perfectly! The performance on LiveCodeBench is the same as the older version.

If the maintainers are interested, I would be more than happy to submit a Pull Request with these updates to make the repo fully compatible with the latest transformers.(https://huggingface.co/ByteDance-Seed/Stable-DiffCoder-8B-Instruct/discussions/8)

Apologies for the PR noise earlier! 🙏

As I was testing the initial fix for the premature EOS issue, I realized the root cause (the prompt_length % block_length logic) was actually a double-edged sword that also triggered a PyTorch 0-element tensor crash under different conditions.

I closed the previous PRs to avoid confusion and consolidated all the related fixes into this single, final PR. This version completely resolves both the empty response issue and the dimension crash. Thanks for your patience!

there are the full generate_block() code :

    @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)]

        # Only handle residual blocks if the prompt length is NOT cleanly divisible
        remainder = prompt_length % block_length
        if remainder != 0:
            res_block = block_length - remainder
            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
            ]
            # Fix 1: Explicitly pass cache_position for newer transformers prefill
            cache_pos = torch.arange(prefill_length, device=x.device)
            self(
                x[:, :prefill_length],
                past_key_values=past_key_values,
                attention_mask=cur_attn_mask,
                use_cache=True,
                cache_position=cache_pos,
            )

        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 > 0:
                    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.item() if threshold is None else None, 
                        threshold,
                        shift=shift,
                    )
                    x[:, block_start:block_end][transfer_map] = x0[transfer_map]

                if (x[:, block_start:block_end] == mask_id).sum() == 0:
                    
                   # Fix 2: Calculate where the generated tokens ACTUALLY start in this block
                    gen_start = max(block_start, prompt_length)
                    
                    if (
                        eos_id is not None
                        and gen_start < block_end
                        and (x[:, gen_start:block_end] == eos_id).sum() > 0
                    ):
                        final_flag = True
                        x = x[:, :block_end]
                        eos_pos = (x[:, gen_start:block_end] == eos_id).nonzero(as_tuple=True)[1][0].item() + gen_start
                        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

Natt1e avatar Mar 15 '26 08:03 Natt1e

Thanks for catching this and for the helpful fix. The changes look good, and I’ll merge them in.

Facico avatar Mar 15 '26 12:03 Facico