devoppro commited on
Commit
b13428f
·
verified ·
1 Parent(s): 8f77965

Upload 5 files

Browse files
Files changed (5) hide show
  1. .gitignore +4 -0
  2. Dockerfile +23 -0
  3. README.md +21 -33
  4. app.py +155 -104
  5. requirements.txt +6 -4
.gitignore ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ .env
4
+ /data/
Dockerfile ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvidia/cuda:12.4.1-cudnn-devel-ubuntu22.04
2
+
3
+ ENV DEBIAN_FRONTEND=noninteractive
4
+ ENV PYTHONUNBUFFERED=1
5
+ ENV PIP_NO_CACHE_DIR=1
6
+ ENV HF_HOME=/data/huggingface
7
+ ENV HUGGINGFACE_HUB_CACHE=/data/huggingface/hub
8
+ ENV TRANSFORMERS_CACHE=/data/huggingface/transformers
9
+ ENV AIRLLM_CACHE_DIR=/data/airllm
10
+
11
+ RUN apt-get update && apt-get install -y --no-install-recommends python3 python3-pip python3-dev git build-essential libsndfile1 ffmpeg && rm -rf /var/lib/apt/lists/* && ln -sf /usr/bin/python3 /usr/bin/python
12
+
13
+ WORKDIR /app
14
+ COPY requirements.txt /app/requirements.txt
15
+
16
+ RUN python3 -m pip install --upgrade pip setuptools wheel && python3 -m pip install --index-url https://download.pytorch.org/whl/cu124 torch torchvision torchaudio && python3 -m pip install -r /app/requirements.txt && python3 -m pip install flash-attn --no-build-isolation
17
+
18
+ COPY app.py /app/app.py
19
+
20
+ RUN mkdir -p /data/huggingface /data/models /data/airllm && chmod -R 777 /data
21
+
22
+ EXPOSE 7860
23
+ CMD ["python3", "/app/app.py"]
README.md CHANGED
@@ -1,33 +1,21 @@
1
- ---
2
- title: Kimi K3 Demo
3
- colorFrom: yellow
4
- colorTo: red
5
- sdk: gradio
6
- sdk_version: 6.0.0
7
- app_file: app.py
8
- pinned: false
9
- ---
10
-
11
- # Kimi K3 Demo
12
-
13
- A clean Gradio chat demo for `devoppro/Kimi-K3`.
14
-
15
- The app uses Hugging Face Inference Providers through the Hugging Face OpenAI-compatible router, so the enormous Kimi K3 weights are **not downloaded into the Space**.
16
-
17
- ## Setup
18
-
19
- 1. Create a Hugging Face Space using this repository.
20
- 2. In **Settings → Secrets**, add:
21
- - `HF_TOKEN` = your Hugging Face access token with inference access.
22
- 3. Restart/rebuild the Space.
23
-
24
- The model is a 2.8T-parameter native multimodal model, so remote inference is used instead of trying to load the model on the Space's CPU/GPU.
25
-
26
- ## Features
27
-
28
- - Chat UI
29
- - Image input for Kimi K3's vision capability
30
- - Conversation history
31
- - Temperature and max-token controls
32
- - Clear-chat button
33
- - Friendly error messages
 
1
+ ---
2
+ title: Kimi K3 AirLLM
3
+ emoji: 🤖
4
+ colorFrom: yellow
5
+ colorTo: red
6
+ sdk: docker
7
+ app_port: 7860
8
+ pinned: false
9
+ ---
10
+
11
+ # Kimi K3 + AirLLM
12
+
13
+ Gradio demo for `devoppro/Kimi-K3` using AirLLM's Kimi K3 support.
14
+
15
+ ## Required setup
16
+
17
+ Attach persistent storage at `/data`. The K3 checkpoint is enormous, so the ephemeral Space filesystem is not suitable.
18
+
19
+ Add a Space Secret named `HF_TOKEN` with a token that can read `devoppro/Kimi-K3`.
20
+
21
+ The app stores the downloaded checkpoint under `/data/models/devoppro-Kimi-K3`.
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -1,140 +1,191 @@
1
  import os
 
 
 
2
  import gradio as gr
3
- from huggingface_hub import InferenceClient
4
 
5
- MODEL = "devoppro/Kimi-K3"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- def get_client():
8
- token = os.getenv("HF_TOKEN")
9
- if not token:
10
- raise RuntimeError(
11
- "HF_TOKEN is missing. Add it in your Space Settings → Secrets."
 
 
 
12
  )
13
- return InferenceClient(
14
- api_key=token,
15
- base_url="https://router.huggingface.co/v1",
16
- )
17
 
18
- def respond(message, image, history, temperature, max_tokens):
19
- if not message and image is None:
20
- return history, ""
 
 
 
 
 
 
 
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  history = history or []
23
 
24
- content = []
25
- if message:
26
- content.append({"type": "text", "text": message})
27
-
28
- if image is not None:
29
- # Gradio gives us a local file path. Convert it to a data URL so
30
- # the remote multimodal provider can receive the image.
31
- import base64
32
- from pathlib import Path
33
-
34
- p = Path(image)
35
- mime = "image/png"
36
- suffix = p.suffix.lower()
37
- if suffix in [".jpg", ".jpeg"]:
38
- mime = "image/jpeg"
39
- elif suffix == ".webp":
40
- mime = "image/webp"
41
-
42
- encoded = base64.b64encode(p.read_bytes()).decode("utf-8")
43
- content.append({
44
- "type": "image_url",
45
- "image_url": {
46
- "url": f"data:{mime};base64,{encoded}"
47
- }
48
- })
49
-
50
- history_for_api = []
51
- for user_msg, assistant_msg in history:
52
- history_for_api.append({"role": "user", "content": user_msg})
53
- history_for_api.append({"role": "assistant", "content": assistant_msg})
54
-
55
- history_for_api.append({"role": "user", "content": content})
56
 
57
  try:
58
- client = get_client()
59
- completion = client.chat.completions.create(
60
- model=MODEL,
61
- messages=history_for_api,
62
- temperature=float(temperature),
63
- max_tokens=int(max_tokens),
 
64
  )
65
- answer = completion.choices[0].message.content or ""
66
- except Exception as e:
67
- answer = (
68
- "⚠️ Kimi K3 could not be reached.\n\n"
69
- f"`{type(e).__name__}: {e}`\n\n"
70
- "If this is a provider/model availability error, check the "
71
- "model's Hugging Face Inference Providers availability."
72
  )
73
 
74
- history.append((message or "[image]", answer))
75
- return history, ""
 
 
 
 
 
 
 
 
76
 
77
- def clear():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  return [], ""
79
 
80
- with gr.Blocks(
81
- title="Kimi K3",
82
- css="""
83
- .title { text-align:center; margin-bottom:0.2rem; }
84
- .subtitle { text-align:center; opacity:0.7; margin-bottom:1rem; }
85
- """
86
- ) as demo:
87
- gr.Markdown("# 🧠 Kimi K3", elem_classes="title")
88
  gr.Markdown(
89
- "Multimodal demo powered by `devoppro/Kimi-K3`",
90
- elem_classes="subtitle"
 
 
91
  )
92
 
93
  chatbot = gr.Chatbot(
94
- label="Conversation",
95
- height=560,
96
- type="messages",
97
- )
98
 
99
  with gr.Row():
100
- with gr.Column(scale=4):
101
- message = gr.Textbox(
102
- label="Message",
103
- placeholder="Ask Kimi K3 anything…",
104
- lines=3,
105
- )
106
- with gr.Column(scale=1):
107
- image = gr.Image(
108
- label="Optional image",
109
- type="filepath",
110
- sources=["upload", "clipboard"],
111
- )
112
 
113
  with gr.Row():
114
- temperature = gr.Slider(
115
- minimum=0.0, maximum=2.0, value=0.6, step=0.05,
116
- label="Temperature"
117
- )
118
  max_tokens = gr.Slider(
119
- minimum=64, maximum=4096, value=1024, step=64,
120
- label="Max tokens"
121
  )
122
-
123
- with gr.Row():
124
- send = gr.Button("Send", variant="primary")
125
- clear_btn = gr.Button("Clear")
126
 
127
  send.click(
128
- respond,
129
- inputs=[message, image, chatbot, temperature, max_tokens],
130
  outputs=[chatbot, message],
131
  )
132
  message.submit(
133
- respond,
134
- inputs=[message, image, chatbot, temperature, max_tokens],
135
  outputs=[chatbot, message],
136
  )
137
- clear_btn.click(clear, outputs=[chatbot, message])
 
138
 
139
  if __name__ == "__main__":
140
- demo.launch()
 
1
  import os
2
+ import threading
3
+ from pathlib import Path
4
+
5
  import gradio as gr
 
6
 
7
+ MODEL_ID = "devoppro/Kimi-K3"
8
+ MODEL_DIR = Path("/data/models/devoppro-Kimi-K3")
9
+
10
+ os.environ.setdefault("HF_HOME", "/data/huggingface")
11
+ os.environ.setdefault("HUGGINGFACE_HUB_CACHE", "/data/huggingface/hub")
12
+ os.environ.setdefault("TRANSFORMERS_CACHE", "/data/huggingface/transformers")
13
+ os.environ.setdefault("AIRLLM_CACHE_DIR", "/data/airllm")
14
+
15
+ _model = None
16
+ _tokenizer = None
17
+ _model_lock = threading.Lock()
18
+
19
+
20
+ def load_model():
21
+ global _model, _tokenizer
22
+
23
+ if _model is not None:
24
+ return _model, _tokenizer
25
+
26
+ with _model_lock:
27
+ if _model is not None:
28
+ return _model, _tokenizer
29
+
30
+ if not os.getenv("HF_TOKEN"):
31
+ raise RuntimeError("HF_TOKEN is missing. Add it in Space Settings → Secrets.")
32
+
33
+ import torch
34
+ if not torch.cuda.is_available():
35
+ raise RuntimeError("CUDA GPU is required. Select GPU hardware for this Space.")
36
+
37
+ from huggingface_hub import snapshot_download
38
+ from airllm import AutoModel
39
 
40
+ MODEL_DIR.mkdir(parents=True, exist_ok=True)
41
+
42
+ print(f"Downloading/checking {MODEL_ID}...", flush=True)
43
+ snapshot_download(
44
+ repo_id=MODEL_ID,
45
+ local_dir=str(MODEL_DIR),
46
+ token=os.environ["HF_TOKEN"],
47
+ resume_download=True,
48
  )
 
 
 
 
49
 
50
+ print("Loading Kimi K3 with AirLLM...", flush=True)
51
+ _model = AutoModel.from_pretrained(
52
+ str(MODEL_DIR),
53
+ trust_remote_code=True,
54
+ )
55
+ _tokenizer = _model.tokenizer
56
+ print("Kimi K3 initialized.", flush=True)
57
+
58
+ return _model, _tokenizer
59
+
60
 
61
+ def build_messages(history, user_text):
62
+ messages = []
63
+ for item in history or []:
64
+ if isinstance(item, dict) and item.get("role") in ("user", "assistant"):
65
+ if item.get("content"):
66
+ messages.append({
67
+ "role": item["role"],
68
+ "content": item["content"],
69
+ })
70
+ messages.append({"role": "user", "content": user_text})
71
+ return messages
72
+
73
+
74
+ def generate_reply(message, history, max_new_tokens, temperature):
75
  history = history or []
76
 
77
+ if not message or not message.strip():
78
+ yield history, ""
79
+ return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  try:
82
+ model, tokenizer = load_model()
83
+
84
+ messages = build_messages(history, message)
85
+ prompt = tokenizer.apply_chat_template(
86
+ messages,
87
+ tokenize=False,
88
+ add_generation_prompt=True,
89
  )
90
+
91
+ inputs = tokenizer(
92
+ [prompt],
93
+ return_tensors="pt",
94
+ padding=True,
95
+ truncation=True,
 
96
  )
97
 
98
+ input_ids = inputs["input_ids"].cuda()
99
+ attention_mask = inputs.get("attention_mask")
100
+ if attention_mask is not None:
101
+ attention_mask = attention_mask.cuda()
102
+
103
+ kwargs = {
104
+ "max_new_tokens": int(max_new_tokens),
105
+ "do_sample": float(temperature) > 0,
106
+ "temperature": float(temperature),
107
+ }
108
 
109
+ if attention_mask is not None:
110
+ kwargs["attention_mask"] = attention_mask
111
+
112
+ output = model.generate(input_ids, **kwargs)
113
+
114
+ generated = output[0][input_ids.shape[-1]:]
115
+ answer = tokenizer.decode(
116
+ generated,
117
+ skip_special_tokens=True,
118
+ ).strip()
119
+
120
+ new_history = history + [
121
+ {"role": "user", "content": message},
122
+ {"role": "assistant", "content": answer},
123
+ ]
124
+
125
+ yield new_history, ""
126
+
127
+ except Exception as exc:
128
+ error = (
129
+ "⚠️ **Kimi K3 failed.**\n\n"
130
+ f"`{type(exc).__name__}: {exc}`\n\n"
131
+ "Check the Space logs. Initial K3 setup can take a very long time."
132
+ )
133
+
134
+ new_history = history + [
135
+ {"role": "user", "content": message},
136
+ {"role": "assistant", "content": error},
137
+ ]
138
+ yield new_history, ""
139
+
140
+
141
+ def clear_chat():
142
  return [], ""
143
 
144
+
145
+ with gr.Blocks(title="Kimi K3 — AirLLM") as demo:
 
 
 
 
 
 
146
  gr.Markdown(
147
+ "# 🤖 Kimi K3 + AirLLM\n"
148
+ "**Kimi K3 running through AirLLM expert streaming.**\n\n"
149
+ "The first initialization can take a very long time because the full "
150
+ "checkpoint must be available on persistent storage."
151
  )
152
 
153
  chatbot = gr.Chatbot(
154
+ label="Kimi K3",
155
+ type="messages",
156
+ height=600,
157
+ )
158
 
159
  with gr.Row():
160
+ message = gr.Textbox(
161
+ label="Message",
162
+ placeholder="Ask Kimi K3 something...",
163
+ lines=3,
164
+ scale=5,
165
+ )
166
+ send = gr.Button("Send", variant="primary", scale=1)
 
 
 
 
 
167
 
168
  with gr.Row():
 
 
 
 
169
  max_tokens = gr.Slider(
170
+ 1, 512, value=128, step=1, label="Max new tokens"
 
171
  )
172
+ temperature = gr.Slider(
173
+ 0.0, 1.5, value=0.6, step=0.05, label="Temperature"
174
+ )
175
+ clear = gr.Button("Clear")
176
 
177
  send.click(
178
+ generate_reply,
179
+ inputs=[message, chatbot, max_tokens, temperature],
180
  outputs=[chatbot, message],
181
  )
182
  message.submit(
183
+ generate_reply,
184
+ inputs=[message, chatbot, max_tokens, temperature],
185
  outputs=[chatbot, message],
186
  )
187
+ clear.click(clear_chat, outputs=[chatbot, message])
188
+
189
 
190
  if __name__ == "__main__":
191
+ demo.launch(server_name="0.0.0.0", server_port=7860)
requirements.txt CHANGED
@@ -1,7 +1,9 @@
1
- torch >= 2.4
2
- transformers >= 4.49,<5.13
3
- accelerate >= 1.0
 
4
  safetensors
5
  huggingface-hub
 
6
  scipy
7
- sentencepiece
 
1
+ airllm==3.1.0
2
+ transformers==4.56.2
3
+ compressed-tensors
4
+ accelerate>=1.0
5
  safetensors
6
  huggingface-hub
7
+ sentencepiece
8
  scipy
9
+ gradio>=5.0,<6.0