Tbain20 commited on
Commit
d18a277
·
1 Parent(s): 5e0335d

Use transformers AutoModelForCausalLM — no OLMo-Core dependency

Browse files
Files changed (2) hide show
  1. app.py +37 -42
  2. requirements.txt +3 -4
app.py CHANGED
@@ -1,79 +1,74 @@
1
- import os, torch, gradio as gr
 
 
2
  import torch.nn.functional as F
3
  from huggingface_hub import hf_hub_download
4
- from transformers import AutoTokenizer
5
- from olmo_core.nn.transformer import TransformerConfig
6
 
7
- # Load from HuggingFace — works without lab server
8
  REPO_ID = "Tbain20/olmo2-1b-eeg-v11"
9
- VOCAB_SIZE = 100278
10
- DEVICE = "cpu" # HF free tier is CPU only
11
  PREFIX_I = "### Instruction:\n"
12
  PREFIX_R = "\n\n### Response:\n"
13
 
14
- print("Downloading model from HuggingFace...")
15
- ckpt_path = hf_hub_download(repo_id=REPO_ID, filename="best_model.pt")
16
-
17
  print("Loading tokenizer...")
18
  tokenizer = AutoTokenizer.from_pretrained("allenai/OLMo-2-1124-7B")
19
 
20
- print("Building model...")
21
- cfg = TransformerConfig.olmo2_1B(vocab_size=VOCAB_SIZE)
22
- model = cfg.build()
23
- ckpt = torch.load(ckpt_path, map_location="cpu")
24
- model.load_state_dict(ckpt["model_state_dict"])
 
25
  model.eval()
26
- print("Ready")
27
 
28
  @torch.no_grad()
29
  def generate_code(prompt, max_new_tokens=300, temperature=0.7):
30
  if not prompt.strip():
31
  return "Please enter a prompt."
32
  full = PREFIX_I + prompt.strip() + PREFIX_R
33
- ids = tokenizer.encode(full)
34
- x = torch.tensor([ids], dtype=torch.long)
35
- for _ in range(max_new_tokens):
36
- logits = model(x)
37
- logits = logits[:, -1, :] / temperature
38
- vals, idxs = torch.topk(logits, k=40)
39
- probs = F.softmax(vals, dim=-1)
40
- next_tok = idxs.gather(-1, torch.multinomial(probs, 1))
41
- x = torch.cat([x, next_tok], dim=1)
42
- if next_tok.item() == tokenizer.eos_token_id:
43
- break
44
- out = tokenizer.decode(x[0].tolist(), skip_special_tokens=True)
45
- return out[len(full):].strip()
46
 
47
  EXAMPLES = [
48
  ["Write a Python function using MNE to filter EEG data for beta waves (13-30 Hz)"],
49
- ["Write a Python function to compute beta band power from STN LFP recordings"],
50
  ["Write a Python function to compare beta power between on and off medication Parkinson's patients"],
51
- ["Write a Python function to load TDT block and extract RSn1 LFP stream"],
52
  ["Write a Python function to suppress DBS stimulation artifacts using sample-and-hold"],
53
  ["Write a MATLAB function using FieldTrip to compute beta band power from LFP"],
54
  ]
55
 
56
  with gr.Blocks(title="OLMo EEG Code Generator") as demo:
57
- gr.Markdown("# 🧠 OLMo EEG Code Generator\n### NDML Lab — Parkinson's & EEG Analysis Assistant\n*Note: Running on CPU — generation takes 1-2 minutes*")
 
 
 
 
58
  with gr.Row():
59
  with gr.Column():
60
  prompt_box = gr.Textbox(label="Describe what you need", lines=4,
61
  placeholder="e.g. Write a Python function using MNE to filter EEG for beta waves")
62
- temperature = gr.Slider(0.3, 1.2, value=0.7, step=0.05, label="Temperature")
63
- max_tokens = gr.Slider(100, 500, value=300, step=50, label="Max tokens")
 
64
  with gr.Row():
65
  generate_btn = gr.Button("Generate Code", variant="primary", scale=2)
66
  clear_btn = gr.Button("Clear", scale=1)
67
- gr.Examples(examples=EXAMPLES, inputs=prompt_box)
68
  with gr.Column():
69
- output_box = gr.Code(label="Generated Code", language="python", lines=25)
70
 
71
- generate_btn.click(
72
- fn=lambda p,t,m: generate_code(p, int(m), float(t)),
73
- inputs=[prompt_box, temperature, max_tokens], outputs=output_box)
74
- prompt_box.submit(
75
- fn=lambda p,t,m: generate_code(p, int(m), float(t)),
76
- inputs=[prompt_box, temperature, max_tokens], outputs=output_box)
77
- clear_btn.click(fn=lambda: ("",""), outputs=[prompt_box, output_box])
78
 
