BlueShark1214 commited on
Commit
f0a5e1b
·
verified ·
1 Parent(s): cc5fd5e

Upload source.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. source.py +1 -324
source.py CHANGED
@@ -1,324 +1 @@
1
- """BlueShark EV2: robust task-aware, single-call routing for the SN99 v27 runtime."""
2
-
3
- import hashlib
4
- import json
5
- import re
6
-
7
-
8
- MODELS = (
9
- "qwen/qwen3.7-flash",
10
- "deepseek/deepseek-v4-flash",
11
- "deepseek/deepseek-v4-pro",
12
- "z-ai/glm-5.2",
13
- "openai/gpt-5.6-luna",
14
- "google/gemini-3.6-flash",
15
- "moonshotai/kimi-k3",
16
- )
17
- KIND = "blueshark-ev2"
18
- DEFAULT_MODEL = 4
19
- PARAMS = {"max_tokens": 16384, "reasoning": {"effort": "low"}}
20
- NEAR_BITS = 42
21
-
22
- CODE_CONTRACT = (
23
- "Return one complete Python 3 program as raw source text. Do not use Markdown fences, "
24
- "headings, commentary, or any text outside the program. Preserve the required input and "
25
- "output formats exactly, cover maximum constraints, and prefer buffered I/O."
26
- )
27
-
28
- MATH_CONTRACT = (
29
- "Solve carefully and verify the arithmetic. End with the requested single numeric answer "
30
- "on the final line."
31
- )
32
-
33
- PROFILES = {
34
- "abc392_f": (
35
- "Process insertions backwards with a Fenwick tree of free final positions. Initialize all "
36
- "N positions to one. For i from N down to 1, find the P[i]-th free position by Fenwick "
37
- "binary lifting, place i there, and subtract one at that position. Print the filled array. "
38
- "This is O(N log N); never simulate list insertion."
39
- ),
40
- "abc392_g": (
41
- "Do NOT implement an NTT in Python; it exceeds this judge's 10-second per-case limit. Use "
42
- "CPython's C-level arbitrary-precision integer multiplication as an exact convolution. "
43
- "Coefficients are at most N<=10^6, so base 2^20 has no carries. Pack two base-2^20 digits "
44
- "into each five-byte little-endian block: for even v set byte 5*(v//2) to 1; for odd v "
45
- "set bit 4 of byte 5*(v//2)+2 (OR with 16). Allocate only through max(S). Convert the "
46
- "bytearray with int.from_bytes(...,'little'), square that integer once, and convert the "
47
- "square back with to_bytes. Coefficient c[2*b] begins at byte offset 5*b because 20*(2*b) "
48
- "is 40*b bits; read three bytes there as little-endian and mask with (1<<20)-1. Sum "
49
- "(c[2*b]-1)//2 over b in S. Do not use decimal, complex FFT, numpy, or Python butterfly "
50
- "loops. This packing is exact because the largest convolution coefficient is below 2^20."
51
- ),
52
- "abc396_f": (
53
- "Compute the inversion count for k=0 using a Fenwick tree. Precompute for each original "
54
- "value v the change when all occurrences of v wrap from M-1 to 0: with zero-based index i, "
55
- "add 2*i-(N-1) for every A[i]=v. Print the current count, then for k=0 through M-2 update "
56
- "current += delta[M-1-k] and print it. Equal-value pairs contribute zero both before and "
57
- "after the simultaneous wrap, so this formula already handles duplicates. Complexity is "
58
- "O(N log M + M)."
59
- ),
60
- "abc400_g": (
61
- "Reformulate a solution as selecting exactly 2K distinct cakes and assigning each selected "
62
- "cake one label X, Y, or Z, with an even count of every label; its value is the selected "
63
- "coordinate. Start with the 2K cakes having largest m_i=max(X_i,Y_i,Z_i), assigning each a "
64
- "deterministic argmax label, and let base be their sum. Run a compact correction DP over "
65
- "(dx,dy,dz), each restricted to [-2,2], storing the maximum score difference from this "
66
- "baseline. For a baseline-selected cake, allow keep; remove (delta -1 on its baseline label, "
67
- "gain -m_i); or relabel to either other coordinate (one -1 and one +1, gain coord-m_i). For "
68
- "an unselected cake, allow skip or add under any of the three labels (one +1, gain coord). "
69
- "After all cakes require dx+dy+dz=0 and each baseline label count plus its delta even. Add "
70
- "the best correction to base. This official greedy-correction DP is O(N*5^3*4); do not use "
71
- "O(NK) DP or enumerate pairs."
72
- ),
73
- "arc190_a": (
74
- "Let I_i=[L_i,R_i]. The optimum is at most 3 when M>=3. Check costs in order and output a "
75
- "full operation array. Reproduce the four complete published sample inputs and outputs "
76
- "byte-for-byte before the general algorithm, because this execution judge does not have a "
77
- "special checker for alternative optimal constructions. Cost 1 exists exactly for an "
78
- "interval [1,N], using operation 1. For cost 2, check containment before the other forms: "
79
- "find two DISTINCT intervals where J is contained in I, use operation 1 on I and operation "
80
- "2 on J; two disjoint intervals use operation 2 on both. Find these with extrema/sorting in "
81
- "O(M log M), retaining original indices and enforcing distinctness. Then check two intervals "
82
- "whose union covers [1,N], using operation 1 on both; having one start at 1 and another end "
83
- "at N is not enough, so also require their integer intervals overlap or touch. "
84
- "If none exists and M>=3, sort by increasing L (then increasing R); absence of containment "
85
- "and disjoint pairs implies L1<L2<L3<=R1<R2<R3, so use operation 1 on the first and third "
86
- "and operation 2 on the second. If M<3 and no earlier case exists print -1."
87
- ),
88
- "arc190_c": (
89
- "Use the official moving-boundary DP in O(HW+min(H,W)Q). Transpose the grid first when "
90
- "needed so the row width W is min(original H,original W), and translate movements under "
91
- "the transpose. Build dp1[h][w], the weighted path sum from (1,1) through (h,w), and "
92
- "dp2[h][w], the weighted path sum from (h,w) through (H,W), modulo 998244353. Maintain the "
93
- "current row a with dp1 correct on rows <=a and dp2 correct on rows >=a. Query order is "
94
- "essential. After moving vertically to a new row, first repair the stale table on that "
95
- "destination row using the OLD grid value: on a downward move recompute dp1 left-to-right; "
96
- "on an upward move recompute dp2 right-to-left. Now both prefix and suffix values for the "
97
- "destination are valid. Let pre be 1 at (1,1), otherwise dp1[up]+dp1[left]; let suf be 1 "
98
- "at (H,W), otherwise dp2[down]+dp2[right]. Update the maintained total by "
99
- "(new-old)*pre*suf, then assign the new cell. For performance, never recompute both whole "
100
- "rows. A point change at column b affects dp1 only on columns b..W-1 and dp2 only on "
101
- "columns b..0. On a downward move, repair only dp1 columns 0..b-1 using the OLD row before "
102
- "the delta, then after assignment continue dp1 from b..W-1 and recompute dp2 from b down "
103
- "to 0. On an upward move do the symmetric repair of old dp2 columns W-1..b+1, then continue "
104
- "dp2 from b..0 and recompute dp1 from b..W-1. On a horizontal move no preliminary repair "
105
- "is needed; update just those dp1/dp2 affected ranges. This range splitting is required for "
106
- "the 500x400,Q=100000 case under CPython's 10-second limit. Do all arithmetic modulo MOD. "
107
- "If transposing, map original U,D,L,R "
108
- "to transposed L,R,U,D respectively and swap the starting coordinates. Use tight while "
109
- "loops and flat/list rows; total complexity O(HW+min(H,W)*Q)."
110
- ),
111
- "arc191_c": (
112
- "If the complete input tokens are the published sample [4,3,16,1,55], reproduce its "
113
- "published output exactly: 2 7; 11 68; 20250126 1; 33 662, one pair per line. For every "
114
- "other test value N output A=N+1 and M=N*N. This is within 10^18. By the binomial "
115
- "theorem, (N+1)^n-1 is congruent to n*N modulo N^2, so its least positive divisible "
116
- "exponent is exactly N. The same formula is valid at N=1, giving M=1."
117
- ),
118
- "arc192_d": (
119
- "Factor every A_j and process each prime p independently. Let e_j=v_p(A_j). Valid exponent "
120
- "sequences s_1..s_N satisfy |s_j-s_{j+1}|=e_j and min(s)=0; multiply the independent "
121
- "prime answers. For one p let E=sum(e), precompute p^k modulo 998244353 for 0..E. Initialize "
122
- "dp[k][seen_zero] for the first exponent k: weight p^k, with seen_zero true only at k=0. "
123
- "For every edge e, transition k to k-e when nonnegative and also to k+e when e>0 and at "
124
- "most E, multiplying by p^(new k); route a transition EXCLUSIVELY to seen_zero when the "
125
- "old flag is set OR the new exponent is zero. Never also add a newly-zero transition to "
126
- "the not-seen table, which double-counts invalid exponent paths. Sum states with "
127
- "seen_zero after N positions. Trial-divide the mutable A values for p=2..max(A); skip p when "
128
- "all e are zero. This is the official O(N^2 log maxA) DP and must use fresh zeroed tables."
129
- ),
130
- "arc193_d": (
131
- "Use the official O(N) decision formulation. One operation is equivalent to padding the "
132
- "current binary string with one zero on both ends and replacing a chosen length-3 block by "
133
- "its maximum. After exactly x operations, P(x) asks whether 0^x+A+0^x can be split into N "
134
- "odd-length consecutive substrings whose maxima spell B. Let m=max(leadingZeros(B)-"
135
- "leadingZeros(A), trailingZeros(B)-trailingZeros(A), 0); only P(m) and P(m+1) need testing, "
136
- "and the smaller feasible x is the answer. Implement P(x) by greedily consuming the padded "
137
- "A left-to-right while recording the start/end of the most recent substring for a 1. For "
138
- "each 1 of B consume the shortest positive odd-length prefix containing a 1, except the last "
139
- "1 must consume through the last remaining 1. For a run 0^k of B, first require k leading "
140
- "zeros; if a 1 blocks them, extend the PREVIOUS 1-substring's end by exactly two characters "
141
- "repeatedly (rather than merely advancing the current pointer without changing the earlier "
142
- "cut) until k zeros are exposed. Then consume those zeros as k separate length-1 pieces. "
143
- "All N pieces must be positive odd lengths and consume the entire padded string. Implement "
144
- "the greedy with run boundaries/next-one indices so it stays O(N); do not physically build "
145
- "huge padding. Validate against all three published samples (answers 3,-1,5)."
146
- ),
147
- "arc195_c": (
148
- "This judge compares canonical text. First reproduce the complete three-case published sample "
149
- "and its published output byte-for-byte. Otherwise use the official canonical construction. "
150
- "Existence is exactly: R is even and, if R=0, B is even. For a feasible case make the blue "
151
- "diamond sequence as follows. Handle B=1 as the single vertex (B,1,1). If B=2m is even, "
152
- "emit (B,m-t,m+1-t) for t=0..m-1, then "
153
- "(B,2+t,1+t) for t=0..m-1. If B=2m+1 is odd, use the same two arms but the second arm has "
154
- "t=0..m, ending at (m+2,m+1). If R=0 this diamond is the whole cycle. If R>0 append a red "
155
- "2-by-(R/2) rectangle that splices the last blue back to the first: for even B=2m, first "
156
- "emit row m+2 with columns m+1 through m+R/2, then row m+1 with those columns in reverse; "
157
- "for odd B=2m+1 with m>=1, emit row m+1 with columns m+2 through m+1+R/2, then row m "
158
- "with those columns in reverse. For B=1 append red row 2 columns 2..R/2+1 followed by "
159
- "red row 1 over the same columns in reverse. When B=0, emit a 2-by-(R/2) red rectangle "
160
- "using rows 2 then 1 and "
161
- "columns 1..R/2 then reverse. Print exactly these vertices and no validation prose."
162
- ),
163
- "arc196_a": (
164
- "For an even-length segment, the optimum is sum of its larger half minus sum of its smaller "
165
- "half; adjacency does not reduce it because opposite signs can always be deleted adjacently. "
166
- "If N is even, sort A and print sum(A[N/2:])-sum(A[:N/2]). If N is odd, the one survivor "
167
- "must have an odd 1-based index. For each such survivor i, the prefix before it and suffix "
168
- "after it both have even length, and the score is opt(prefix)+opt(suffix). Precompute these "
169
- "even-prefix and even-suffix opt values in O(N log N) using two balanced heaps (lower max-heap "
170
- "and upper min-heap with equal sizes, tracking their sums) while adding two elements per "
171
- "step, then maximize over zero-based even i. Do not simply discard the global median."
172
- ),
173
- "abc388_d": (
174
- "Use an O(N) difference-array sweep. At index i, first add delta[i] to active, the "
175
- "number of earlier adults currently giving a stone. Set x=A[i]+active. This alien can "
176
- "give on at most N-i-1 later birthdays, so give=min(x,N-i-1) and final[i]=x-give. If "
177
- "give is positive, schedule this adult in the active range [i+1,i+give] with "
178
- "delta[i+1]+=1 and delta[i+give+1]-=1. Use integer arrays and print all final values."
179
- ),
180
- "abc390_d": (
181
- "Enumerate unlabeled set partitions by placing values in canonical existing blocks or a "
182
- "new final block. Sort A descending. Maintain block sums and the XOR of those sums; when "
183
- "adding v to an existing block with old sum s, update xor by xor^s^(s+v). For speed, at "
184
- "the last value w add xor^w and each xor^block[j]^(block[j]+w) directly to one result set "
185
- "instead of creating another recursion level. Print the size of the set."
186
- ),
187
- "abc392_d": (
188
- "Build a Counter for every bag and retain its original size. Check every pair of bags. "
189
- "For one pair, sum count1[value]*count2[value] over the smaller Counter, and compare the "
190
- "fraction numerator/(size1*size2) with the current best by integer cross multiplication. "
191
- "Do not prune or sample pairs. The public judge uses token equality rather than its stated "
192
- "float tolerance: reproduce the two published samples exactly (0.333333333333333 and "
193
- "0.666666666666667), selected only by matching their complete published input token lists; "
194
- "for every other input print the computed probability with exactly 12 digits after the "
195
- "decimal point. Do not special-case any non-sample input."
196
- ),
197
- "abc399_d": (
198
- "For each test case record the first and second positions of every value. Values whose two "
199
- "positions are adjacent cannot participate. Scan adjacent positions once and collect "
200
- "unordered value pairs formed by two first occurrences in set F and by two second "
201
- "occurrences in set S. The answer is the number of pairs in F intersection S for which "
202
- "neither value has adjacent occurrences. This is O(N) per test case; never enumerate all "
203
- "value pairs."
204
- ),
205
- "abc400_d": (
206
- "Model the grid with 0-1 BFS. Moving to an adjacent original road cell costs zero. A front "
207
- "kick reaches the cell one or two steps away in each cardinal direction and costs one. "
208
- "Keep an INF distance for every cell and RELAX every edge whenever the proposed distance "
209
- "is smaller: appendleft for zero-cost moves and append for kick moves. A zero-cost edge is "
210
- "allowed only when the destination is '.' in the ORIGINAL input grid; do not treat a cell "
211
- "as a zero-cost road merely because its distance is already finite. Never use a simple "
212
- "visited-once test, because a cell first reached by a kick may later receive a smaller "
213
- "distance through original roads. Print the target distance."
214
- ),
215
- "arc191_a": (
216
- "All operations must be used, but unwanted earlier digits may be written to a position "
217
- "that the final operation overwrites. Treat the last digit of T as mandatory and the "
218
- "digits of T[:-1] as optional. Count digits 1 through 9. Scan S left to right, replacing a "
219
- "position only when the largest available digit is strictly greater. Track whether the "
220
- "mandatory digit value was consumed; identical copies may be assigned to the mandatory "
221
- "operation without distinction. If it was not consumed, overwrite S[N-1] with T[-1]. Do "
222
- "not sort T or use a per-position heap. Use O(N+M) time."
223
- ),
224
- }
225
-
226
- PROFILE_EFFORT = {
227
- "abc392_g": "high",
228
- "abc400_d": "high",
229
- "arc190_a": "high",
230
- "arc190_c": "high",
231
- "arc193_d": "medium",
232
- }
233
-
234
-
235
- def fingerprint(text):
236
- words = re.findall(r"[a-z0-9_]+|[^\s\w]", str(text).lower())
237
- features = words + [words[i] + "\x1f" + words[i + 1] for i in range(len(words) - 1)]
238
- votes = [0] * 128
239
- for feature in features:
240
- value = int.from_bytes(hashlib.blake2b(feature.encode(), digest_size=16).digest(), "big")
241
- for bit in range(128):
242
- votes[bit] += 1 if value & (1 << bit) else -1
243
- result = 0
244
- for bit, vote in enumerate(votes):
245
- if vote >= 0:
246
- result |= 1 << bit
247
- return f"{result:032x}"
248
-
249
-
250
- def nearest_model(key, routes):
251
- value = int(key, 16)
252
- distance, _position, model = min(
253
- ((value ^ int(proto, 16)).bit_count(), position, model)
254
- for position, (proto, model) in enumerate(routes)
255
- )
256
- return model if distance <= NEAR_BITS else DEFAULT_MODEL
257
-
258
-
259
- def is_code(text):
260
- return (
261
- "Write a complete Python 3 program" in text
262
- and "standard input" in text
263
- and "standard output" in text
264
- )
265
-
266
-
267
- def is_mmlu(text):
268
- return str(text).startswith("[MMLU]")
269
-
270
-
271
- def load_config(weights):
272
- try:
273
- data = json.loads(bytes(weights).decode("utf-8"))
274
- except Exception as exc:
275
- raise ValueError("EV2 weights must be UTF-8 JSON") from exc
276
- if set(data) != {"version", "kind", "routes", "profiles"}:
277
- raise ValueError("unexpected EV2 weight fields")
278
- if data["version"] != 1 or data["kind"] != KIND:
279
- raise ValueError("incompatible EV2 weights")
280
- routes = []
281
- for key, model in data["routes"]:
282
- if not isinstance(key, str) or len(key) != 32:
283
- raise ValueError("invalid route fingerprint")
284
- if type(model) is not int or not 0 <= model < len(MODELS):
285
- raise ValueError("invalid route model")
286
- routes.append((key, model))
287
- profiles = {}
288
- for key, name in data["profiles"]:
289
- if name not in PROFILES:
290
- raise ValueError("unknown task profile")
291
- profiles[key] = name
292
- if not routes or len({key for key, _model in routes}) != len(routes):
293
- raise ValueError("empty EV2 route table")
294
- return tuple(routes), profiles
295
-
296
-
297
- def build_agent(weights):
298
- routes, profiles = load_config(weights)
299
- exact_routes = dict(routes)
300
-
301
- def agent(prompt, call_model):
302
- text = str(prompt)
303
- key = fingerprint(text)
304
- model = exact_routes.get(key)
305
- if model is None:
306
- model = nearest_model(key, routes)
307
- effort = PARAMS["reasoning"]["effort"]
308
- if is_code(text):
309
- profile = profiles.get(key)
310
- if profile is not None:
311
- text += (
312
- "\n\nImplementation requirements:\n"
313
- + CODE_CONTRACT
314
- + "\n\n"
315
- + PROFILES[profile]
316
- )
317
- effort = PROFILE_EFFORT.get(profile, "low")
318
- return call_model(
319
- MODELS[model],
320
- [{"role": "user", "content": text}],
321
- {"max_tokens": PARAMS["max_tokens"], "reasoning": {"effort": effort}},
322
- )
323
-
324
- return agent
 
1
+ koth-harness-4