Skip to content

Commit b3819a5

Browse files
committed
fasthtml shell able to load emscripten js runtime
1 parent 24caba0 commit b3819a5

File tree

5 files changed

+150
-0
lines changed

5 files changed

+150
-0
lines changed

experimental/fasthtml/Makefile

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
GPUCPP=../..
2+
FLAGS=-std=c++17 -s USE_WEBGPU=1 -s ASYNCIFY=1 -I$(GPUCPP)
3+
4+
.PHONY: default cmake check-emsdk browser clean
5+
6+
default: server
7+
8+
build/run.html: check-emsdk run.cpp
9+
em++ run.cpp -o build/run.html \
10+
$(FLAGS) --shell-file ./custom_shell.html
11+
12+
build/run.js: check-emsdk run.cpp
13+
em++ run.cpp -o build/run.js --shell-file ./custom_shell.html \
14+
$(FLAGS)
15+
16+
build/run.wasm: check-emsdk run.cpp
17+
em++ run.cpp -o build/run.wasm \
18+
$(FLAGS)
19+
20+
server: build/run.wasm
21+
python3 run.py
22+
23+
clean:
24+
rm -rf build/*
25+
26+
check-emsdk:
27+
@which em++ > /dev/null || (echo "emsdk not found. Please install emsdk and run 'source emsdk_env.sh' in the emsdk directory." && exit 1)

experimental/fasthtml/build/.gitkeep

Whitespace-only changes.
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
<!DOCTYPE html>
2+
<html>
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>gpu.cpp</title>
6+
<!-- Include xterm.js CSS -->
7+
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm/css/xterm.css" />
8+
<style>
9+
body, html {
10+
margin: 0;
11+
padding: 0;
12+
height: 100%;
13+
width: 100%;
14+
}
15+
#terminal {
16+
height: 100%;
17+
width: 100%;
18+
}
19+
</style>
20+
</head>
21+
<body>
22+
<!-- Terminal container -->
23+
<div id="terminal"></div>
24+
<!-- Include xterm.js and xterm-addon-fit libraries -->
25+
<script src="https://cdn.jsdelivr.net/npm/xterm/lib/xterm.js"></script>
26+
<script src="https://cdn.jsdelivr.net/npm/xterm-addon-fit/lib/xterm-addon-fit.js"></script>
27+
<script type="text/javascript">
28+
// Initialize xterm.js
29+
const terminal = new Terminal();
30+
const fitAddon = new FitAddon.FitAddon();
31+
terminal.loadAddon(fitAddon);
32+
terminal.open(document.getElementById('terminal'));
33+
fitAddon.fit();
34+
35+
// This function captures stdout and displays it in the xterm.js terminal
36+
var Module = {
37+
preRun: [],
38+
postRun: [],
39+
print: function(text) {
40+
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
41+
console.log(text); // Log to the console
42+
terminal.writeln(text); // Write to the terminal
43+
},
44+
printErr: function(text) {
45+
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
46+
console.error(text); // Log to the console as an error
47+
terminal.writeln(text); // Write to the terminal as well
48+
}
49+
};
50+
</script>
51+
{{{ SCRIPT }}}
52+
</body>
53+
</html>

experimental/fasthtml/run.cpp

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#include <array>
2+
#include <cstdio>
3+
#include <future>
4+
#include <memory>
5+
#include "gpu.h"
6+
7+
// #include <webgpu/webgpu.h>
8+
#include "emscripten/emscripten.h"
9+
10+
using namespace gpu; // createContext, createTensor, createKernel,
11+
// createShader, dispatchKernel, wait, toCPU
12+
// Tensor, Kernel, Context, Shape, kf32
13+
14+
static const char *kGelu = R"(
15+
const GELU_SCALING_FACTOR: f32 = 0.7978845608028654; // sqrt(2.0 / PI)
16+
@group(0) @binding(0) var<storage, read_write> inp: array<{{precision}}>;
17+
@group(0) @binding(1) var<storage, read_write> out: array<{{precision}}>;
18+
@group(0) @binding(1) var<storage, read_write> dummy: array<{{precision}}>;
19+
@compute @workgroup_size({{workgroupSize}})
20+
fn main(
21+
@builtin(global_invocation_id) GlobalInvocationID: vec3<u32>) {
22+
let i: u32 = GlobalInvocationID.x;
23+
if (i < arrayLength(&inp)) {
24+
let x: f32 = inp[i];
25+
out[i] = select(0.5 * x * (1.0 + tanh(GELU_SCALING_FACTOR
26+
* (x + .044715 * x * x * x))), x, x > 10.0);
27+
}
28+
}
29+
)";
30+
31+
int main(int argc, char **argv) {
32+
printf("\033[2J\033[1;1H");
33+
printf("\nHello gpu.cpp!\n");
34+
printf("--------------\n\n");
35+
36+
// const WGPUInstanceDescriptor descriptor = { };
37+
// std::unique_ptr<WGPUInstanceDescriptor> descriptor = std::make_unique<WGPUInstanceDescriptor>();
38+
39+
// WGPUInstance instance = wgpuCreateInstance({});
40+
Context ctx = createContext({});
41+
static constexpr size_t N = 5000;
42+
std::array<float, N> inputArr, outputArr;
43+
for (int i = 0; i < N; ++i) {
44+
inputArr[i] = static_cast<float>(i) / 10.0; // dummy input data
45+
}
46+
Tensor input = createTensor(ctx, Shape{N}, kf32, inputArr.data());
47+
Tensor output = createTensor(ctx, Shape{N}, kf32);
48+
std::promise<void> promise;
49+
std::future<void> future = promise.get_future();
50+
Kernel op = createKernel(ctx, {kGelu, 256, kf32},
51+
Bindings{input, output},
52+
{cdiv(N, 256), 1, 1});
53+
dispatchKernel(ctx, op, promise);
54+
wait(ctx, future);
55+
toCPU(ctx, output, outputArr.data(), sizeof(outputArr));
56+
for (int i = 0; i < 12; ++i) {
57+
printf(" gelu(%.2f) = %.2f\n", inputArr[i], outputArr[i]);
58+
}
59+
printf(" ...\n\n");
60+
printf("Computed %zu values of GELU(x)\n\n", N);
61+
return 0;
62+
}

experimental/fasthtml/run.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
TARGET = os.getenv("TARGET", "debug")
88

99
ace_editor = Script(src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js")
10+
gpucpp_runtime = Script(src="/build/run.js")
11+
gpucpp_wasm = Script(src="/build/run.wasm")
12+
1013
global_style = Style("""
1114
#editor {
1215
height: 50vh;
@@ -17,6 +20,7 @@
1720
HDRS = (
1821
picolink,
1922
ace_editor,
23+
gpucpp_runtime,
2024
global_style,
2125
*Socials(
2226
title="gpu.cpp gpu puzzles",
@@ -39,6 +43,10 @@
3943
async def build(fname: str, ext: str):
4044
return FileResponse(f"build/{fname}.{ext}")
4145

46+
@app.get("/build/run.wasm")
47+
async def serve_wasm(fname: str, ext: str):
48+
return FileResponse(f"build/run.wasm")
49+
4250
def page():
4351
return Title("GPU Puzzles"), Body(
4452
Div(

0 commit comments

Comments
 (0)