YongdongWang commited on
Commit
9ffc795
·
0 Parent(s):

initial commit

Browse files
Files changed (4) hide show
  1. .gitattributes +35 -0
  2. README.md +112 -0
  3. app.py +288 -0
  4. requirements.txt +11 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Robot Task Planning - Llama 3.1 8B
3
+ emoji: 🤖
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: gradio
7
+ app_file: app.py
8
+ pinned: false
9
+ license: llama3.1
10
+ ---
11
+
12
+ # 🤖 Robot Task Planning - Llama 3.1 8B (ZeroGPU)
13
+
14
+ This Space demonstrates a fine-tuned version of Meta's **Llama 3.1 8B** model specialized for **robot task planning** using QLoRA (4-bit quantization + LoRA) technique.
15
+
16
+ ## 🚀 Hardware: ZeroGPU
17
+
18
+ This Space uses **ZeroGPU** - dynamic GPU allocation with Nvidia H200:
19
+ - **Free** for HuggingFace users
20
+ - **Dynamic allocation** - GPU resources allocated on-demand
21
+ - **High performance** - H200 offers superior performance
22
+ - **60-second duration** per request
23
+
24
+ ## 🎯 Purpose
25
+
26
+ Convert natural language commands into structured task sequences for construction robots including:
27
+ - **Excavators** - Digging, loading, positioning
28
+ - **Dump Trucks** - Material transport, loading, unloading
29
+ - **Multi-robot Coordination** - Complex task dependencies
30
+
31
+ ## 🔗 Model
32
+
33
+ **Fine-tuned Model**: [YongdongWang/llama-3.1-8b-dart-qlora](https://huggingface.co/YongdongWang/llama-3.1-8b-dart-qlora)
34
+
35
+ **Base Model**: [meta-llama/Llama-3.1-8B](https://huggingface.co/meta-llama/Llama-3.1-8B)
36
+
37
+ ## ✨ Features
38
+
39
+ - 🎮 **Interactive Chat Interface** - Real-time robot command processing
40
+ - ⚙️ **Configurable Generation** - Adjust temperature, top-p, max tokens
41
+ - 📝 **Example Commands** - Pre-built scenarios to get started
42
+ - 🚀 **Optimized Performance** - 4-bit quantization for efficient inference
43
+ - 📊 **Structured Output** - JSON-formatted task sequences
44
+ - ⚡ **ZeroGPU Powered** - Dynamic GPU allocation for free users
45
+
46
+ ## 🚀 Usage
47
+
48
+ 1. **Input**: Natural language robot commands
49
+ ```
50
+ "Deploy Excavator 1 to Soil Area 1 for excavation"
51
+ ```
52
+
53
+ 2. **Output**: Structured task sequences
54
+ ```json
55
+ {
56
+ "tasks": [
57
+ {
58
+ "robot": "Excavator_1",
59
+ "action": "move_to",
60
+ "target": "Soil_Area_1",
61
+ "duration": 30
62
+ },
63
+ {
64
+ "robot": "Excavator_1",
65
+ "action": "excavate",
66
+ "target": "Soil_Area_1",
67
+ "duration": 120
68
+ }
69
+ ]
70
+ }
71
+ ```
72
+
73
+ ## 🛠️ Technical Details
74
+
75
+ - **Architecture**: Llama 3.1 8B + QLoRA adapters
76
+ - **Quantization**: 4-bit (NF4) with double quantization
77
+ - **Framework**: Transformers + PEFT + BitsAndBytesConfig
78
+ - **Hardware**: ZeroGPU (Dynamic Nvidia H200)
79
+
80
+ ## ⚡ Performance Notes
81
+
82
+ - **First Generation**: 5-10 seconds (GPU allocation + model loading)
83
+ - **Subsequent Generations**: 2-5 seconds per response
84
+ - **Memory Usage**: ~8GB VRAM with 4-bit quantization
85
+ - **Context Length**: Up to 2048 tokens
86
+ - **GPU Duration**: 60 seconds per request
87
+
88
+ ## 📚 Example Commands
89
+
90
+ Try these robot commands:
91
+
92
+ - `"Deploy Excavator 1 to Soil Area 1 for excavation"`
93
+ - `"Send Dump Truck 1 to collect material, then unload at storage"`
94
+ - `"Coordinate multiple excavators across different areas"`
95
+ - `"Create evacuation sequence for all robots from dangerous zone"`
96
+
97
+ ## 🔬 Research Applications
98
+
99
+ This model demonstrates:
100
+ - **Natural Language → Robot Planning** translation
101
+ - **Multi-agent Task Coordination**
102
+ - **Efficient LLM Fine-tuning** with QLoRA
103
+ - **Real-time Robot Command Processing**
104
+ - **ZeroGPU Integration** for scalable deployment
105
+
106
+ ## 📄 License
107
+
108
+ This project uses Meta's Llama 3.1 license. Please review the license terms before use.
109
+
110
+ ## 🤝 Contributing
111
+
112
+ For issues, improvements, or questions about the model, please visit the [model repository](https://huggingface.co/YongdongWang/llama-3.1-8b-dart-qlora).
app.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import spaces # Import spaces module for ZeroGPU
3
+ from huggingface_hub import login
4
+ import os
5
+
6
+ # 1) Read Secrets
7
+ hf_token = os.getenv("HUGGINGFACE_TOKEN")
8
+ if not hf_token:
9
+ raise RuntimeError("❌ HUGGINGFACE_TOKEN not detected, please check Space Settings → Secrets")
10
+ # 2) Login to ensure all subsequent from_pretrained calls have proper permissions
11
+ login(hf_token)
12
+
13
+ import torch
14
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
15
+ from peft import PeftModel
16
+ import warnings
17
+ import os
18
+ warnings.filterwarnings("ignore")
19
+
20
+ # Model configuration
21
+ MODEL_NAME = "meta-llama/Llama-3.1-8B"
22
+ LORA_MODEL = "YongdongWang/llama-3.1-8b-dart-qlora"
23
+
24
+ # Global variables to store model and tokenizer
25
+ model = None
26
+ tokenizer = None
27
+ model_loaded = False
28
+
29
+ def load_model_and_tokenizer():
30
+ """Load tokenizer - executed on CPU"""
31
+ global tokenizer, model_loaded
32
+
33
+ if model_loaded:
34
+ return
35
+
36
+ print("🔄 Loading tokenizer...")
37
+
38
+ # Load tokenizer (on CPU)
39
+ tokenizer = AutoTokenizer.from_pretrained(
40
+ MODEL_NAME,
41
+ use_fast=False,
42
+ trust_remote_code=True
43
+ )
44
+ if tokenizer.pad_token is None:
45
+ tokenizer.pad_token = tokenizer.eos_token
46
+
47
+ model_loaded = True
48
+ print("✅ Tokenizer loaded successfully!")
49
+
50
+ @spaces.GPU(duration=60) # Request GPU for loading model at startup
51
+ def load_model_on_gpu():
52
+ """Load model on GPU"""
53
+ global model
54
+
55
+ if model is not None:
56
+ return model
57
+
58
+ print("🔄 Loading model on GPU...")
59
+
60
+ try:
61
+ # 4-bit quantization configuration
62
+ bnb_config = BitsAndBytesConfig(
63
+ load_in_4bit=True,
64
+ bnb_4bit_quant_type="nf4",
65
+ bnb_4bit_compute_dtype=torch.float16,
66
+ bnb_4bit_use_double_quant=True,
67
+ )
68
+
69
+ # Load base model
70
+ base_model = AutoModelForCausalLM.from_pretrained(
71
+ MODEL_NAME,
72
+ quantization_config=bnb_config,
73
+ device_map="auto",
74
+ torch_dtype=torch.float16,
75
+ trust_remote_code=True,
76
+ low_cpu_mem_usage=True
77
+ )
78
+
79
+ # Load LoRA adapter
80
+ model = PeftModel.from_pretrained(
81
+ base_model,
82
+ LORA_MODEL,
83
+ torch_dtype=torch.float16
84
+ )
85
+ model.eval()
86
+
87
+ print("✅ Model loaded on GPU successfully!")
88
+ return model
89
+
90
+ except Exception as load_error:
91
+ print(f"❌ Model loading failed: {load_error}")
92
+ raise load_error
93
+
94
+ @spaces.GPU(duration=60) # GPU inference
95
+ def generate_response_gpu(prompt, max_tokens=200, temperature=0.7, top_p=0.9):
96
+ """Generate response - executed on GPU"""
97
+ global model
98
+
99
+ # Ensure tokenizer is loaded
100
+ if tokenizer is None:
101
+ load_model_and_tokenizer()
102
+
103
+ # Ensure model is loaded on GPU
104
+ if model is None:
105
+ model = load_model_on_gpu()
106
+
107
+ if model is None:
108
+ return "❌ Model failed to load. Please check the Space logs."
109
+
110
+ try:
111
+ # Format input
112
+ formatted_prompt = f"### Human: {prompt.strip()}\n### Assistant:"
113
+
114
+ # Encode input
115
+ inputs = tokenizer(
116
+ formatted_prompt,
117
+ return_tensors="pt",
118
+ truncation=True,
119
+ max_length=2048
120
+ ).to(model.device)
121
+
122
+ # Generate response
123
+ with torch.no_grad():
124
+ outputs = model.generate(
125
+ **inputs,
126
+ max_new_tokens=max_tokens,
127
+ do_sample=True,
128
+ temperature=temperature,
129
+ top_p=top_p,
130
+ pad_token_id=tokenizer.pad_token_id,
131
+ eos_token_id=tokenizer.eos_token_id,
132
+ repetition_penalty=1.1,
133
+ early_stopping=True,
134
+ no_repeat_ngram_size=3
135
+ )
136
+
137
+ # Decode output
138
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
139
+
140
+ # Extract generated part
141
+ if "### Assistant:" in response:
142
+ response = response.split("### Assistant:")[-1].strip()
143
+ elif len(response) > len(formatted_prompt):
144
+ response = response[len(formatted_prompt):].strip()
145
+
146
+ return response if response else "❌ No response generated. Please try again with a different prompt."
147
+
148
+ except Exception as generation_error:
149
+ return f"❌ Generation Error: {str(generation_error)}"
150
+
151
+ def chat_interface(message, history, max_tokens, temperature, top_p):
152
+ """Chat interface - runs on CPU, calls GPU functions"""
153
+ if not message.strip():
154
+ return history, ""
155
+
156
+ # Initialize tokenizer (if needed)
157
+ if tokenizer is None:
158
+ load_model_and_tokenizer()
159
+
160
+ try:
161
+ # Call GPU function to generate response
162
+ response = generate_response_gpu(message, max_tokens, temperature, top_p)
163
+ history.append((message, response))
164
+ return history, ""
165
+ except Exception as chat_error:
166
+ error_msg = f"❌ Chat Error: {str(chat_error)}"
167
+ history.append((message, error_msg))
168
+ return history, ""
169
+
170
+ # Load tokenizer at startup
171
+ load_model_and_tokenizer()
172
+
173
+ # Create Gradio application
174
+ with gr.Blocks(
175
+ title="Robot Task Planning - Llama 3.1 8B",
176
+ theme=gr.themes.Soft(),
177
+ css="""
178
+ .gradio-container {
179
+ max-width: 1200px;
180
+ margin: auto;
181
+ }
182
+ """
183
+ ) as app:
184
+ gr.Markdown("""
185
+ # 🤖 Llama 3.1 8B - Robot Task Planning
186
+
187
+ This is a fine-tuned version of Meta's Llama 3.1 8B model specialized for **robot task planning** using QLoRA technique.
188
+
189
+ **Capabilities**: Convert natural language robot commands into structured task sequences for excavators, dump trucks, and other construction robots.
190
+
191
+ **Model**: [YongdongWang/llama-3.1-8b-dart-qlora](https://huggingface.co/YongdongWang/llama-3.1-8b-dart-qlora)
192
+
193
+ ⚡ **Using ZeroGPU**: This Space uses dynamic GPU allocation (Nvidia H200). First generation might take a bit longer.
194
+ """)
195
+
196
+ with gr.Row():
197
+ with gr.Column(scale=3):
198
+ chatbot = gr.Chatbot(
199
+ label="Task Planning Results",
200
+ height=500,
201
+ show_label=True,
202
+ container=True,
203
+ bubble_full_width=False,
204
+ show_copy_button=True
205
+ )
206
+
207
+ msg = gr.Textbox(
208
+ label="Robot Command",
209
+ placeholder="Enter robot task command (e.g., 'Deploy Excavator 1 to Soil Area 1')...",
210
+ lines=2,
211
+ max_lines=5,
212
+ show_label=True,
213
+ container=True
214
+ )
215
+
216
+ with gr.Row():
217
+ send_btn = gr.Button("🚀 Generate Tasks", variant="primary", size="sm")
218
+ clear_btn = gr.Button("🗑️ Clear", variant="secondary", size="sm")
219
+
220
+ with gr.Column(scale=1):
221
+ gr.Markdown("### ⚙️ Generation Settings")
222
+
223
+ max_tokens = gr.Slider(
224
+ minimum=50,
225
+ maximum=500,
226
+ value=200,
227
+ step=10,
228
+ label="Max Tokens",
229
+ info="Maximum number of tokens to generate"
230
+ )
231
+
232
+ temperature = gr.Slider(
233
+ minimum=0.1,
234
+ maximum=2.0,
235
+ value=0.7,
236
+ step=0.1,
237
+ label="Temperature",
238
+ info="Controls randomness (lower = more focused)"
239
+ )
240
+
241
+ top_p = gr.Slider(
242
+ minimum=0.1,
243
+ maximum=1.0,
244
+ value=0.9,
245
+ step=0.05,
246
+ label="Top-p",
247
+ info="Nucleus sampling threshold"
248
+ )
249
+
250
+ gr.Markdown("""
251
+ ### 📊 Model Status
252
+ - **Hardware**: ZeroGPU (Dynamic Nvidia H200)
253
+ - **Status**: Ready
254
+ - **Note**: First generation allocates GPU resources
255
+ """)
256
+
257
+ # Example conversations
258
+ gr.Examples(
259
+ examples=['Deploy Excavator 1 to Soil Area 1 for excavation.', 'Send Dump Truck 1 to collect material from Excavator 1, then unload at storage area.', 'Move all robots to avoid Puddle 1 after inspection.', 'Deploy multiple excavators to different soil areas simultaneously.', 'Coordinate dump trucks to transport materials from excavation site to storage.', 'Send robot to inspect rock area, then avoid with all other robots if dangerous.', 'Return all robots to start position after completing tasks.', 'Create a sequence: excavate, load, transport, unload, repeat.'],
260
+ inputs=msg,
261
+ label="💡 Example Robot Commands"
262
+ )
263
+
264
+ # Event handling
265
+ msg.submit(
266
+ chat_interface,
267
+ inputs=[msg, chatbot, max_tokens, temperature, top_p],
268
+ outputs=[chatbot, msg]
269
+ )
270
+
271
+ send_btn.click(
272
+ chat_interface,
273
+ inputs=[msg, chatbot, max_tokens, temperature, top_p],
274
+ outputs=[chatbot, msg]
275
+ )
276
+
277
+ clear_btn.click(
278
+ lambda: ([], ""),
279
+ outputs=[chatbot, msg]
280
+ )
281
+
282
+ if __name__ == "__main__":
283
+ app.launch(
284
+ server_name="0.0.0.0",
285
+ server_port=7860,
286
+ share=True,
287
+ show_error=True
288
+ )
requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ pydantic
2
+ gradio
3
+ transformers
4
+ torch
5
+ peft
6
+ bitsandbytes
7
+ accelerate
8
+ scipy
9
+ sentencepiece
10
+ protobuf
11
+ spaces