-
Notifications
You must be signed in to change notification settings - Fork 0
/
scalene-gui.js
2284 lines (2138 loc) · 72.9 KB
/
scalene-gui.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// <reference types="aws-sdk" />
function vsNavigate(filename, lineno) {
// If we are in VS Code, clicking on a line number in Scalene's web UI will navigate to that line in the source code.
try {
const vscode = acquireVsCodeApi();
vscode.postMessage({
command: "jumpToLine",
filePath: filename,
lineNumber: lineno,
});
} catch {}
}
function generateScaleneOptimizedCodeRequest(
context,
sourceCode,
line,
recommendedLibraries = [],
includeGpuOptimizations = false,
) {
// Default high-performance libraries known for their efficiency
const defaultLibraries = [
"NumPy",
"Scikit-learn",
"Pandas",
"TensorFlow",
"PyTorch",
];
const highPerformanceLibraries = [
...new Set([...defaultLibraries, ...recommendedLibraries]),
];
let promptParts = [
"Optimize the following Python code to make it more efficient WITHOUT CHANGING ITS RESULTS.\n\n",
context.trim(),
"\n# Start of code\n",
sourceCode.trim(),
"\n# End of code\n\n",
"Rewrite the above Python code from 'Start of code' to 'End of code', aiming for clear and simple optimizations. ",
"Your output should consist only of valid Python code, with brief explanatory comments prefaced with #. ",
"Include a detailed explanatory comment before the code, starting with '# Proposed optimization:'. ",
"Leverage high-performance native libraries, especially those utilizing GPU, for significant performance improvements. ",
"Consider using the following other libraries, if appropriate:\n",
highPerformanceLibraries.map((e) => " import " + e).join("\n") + "\n",
"Eliminate as many for loops, while loops, and list or dict comprehensions as possible, replacing them with vectorized equivalents. ",
// "Consider GPU utilization, memory consumption, and copy volume when using GPU-accelerated libraries. ",
// "Low GPU utilization and high copy volume indicate inefficient use of such libraries. ",
"Quantify the expected speedup in terms of orders of magnitude if possible. ",
"Fix any errors in the optimized code. ",
// "Consider the peak amount of memory used per line and CPU utilization for targeted optimization. ",
// "Note on CPU utilization: Low utilization in libraries known for multi-threading/multi-processing indicates inefficiency.\n\n",
];
// Conditional inclusion of GPU optimizations
if (includeGpuOptimizations) {
promptParts.push(
"Use GPU-accelerated libraries whenever it would substantially increase performance. ",
);
}
// Performance Insights
promptParts.push(
"Consider the following insights gathered from the Scalene profiler for optimization:\n",
);
const total_cpu_percent =
line.n_cpu_percent_python + line.n_cpu_percent_c + line.n_sys_percent;
promptParts.push(
`- CPU time: percent spent in the Python interpreter: ${((100 * line.n_cpu_percent_python) / total_cpu_percent).toFixed(2)}%\n`,
);
promptParts.push(
`- CPU time: percent spent executing native code: ${((100 * line.n_cpu_percent_c) / total_cpu_percent).toFixed(2)}%\n`,
);
promptParts.push(
`- CPU time: percent of system time: ${((100 * line.n_sys_percent) / total_cpu_percent).toFixed(2)}%\n`,
);
// `- CPU utilization: ${performanceMetrics.cpu_utilization}. Low utilization with high-core count might indicate inefficient use of multi-threaded/multi-process libraries.\n`,
promptParts.push(
`- Core utilization: ${((100 * line.n_core_utilization) / total_cpu_percent).toFixed(2)}%\n`,
);
// `- Peak memory per line: Focus on lines with high memory usage, specifically ${performanceMetrics.peak_memory_per_line}.\n`,
promptParts.push(
`- Peak memory usage: ${line.n_peak_mb.toFixed(0)}MB (${(100 * line.n_python_fraction).toFixed(2)}% Python memory)\n`,
);
// `- Copy volume: ${performanceMetrics.copy_volume} MB. High volume indicates inefficient data handling with GPU libraries.\n`,
if (line.n_copy_mb_s > 1) {
promptParts.push(
`- Megabytes copied per second by memcpy/strcpy: ${line.n_copy_mb_s.toFixed(2)}\n`,
);
}
if (includeGpuOptimizations) {
// ` - GPU utilization: ${performanceMetrics.gpu_utilization}%. Low utilization indicates potential inefficiencies in GPU-accelerated library use.\n`
promptParts.push(
`- GPU percent utilization: ${(100 * line.n_gpu_percent).toFixed(2)}%\n`,
);
// ` - GPU memory usage: ${performanceMetrics.gpu_memory} MB. Optimize to reduce unnecessary GPU memory consumption.\n`
// TODO GPU memory
}
promptParts.push(`Optimized code:`);
return promptParts.join("");
}
const recommendedLibraries = ["Cython", "Dask"]; // Add any domain-specific libraries here
// const prompt = generateScaleneOptimizedCodeRequest(context, sourceCode, line, recommendedLibraries, true);
function extractPythonCodeBlock(markdown) {
// Pattern to match code blocks optionally tagged with "python"
// - ``` optionally followed by "python"
// - Non-greedy match for any characters (including new lines) between the backticks
// - Flags:
// - 'g' for global search to find all matches
// - 's' to allow '.' to match newline characters
const pattern = /```python\s*([\s\S]*?)```|```([\s\S]*?)```/g;
let match;
let extractedCode = "";
// Use a loop to find all matches
while ((match = pattern.exec(markdown)) !== null) {
// Check which group matched. Group 1 is for explicitly tagged Python code, group 2 for any code block
const codeBlock = match[1] ? match[1] : match[2];
// Concatenate the extracted code blocks, separated by new lines if there's more than one block
if (extractedCode && codeBlock) extractedCode += "\n\n";
extractedCode += codeBlock;
}
return extractedCode;
}
const RightTriangle = "►"; // right-facing triangle symbol (collapsed view)
const DownTriangle = "▼"; // downward-facing triangle symbol (expanded view)
const Lightning = "⚡"; // lightning bolt (for optimizing a line)
const Explosion = "💥"; // explosion (for optimizing a region)
const WhiteLightning = `<span style="opacity:0">${Lightning}</span>`; // invisible but same width as lightning bolt
const WhiteExplosion = `<span style="opacity:0">${Explosion}</span>`; // invisible but same width as lightning bolt
const maxLinesPerRegion = 50; // Only show regions that are no more than this many lines.
let showedExplosion = {}; // Used so we only show one explosion per region.
function unescapeUnicode(s) {
return s.replace(/\\u([\dA-F]{4})/gi, function (match, p1) {
return String.fromCharCode(parseInt(p1, 16));
});
}
async function tryApi(apiKey) {
const response = await fetch("https://api.openai.com/v1/completions", {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
});
return response;
}
async function isValidApiKey(apiKey) {
const response = await tryApi(apiKey);
const data = await response.json();
if (
data.error &&
data.error.code in
{
invalid_api_key: true,
invalid_request_error: true,
model_not_found: true,
insufficient_quota: true,
}
) {
return false;
} else {
return true;
}
}
function checkApiKey(apiKey) {
(async () => {
try {
window.localStorage.setItem("scalene-api-key", apiKey);
} catch {}
// If the API key is empty, clear the status indicator.
if (apiKey.length === 0) {
document.getElementById("valid-api-key").innerHTML = "";
return;
}
const isValid = await isValidApiKey(apiKey);
if (!isValid) {
document.getElementById("valid-api-key").innerHTML = "✕";
} else {
document.getElementById("valid-api-key").innerHTML = "✓";
}
})();
}
function extractCode(text) {
/**
* Extracts code block from the given completion text.
*
* @param {string} text - A string containing text and other data.
* @returns {string} Extracted code block from the completion object.
*/
if (!text) {
return text;
}
const lines = text.split("\n");
let i = 0;
while (i < lines.length && lines[i].trim() === "") {
i++;
}
const first_line = lines[i].trim();
let code_block;
if (first_line === "```") {
code_block = text.slice(3);
} else if (first_line.startsWith("```")) {
const word = first_line.slice(3).trim();
if (word.length > 0 && !word.includes(" ")) {
code_block = text.slice(first_line.length);
} else {
code_block = text;
}
} else {
code_block = text;
}
const end_index = code_block.indexOf("```");
if (end_index !== -1) {
code_block = code_block.slice(0, end_index);
}
return code_block;
}
async function sendPromptToOpenAI(prompt, len, apiKey) {
const endpoint = "https://api.openai.com/v1/chat/completions";
const model = document.getElementById("language-model-openai").value;
const body = JSON.stringify({
model: model,
messages: [
{
role: "system",
content:
"You are a Python programming assistant who ONLY responds with blocks of commented, optimized code. You never respond with text. Just code, starting with ``` and ending with ```.",
},
{
role: "user",
content: prompt,
},
],
user: "scalene-user",
});
console.log(body);
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: body,
});
const data = await response.json();
if (data.error) {
if (
data.error.code in
{
invalid_request_error: true,
model_not_found: true,
insufficient_quota: true,
}
) {
if (data.error.code === "model_not_found" && model === "gpt-4") {
// Technically, model_not_found applies only for GPT-4.0
// if an account has not been funded with at least $1.
alert(
"You either need to add funds to your OpenAI account to use this feature, or you need to switch to GPT-3.5 if you are using free credits.",
);
} else {
alert(
"You need to add funds to your OpenAI account to use this feature.",
);
}
return "";
}
}
try {
console.log(
`Debugging info: Retrieved ${JSON.stringify(data.choices[0], null, 4)}`,
);
} catch {
console.log(
`Debugging info: Failed to retrieve data.choices from the server. data = ${JSON.stringify(
data,
)}`,
);
}
try {
return data.choices[0].message.content.replace(/^\s*[\r\n]/gm, "");
} catch {
// return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
}
}
async function sendPromptToAzureOpenAI(prompt, len, apiKey, apiUrl, aiModel) {
const apiVersion = document.getElementById("azure-api-model-version").value;
const endpoint = `${apiUrl}/openai/deployments/${aiModel}/chat/completions?api-version=${apiVersion}`;
const body = JSON.stringify({
messages: [
{
role: "system",
content:
"You are a Python programming assistant who ONLY responds with blocks of commented, optimized code. You never respond with text. Just code, starting with ``` and ending with ```.",
},
{
role: "user",
content: prompt,
},
],
user: "scalene-user",
});
console.log(body);
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
"api-key": apiKey,
},
body: body,
});
const data = await response.json();
if (data.error) {
if (
data.error.code in
{
invalid_request_error: true,
model_not_found: true,
insufficient_quota: true,
}
) {
return "";
}
}
try {
console.log(
`Debugging info: Retrieved ${JSON.stringify(data.choices[0], null, 4)}`,
);
} catch {
console.log(
`Debugging info: Failed to retrieve data.choices from the server. data = ${JSON.stringify(
data,
)}`,
);
}
try {
return data.choices[0].message.content.replace(/^\s*[\r\n]/gm, "");
} catch {
// return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
}
}
async function sendPromptToAmazon(prompt, len) {
const serviceName = "bedrock";
const region = "us-west-2";
const modelId = "anthropic.claude-v2";
const endpoint = `https://${serviceName}-runtime.${region}.amazonaws.com/model/${modelId}/invoke`;
// const model = document.getElementById('language-model-amazon').value;
const body = JSON.stringify({
prompt: `Human: ${prompt}\n\nAssistant:\n`,
max_tokens_to_sample: 2048,
temperature: 0,
top_k: 250,
top_p: 1,
stop_sequences: ["\n\nHuman:"],
anthropic_version: "bedrock-2023-05-31",
});
console.log(body);
var bedrockruntime = new AWS.BedrockRuntime();
bedrockruntime.invokeModel(body, function (err, data) {
if (err)
console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
});
const response = await fetch(endpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
// Authorization: `Bearer ${apiKey}`,
},
body: body,
});
const data = await response.json();
console.log(data);
try {
console.log(
`Debugging info: Retrieved ${JSON.stringify(data.choices[0], null, 4)}`,
);
} catch {
console.log(
`Debugging info: Failed to retrieve data.choices from the server. data = ${JSON.stringify(
data,
)}`,
);
}
try {
return data.choices[0].message.content.replace(/^\s*[\r\n]/gm, "");
} catch {
// return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
}
}
async function sendPromptToOllama(prompt, len, model, ipAddr, portNum) {
const url = `http://${ipAddr}:${portNum}/api/chat`;
const headers = { "Content-Type": "application/json" };
const body = JSON.stringify({
model: model,
messages: [
{
role: "system",
content:
"You are an expert code assistant who only responds in Python code.", //You are a Python programming assistant who ONLY responds with blocks of commented, optimized code. You never respond with text. Just code, in a JSON object with the key "code".'
},
{
role: "user",
content: prompt,
},
],
stream: false,
// format: "json",
temperature: 0.3,
frequency_penalty: 0,
presence_penalty: 0,
user: "scalene-user",
});
console.log(body);
let done = false;
let responseAggregated = "";
let retried = 0;
const retries = 3;
while (!done) {
if (retried >= retries) {
return {};
}
try {
const response = await fetch(url, {
method: "POST",
headers: headers,
body: body,
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const text = await response.text();
const responses = text.split("\n");
for (const resp of responses) {
const responseJson = JSON.parse(resp);
if (responseJson.message && responseJson.message.content) {
responseAggregated += responseJson.message.content;
}
if (responseJson.done) {
done = true;
break;
}
}
} catch (error) {
console.log(`Error: ${error}`);
retried++;
}
}
console.log(responseAggregated);
try {
return responseAggregated; // data.choices[0].message.content.replace(/^\s*[\r\n]/gm, "");
} catch {
// return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
return "# Query failed. See JavaScript console (in Chrome: View > Developer > JavaScript Console) for more info.\n";
}
}
function countSpaces(str) {
// Use a regular expression to match any whitespace character at the start of the string
const match = str.match(/^\s+/);
// If there was a match, return the length of the match
if (match) {
return match[0].length;
}
// Otherwise, return 0
return 0;
}
async function optimizeCode(imports, code, line, context) {
// Tailor prompt to request GPU optimizations or not.
const useGPUs = document.getElementById("use-gpu-checkbox").checked; // globalThis.profile.gpu;
let recommendedLibraries = ["sklearn"];
if (useGPUs) {
// Suggest cupy if we are using the GPU.
recommendedLibraries.push("cupy");
} else {
// Suggest numpy otherwise.
recommendedLibraries.push("numpy");
}
// TODO: remove anything already imported in imports
const bigPrompt = generateScaleneOptimizedCodeRequest(
context,
code,
line,
recommendedLibraries,
useGPUs,
);
const useGPUstring = useGPUs ? " or the GPU " : " ";
// Check for a valid API key.
// TODO: Add checks for Amazon / local
let apiKey = "";
let aiService = document.getElementById("service-select").value;
if (aiService === "openai") {
apiKey = document.getElementById("api-key").value;
} else if (aiService === "azure-openai") {
apiKey = document.getElementById("azure-api-key").value;
}
if ((aiService === "openai" || aiService === "azure-openai") && !apiKey) {
alert(
"To activate proposed optimizations, enter an OpenAI API key in AI optimization options.",
);
document.getElementById("ai-optimization-options").open = true;
return "";
}
// If the code to be optimized is just one line of code, say so.
let lineOf = " ";
if (code.split("\n").length <= 2) {
lineOf = " line of ";
}
let libraries = "import sklearn";
if (useGPUs) {
// Suggest cupy if we are using the GPU.
libraries += "\nimport cupy";
} else {
// Suggest numpy otherwise.
libraries += "\nimport numpy as np";
}
// Construct the prompt.
const optimizePerformancePrompt = `Optimize the following${lineOf}Python code:\n\n${context}\n\n# Start of code\n\n${code}\n\n# End of code\n\nRewrite the above Python code only from "Start of code" to "End of code", to make it more efficient WITHOUT CHANGING ITS RESULTS. Assume the code has already executed all these imports; do NOT include them in the optimized code:\n\n${imports}\n\nUse native libraries if that would make it faster than pure Python. Consider using the following other libraries, if appropriate:\n\n${libraries}\n\nYour output should only consist of valid Python code. Output the resulting Python with brief explanations only included as comments prefaced with #. Include a detailed explanatory comment before the code, starting with the text "# Proposed optimization:". Make the code as clear and simple as possible, while also making it as fast and memory-efficient as possible. Use vectorized operations${useGPUstring}whenever it would substantially increase performance, and quantify the speedup in terms of orders of magnitude. Eliminate as many for loops, while loops, and list or dict comprehensions as possible, replacing them with vectorized equivalents. If the performance is not likely to increase, leave the code unchanged. Fix any errors in the optimized code. Optimized${lineOf}code:`;
const context_ollama = "";
const optimizePerformancePrompt_ollama_prev = `Optimize the following${lineOf}Python code:\n\n${context_ollama}\n\n# Start of code\n\n${code}\n\n# End of code\n\nRewrite the above Python code only from "Start of code" to "End of code", to make it more efficient WITHOUT CHANGING ITS RESULTS. Only output your result in JSON, with the optimized code in "code". Optimized${lineOf}code:`;
const optimizePerformancePrompt_ollama_pp = `Rewrite the following Python code to make it run faster. Use vectorization if possible, eliminating as many loops as possible. Try to reduce computational complexity of operations. Only output the optimized code in JSON with the key 'code'. Original code: ${code}. Optimized code:`;
// TODO parameterize based on CPU utilization, Python vs. C time, GPU choice, memory efficiency.
const optimizePerformancePrompt_ollama = `# Original code\n${code}\n\n# This code is an optimized version of the original code that dramatically improves its performance. Whenever possible, the code has been changed to use native libraries and vectorization, and data structures like lists have been replaced by sets or dicts. Do not change any function names. Optimized code:\n`;
const pure_optimizePerformancePrompt = `Optimize the following${lineOf}Python code:\n\n${context}\n\n# Start of code\n\n${code}\n\n# End of code\n\nRewrite the above Python code only from "Start of code" to "End of code", to make it more efficient WITHOUT CHANGING ITS RESULTS. Assume the code has already executed all these imports; do NOT include them in the optimized code:\n\n${imports}\n\nONLY USE PURE PYTHON.\n\nYour output should only consist of valid Python code. Output the resulting Python with brief explanations only included as comments prefaced with #. Include a detailed explanatory comment before the code, starting with the text "# Proposed optimization:". Make the code as clear and simple as possible, while also making it as fast and memory-efficient as possible. If the performance is not likely to increase, leave the code unchanged. Fix any errors in the optimized code. Optimized${lineOf}code:`;
const memoryEfficiencyPrompt = `Optimize the following${lineOf} Python code:\n\n${context}\n\n# Start of code\n\n${code}\n\n\n# End of code\n\nRewrite the above Python code only from "Start of code" to "End of code", to make it more memory-efficient WITHOUT CHANGING ITS RESULTS. Assume the code has already executed all these imports; do NOT include them in the optimized code:\n\n${imports}\n\nUse native libraries if that would make it more space efficient than pure Python. Consider using the following other libraries, if appropriate:\n\n${libraries}\n\nYour output should only consist of valid Python code. Output the resulting Python with brief explanations only included as comments prefaced with #. Include a detailed explanatory comment before the code, starting with the text "# Proposed optimization:". Make the code as clear and simple as possible, while also making it as fast and memory-efficient as possible. Use native libraries whenever possible to reduce memory consumption; invoke del on variables and array elements as soon as it is safe to do so. If the memory consumption is not likely to be reduced, leave the code unchanged. Fix any errors in the optimized code. Optimized${lineOf}code:`;
const optimizePerf = document.getElementById("optimize-performance").checked;
let prompt;
if (optimizePerf) {
prompt = optimizePerformancePrompt;
} else {
prompt = memoryEfficiencyPrompt;
}
// Just use big prompt maybe FIXME
prompt = bigPrompt;
// Use number of words in the original code as a proxy for the number of tokens.
const numWords = code.match(/\b\w+\b/g).length;
switch (document.getElementById("service-select").value) {
case "openai": {
console.log(prompt);
const result = await sendPromptToOpenAI(
prompt,
Math.max(numWords * 4, 500),
apiKey,
);
return extractCode(result);
}
case "local": {
console.log("Running " + document.getElementById("service-select").value);
console.log(prompt);
// console.log(optimizePerformancePrompt_ollama);
const result = await sendPromptToOllama(
prompt, // optimizePerformancePrompt_ollama,
Math.max(numWords * 4, 500),
document.getElementById("language-model-local").value,
document.getElementById("local-ip").value,
document.getElementById("local-port").value,
);
if (result.includes("```")) {
return extractPythonCodeBlock(result);
} else {
return result;
}
}
case "amazon": {
console.log("Running " + document.getElementById("service-select").value);
console.log(prompt); // optimizePerformancePrompt_ollama);
const result = await sendPromptToAmazon(
prompt, // optimizePerformancePrompt_ollama,
Math.max(numWords * 4, 500),
);
console.log(
document.getElementById("service-select").value + " not yet supported.",
);
return "";
}
case "azure-openai": {
console.log("Running " + document.getElementById("service-select").value);
console.log(prompt);
let azureOpenAiEndpoint = document.getElementById("azure-api-url").value;
let azureOpenAiModel = document.getElementById("azure-api-model").value;
const result = await sendPromptToAzureOpenAI(
prompt,
Math.max(numWords * 4, 500),
apiKey,
azureOpenAiEndpoint,
azureOpenAiModel,
);
return extractCode(result);
}
}
}
function proposeOptimizationRegion(filename, file_number, line) {
proposeOptimization(
filename,
file_number,
JSON.parse(decodeURIComponent(line)),
{ regions: true },
);
}
function proposeOptimizationLine(filename, file_number, line) {
proposeOptimization(
filename,
file_number,
JSON.parse(decodeURIComponent(line)),
{ regions: false },
);
}
function proposeOptimization(filename, file_number, line, params) {
filename = unescape(filename);
const useRegion = params["regions"];
const prof = globalThis.profile;
const this_file = prof.files[filename].lines;
const imports = prof.files[filename].imports.join("\n");
const start_region_line = this_file[line.lineno - 1]["start_region_line"];
const end_region_line = this_file[line.lineno - 1]["end_region_line"];
let context;
const code_line = this_file[line.lineno - 1]["line"];
let code_region;
if (useRegion) {
code_region = this_file
.slice(start_region_line - 1, end_region_line)
.map((e) => e["line"])
.join("");
context = this_file
.slice(
Math.max(0, start_region_line - 10),
Math.min(start_region_line - 1, this_file.length),
)
.map((e) => e["line"])
.join("");
} else {
code_region = code_line;
context = this_file
.slice(
Math.max(0, line.lineno - 10),
Math.min(line.lineno - 1, this_file.length),
)
.map((e) => e["line"])
.join("");
}
// Count the number of leading spaces to match indentation level on output
let leadingSpaceCount = countSpaces(code_line) + 3; // including the lightning bolt and explosion
let indent =
WhiteLightning + WhiteExplosion + " ".repeat(leadingSpaceCount - 1);
const elt = document.getElementById(`code-${file_number}-${line.lineno}`);
(async () => {
// TODO: check Amazon credentials
const service = document.getElementById("service-select").value;
if (service === "openai") {
const isValid = await isValidApiKey(
document.getElementById("api-key").value,
);
if (!isValid) {
alert(
"You must enter a valid OpenAI API key to activate proposed optimizations.",
);
document.getElementById("ai-optimization-options").open = true;
return;
}
}
if (service == "local") {
if (
document.getElementById("local-models-list").style.display === "none"
) {
// No service was found.
alert(
"You must be connected to a running Ollama server to activate proposed optimizations.",
);
document.getElementById("ai-optimization-options").open = true;
return;
}
}
elt.innerHTML = `<em>${indent}working...</em>`;
let message = await optimizeCode(imports, code_region, line, context);
if (!message) {
elt.innerHTML = "";
return;
}
// Canonicalize newlines
message = message.replace(new RegExp("\r?\n", "g"), "\n");
// Indent every line and format it
const formattedCode = message
.split("\n")
.map(
(line) =>
indent + Prism.highlight(line, Prism.languages.python, "python"),
)
.join("<br />");
// Display the proposed optimization, with click-to-copy functionality.
elt.innerHTML = `<hr><span title="click to copy" style="cursor: copy" id="opt-${file_number}-${line.lineno}">${formattedCode}</span>`;
thisElt = document.getElementById(`opt-${file_number}-${line.lineno}`);
thisElt.addEventListener("click", async (e) => {
await copyOnClick(e, message);
// After copying, briefly change the cursor back to the default to provide some visual feedback..
thisElt.style = "cursor: auto";
await new Promise((resolve) => setTimeout(resolve, 125));
thisElt.style = "cursor: copy";
});
})();
}
async function copyOnClick(event, message) {
event.preventDefault();
event.stopPropagation();
await navigator.clipboard.writeText(message);
}
function memory_consumed_str(size_in_mb) {
// Return a string corresponding to amount of memory consumed.
let gigabytes = Math.floor(size_in_mb / 1024);
let terabytes = Math.floor(gigabytes / 1024);
if (terabytes > 0) {
return `${(size_in_mb / 1048576).toFixed(0)}T`;
} else if (gigabytes > 0) {
return `${(size_in_mb / 1024).toFixed(0)}G`;
} else {
return `${size_in_mb.toFixed(0)}M`;
}
}
function time_consumed_str(time_in_ms) {
let hours = Math.floor(time_in_ms / 3600000);
let minutes = Math.floor((time_in_ms % 3600000) / 60000);
let seconds = Math.floor((time_in_ms % 60000) / 1000);
let hours_exact = time_in_ms / 3600000;
let minutes_exact = (time_in_ms % 3600000) / 60000;
let seconds_exact = (time_in_ms % 60000) / 1000;
if (hours > 0) {
return `${hours.toFixed(0)}h:${minutes_exact.toFixed(
0,
)}m:${seconds_exact.toFixed(3)}s`;
} else if (minutes >= 1) {
return `${minutes.toFixed(0)}m:${seconds_exact.toFixed(3)}s`;
} else if (seconds >= 1) {
return `${seconds_exact.toFixed(3)}s`;
} else {
return `${time_in_ms.toFixed(0)}ms`;
}
}
function makeTooltip(title, value) {
// Tooltip for time bars, below
let secs = value / 100 * globalThis.profile.elapsed_time_sec;
return `(${title}) ` + value.toFixed(1) + "%" + " [" + time_consumed_str(secs * 1e3) + "]"
}
function makeBar(python, native, system, params) {
// Make a time bar
const widthThreshold1 = 20;
const widthThreshold2 = 10;
// console.log(`makeBar ${python} ${native} ${system}`);
return {
$schema: "https://vega.github.io/schema/vega-lite/v5.json",
config: {
view: {
stroke: "transparent",
},
},
autosize: {
contains: "padding",
},
width: params.width,
height: params.height,
padding: 0,
data: {
values: [
{
x: 0,
y: python.toFixed(1),
c: makeTooltip("Python", python),
d:
python >= widthThreshold1
? python.toFixed(0) + "%"
: python >= widthThreshold2
? python.toFixed(0)
: "",
q: python / 2,
},
{
x: 0,
y: native.toFixed(1),
c: makeTooltip("native", native),
d:
native >= widthThreshold1
? native.toFixed(0) + "%"
: native >= widthThreshold2
? native.toFixed(0)
: "",
q: python + native / 2,
},
{
x: 0,
y: system.toFixed(1),
c: makeTooltip("system", system),
d:
system >= widthThreshold1
? system.toFixed(0) + "%"
: system >= widthThreshold2
? system.toFixed(0)
: "",
q: python + native + system / 2,
},
],
},
layer: [
{
mark: { type: "bar" },
encoding: {
x: {
aggregate: "sum",
field: "y",
axis: false,
stack: "zero",
scale: { domain: [0, 100] },
},
color: {
field: "c",
type: "nominal",
legend: false,
scale: { range: ["darkblue", "#6495ED", "blue"] },
},
tooltip: [{ field: "c", type: "nominal", title: "time" }],
},
},
{
mark: {
type: "text",
align: "center",
baseline: "middle",
dx: 0,
},
encoding: {
x: {
aggregate: "sum",
field: "q",
axis: false,
},
text: { field: "d" },
color: { value: "white" },
tooltip: [{ field: "c", type: "nominal", title: "time" }],
},
},
],
};
}
function makeGPUPie(util, gpu_device, params) {
return {
$schema: "https://vega.github.io/schema/vega-lite/v5.json",
config: {
view: {
stroke: "transparent",
},
},
autosize: {
contains: "padding",
},
width: 30,
height: 20,
padding: 0,
data: {
values: [
{
category: 1,
value: util.toFixed(1),
c: "in use: " + util.toFixed(1) + "%",
},
],
},
mark: "arc",
encoding: {
theta: {
field: "value",
type: "quantitative",
scale: { domain: [0, 100] },
},
color: {
field: "c",
type: "nominal",
legend: false,
scale: { range: ["goldenrod", "#f4e6c2"] },
},
tooltip: [{ field: "c", type: "nominal", title: gpu_device }],
},
};
}
function makeGPUBar(util, gpu_device, params) {
return {
$schema: "https://vega.github.io/schema/vega-lite/v5.json",
config: {
view: {
stroke: "transparent",
},
},
autosize: {
contains: "padding",
},
width: params.width,
height: params.height,
padding: 0,
data: {
values: [
{
x: 0,
y: util.toFixed(0),
q: (util / 2).toFixed(0),
d: util >= 20 ? util.toFixed(0) + "%" : "",
dd: "in use: " + util.toFixed(0) + "%",
},
],
},
layer: [
{
mark: { type: "bar" },
encoding: {
x: {
aggregate: "sum",
field: "y",
axis: false,
scale: { domain: [0, 100] },
},
color: {
field: "dd",
type: "nominal",
legend: false,
scale: { range: ["goldenrod", "#f4e6c2"] },
},
tooltip: [{ field: "dd", type: "nominal", title: gpu_device + ":" } ],
},
},
{
mark: {