79
  demo.launch()
 
1
+ import os
2
+ import torch
3
+ import gradio as gr
4
  import torch.nn.functional as F
5
  from huggingface_hub import hf_hub_download
6
+ from transformers import AutoTokenizer, AutoModelForCausalLM
 
7
 
 
8
  REPO_ID = "Tbain20/olmo2-1b-eeg-v11"
 
 
9
  PREFIX_I = "### Instruction:\n"
10
  PREFIX_R = "\n\n### Response:\n"
11
 
 
 
 
12
  print("Loading tokenizer...")
13
  tokenizer = AutoTokenizer.from_pretrained("allenai/OLMo-2-1124-7B")
14
 
15
+ print("Loading model from HuggingFace...")
16
+ model = AutoModelForCausalLM.from_pretrained(
17
+ REPO_ID,
18
+ torch_dtype=torch.float32,
19
+ device_map="cpu",
20
+ )
21
  model.eval()
22
+ print("Model ready")
23
 
24
  @torch.no_grad()
25
  def generate_code(prompt, max_new_tokens=300, temperature=0.7):
26
  if not prompt.strip():
27
  return "Please enter a prompt."
28
  full = PREFIX_I + prompt.strip() + PREFIX_R
29
+ ids = tokenizer(full, return_tensors="pt").input_ids
30
+ out = model.generate(
31
+ ids,
32
+ max_new_tokens=int(max_new_tokens),
33
+ temperature=float(temperature),
34
+ do_sample=True,
35
+ top_k=40,
36
+ pad_token_id=tokenizer.eos_token_id,
37
+ )
38
+ generated = out[0][ids.shape[1]:]
39
+ return tokenizer.decode(generated, skip_special_tokens=True).strip()
 
 
40
 
41
  EXAMPLES = [
42
  ["Write a Python function using MNE to filter EEG data for beta waves (13-30 Hz)"],
43
+ ["Write a Python function to compute beta band power from STN LFP using Welch method"],
44
  ["Write a Python function to compare beta power between on and off medication Parkinson's patients"],
45
+ ["Write a Python function to load TDT block and extract RSn1 LFP stream at 24414 Hz"],
46
  ["Write a Python function to suppress DBS stimulation artifacts using sample-and-hold"],
47
  ["Write a MATLAB function using FieldTrip to compute beta band power from LFP"],
48
  ]
49
 
50
  with gr.Blocks(title="OLMo EEG Code Generator") as demo:
51
+ gr.Markdown("""# 🧠 OLMo EEG Code Generator
52
+ ### NDML Lab — Parkinson's & EEG Analysis Assistant
53
+ *Neural Dynamics and Modulation Lab, Cleveland Clinic*
54
+
55
+ > ⚠️ Running on CPU — generation takes 2-3 minutes. For fast generation use the lab server demo.""")
56
  with gr.Row():
57
  with gr.Column():
58
  prompt_box = gr.Textbox(label="Describe what you need", lines=4,
59
  placeholder="e.g. Write a Python function using MNE to filter EEG for beta waves")
60
+ with gr.Row():
61
+ temperature = gr.Slider(0.3, 1.2, value=0.7, step=0.05, label="Temperature")
62
+ max_tokens = gr.Slider(100, 400, value=300, step=50, label="Max tokens")
63
  with gr.Row():
64
  generate_btn = gr.Button("Generate Code", variant="primary", scale=2)
65
  clear_btn = gr.Button("Clear", scale=1)
66
+ gr.Examples(examples=EXAMPLES, inputs=prompt_box, label="Example prompts")
67
  with gr.Column():
68
+ output_box = gr.Code(label="Generated Code", language="python", lines=22)
69
 
70
+ generate_btn.click(fn=generate_code, inputs=[prompt_box, temperature, max_tokens], outputs=output_box)
71
+ prompt_box.submit(fn=generate_code, inputs=[prompt_box, temperature, max_tokens], outputs=output_box)
72
+ clear_btn.click(fn=lambda: ("", ""), outputs=[prompt_box, output_box])
 
 
 
 
73
 
74
  demo.launch()
requirements.txt CHANGED
@@ -1,6 +1,5 @@
1
  gradio==4.44.0
2
- transformers
3
- torch
4
- numpy
5
  huggingface_hub
6
- ai2-olmo
 
1
  gradio==4.44.0
2
+ torch==2.1.0
3
+ transformers>=4.40.0
 
4
  huggingface_hub
5
+ numpy