mjpsm commited on
Commit
bf18f01
·
verified ·
1 Parent(s): f3bdedd

Add system-prompt KV cache; prompt-only request; drop raw_output

Browse files
Files changed (2) hide show
  1. README.md +5 -2
  2. app.py +58 -22
README.md CHANGED
@@ -17,14 +17,17 @@ FastAPI endpoint for the V2 fine-tuned project-creation model. **Upload the merg
17
  POST `/predict`:
18
 
19
  ```json
20
- {"prompt": "Can you put together a project for 7th graders on ocean conservation?", "max_new_tokens": 512, "temperature": 0.7}
21
  ```
22
 
23
- Returns `title`, `description`, `paragraphs`, `raw_output`, and `model`.
 
 
24
  K–5 requests produce 4 paragraphs (including parents and caregivers); grade 6+ requests produce 3.
25
 
26
  ## Operational notes
27
 
 
28
  * `TORCH_NUM_THREADS` defaults to 2 (CPU Basic's vCPUs). Raise it if you upgrade the hardware.
29
  * A public Space is a public endpoint; add authentication/rate limiting before production use.
30
  * This is a separate Space from V1; switch MyVillage over only after comparing outputs.
 
17
  POST `/predict`:
18
 
19
  ```json
20
+ {"prompt": "Can you put together a project for 7th graders on ocean conservation?"}
21
  ```
22
 
23
+ Only `prompt` is accepted; generation settings are fixed server-side (`max_new_tokens=512`, `temperature=0.7`, `top_p=0.9`, `repetition_penalty=1.08`).
24
+
25
+ Returns `title`, `description`, `paragraphs`, and `model`.
26
  K–5 requests produce 4 paragraphs (including parents and caregivers); grade 6+ requests produce 3.
27
 
28
  ## Operational notes
29
 
30
+ * The system prompt's KV cache is computed once at startup and copied per request, so each request only prefills the user prompt.
31
  * `TORCH_NUM_THREADS` defaults to 2 (CPU Basic's vCPUs). Raise it if you upgrade the hardware.
32
  * A public Space is a public endpoint; add authentication/rate limiting before production use.
33
  * This is a separate Space from V1; switch MyVillage over only after comparing outputs.
app.py CHANGED
@@ -1,22 +1,30 @@
1
-
2
  import os
3
  import re
4
  import threading
 
5
  from typing import List
6
 
7
  import torch
8
  from fastapi import FastAPI
9
  from pydantic import BaseModel, Field
10
- from transformers import AutoTokenizer, AutoModelForCausalLM
11
 
12
  MODEL_ID = os.environ.get("MODEL_ID", "mjpsm/project-creation-qwen2.5-1.5b-sft-v2")
13
  SYSTEM_PROMPT = "You are the MyVillage educational project creator. Given a request that names a student audience (grade or age) and a theme, write exactly one project: one title and one general project description. Format: **Project Title:** <title>, a blank line, **Project Description:**, a blank line, then the paragraphs separated by blank lines. For kindergarten through 5th grade write exactly four paragraphs: a fun introduction where the reader explores the theme with their teammates; the one technology-based creation the team will make and what they will learn; how parents and caregivers can support young creators; and a clear definition of done describing the finished creation. For 6th grade and above, including college, write exactly three paragraphs: a project overview where the reader collaborates with their teammates; the one technology-based creation and the learning involved; and a definition of done describing the finished, modest artifact. Match complexity and tone to the audience. Describe what the team makes, learns, and finishes, not how to build it: no step-by-step instructions, and do not name specific tools, programming languages, platforms, or products. Handle sensitive topics supportively without asking anyone to share private information."
 
 
 
 
 
 
 
14
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
15
  # Size the thread pool from an env var (default = the Space's real vCPUs), not os.cpu_count(),
16
  # which reports the host's cores on Hugging Face Spaces.
17
  torch.set_num_threads(int(os.environ.get("TORCH_NUM_THREADS", "2")))
18
 
19
- app = FastAPI(title="MyVillage Project Creation API (V2)", version="2.0.0")
20
  lock = threading.Lock() # keep CPU generations serialized on a small Space
21
 
22
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
@@ -24,30 +32,53 @@ if tokenizer.pad_token is None:
24
  tokenizer.pad_token = tokenizer.eos_token
25
  model = AutoModelForCausalLM.from_pretrained(MODEL_ID, torch_dtype=torch.float32, low_cpu_mem_usage=True)
26
  model.eval()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
  class ProjectRequest(BaseModel):
29
  prompt: str = Field(min_length=8, max_length=1500)
30
- max_new_tokens: int = Field(default=512, ge=128, le=1000)
31
- temperature: float = Field(default=0.7, gt=0, le=1.5)
32
 
33
  class ProjectResponse(BaseModel):
34
  title: str
35
  description: str
36
  paragraphs: List[str]
37
- raw_output: str
38
  model: str
39
 
 
40
  @app.get("/")
41
  def root():
42
  return {"service": "MyVillage Project Creation API (V2)", "docs": "/docs"}
43
 
 
44
  @app.get("/health")
45
  def health():
46
- return {"status": "ok", "model": MODEL_ID}
 
47
 
48
  TITLE_RE = re.compile(r"^\*\*Project Title:\*\*[ \t]+(\S[^\n]*)", re.MULTILINE)
49
  DESC_RE = re.compile(r"\*\*Project Description:\*\*\s*(.*)", re.DOTALL)
50
 
 
51
  def parse_output(text: str):
52
  t = TITLE_RE.search(text)
53
  d = DESC_RE.search(text)
@@ -56,25 +87,30 @@ def parse_output(text: str):
56
  paragraphs = [p.strip() for p in re.split(r"\n\s*\n", description) if p.strip()]
57
  return title, description, paragraphs
58
 
 
59
  @app.post("/predict", response_model=ProjectResponse)
60
  def predict(body: ProjectRequest):
61
- messages = [
62
- {"role": "system", "content": SYSTEM_PROMPT},
63
- {"role": "user", "content": body.prompt},
64
- ]
65
- rendered = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
66
- inputs = tokenizer(rendered, return_tensors="pt")
67
- with lock, torch.inference_mode():
68
  ids = model.generate(
69
- **inputs,
70
- max_new_tokens=body.max_new_tokens,
 
 
71
  do_sample=True,
72
- temperature=body.temperature,
73
- top_p=0.9,
74
- repetition_penalty=1.08,
75
- eos_token_id=tokenizer.convert_tokens_to_ids("<|im_end|>"),
76
  pad_token_id=tokenizer.pad_token_id,
77
  )
78
- raw = tokenizer.decode(ids[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True).strip()
 
 
 
79
  title, description, paragraphs = parse_output(raw)
80
- return ProjectResponse(title=title, description=description, paragraphs=paragraphs, raw_output=raw, model=MODEL_ID)
 
1
+ import copy
2
  import os
3
  import re
4
  import threading
5
+ import time
6
  from typing import List
7
 
8
  import torch
9
  from fastapi import FastAPI
10
  from pydantic import BaseModel, Field
11
+ from transformers import AutoTokenizer, AutoModelForCausalLM, DynamicCache
12
 
13
  MODEL_ID = os.environ.get("MODEL_ID", "mjpsm/project-creation-qwen2.5-1.5b-sft-v2")
14
  SYSTEM_PROMPT = "You are the MyVillage educational project creator. Given a request that names a student audience (grade or age) and a theme, write exactly one project: one title and one general project description. Format: **Project Title:** <title>, a blank line, **Project Description:**, a blank line, then the paragraphs separated by blank lines. For kindergarten through 5th grade write exactly four paragraphs: a fun introduction where the reader explores the theme with their teammates; the one technology-based creation the team will make and what they will learn; how parents and caregivers can support young creators; and a clear definition of done describing the finished creation. For 6th grade and above, including college, write exactly three paragraphs: a project overview where the reader collaborates with their teammates; the one technology-based creation and the learning involved; and a definition of done describing the finished, modest artifact. Match complexity and tone to the audience. Describe what the team makes, learns, and finishes, not how to build it: no step-by-step instructions, and do not name specific tools, programming languages, platforms, or products. Handle sensitive topics supportively without asking anyone to share private information."
15
+
16
+ # Generation settings are fixed server-side (no longer request fields).
17
+ MAX_NEW_TOKENS = 512
18
+ TEMPERATURE = 0.7
19
+ TOP_P = 0.9
20
+ REPETITION_PENALTY = 1.08
21
+
22
  os.environ["TOKENIZERS_PARALLELISM"] = "false"
23
  # Size the thread pool from an env var (default = the Space's real vCPUs), not os.cpu_count(),
24
  # which reports the host's cores on Hugging Face Spaces.
25
  torch.set_num_threads(int(os.environ.get("TORCH_NUM_THREADS", "2")))
26
 
27
+ app = FastAPI(title="MyVillage Project Creation API (V2)", version="2.1.0")
28
  lock = threading.Lock() # keep CPU generations serialized on a small Space
29
 
30
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
 
32
  tokenizer.pad_token = tokenizer.eos_token
33
  model = AutoModelForCausalLM.from_pretrained(MODEL_ID, torch_dtype=torch.float32, low_cpu_mem_usage=True)
34
  model.eval()
35
+ EOS_ID = tokenizer.convert_tokens_to_ids("<|im_end|>")
36
+
37
+ # --- System-prompt KV cache --------------------------------------------------
38
+ # Every request starts with the same system prompt, so its key/value tensors are
39
+ # computed once here. Each request deep-copies this cache and only has to prefill
40
+ # its own user prompt before decoding.
41
+ _SENTINEL = "\x00USER_PROMPT\x00"
42
+ _template = tokenizer.apply_chat_template(
43
+ [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": _SENTINEL}],
44
+ tokenize=False,
45
+ add_generation_prompt=True,
46
+ )
47
+ PREFIX_TEXT, SUFFIX_TEMPLATE = _template.split(_SENTINEL)
48
+ PREFIX_IDS = tokenizer(PREFIX_TEXT, return_tensors="pt", add_special_tokens=False).input_ids
49
+
50
+ _t0 = time.time()
51
+ with torch.no_grad():
52
+ PREFIX_CACHE = DynamicCache()
53
+ model(input_ids=PREFIX_IDS, past_key_values=PREFIX_CACHE, use_cache=True)
54
+ print(f"[startup] cached system prompt: {PREFIX_IDS.shape[-1]} tokens in {time.time() - _t0:.2f}s", flush=True)
55
+
56
 
57
  class ProjectRequest(BaseModel):
58
  prompt: str = Field(min_length=8, max_length=1500)
59
+
 
60
 
61
  class ProjectResponse(BaseModel):
62
  title: str
63
  description: str
64
  paragraphs: List[str]
 
65
  model: str
66
 
67
+
68
  @app.get("/")
69
  def root():
70
  return {"service": "MyVillage Project Creation API (V2)", "docs": "/docs"}
71
 
72
+
73
  @app.get("/health")
74
  def health():
75
+ return {"status": "ok", "model": MODEL_ID, "cached_prefix_tokens": int(PREFIX_IDS.shape[-1])}
76
+
77
 
78
  TITLE_RE = re.compile(r"^\*\*Project Title:\*\*[ \t]+(\S[^\n]*)", re.MULTILINE)
79
  DESC_RE = re.compile(r"\*\*Project Description:\*\*\s*(.*)", re.DOTALL)
80
 
81
+
82
  def parse_output(text: str):
83
  t = TITLE_RE.search(text)
84
  d = DESC_RE.search(text)
 
87
  paragraphs = [p.strip() for p in re.split(r"\n\s*\n", description) if p.strip()]
88
  return title, description, paragraphs
89
 
90
+
91
  @app.post("/predict", response_model=ProjectResponse)
92
  def predict(body: ProjectRequest):
93
+ suffix_ids = tokenizer(body.prompt + SUFFIX_TEMPLATE, return_tensors="pt", add_special_tokens=False).input_ids
94
+ input_ids = torch.cat([PREFIX_IDS, suffix_ids], dim=-1)
95
+ attention_mask = torch.ones_like(input_ids)
96
+ with lock, torch.no_grad():
97
+ t0 = time.time()
98
+ cache = copy.deepcopy(PREFIX_CACHE) # per-request copy; generate() mutates the cache
 
99
  ids = model.generate(
100
+ input_ids=input_ids,
101
+ attention_mask=attention_mask,
102
+ past_key_values=cache,
103
+ max_new_tokens=MAX_NEW_TOKENS,
104
  do_sample=True,
105
+ temperature=TEMPERATURE,
106
+ top_p=TOP_P,
107
+ repetition_penalty=REPETITION_PENALTY,
108
+ eos_token_id=EOS_ID,
109
  pad_token_id=tokenizer.pad_token_id,
110
  )
111
+ new_tokens = ids.shape[-1] - input_ids.shape[-1]
112
+ print(f"[predict] prompt={suffix_ids.shape[-1]} tok (+{PREFIX_IDS.shape[-1]} cached), "
113
+ f"generated={new_tokens} tok in {time.time() - t0:.1f}s", flush=True)
114
+ raw = tokenizer.decode(ids[0][input_ids.shape[-1]:], skip_special_tokens=True).strip()
115
  title, description, paragraphs = parse_output(raw)
116
+ return ProjectResponse(title=title, description=description, paragraphs=paragraphs, model=MODEL_ID)