ndemirdemir commited on
Commit
d3ce9ae
·
verified ·
1 Parent(s): 4f7f1e5

Add Colab example timing ten questions with one model load

Browse files

Separate model loading and warm-up from synchronized prediction timings. Explain process lifetime and the scope of the short-text example.

Files changed (1) hide show
  1. README.md +197 -0
README.md CHANGED
@@ -48,6 +48,10 @@ The initial dependency installation and kernel build can take several minutes.
48
  Run the examples below with `.venv/bin/python`, or select that environment in
49
  your notebook. These setup scripts install inference dependencies only.
50
 
 
 
 
 
51
  ## Text example
52
 
53
  ```python
@@ -103,6 +107,199 @@ print(image_result["selected_id"])
103
  print(dict(zip(image_result["candidate_ids"], image_result["probabilities"])))
104
  ```
105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  ## Inputs and outputs
107
 
108
  - `state`: situation or evidence as text.
 
48
  Run the examples below with `.venv/bin/python`, or select that environment in
49
  your notebook. These setup scripts install inference dependencies only.
50
 
51
+ For a complete Colab cell using this environment, see
52
+ [Ten questions with timing in Colab](#ten-questions-with-timing-in-colab).
53
+ Creating `.venv` does not switch the notebook's own Python environment.
54
+
55
  ## Text example
56
 
57
  ```python
 
107
  print(dict(zip(image_result["candidate_ids"], image_result["probabilities"])))
108
  ```
109
 
110
+ ## Ten questions with timing in Colab
111
+
112
+ After installation finishes, paste this entire block into one Colab code cell.
113
+ It assumes the environment is at `/content/.venv`, as with the setup above run
114
+ from Colab's default `/content` directory. The first line must be `%%bash`.
115
+
116
+ The model loads once, runs a separate warm-up example, then answers ten different
117
+ text questions with three choices each. Each prediction's timer includes input
118
+ preparation and inference, with CUDA synchronization before and after the call.
119
+ Model loading, warm-up, and printing are excluded from those prediction times.
120
+ The summary reports loading and warm-up separately, plus the total, mean,
121
+ median, fastest, and slowest prediction times.
122
+
123
+ ```bash
124
+ %%bash
125
+ set -e
126
+ /content/.venv/bin/python -u - <<'PY'
127
+ import os
128
+ import time
129
+ import statistics
130
+ import torch
131
+ from transformers import AutoModel
132
+
133
+
134
+ def make_request(state, question, choices):
135
+ return {
136
+ "state": state,
137
+ "question": question,
138
+ "candidates": [
139
+ {"id": str(i), "description": choice}
140
+ for i, choice in enumerate(choices)
141
+ ],
142
+ }
143
+
144
+
145
+ # Load once.
146
+ started = time.perf_counter()
147
+ model = AutoModel.from_pretrained(
148
+ os.environ.get("BRANCHONE_MODEL", "ndemirdemir/BranchOne"),
149
+ trust_remote_code=True,
150
+ device="cuda",
151
+ )
152
+ torch.cuda.synchronize()
153
+ loading_seconds = time.perf_counter() - started
154
+
155
+ print("GPU:", torch.cuda.get_device_name(0))
156
+ print(f"Model loading: {loading_seconds:.3f} seconds")
157
+
158
+
159
+ questions = [
160
+ (
161
+ "The parcel arrived, but the item inside is broken.",
162
+ "What should happen next?",
163
+ [
164
+ "Arrange a replacement for the damaged item.",
165
+ "Track the parcel because it has not arrived.",
166
+ "Send a receipt for a new purchase.",
167
+ ],
168
+ ),
169
+ (
170
+ "Buenos días. ¿A qué hora abre la tienda?",
171
+ "Which language is this text written in?",
172
+ ["Spanish.", "French.", "English."],
173
+ ),
174
+ (
175
+ "Alex cannot attend on Tuesday. Alex is available Thursday after 2 PM.",
176
+ "Which appointment fits Alex's availability?",
177
+ ["Tuesday at 10 AM.", "Thursday at 3 PM.", "Thursday at 9 AM."],
178
+ ),
179
+ (
180
+ "Refunds are allowed within 30 days with a receipt. "
181
+ "The customer purchased the item 10 days ago and has the receipt.",
182
+ "Does this request meet the stated refund conditions?",
183
+ [
184
+ "Yes, both conditions are satisfied.",
185
+ "No, the purchase was too long ago.",
186
+ "No, the receipt is missing.",
187
+ ],
188
+ ),
189
+ (
190
+ "Ingredients: flour, eggs, and milk. Mix together, "
191
+ "pour into a pan, and bake for 25 minutes.",
192
+ "What kind of document is this?",
193
+ ["A recipe.", "An invoice.", "Meeting minutes."],
194
+ ),
195
+ (
196
+ "A Python program reports: FileNotFoundError: "
197
+ "No such file or directory: '/data/input.csv'.",
198
+ "What problem does this error describe?",
199
+ [
200
+ "The requested file cannot be found at that path.",
201
+ "The network connection timed out.",
202
+ "The password was rejected.",
203
+ ],
204
+ ),
205
+ (
206
+ "Maya will send the draft on Friday. Leon will review it on Monday.",
207
+ "Who is responsible for sending the draft?",
208
+ ["Maya.", "Leon.", "Both Maya and Leon."],
209
+ ),
210
+ (
211
+ "The rule says: reorder when stock falls below five items. "
212
+ "There are currently two items in stock.",
213
+ "What action follows the rule?",
214
+ [
215
+ "Place a replenishment order.",
216
+ "Wait because stock is above the threshold.",
217
+ "Permanently stop selling the item.",
218
+ ],
219
+ ),
220
+ (
221
+ "The picnic will be indoors if it rains and outdoors otherwise. "
222
+ "It is raining.",
223
+ "Where should the picnic take place?",
224
+ ["Indoors.", "Outdoors.", "The location cannot be determined."],
225
+ ),
226
+ (
227
+ "This product broke after one day. I regret buying it "
228
+ "and would not recommend it.",
229
+ "What is the overall sentiment?",
230
+ ["Positive.", "Negative.", "Neutral."],
231
+ ),
232
+ ]
233
+
234
+
235
+ # Separate warm-up: excluded from the ten measured questions.
236
+ warmup = make_request(
237
+ "The delivery arrived on time and everything is intact.",
238
+ "Which description matches the delivery?",
239
+ ["On time and undamaged.", "Missing.", "Damaged."],
240
+ )
241
+
242
+ torch.cuda.synchronize()
243
+ started = time.perf_counter()
244
+ model.predict(warmup)
245
+ torch.cuda.synchronize()
246
+ warmup_seconds = time.perf_counter() - started
247
+
248
+ print(f"Warm-up: {warmup_seconds:.3f} seconds")
249
+ print("\nRunning 10 timed predictions...")
250
+
251
+
252
+ # Reuse the same loaded model for every question.
253
+ timings = []
254
+
255
+ for number, (state, question, choices) in enumerate(questions, start=1):
256
+ request = make_request(state, question, choices)
257
+
258
+ torch.cuda.synchronize()
259
+ started = time.perf_counter()
260
+
261
+ result = model.predict(request)
262
+
263
+ torch.cuda.synchronize()
264
+ elapsed = time.perf_counter() - started
265
+ timings.append(elapsed)
266
+
267
+ descriptions = {
268
+ candidate["id"]: candidate["description"]
269
+ for candidate in request["candidates"]
270
+ }
271
+
272
+ print(f"\n{number}. {question}")
273
+ print("Selected:", descriptions[result["selected_id"]])
274
+ print(f"Prediction time: {elapsed:.3f} seconds")
275
+ for candidate_id, probability in zip(
276
+ result["candidate_ids"], result["probabilities"]
277
+ ):
278
+ print(f" {probability:.1%} — {descriptions[candidate_id]}")
279
+
280
+
281
+ print("\n--- Timing summary ---")
282
+ print(f"Model loading: {loading_seconds:.3f} seconds")
283
+ print(f"Warm-up: {warmup_seconds:.3f} seconds")
284
+ print(f"10 predictions: {sum(timings):.3f} seconds")
285
+ print(f"Mean per prediction: {statistics.mean(timings):.3f} seconds")
286
+ print(f"Median: {statistics.median(timings):.3f} seconds")
287
+ print(f"Fastest: {min(timings):.3f} seconds")
288
+ print(f"Slowest: {max(timings):.3f} seconds")
289
+ PY
290
+ ```
291
+
292
+ All ten predictions share the loaded model within this process. Re-running the
293
+ whole cell starts a new Python process and reloads the model; separate `%%bash`
294
+ cells cannot share the `model` variable. On first use, loading can also include
295
+ downloading the Qwen backbone. New input shapes may still trigger additional
296
+ kernel initialization after the warm-up.
297
+
298
+ This is a short-text timing example for your runtime, not a representative
299
+ accuracy benchmark or a measurement of long-context or image performance.
300
+ It does not establish sub-second latency. Save any results you need and stop
301
+ your Colab runtime when finished.
302
+
303
  ## Inputs and outputs
304
 
305
  - `state`: situation or evidence as text.