File size: 2,303 Bytes
d4bd786
 
 
 
 
 
 
 
 
e8de58b
 
 
d4bd786
e8de58b
8f44924
e8de58b
 
8f44924
 
e8de58b
d4bd786
 
 
 
 
 
e8de58b
 
d4bd786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# app.py
import os
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
import spaces  # Mandatory library for Hugging Face ZeroGPU [1]

MODEL_ID = "DevStudio-AI/Devstudio-Coder-1.5B"

# Fetch your secure token from the Space Secrets environment
HF_TOKEN = os.environ.get("HF_TOKEN")

print("Loading tokenizer and base model...")

# Pass the token parameter and force use_fast=False to bypass the tokenizer.json loading bug [1.3.1]
tokenizer = AutoTokenizer.from_pretrained(
    MODEL_ID, 
    token=HF_TOKEN,
    use_fast=False
)

# We load the model in 16-bit on CPU first
# ZeroGPU will automatically move the model to the GPU when the decorated function runs [1]
model = AutoModelForCausalLM.from_pretrained(
    MODEL_ID,
    torch_dtype=torch.float16,
    device_map="cpu",
    token=HF_TOKEN
)
print("Model successfully loaded on CPU. Awaiting ZeroGPU allocation...")

# The @spaces.GPU decorator dynamically requests Nvidia A100 resources for this call [1]
@spaces.GPU
def generate_code(prompt, temperature, max_tokens):
    try:
        # Move model to CUDA dynamically inside the GPU context [1]
        model.to("cuda")
        
        inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
        
        outputs = model.generate(
            **inputs,
            max_new_tokens=int(max_tokens),
            temperature=float(temperature),
            do_sample=True,
            eos_token_id=tokenizer.eos_token_id
        )
        
        # Isolate and decode newly generated tokens
        generated_ids = outputs[0][inputs["input_ids"].shape[1]:]
        return tokenizer.decode(generated_ids, skip_special_tokens=True)
    except Exception as e:
        return f"Error during generation: {str(e)}"

# Define the Gradio web interface
demo = gr.Interface(
    fn=generate_code,
    inputs=[
        gr.Textbox(label="Prompt", placeholder="Enter your prompt here..."),
        gr.Slider(minimum=0.1, maximum=1.0, value=0.3, label="Temperature"),
        gr.Slider(minimum=64, maximum=2048, value=1024, step=64, label="Max Tokens")
    ],
    outputs=gr.Textbox(label="Generated Code"),
    title="DevStudio-1.5B API Engine",
    description="Static HTML + Tailwind CSS specialized completion endpoint running on ZeroGPU."
)

demo.launch()