mrfakename commited on
Commit
41cb8fb
·
verified ·
1 Parent(s): 454e339

Initial Space demo

Browse files
Files changed (6) hide show
  1. .gitattributes +2 -0
  2. README.md +13 -7
  3. app.py +280 -0
  4. examples/cats.jpg +3 -0
  5. examples/voice.flac +3 -0
  6. requirements.txt +6 -0
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* 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
 
 
 
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
36
+ examples/cats.jpg filter=lfs diff=lfs merge=lfs -text
37
+ examples/voice.flac filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,13 +1,19 @@
1
  ---
2
- title: Open D1
3
- emoji: 🏆
4
- colorFrom: blue
5
- colorTo: indigo
6
  sdk: gradio
7
- sdk_version: 6.30.0
8
- python_version: '3.13'
9
  app_file: app.py
10
  pinned: false
 
 
 
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
1
  ---
2
+ title: Open d1
3
+ emoji: ⚖️
4
+ colorFrom: yellow
5
+ colorTo: red
6
  sdk: gradio
7
+ sdk_version: "6.30.0"
 
8
  app_file: app.py
9
  pinned: false
10
+ license: other
11
+ short_description: Liquid AI d1 decision models (3B and omni-600M)
12
+ models:
13
+ - LiquidAI/d1-3B
14
+ - LiquidAI/d1-omni-600M
15
  ---
16
 
