in the below both input and generated content coming , i want only generated content
def text_generate(self, prompt: str, **kwargs: Any) -> str:
try:
inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device)
code
# Create a new GenerationConfig with updated parameters
generation_config = GenerationConfig(**{**self.generation_config.to_dict(), **kwargs})
with torch.no_grad():
outputs = self.model.generate(
**inputs,
max_new_tokens=self.max_length,
generation_config=generation_config
)
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
except Exception as e:
logger.error(f"Generation failed: {str(e)}")
raise RuntimeError(f"Generation failed: {str(e)}")
Assistant
To ensure that only the generated content is returned (excluding the input prompt) in your text_generate method, you can adjust the decoding process to exclude the input tokens from the generated output. Here's how you can modify your function:
python
def text_generate(self, prompt: str, **kwargs: Any) -> str:
try:
# Tokenize the input prompt
inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device)
input_length = inputs['input_ids'].shape[-1] # Length of the input prompt in tokens
# Create a new GenerationConfig with updated parameters
generation_config = GenerationConfig(**{**self.generation_config.to_dict(), **kwargs})
with torch.no_grad():
outputs = self.model.generate(
**inputs,
max_new_tokens=self.max_length,
generation_config=generation_config
)
# Extract only the generated tokens by slicing off the input prompt tokens
generated_tokens = outputs[0][input_length:]
# Decode the generated tokens to get the generated text
generated_text = self.tokenizer.decode(generated_tokens, skip_special_tokens=True)
return generated_text.strip() # Remove any leading/trailing whitespace
except Exception as e:
logger.error(f"Generation failed: {str(e)}")
raise RuntimeError(f"Generation failed: {str(e)}")
Explanation of Changes:
Determine the Length of the Input Prompt:
python
input_length = inputs['input_ids'].shape[-1]
After tokenizing the prompt, determine how many tokens the input prompt contains. This is essential to separate the prompt from the generated content in the output.
Convert the isolated generated tokens back into human-readable text.
Return the Cleaned Generated Text:
python
return generated_text.strip()
Return the generated text, optionally stripping any leading or trailing whitespace for cleanliness.
Additional Considerations:
Handling Special Tokens:
The skip_special_tokens=True parameter ensures that any special tokens (like ``) are not included in the final output.
Robustness:
Ensure that your model and tokenizer handle the slicing correctly. Some tokenizers might add additional tokens (like start or end tokens) that you might need to account for.
Edge Cases:
Consider what happens if the model doesn't generate any new tokens or if there's an error in generation. Your existing try-except block handles exceptions, but you might also want to handle cases where generated_tokens is empty.
Example Usage:
python
prompt = "Once upon a time in a land far, far away"
generated_content = your_model_instance.text_generate(prompt)
print(generated_content)
Output:
code
there lived a wise old king who ruled with kindness and justice. His kingdom was prosperous, and the people were happy...
This modification ensures that only the content generated by the model in response to the prompt is returned, excluding the prompt itself.
Feel free to adjust further based on your specific model's behavior and tokenizer nuances!