Mentors4EDU commited on
Commit
57976ee
·
verified ·
1 Parent(s): 72f7994

Publish riemann-prerelease-demo

Browse files
Files changed (3) hide show
  1. README.md +32 -13
  2. app.py +174 -0
  3. requirements.txt +8 -0
README.md CHANGED
@@ -1,13 +1,32 @@
1
- ---
2
- title: My Name Is Riemann Prerelease Basic Demo
3
- emoji: 📚
4
- colorFrom: pink
5
- colorTo: gray
6
- sdk: gradio
7
- sdk_version: 6.30.0
8
- python_version: '3.12'
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: My Name is Riemann Prerelease basic demo
3
+ emoji: 🪜
4
+ colorFrom: indigo
5
+ colorTo: gray
6
+ sdk: gradio
7
+ sdk_version: 5.49.1
8
+ app_file: app.py
9
+ pinned: false
10
+ license: other
11
+ license_name: opnl-2-and-mit
12
+ license_link: https://huggingface.co/OpenPeerAI/My-Name-is-Riemann-Prerelease/blob/main/LICENSE
13
+ models:
14
+ - OpenPeerAI/My-Name-is-Riemann-Prerelease
15
+ - OpenPeerAI/OpenPeerLLM
16
+ short_description: Chat with the 13.1B My Name is Riemann Prerelease on ZeroGPU
17
+ ---
18
+
19
+ # My Name is Riemann Prerelease basic demo
20
+
21
+ Interactive text generation with the stage 6 checkpoint of
22
+ [My Name is Riemann](https://huggingface.co/OpenPeerAI/My-Name-is-Riemann-Prerelease),
23
+ a 13.1 billion parameter model grown from OpenPeerLLM's published weights and
24
+ fine-tuned with the OpenPeer-AI-NTK-Trainer gate controller. The toggle in the
25
+ sidebar attaches or removes the controller so the two can be compared on the
26
+ same prompt.
27
+
28
+ The model loads in bf16 and runs on a ZeroGPU slot. Expect a cold start of a
29
+ minute or two the first time a GPU is assigned.
30
+
31
+ Developed by OpenPeer AI, Riemann Computing Inc., and Andrew Magdy Kamal.
32
+ Released under the Open Innovation License v2 and MIT.
app.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import os
3
+ import threading
4
+ import torch
5
+ import gradio as gr
6
+ import spaces
7
+ from huggingface_hub import hf_hub_download
8
+ from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer
9
+
10
+ MODEL_REPO = os.environ.get("MODEL_REPO", "OpenPeerAI/My-Name-is-Riemann-Prerelease")
11
+ CONTROLLER_PATH_IN_REPO = "ntk_controller/stage6_12.85b.pt"
12
+ HF_TOKEN = os.environ.get("HF_TOKEN")
13
+
14
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO, token=HF_TOKEN)
15
+ if tokenizer.pad_token is None:
16
+ tokenizer.pad_token = tokenizer.eos_token
17
+ model = AutoModelForCausalLM.from_pretrained(
18
+ MODEL_REPO,
19
+ trust_remote_code=True,
20
+ torch_dtype=torch.bfloat16,
21
+ token=HF_TOKEN,
22
+ low_cpu_mem_usage=True,
23
+ )
24
+ model.eval()
25
+
26
+ _controller = {"tuner": None, "attached": False, "error": None}
27
+
28
+
29
+ def _ensure_controller():
30
+ if _controller["tuner"] is not None or _controller["error"]:
31
+ return
32
+ try:
33
+ from ntkmirror import ForwardFineTuner
34
+
35
+ path = hf_hub_download(MODEL_REPO, CONTROLLER_PATH_IN_REPO, token=HF_TOKEN)
36
+ tuner = ForwardFineTuner(model, tokenizer)
37
+ tuner.load(path, allow_model_mismatch=True, map_location="cpu")
38
+ _controller["tuner"] = tuner
39
+ except Exception as exc:
40
+ _controller["error"] = str(exc)
41
+
42
+
43
+ def _set_controller(enabled: bool):
44
+ _ensure_controller()
45
+ tuner = _controller["tuner"]
46
+ if tuner is None:
47
+ return
48
+ if enabled and not _controller["attached"]:
49
+ tuner.controller.to(model.device)
50
+ tuner.controller.attach()
51
+ _controller["attached"] = True
52
+ elif not enabled and _controller["attached"]:
53
+ tuner.controller.remove()
54
+ _controller["attached"] = False
55
+
56
+
57
+ def _format_prompt(message: str, history: list[dict], system: str) -> str:
58
+ parts = []
59
+ if system.strip():
60
+ parts.append(f"system: {system.strip()}")
61
+ for turn in history:
62
+ role = turn.get("role", "user")
63
+ content = turn.get("content", "")
64
+ if content:
65
+ parts.append(f"{role}: {content}")
66
+ parts.append(f"user: {message.strip()}")
67
+ parts.append("assistant:")
68
+ return "\n".join(parts)
69
+
70
+
71
+ @spaces.GPU(duration=120)
72
+ def generate(
73
+ message,
74
+ history,
75
+ system,
76
+ use_controller,
77
+ max_new_tokens,
78
+ temperature,
79
+ top_p,
80
+ repetition_penalty,
81
+ ):
82
+ model.to("cuda")
83
+ _set_controller(bool(use_controller))
84
+ prompt = _format_prompt(message, history, system)
85
+ inputs = tokenizer(
86
+ prompt,
87
+ return_tensors="pt",
88
+ truncation=True,
89
+ max_length=2048 - int(max_new_tokens),
90
+ ).to("cuda")
91
+ streamer = TextIteratorStreamer(
92
+ tokenizer, skip_prompt=True, skip_special_tokens=True
93
+ )
94
+ kwargs = dict(
95
+ **inputs,
96
+ streamer=streamer,
97
+ max_new_tokens=int(max_new_tokens),
98
+ do_sample=temperature > 0,
99
+ temperature=max(float(temperature), 1e-3),
100
+ top_p=float(top_p),
101
+ repetition_penalty=float(repetition_penalty),
102
+ pad_token_id=tokenizer.eos_token_id,
103
+ eos_token_id=tokenizer.eos_token_id,
104
+ )
105
+ thread = threading.Thread(target=model.generate, kwargs=kwargs)
106
+ thread.start()
107
+ out = ""
108
+ for piece in streamer:
109
+ out += piece
110
+ if "\nuser:" in out:
111
+ out = out.split("\nuser:")[0]
112
+ break
113
+ yield out
114
+ thread.join()
115
+ yield out.strip()
116
+
117
+
118
+ DESCRIPTION = f"""
119
+ # My Name is Riemann Prerelease
120
+
121
+ A 13.1 billion parameter decoder-only model grown rung by rung from
122
+ [OpenPeerAI/OpenPeerLLM](https://huggingface.co/OpenPeerAI/OpenPeerLLM) and
123
+ fine-tuned with the [OpenPeer-AI-NTK-Trainer](https://huggingface.co/OpenPeerAI/OpenPeer-AI-NTK-Trainer)
124
+ gate controller instead of LoRA. Weights load in bf16 on ZeroGPU.
125
+
126
+ This is a prerelease trained on about 2.2 billion tokens. It is not an aligned assistant;
127
+ treat output as a draft. The NTK toggle attaches the 6,732-gate controller fitted on the frozen weights.
128
+
129
+ Model card and weights: [{MODEL_REPO}](https://huggingface.co/{MODEL_REPO})
130
+ """
131
+
132
+ with gr.Blocks(title="My Name is Riemann Prerelease") as demo:
133
+ gr.Markdown(DESCRIPTION)
134
+ with gr.Row():
135
+ with gr.Column(scale=3):
136
+ chat = gr.ChatInterface(
137
+ fn=generate,
138
+ type="messages",
139
+ additional_inputs=[
140
+ gr.Textbox(
141
+ value="You are My Name is Riemann, a careful coding and reasoning assistant. Think step by step and show your work.",
142
+ label="System prompt",
143
+ lines=2,
144
+ ),
145
+ gr.Checkbox(value=True, label="Attach NTK gate controller"),
146
+ gr.Slider(16, 512, value=256, step=16, label="Max new tokens"),
147
+ gr.Slider(
148
+ 0.0, 1.5, value=0.7, step=0.05, label="Temperature (0 = greedy)"
149
+ ),
150
+ gr.Slider(0.1, 1.0, value=0.9, step=0.05, label="Top-p"),
151
+ gr.Slider(
152
+ 1.0, 1.5, value=1.1, step=0.05, label="Repetition penalty"
153
+ ),
154
+ ],
155
+ examples=[
156
+ [
157
+ "Write a Python function that returns the n-th prime, with a short explanation."
158
+ ],
159
+ [
160
+ "Explain the difference between a mutex and a semaphore in two paragraphs."
161
+ ],
162
+ ["اشرح نظرية فيثاغورس بإيجاز."],
163
+ [
164
+ "Refactor this to be idempotent:\n\ndef add_user(db, name):\n db.append({'name': name})"
165
+ ],
166
+ ],
167
+ cache_examples=False,
168
+ )
169
+ gr.Markdown(
170
+ "Licensed under the Open Innovation License v2 (OPNL-2) and MIT. "
171
+ "Developed by OpenPeer AI, Riemann Computing Inc., and Andrew Magdy Kamal."
172
+ )
173
+
174
+ demo.queue(max_size=16).launch()
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch>=2.4
2
+ transformers>=4.56,<5
3
+ safetensors>=0.4
4
+ accelerate>=0.33
5
+ gradio>=5.0
6
+ spaces
7
+ huggingface_hub>=0.24
8
+ ntkmirror @ git+https://github.com/leochlon/ntkmirror.git