17
+ Demo of Liquid AI's open d1 decision models. A state (text, JSON, an image or a voice clip) and a set of
18
+ typed questions (`choice`, `noul` yes/no, `score`) go in; calibrated answers come out of one forward pass,
19
+ with zero generated tokens.
app.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import html
2
+ import json
3
+ import time
4
+
5
+ import gradio as gr
6
+ import numpy as np
7
+ import spaces
8
+ import torch
9
+ from transformers import AutoModel
10
+
11
+ D1_3B = "LiquidAI/d1-3B"
12
+ D1_OMNI = "LiquidAI/d1-omni-600M"
13
+ MODELS = {"d1-3B": D1_3B, "d1-omni-600M": D1_OMNI}
14
+
15
+ # Both models are loaded once at startup and stay resident.
16
+ model_3b = AutoModel.from_pretrained(D1_3B, trust_remote_code=True, dtype=torch.bfloat16).to("cuda")
17
+ engine_3b = model_3b.engine # builds the tokenizer now rather than on the first request
18
+ engine_3b.device = torch.device("cuda")
19
+ engine_3b.processor = engine_3b._load_processor()
20
+ # fp16 keeps d1-omni's float32 answers; bf16 does not (model card).
21
+ model_omni = AutoModel.from_pretrained(D1_OMNI, trust_remote_code=True, dtype=torch.float16).to("cuda")
22
+ _ = model_omni.tokenizer
23
+
24
+ TYPES = ["choice", "noul", "score"]
25
+ HEADERS = ["name", "type", "question", "options"]
26
+
27
+
28
+ def parse_questions(rows):
29
+ """Table rows -> {name: Decision Index question}.
30
+
31
+ options: choice `name: description | name: description`
32
+ score `lowest level | ... | highest level`
33
+ noul optional `yes means ... | no means ...`
34
+ """
35
+ if rows is None:
36
+ rows = []
37
+ if hasattr(rows, "values"):
38
+ rows = rows.values.tolist()
39
+ questions = {}
40
+ for i, row in enumerate(rows):
41
+ row = [("" if c is None else str(c)).strip() for c in list(row) + [""] * 4][:4]
42
+ name, kind, text, opts = row
43
+ if not (name or text):
44
+ continue
45
+ name = name or f"q{i + 1}"
46
+ kind = kind.lower() or "choice"
47
+ if kind not in TYPES:
48
+ raise gr.Error(f"Question '{name}': type must be one of {', '.join(TYPES)}.")
49
+ if not text:
50
+ raise gr.Error(f"Question '{name}' has no question text.")
51
+ parts = [p.strip() for p in opts.split("|") if p.strip()]
52
+ q = {"type": kind, "instructions": text}
53
+ if kind == "choice":
54
+ crit = {}
55
+ for p in parts:
56
+ key, _, desc = p.partition(":")
57
+ crit[key.strip()] = desc.strip() or key.strip()
58
+ if len(crit) < 2:
59
+ raise gr.Error(f"Question '{name}': a choice needs at least two options, e.g. `a: ... | b: ...`.")
60
+ q["criteria"] = crit
61
+ elif kind == "score":
62
+ if not 2 <= len(parts) <= 10:
63
+ raise gr.Error(f"Question '{name}': a score needs 2 to 10 levels, lowest first, split by `|`.")
64
+ q["criteria"] = parts
65
+ elif len(parts) == 2:
66
+ q["criteria"] = {"true": parts[0], "false": parts[1]}
67
+ if name in questions:
68
+ raise gr.Error(f"Two questions are named '{name}'.")
69
+ questions[name] = q
70
+ if not questions:
71
+ raise gr.Error("Add at least one question.")
72
+ return questions
73
+
74
+
75
+ def parse_state(text):
76
+ text = (text or "").strip()
77
+ if not text:
78
+ return None
79
+ if text[0] in "{[":
80
+ try:
81
+ return json.loads(text)
82
+ except json.JSONDecodeError:
83
+ pass
84
+ return text
85
+
86
+
87
+ def to_16k_mono(audio):
88
+ sr, data = audio
89
+ x = np.asarray(data)
90
+ if x.dtype == np.int16:
91
+ x = x.astype(np.float32) / 32768.0
92
+ elif x.dtype == np.int32:
93
+ x = x.astype(np.float32) / 2147483648.0
94
+ else:
95
+ x = x.astype(np.float32)
96
+ if x.ndim == 2:
97
+ x = x.mean(axis=1) if x.shape[1] <= 8 else x.mean(axis=0)
98
+ if sr != 16000:
99
+ from scipy.signal import resample_poly
100
+
101
+ g = np.gcd(int(sr), 16000)
102
+ x = resample_poly(x, 16000 // g, int(sr) // g).astype(np.float32)
103
+ return np.clip(x[: 30 * 16000], -1.0, 1.0)
104
+
105
+
106
+ @spaces.GPU(duration=20)
107
+ def _decide(model_name, state, questions, image, audio):
108
+ t0 = time.perf_counter()
109
+ with torch.inference_mode():
110
+ if model_name == "d1-3B":
111
+ out = model_3b.system_one(state, questions, images=[image] if image is not None else None)
112
+ else:
113
+ out = model_omni.system_one(state, questions, images=[image] if image is not None else None, audio=audio)
114
+ torch.cuda.synchronize()
115
+ return out, time.perf_counter() - t0
116
+
117
+
118
+ def render(questions, out, seconds):
119
+ cards = []
120
+ for name, ans in out["answers"].items():
121
+ q = questions[name]
122
+ if ans["type"] == "noul":
123
+ p = float(ans["noul"])
124
+ headline = "yes" if p >= 0.5 else "no"
125
+ conf = max(p, 1 - p)
126
+ rows = [("yes", p), ("no", 1 - p)]
127
+ top = headline
128
+ elif ans["type"] == "choice":
129
+ headline = ans["choice"]
130
+ conf = float(ans["confidence"])
131
+ rows = list(ans["probabilities"].items())
132
+ top = headline
133
+ else:
134
+ headline = f"{ans['score']:.2f}"
135
+ conf = float(ans["confidence"])
136
+ legend = ans["legend"]
137
+ rows = [(f"{k} · {legend[k]}", v) for k, v in ans["probabilities"].items()]
138
+ best = max(ans["probabilities"], key=ans["probabilities"].get)
139
+ top = f"{best} · {legend[best]}"
140
+ bars = "".join(
141
+ f'<div class="d1-row{" d1-top" if label == top else ""}">'
142
+ f'<span class="d1-label">{html.escape(str(label))}</span>'
143
+ f'<span class="d1-track"><span class="d1-fill" style="width:{100 * float(v):.1f}%"></span></span>'
144
+ f'<span class="d1-pct">{100 * float(v):.1f}%</span></div>'
145
+ for label, v in rows
146
+ )
147
+ sub = "expected level" if ans["type"] == "score" else f"{100 * conf:.1f}% confident"
148
+ cards.append(
149
+ f'<div class="d1-card"><div class="d1-head"><span class="d1-name">{html.escape(name)}</span>'
150
+ f'<span class="d1-q">{html.escape(q["instructions"])}</span></div>'
151
+ f'<div class="d1-answer">{html.escape(headline)} <span class="d1-sub">{sub}</span></div>'
152
+ f"{bars}</div>"
153
+ )
154
+ return '<div class="d1-cards">' + "".join(cards) + f'</div><div class="d1-took">took {seconds:.2f} s</div>'
155
+
156
+
157
+ def decide(model_name, state_text, image, audio, rows):
158
+ questions = parse_questions(rows)
159
+ state = parse_state(state_text)
160
+ if model_name == "d1-3B":
161
+ audio = None
162
+ if image is not None and audio is not None:
163
+ raise gr.Error("d1-omni takes an image or a voice clip in one request, not both. Clear one of them.")
164
+ clip = to_16k_mono(audio) if audio is not None else None
165
+ if state is None and image is None and clip is None:
166
+ raise gr.Error("Give the model something to look at: a state, an image or a voice clip.")
167
+ if image is not None:
168
+ image = image.convert("RGB")
169
+ t0 = time.perf_counter()
170
+ out, _ = _decide(model_name, state, questions, image, clip)
171
+ seconds = time.perf_counter() - t0
172
+ return render(questions, out, seconds), out
173
+
174
+
175
+ def on_model(model_name):
176
+ omni = model_name == "d1-omni-600M"
177
+ return gr.update(visible=omni, value=None) if not omni else gr.update(visible=True)
178
+
179
+
180
+ SUPPORT_ROUTING = [
181
+ ["refund", "noul", "Is the customer asking for a refund?", ""],
182
+ ["team", "choice", "Which team should handle this?",
183
+ "billing: Charges, refunds, invoices | technical: App or site faults | fraud: Suspected unauthorised use"],
184
+ ["urgency", "score", "How urgent is this?", "Can wait | Today | Blocking the customer now"],
185
+ ]
186
+ CATS = [
187
+ ["cats", "choice", "How many cats are there?", "one: One | two: Two | more: Three or more"],
188
+ ["remote", "noul", "Is there a remote control in the picture?", ""],
189
+ ["mood", "choice", "What are the cats doing?",
190
+ "sleeping: Lying down, resting or asleep | playing: Playing or fighting | eating: Eating or drinking"],
191
+ ]
192
+ VOICE = [
193
+ ["topic", "choice", "What is the speaker talking about?",
194
+ "food: Food and meals | travel: Travel and transport | weather: The weather"],
195
+ ["question", "noul", "Is the speaker asking a question?", ""],
196
+ ]
197
+ MODERATION = [
198
+ ["toxic", "noul", "Is this comment insulting or abusive?", ""],
199
+ ["action", "choice", "What should a moderator do?",
200
+ "keep: Leave it up | warn: Leave it, warn the author | remove: Take it down"],
201
+ ]
202
+ JUDGE = [
203
+ ["correct", "noul", "Does the answer correctly answer the question?", ""],
204
+ ["quality", "score", "Rate the answer's helpfulness.",
205
+ "Useless | Poor | Okay | Good | Excellent"],
206
+ ]
207
+
208
+ EXAMPLES = [
209
+ ["d1-3B", "I was charged twice this month, please refund one of them.", None, None, SUPPORT_ROUTING],
210
+ ["d1-omni-600M", "", "examples/cats.jpg", None, CATS],
211
+ ["d1-omni-600M", "Voice note from a user.", None, "examples/voice.flac", VOICE],
212
+ ["d1-3B", "You are honestly the dumbest person on this forum, log off.", None, None, MODERATION],
213
+ ["d1-3B", '{"question": "What is the boiling point of water at sea level in Fahrenheit?", '
214
+ '"answer": "Water boils at 212 °F at sea level."}', None, None, JUDGE],
215
+ ["d1-3B", "", "examples/cats.jpg", None, CATS],
216
+ ]
217
+
218
+ CSS = """
219
+ .d1-cards {display:flex; flex-direction:column; gap:10px;}
220
+ .d1-card {border:1px solid var(--border-color-primary); border-radius:8px; padding:12px 14px;
221
+ background:var(--block-background-fill);}
222
+ .d1-head {display:flex; gap:10px; align-items:baseline; flex-wrap:wrap; margin-bottom:4px;}
223
+ .d1-name {font-family:var(--font-mono); font-size:12px; color:var(--body-text-color-subdued);}
224
+ .d1-q {font-size:14px; color:var(--body-text-color);}
225
+ .d1-answer {font-size:22px; font-weight:600; margin:2px 0 8px; color:#b4532a;}
226
+ .d1-sub {font-size:13px; font-weight:400; color:var(--body-text-color-subdued); margin-left:6px;}
227
+ .d1-row {display:grid; grid-template-columns:minmax(80px, 38%) 1fr 56px; gap:10px; align-items:center;
228
+ font-size:13px; padding:2px 0; color:var(--body-text-color-subdued);}
229
+ .d1-row.d1-top {color:var(--body-text-color); font-weight:600;}
230
+ .d1-label {overflow:hidden; text-overflow:ellipsis; white-space:nowrap;}
231
+ .d1-track {height:8px; background:var(--border-color-primary); border-radius:4px; overflow:hidden;}
232
+ .d1-fill {display:block; height:100%; background:#8a8a80;}
233
+ .d1-top .d1-fill {background:#b4532a;}
234
+ .d1-pct {text-align:right; font-variant-numeric:tabular-nums;}
235
+ .d1-took {font-size:12px; color:var(--body-text-color-subdued); margin-top:8px;}
236
+ """
237
+
238
+ with gr.Blocks(title="Open d1") as demo:
239
+ gr.Markdown(
240
+ "# Open d1\n"
241
+ "Liquid AI's decision models: give a state and some typed questions, get calibrated answers "
242
+ "in one forward pass, with no generated text. \n"
243
+ f"[d1-3B](https://huggingface.co/{D1_3B}) (text + images) · "
244
+ f"[d1-omni-600M](https://huggingface.co/{D1_OMNI}) (text + images or voice)"
245
+ )
246
+ with gr.Row():
247
+ with gr.Column(scale=1):
248
+ model_name = gr.Radio(list(MODELS), value="d1-3B", label="Model")
249
+ state = gr.Textbox(label="State", lines=4, value="I was charged twice this month, please refund one of them.",
250
+ placeholder="Text or JSON the questions are about. Can be empty when an image or clip is the whole state.")
251
+ with gr.Row():
252
+ image = gr.Image(label="Image", type="pil", height=220)
253
+ audio = gr.Audio(label="Voice clip (d1-omni, up to 30 s)", type="numpy",
254
+ sources=["upload", "microphone"], visible=False)
255
+ questions = gr.Dataframe(
256
+ headers=HEADERS, datatype=["str", "str", "str", "str"], value=SUPPORT_ROUTING,
257
+ column_count=(4, "fixed"), row_count=(3, "dynamic"), label="Questions", interactive=True,
258
+ wrap=True, column_widths=["14%", "12%", "34%", "40%"],
259
+ )
260
+ gr.Markdown(
261
+ "**type** is `choice`, `noul` (yes/no) or `score`. **options**: for a choice "
262
+ "`name: description | name: description`; for a score the levels, lowest first, split by `|`; "
263
+ "for a yes/no, optionally `what yes means | what no means`.",
264
+ elem_classes="d1-help",
265
+ )
266
+ run = gr.Button("Decide", variant="primary")
267
+ with gr.Column(scale=1):
268
+ result = gr.HTML('<div class="d1-took">Answers appear here.</div>')
269
+ with gr.Accordion("Raw output", open=False):
270
+ raw = gr.JSON(label="system_one(...)")
271
+
272
+ gr.Examples(EXAMPLES, inputs=[model_name, state, image, audio, questions], label="Examples")
273
+ gr.Markdown("[Twitter / X](https://x.com/realmrfakename)")
274
+
275
+ model_name.change(on_model, model_name, audio)
276
+ run.click(decide, [model_name, state, image, audio, questions], [result, raw])
277
+
278
+
279
+ if __name__ == "__main__":
280
+ demo.queue().launch(css=CSS)
examples/cats.jpg ADDED

Git LFS Details

  • SHA256: dea9e7ef97386345f7cff32f9055da4982da5471c48d575146c796ab4563b04e
  • Pointer size: 131 Bytes
  • Size of remote file: 173 kB
examples/voice.flac ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:30885601173f96b0d8ddd020dc959b055c6c1582b85a33e3fcab8c4b08ed94c2
3
+ size 183318
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ transformers>=5.15
2
+ torchvision==0.28.0
3
+ accelerate
4
+ scipy
5
+ soundfile
6
+ pillow