- 
                Notifications
    You must be signed in to change notification settings 
- Fork 4.8k
Add support for Gemma 3 models within Fastchat #3705
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Open
      
      
            deep1401
  wants to merge
  3
  commits into
  lm-sys:main
  
    
      
        
          
  
    
      Choose a base branch
      
     
    
      
        
      
      
        
          
          
        
        
          
            
              
              
              
  
           
        
        
          
            
              
              
           
        
       
     
  
        
          
            
          
            
          
        
       
    
      
from
transformerlab:add/gemma-3
  
      
      
   
  
    
  
  
  
 
  
      
    base: main
Could not load branches
            
              
  
    Branch not found: {{ refName }}
  
            
                
      Loading
              
            Could not load tags
            
            
              Nothing to show
            
              
  
            
                
      Loading
              
            Are you sure you want to change the base?
            Some commits from the old base branch may be removed from the timeline,
            and old review comments may become outdated.
          
          
      
        
          +185
        
        
          −1
        
        
          
        
      
    
  
  
     Open
                    Changes from all commits
      Commits
    
    
            Show all changes
          
          
            3 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      
    File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| from threading import Thread | ||
| import gc | ||
| import torch | ||
| from transformers import TextIteratorStreamer | ||
|  | ||
|  | ||
| def generate_stream_gemma3( | ||
| model, | ||
| tokenizer, | ||
| params, | ||
| device, | ||
| context_len, | ||
| stream_interval=2, | ||
| judge_sent_end=False, | ||
| ): | ||
| """Custom generate stream function for Gemma-3 models""" | ||
| # Get parameters from the request | ||
| prompt = params.get("prompt", "") | ||
| messages = params.get("messages", None) | ||
| temperature = float(params.get("temperature", 1.0)) | ||
| repetition_penalty = float(params.get("repetition_penalty", 1.0)) | ||
| top_p = float(params.get("top_p", 1.0)) | ||
| top_k = int(params.get("top_k", -1)) # -1 means disable | ||
| max_new_tokens = int(params.get("max_new_tokens", 256)) | ||
| echo = bool(params.get("echo", True)) | ||
| stop_str = params.get("stop", None) | ||
| stop_token_ids = params.get("stop_token_ids", None) or [] | ||
| model_name = params.get("model", None) | ||
|  | ||
| if tokenizer.eos_token_id not in stop_token_ids: | ||
| stop_token_ids.append(tokenizer.eos_token_id) | ||
|  | ||
| is_base_model = "pt" in model_name.lower() or "base" in model_name.lower() | ||
|  | ||
| if not is_base_model: | ||
| # Format input based on whether we have messages or a plain prompt | ||
| if messages: | ||
| inputs = tokenizer.apply_chat_template( | ||
| messages, | ||
| add_generation_prompt=True, | ||
| tokenize=True, | ||
| return_dict=True, | ||
| return_tensors="pt", | ||
| ).to(model.device) | ||
| else: | ||
| messages = [{"role": "user", "content": [{"type": "text", "text": prompt}]}] | ||
| inputs = tokenizer.apply_chat_template( | ||
| messages, | ||
| add_generation_prompt=True, | ||
| tokenize=True, | ||
| return_dict=True, | ||
| return_tensors="pt", | ||
| ).to(model.device) | ||
| else: | ||
| inputs = tokenizer(prompt, return_tensors="pt").to(model.device) | ||
|  | ||
| input_ids = inputs["input_ids"] | ||
| input_echo_len = input_ids.shape[1] | ||
|  | ||
| # Configure generation parameters | ||
| generate_kwargs = { | ||
| "max_new_tokens": max_new_tokens, | ||
| "do_sample": temperature > 0.0, | ||
| "temperature": temperature if temperature > 0.0 else 1.0, | ||
| } | ||
|  | ||
| if top_p < 1.0: | ||
| generate_kwargs["top_p"] = top_p | ||
| if top_k > 0: | ||
| generate_kwargs["top_k"] = top_k | ||
| if repetition_penalty > 1.0: | ||
| generate_kwargs["repetition_penalty"] = repetition_penalty | ||
|  | ||
| streamer = TextIteratorStreamer( | ||
| tokenizer, skip_prompt=not echo, skip_special_tokens=True | ||
| ) | ||
| generate_kwargs["streamer"] = streamer | ||
|  | ||
| # Start generation in a separate thread | ||
| thread = Thread( | ||
| target=lambda: model.generate(input_ids=input_ids, **generate_kwargs) | ||
| ) | ||
| thread.start() | ||
|  | ||
| # Track generation progress | ||
| generated_tokens = 0 | ||
| output_text = "" | ||
|  | ||
| # Stream tokens | ||
| for new_text in streamer: | ||
| output_text += new_text | ||
| generated_tokens += 1 | ||
|  | ||
| # Check for stop strings | ||
| should_stop = False | ||
| if stop_str: | ||
| if isinstance(stop_str, str): | ||
| if stop_str in output_text: | ||
| output_text = output_text[: output_text.find(stop_str)] | ||
| should_stop = True | ||
| elif isinstance(stop_str, list): | ||
| for stop in stop_str: | ||
| if stop in output_text: | ||
| output_text = output_text[: output_text.find(stop)] | ||
| should_stop = True | ||
| break | ||
|  | ||
| # Stream at intervals or when stopping | ||
| if generated_tokens % stream_interval == 0 or should_stop: | ||
| yield { | ||
| "text": output_text, | ||
| "usage": { | ||
| "prompt_tokens": input_echo_len, | ||
| "completion_tokens": generated_tokens, | ||
| "total_tokens": input_echo_len + generated_tokens, | ||
| }, | ||
| "finish_reason": "stop" if should_stop else None, | ||
| } | ||
|  | ||
| if should_stop: | ||
| break | ||
|  | ||
| # Final output with finish reason | ||
| if thread.is_alive(): | ||
| thread.join( | ||
| timeout=3600 | ||
| ) # Arbitrary value, but if it doesn't complete in this much time then something is wrong | ||
|  | ||
| yield { | ||
| "text": output_text, | ||
| "usage": { | ||
| "prompt_tokens": input_echo_len, | ||
| "completion_tokens": generated_tokens, | ||
| "total_tokens": input_echo_len + generated_tokens, | ||
| }, | ||
| "finish_reason": "length", | ||
| } | ||
|  | ||
| # Clean up | ||
| gc.collect() | ||
| torch.cuda.empty_cache() | ||
| if device == "xpu": | ||
| torch.xpu.empty_cache() | ||
| if device == "npu": | ||
| torch.npu.empty_cache() | 
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi,
I have a small suggestion:
See this similar issue in huggingface/transformers: huggingface/transformers#36815
Some prompts may trigger an error similar to the following:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi,
Thanks for this, we actually ended up creating: https://www.github.com/transformerlab/transformerlab-inference.
We use that instead since fastchat hasn't been merging and stopped new developments.
This model is added on there and works without flash attention which was causing your original issue, please let me know if it also occuses without flash attention too?