Trouter-Library commited on
Commit
9426882
·
verified ·
1 Parent(s): 758bb3e

Create example_usage.py

Browse files
Files changed (1) hide show
  1. example_usage.py +362 -0
example_usage.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helion-V1.5-XL Usage Examples
3
+ Demonstrates various use cases and configurations
4
+ """
5
+
6
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
7
+ import torch
8
+
9
+ # Initialize model and tokenizer
10
+ MODEL_NAME = "DeepXR/Helion-V1.5-XL"
11
+
12
+ def load_model(quantization="none"):
13
+ """Load model with optional quantization"""
14
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
15
+
16
+ if quantization == "4bit":
17
+ from transformers import BitsAndBytesConfig
18
+ quantization_config = BitsAndBytesConfig(
19
+ load_in_4bit=True,
20
+ bnb_4bit_compute_dtype=torch.bfloat16,
21
+ bnb_4bit_use_double_quant=True,
22
+ bnb_4bit_quant_type="nf4"
23
+ )
24
+ model = AutoModelForCausalLM.from_pretrained(
25
+ MODEL_NAME,
26
+ quantization_config=quantization_config,
27
+ device_map="auto",
28
+ trust_remote_code=True
29
+ )
30
+ else:
31
+ model = AutoModelForCausalLM.from_pretrained(
32
+ MODEL_NAME,
33
+ torch_dtype=torch.bfloat16,
34
+ device_map="auto",
35
+ trust_remote_code=True
36
+ )
37
+
38
+ return model, tokenizer
39
+
40
+
41
+ # Example 1: Simple Text Generation
42
+ def example_simple_generation():
43
+ """Basic text generation example"""
44
+ print("\n" + "="*80)
45
+ print("EXAMPLE 1: Simple Text Generation")
46
+ print("="*80)
47
+
48
+ model, tokenizer = load_model()
49
+
50
+ prompt = "Explain the concept of neural networks in simple terms:"
51
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
52
+
53
+ outputs = model.generate(
54
+ **inputs,
55
+ max_new_tokens=256,
56
+ temperature=0.7,
57
+ top_p=0.9,
58
+ do_sample=True
59
+ )
60
+
61
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
62
+ print(f"\nPrompt: {prompt}")
63
+ print(f"\nResponse: {response[len(prompt):]}")
64
+
65
+
66
+ # Example 2: Chat Conversation
67
+ def example_chat_conversation():
68
+ """Multi-turn conversation example"""
69
+ print("\n" + "="*80)
70
+ print("EXAMPLE 2: Chat Conversation")
71
+ print("="*80)
72
+
73
+ model, tokenizer = load_model()
74
+
75
+ conversation = [
76
+ {"role": "system", "content": "You are a helpful AI assistant."},
77
+ {"role": "user", "content": "What are the main benefits of renewable energy?"},
78
+ ]
79
+
80
+ prompt = tokenizer.apply_chat_template(
81
+ conversation,
82
+ tokenize=False,
83
+ add_generation_prompt=True
84
+ )
85
+
86
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
87
+ outputs = model.generate(**inputs, max_new_tokens=300, temperature=0.7)
88
+
89
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
90
+ print(f"\nConversation:\n{response}")
91
+
92
+
93
+ # Example 3: Code Generation
94
+ def example_code_generation():
95
+ """Code generation example"""
96
+ print("\n" + "="*80)
97
+ print("EXAMPLE 3: Code Generation")
98
+ print("="*80)
99
+
100
+ model, tokenizer = load_model()
101
+
102
+ prompt = """Write a Python function that finds the longest palindromic substring:
103
+
104
+ def longest_palindrome(s: str) -> str:"""
105
+
106
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
107
+
108
+ outputs = model.generate(
109
+ **inputs,
110
+ max_new_tokens=512,
111
+ temperature=0.2, # Lower temperature for code
112
+ top_p=0.95,
113
+ do_sample=True
114
+ )
115
+
116
+ code = tokenizer.decode(outputs[0], skip_special_tokens=True)
117
+ print(f"\nGenerated Code:\n{code}")
118
+
119
+
120
+ # Example 4: Structured Output (JSON)
121
+ def example_structured_output():
122
+ """Generate structured JSON output"""
123
+ print("\n" + "="*80)
124
+ print("EXAMPLE 4: Structured JSON Output")
125
+ print("="*80)
126
+
127
+ model, tokenizer = load_model()
128
+
129
+ prompt = """Generate a JSON object describing a fictional book:
130
+ {
131
+ "title": "The Last Algorithm",
132
+ "author": """
133
+
134
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
135
+
136
+ outputs = model.generate(
137
+ **inputs,
138
+ max_new_tokens=256,
139
+ temperature=0.4,
140
+ top_p=0.9
141
+ )
142
+
143
+ result = tokenizer.decode(outputs[0], skip_special_tokens=True)
144
+ print(f"\nGenerated JSON:\n{result}")
145
+
146
+
147
+ # Example 5: Batch Processing
148
+ def example_batch_processing():
149
+ """Process multiple prompts in batch"""
150
+ print("\n" + "="*80)
151
+ print("EXAMPLE 5: Batch Processing")
152
+ print("="*80)
153
+
154
+ model, tokenizer = load_model()
155
+
156
+ prompts = [
157
+ "List three benefits of exercise:",
158
+ "What is quantum computing?",
159
+ "Explain photosynthesis briefly:"
160
+ ]
161
+
162
+ inputs = tokenizer(
163
+ prompts,
164
+ return_tensors="pt",
165
+ padding=True,
166
+ truncation=True
167
+ ).to(model.device)
168
+
169
+ outputs = model.generate(
170
+ **inputs,
171
+ max_new_tokens=128,
172
+ temperature=0.7,
173
+ do_sample=True
174
+ )
175
+
176
+ for i, output in enumerate(outputs):
177
+ response = tokenizer.decode(output, skip_special_tokens=True)
178
+ print(f"\nPrompt {i+1}: {prompts[i]}")
179
+ print(f"Response: {response[len(prompts[i]):]}\n")
180
+
181
+
182
+ # Example 6: Creative Writing
183
+ def example_creative_writing():
184
+ """Creative writing with higher temperature"""
185
+ print("\n" + "="*80)
186
+ print("EXAMPLE 6: Creative Writing")
187
+ print("="*80)
188
+
189
+ model, tokenizer = load_model()
190
+
191
+ prompt = "Write the opening paragraph of a science fiction story:"
192
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
193
+
194
+ outputs = model.generate(
195
+ **inputs,
196
+ max_new_tokens=512,
197
+ temperature=0.9, # Higher for creativity
198
+ top_p=0.95,
199
+ top_k=100,
200
+ repetition_penalty=1.15,
201
+ do_sample=True
202
+ )
203
+
204
+ story = tokenizer.decode(outputs[0], skip_special_tokens=True)
205
+ print(f"\n{story}")
206
+
207
+
208
+ # Example 7: Using Pipeline API
209
+ def example_pipeline_api():
210
+ """Use the transformers pipeline API"""
211
+ print("\n" + "="*80)
212
+ print("EXAMPLE 7: Pipeline API")
213
+ print("="*80)
214
+
215
+ generator = pipeline(
216
+ "text-generation",
217
+ model=MODEL_NAME,
218
+ torch_dtype=torch.bfloat16,
219
+ device_map="auto"
220
+ )
221
+
222
+ results = generator(
223
+ "The future of artificial intelligence is",
224
+ max_new_tokens=200,
225
+ temperature=0.7,
226
+ top_p=0.9,
227
+ num_return_sequences=1
228
+ )
229
+
230
+ print(f"\nGenerated text:\n{results[0]['generated_text']}")
231
+
232
+
233
+ # Example 8: Streaming Generation
234
+ def example_streaming_generation():
235
+ """Generate text with streaming (token by token)"""
236
+ print("\n" + "="*80)
237
+ print("EXAMPLE 8: Streaming Generation")
238
+ print("="*80)
239
+
240
+ from transformers import TextIteratorStreamer
241
+ from threading import Thread
242
+
243
+ model, tokenizer = load_model()
244
+
245
+ prompt = "Explain machine learning in three sentences:"
246
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
247
+
248
+ streamer = TextIteratorStreamer(tokenizer, skip_special_tokens=True)
249
+
250
+ generation_kwargs = dict(
251
+ **inputs,
252
+ max_new_tokens=256,
253
+ temperature=0.7,
254
+ streamer=streamer
255
+ )
256
+
257
+ thread = Thread(target=model.generate, kwargs=generation_kwargs)
258
+ thread.start()
259
+
260
+ print(f"\nPrompt: {prompt}\n\nResponse (streaming): ", end="")
261
+ for new_text in streamer:
262
+ print(new_text, end="", flush=True)
263
+
264
+ print("\n")
265
+ thread.join()
266
+
267
+
268
+ # Example 9: Few-Shot Learning
269
+ def example_few_shot():
270
+ """Few-shot learning example"""
271
+ print("\n" + "="*80)
272
+ print("EXAMPLE 9: Few-Shot Learning")
273
+ print("="*80)
274
+
275
+ model, tokenizer = load_model()
276
+
277
+ prompt = """Translate English to French:
278
+
279
+ English: Hello, how are you?
280
+ French: Bonjour, comment allez-vous?
281
+
282
+ English: What is your name?
283
+ French: Comment vous appelez-vous?
284
+
285
+ English: I love programming.
286
+ French:"""
287
+
288
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
289
+ outputs = model.generate(**inputs, max_new_tokens=50, temperature=0.3)
290
+
291
+ result = tokenizer.decode(outputs[0], skip_special_tokens=True)
292
+ print(f"\n{result}")
293
+
294
+
295
+ # Example 10: Custom Generation Parameters
296
+ def example_custom_parameters():
297
+ """Advanced generation parameter tuning"""
298
+ print("\n" + "="*80)
299
+ print("EXAMPLE 10: Custom Generation Parameters")
300
+ print("="*80)
301
+
302
+ model, tokenizer = load_model()
303
+
304
+ prompt = "Write a haiku about technology:"
305
+ inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
306
+
307
+ # Multiple generations with different parameters
308
+ configs = [
309
+ {"name": "Conservative", "temperature": 0.3, "top_p": 0.9, "top_k": 30},
310
+ {"name": "Balanced", "temperature": 0.7, "top_p": 0.9, "top_k": 50},
311
+ {"name": "Creative", "temperature": 1.0, "top_p": 0.95, "top_k": 100},
312
+ ]
313
+
314
+ for config in configs:
315
+ outputs = model.generate(
316
+ **inputs,
317
+ max_new_tokens=128,
318
+ temperature=config["temperature"],
319
+ top_p=config["top_p"],
320
+ top_k=config["top_k"],
321
+ do_sample=True
322
+ )
323
+
324
+ result = tokenizer.decode(outputs[0], skip_special_tokens=True)
325
+ print(f"\n{config['name']} (temp={config['temperature']}):")
326
+ print(result[len(prompt):])
327
+
328
+
329
+ def main():
330
+ """Run all examples"""
331
+ print("\n" + "="*80)
332
+ print("HELION-V1.5-XL USAGE EXAMPLES")
333
+ print("="*80)
334
+
335
+ examples = [
336
+ ("Simple Generation", example_simple_generation),
337
+ ("Chat Conversation", example_chat_conversation),
338
+ ("Code Generation", example_code_generation),
339
+ ("Structured Output", example_structured_output),
340
+ ("Batch Processing", example_batch_processing),
341
+ ("Creative Writing", example_creative_writing),
342
+ ("Pipeline API", example_pipeline_api),
343
+ ("Streaming Generation", example_streaming_generation),
344
+ ("Few-Shot Learning", example_few_shot),
345
+ ("Custom Parameters", example_custom_parameters),
346
+ ]
347
+
348
+ print("\nAvailable examples:")
349
+ for i, (name, _) in enumerate(examples, 1):
350
+ print(f" {i}. {name}")
351
+
352
+ print("\nRun individual examples or all examples.")
353
+ print("Example: python example_usage.py")
354
+
355
+ # Uncomment to run specific examples
356
+ # example_simple_generation()
357
+ # example_chat_conversation()
358
+ # example_code_generation()
359
+
360
+
361
+ if __name__ == "__main__":
362
+ main()