Campcraft commited on
Commit
ff5d3ef
·
verified ·
1 Parent(s): 1211748

Upload 5 files

Browse files
Files changed (5) hide show
  1. README.md +37 -14
  2. app.py +157 -0
  3. find_north.md +4 -0
  4. hypothermia.md +8 -0
  5. requirements.txt +8 -0
README.md CHANGED
@@ -1,14 +1,37 @@
1
- ---
2
- title: Field Guide
3
- emoji: ⚡
4
- colorFrom: pink
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 5.46.0
8
- app_file: app.py
9
- pinned: false
10
- license: agpl-3.0
11
- short_description: Basic LocalLLM Fieldguide
12
- ---
13
-
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Campfire Space: Micro‑LLM + Local RAG (Demo)
2
+
3
+ This is a drop‑in template for a Hugging Face **Space** that lets you evaluate a small instruction‑tuned LLM against a **local field guide** using hybrid retrieval.
4
+
5
+ It runs on **CPU** with a ~1B model by default (TinyLlama) and can be switched to a 3B model (e.g., Qwen2.5‑3B‑Instruct) on a GPU Space. You can also point it at a **TGI** or **vLLM** server via an environment variable and use this Space purely as the UI/RAG layer.
6
+
7
+ ## Quick start (Spaces UI)
8
+
9
+ 1. Create a new Space → **Gradio** → Python.
10
+ 2. Upload these files (drag‑drop the ZIP contents).
11
+ 3. On the **Settings → Variables & secrets** page, you may set:
12
+ - `MODEL_ID` (default: `TinyLlama/TinyLlama-1.1B-Chat-v1.0`)
13
+ - `USE_TGI_URL` (optional: e.g., `https://your-tgi.space`) to call TGI `/v1/chat/completions` instead of local Transformers.
14
+ - `TOP_K` (optional, default `4`) retrieved chunks.
15
+ 4. Choose hardware:
16
+ - **CPU Basic**: fine for TinyLlama (1.1B) demo.
17
+ - **GPU (e.g., T4/A10G)**: recommended for 3B–4B models (Qwen2.5‑3B, Phi‑3‑mini).
18
+ 5. Click **Deploy**.
19
+
20
+ ## Local dev
21
+
22
+ ```bash
23
+ pip install -r requirements.txt
24
+ python app.py
25
+ # open http://127.0.0.1:7860
26
+ ```
27
+
28
+ ## Swap models
29
+
30
+ - CPU (free tier): `TinyLlama/TinyLlama-1.1B-Chat-v1.0`
31
+ - GPU (A10G/T4): `Qwen/Qwen2.5-3B-Instruct` or `microsoft/Phi-3-mini-4k-instruct`
32
+
33
+ ## Notes
34
+
35
+ - Field guide lives under `field_guide/` as markdown. Replace with your own content and redeploy.
36
+ - The retrieval index is built on startup (BM25 + MiniLM embeddings). For large corpora, consider precomputing and saving `rag/index.npz`.
37
+ - To mirror your future **on‑device** stack, you can export models to **GGUF** separately and keep the same prompts/index. This Space is for **product fit** validation first.
app.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, re, json, time, pathlib, math
2
+ import gradio as gr
3
+ import numpy as np
4
+
5
+ TOP_K = int(os.getenv("TOP_K", "4"))
6
+ MODEL_ID = os.getenv("MODEL_ID", "TinyLlama/TinyLlama-1.1B-Chat-v1.0")
7
+ USE_TGI_URL = os.getenv("USE_TGI_URL") # if set, call TGI /v1/chat/completions
8
+
9
+ SYSTEM_PROMPT = (
10
+ "You are the Campfire guide. Be concise. Prefer numbered steps for procedures. "
11
+ "Safety first. If unsure or outside scope, say so. Cite the provided snippets like [S1], [S2]."
12
+ )
13
+
14
+ # --- Retrieval helpers ---
15
+ from sentence_transformers import SentenceTransformer
16
+ from rank_bm25 import BM25Okapi
17
+
18
+ EMB_MODEL_ID = os.getenv("EMB_MODEL_ID", "sentence-transformers/all-MiniLM-L6-v2")
19
+ emb_model = SentenceTransformer(EMB_MODEL_ID)
20
+
21
+ def read_chunks(base="field_guide"):
22
+ chunks, metas = [], []
23
+ base = pathlib.Path(base)
24
+ for md in sorted(base.rglob("*.md")):
25
+ text = md.read_text(encoding="utf-8", errors="ignore")
26
+ # naive chunking into ~600-char pieces on paragraph boundaries
27
+ paras = [p.strip() for p in text.split("\n\n") if p.strip()]
28
+ buf = ""
29
+ for p in paras:
30
+ if len(buf) + len(p) < 600:
31
+ buf = (buf + "\n\n" + p).strip()
32
+ else:
33
+ if buf:
34
+ chunks.append(buf); metas.append({"path": str(md), "title": md.stem})
35
+ buf = p
36
+ if buf:
37
+ chunks.append(buf); metas.append({"path": str(md), "title": md.stem})
38
+ return chunks, metas
39
+
40
+ CHUNKS, METAS = read_chunks()
41
+ BM25 = BM25Okapi([c.split() for c in CHUNKS])
42
+ EMB = emb_model.encode(CHUNKS, normalize_embeddings=True)
43
+
44
+ def retrieve(query, top_k=TOP_K):
45
+ q_emb = emb_model.encode([query], normalize_embeddings=True)[0]
46
+ # semantic
47
+ sims = EMB @ q_emb
48
+ top_sem_idx = np.argsort(-sims)[:top_k*2]
49
+ # lexical
50
+ bm25_scores = BM25.get_scores(query.split())
51
+ top_lex_idx = np.argsort(-bm25_scores)[:top_k*2]
52
+ # merge
53
+ cand = set(top_sem_idx.tolist() + top_lex_idx.tolist())
54
+ scored = sorted([(i, (sims[i] + bm25_scores[i]/10.0)) for i in cand], key=lambda x: -x[1])
55
+ picks = [i for i,_ in scored[:top_k]]
56
+ snippets = []
57
+ for rank, i in enumerate(picks, 1):
58
+ meta = METAS[i]
59
+ snippets.append((f"S{rank}", CHUNKS[i], meta))
60
+ return snippets
61
+
62
+ def build_context(snippets):
63
+ lines = []
64
+ for tag, text, meta in snippets:
65
+ title = meta.get("title", "note")
66
+ lines.append(f"[{tag}] {title}: {text}")
67
+ return "\n\n".join(lines)
68
+
69
+ # --- Generation backends ---
70
+ def chat_local(model_id, messages, max_new_tokens=256, temperature=0.3, top_p=0.9):
71
+ from transformers import AutoTokenizer, AutoModelForCausalLM, TextStreamer
72
+ import torch
73
+ tok = AutoTokenizer.from_pretrained(model_id, use_fast=True)
74
+ # device_map auto so it uses GPU if available
75
+ model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, device_map="auto")
76
+ # simple chat template if available
77
+ if hasattr(tok, "apply_chat_template"):
78
+ prompt = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
79
+ else:
80
+ # fallback: concatenate
81
+ prompt = ""
82
+ for m in messages:
83
+ role = m.get("role","user")
84
+ content = m.get("content","")
85
+ prompt += f"{role.upper()}: {content}\n"
86
+ prompt += "ASSISTANT:"
87
+ inputs = tok([prompt], return_tensors="pt").to(model.device)
88
+ gen = model.generate(
89
+ **inputs,
90
+ max_new_tokens=max_new_tokens,
91
+ do_sample=temperature > 0,
92
+ temperature=temperature,
93
+ top_p=top_p,
94
+ repetition_penalty=1.1,
95
+ pad_token_id=tok.eos_token_id,
96
+ )
97
+ out = tok.decode(gen[0], skip_special_tokens=True)
98
+ # naive split to get assistant part
99
+ if "ASSISTANT:" in out:
100
+ out = out.split("ASSISTANT:")[-1].strip()
101
+ else:
102
+ # try to remove the prompt prefix
103
+ out = out[len(prompt):].strip()
104
+ return out
105
+
106
+ def chat_tgi(url, messages, max_new_tokens=256, temperature=0.3, top_p=0.9, stream=False):
107
+ import requests
108
+ payload = {
109
+ "model": "dummy",
110
+ "messages": messages,
111
+ "max_tokens": max_new_tokens,
112
+ "temperature": temperature,
113
+ "top_p": top_p,
114
+ "stream": stream,
115
+ }
116
+ r = requests.post(url.rstrip("/") + "/v1/chat/completions", json=payload, timeout=120)
117
+ r.raise_for_status()
118
+ data = r.json()
119
+ return data["choices"][0]["message"]["content"]
120
+
121
+ def answer(query, mode, max_new_tokens, temperature, top_p):
122
+ t0 = time.time()
123
+ snippets = retrieve(query, top_k=TOP_K)
124
+ context = build_context(snippets)
125
+ sys_preface = SYSTEM_PROMPT + (" Always use a numbered list." if mode == "Step-by-step" else "")
126
+ ctx_header = f"Use ONLY these notes to answer. If not in notes, say you don't know and propose a safe fallback.\n\n{context}\n\n"
127
+ messages = [
128
+ {"role": "system", "content": sys_preface},
129
+ {"role": "user", "content": ctx_header + "\nQuestion: " + query},
130
+ ]
131
+ if USE_TGI_URL:
132
+ out = chat_tgi(USE_TGI_URL, messages, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p)
133
+ else:
134
+ out = chat_local(MODEL_ID, messages, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p)
135
+ dt = time.time() - t0
136
+ sources = "\n".join([f"[{tag}] {meta.get('title')} — {meta.get('path')}" for tag, _, meta in snippets])
137
+ return out, sources, f"{dt:.1f}s"
138
+
139
+ with gr.Blocks(title="Campfire — Micro‑LLM + Local RAG") as demo:
140
+ gr.Markdown(\"\"\"# Campfire — Micro‑LLM + Local RAG
141
+ Type a question. The model answers **only** from the local field guide below and cites snippets.
142
+ \"\"\" )
143
+ with gr.Row():
144
+ inp = gr.Textbox(label="Question", placeholder="How do I treat mild hypothermia?")
145
+ with gr.Row():
146
+ mode = gr.Radio(["Concise", "Step-by-step"], value="Concise", label="Style")
147
+ max_new = gr.Slider(32, 512, 256, step=32, label="Max new tokens")
148
+ temp = gr.Slider(0.0, 1.0, 0.3, step=0.05, label="Temperature")
149
+ topp = gr.Slider(0.1, 1.0, 0.9, step=0.05, label="Top-p")
150
+ btn = gr.Button("Answer")
151
+ out = gr.Markdown(label="Answer")
152
+ src = gr.Markdown(label="Sources")
153
+ lat = gr.Label(label="Latency")
154
+ btn.click(answer, inputs=[inp, mode, max_new, temp, topp], outputs=[out, src, lat])
155
+
156
+ if __name__ == "__main__":
157
+ demo.launch()
find_north.md ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Finding North Without a Compass (Sun Method)
2
+ - In the Northern Hemisphere, the sun rises in the east and sets in the west.
3
+ - At local noon, the sun is roughly due south; a shadow will point roughly north.
4
+ - Use a stick in the ground: mark the tip of the shadow; wait 15 minutes; mark again. The first mark is west, the second is east; a line between them gives E–W. Perpendicular to the midpoint is N–S.
hypothermia.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # Hypothermia (Mild)
2
+ - Move the person to a warm, dry shelter.
3
+ - Replace wet clothing with dry layers; insulate head, neck, hands, and feet.
4
+ - Give warm, sweet (non‑alcoholic) drinks **if conscious** and able to swallow.
5
+ - Apply external heat to core areas (chest/armpits/groin) using warm packs or body heat. Avoid direct high heat.
6
+ - Monitor breathing; handle gently; **do not** massage extremities.
7
+
8
+ **Evacuate** if shivering stops, mental status worsens, or if there are signs of moderate/severe hypothermia.
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ gradio>=4.44.0
2
+ transformers>=4.42.4
3
+ accelerate>=0.33.0
4
+ torch>=2.3.0
5
+ sentence-transformers>=3.0.1
6
+ rank-bm25>=0.2.2
7
+ numpy>=1.26.4
8
+ scipy>=1.11.4