Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding the ILGPU WebAssembly demo #901

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
477 changes: 477 additions & 0 deletions Demo/.gitignore

Large diffs are not rendered by default.

53 changes: 53 additions & 0 deletions Demo/CodeBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using ILGPU;

namespace ILGPUwebCompiler
{
public static class CodeBuilder
{
private static string _usings = @"using System;
using ILGPU.Backends.EntryPoints;
using ILGPU.Backends.PTX;
using ILGPU.Runtime.Cuda;
using ILGPU;
using ILGPUwebCompiler;
using ILGPU.Runtime.CPU;
using System.Reflection;
using System.Threading;
";
private static string _opening = @"namespace ConsoleApp {
class Program {
";
private static string _main = @"public static void Main()
{{
using var context = Context.Create(builder => builder
.CPU(new CPUDevice(2, 1, 1)) // Use a very simplistic CPU accelerator instance
{0}.Assertions() // Uncomment to use assertions
{1}.Debug() // Uncomment to enable debug symbols
.Optimize((OptimizationLevel){2}));

using var backend = new PTXBackend(
context,
CudaArchitecture.SM_70,
CudaInstructionSet.ISA_70,
null);

var entryPoint = EntryPointDescription.FromExplicitlyGroupedKernel(
typeof(Program).GetMethod(nameof(TestKernel),
BindingFlags.NonPublic | BindingFlags.Static));

var compiledKernel = backend.Compile(entryPoint, default) as PTXCompiledKernel;
Console.WriteLine(compiledKernel!.PTXAssembly);

}}
";
private static string _closing = @" }
}";
public static string getCode(string kernel, bool debug, bool assertions, OptimizationLevel optimizationLevel)
{
string formattedMain = String.Format(_main, debug ? "" : "//", assertions ? "" : "//", (int)optimizationLevel);
return _usings + _opening + kernel + formattedMain + _closing;
}
}
}
114 changes: 114 additions & 0 deletions Demo/Compiler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

namespace ILGPUwebCompiler
{
internal class Compiler
{
private List<MetadataReference> references { get; set; }
public void Init()
{
if (references == null)
{
references = new List<MetadataReference>();
for (int i = 0; i < Service.GetAmmountOfReferences(); i++)
{
var file = Service.GetReference(i);
using var wri = new BinaryWriter(System.IO.File.OpenWrite(i + ".dll"));
wri.Write(file);
var reference = MetadataReference.CreateFromFile(i + ".dll");
references.Add(reference);
}
}


}

private Assembly Compile(string code)
{
CSharpCompilation compilation = CSharpCompilation.Create("DynamicCode")
.WithOptions(new CSharpCompilationOptions(OutputKind.ConsoleApplication))
.AddReferences(references)
.AddSyntaxTrees(CSharpSyntaxTree.ParseText(code, new CSharpParseOptions(LanguageVersion.Preview)));

var diagnostic = compilation.GetDiagnostics();
bool error = false;
foreach (Diagnostic diag in diagnostic)
{
switch (diag.Severity)
{
case DiagnosticSeverity.Info:
Console.WriteLine(diag.ToString());
break;
case DiagnosticSeverity.Warning:
Console.WriteLine(diag.ToString());
break;
case DiagnosticSeverity.Error:
error = true;
Console.WriteLine(diag.ToString());
break;
}
}
if (error)
{
return null;
}


var outputAssembly = new MemoryStream();
var res = compilation.Emit(outputAssembly);

return Assembly.Load(outputAssembly.ToArray());

}

public async Task<string> CompileAndRun(string code)
{
//redirecting console output on a stream writer
var writer = new StringWriter();
Console.SetOut(writer);
string output = "";
Init();

var currentOut = Console.Out;

var sw = Stopwatch.StartNew(); //recording time
string exception = "";
try
{
var assembly = this.Compile(code);
if (assembly != null)
{
var entry = assembly.EntryPoint;
if (entry.Name == "<Main>")
{
entry = entry.DeclaringType.GetMethod("Main", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static); // reflect for the async Task Main
}
var hasArgs = entry.GetParameters().Length > 0;
var result = entry.Invoke(null, hasArgs ? new object[] { new string[0] } : null);
if (result is Task t)
{
await t;
}
}
}
catch (Exception ex)
{
exception = ex.ToString();
}
output = writer.ToString();
output += "\r\n" + exception;
sw.Stop();
output += "Done in " + sw.ElapsedMilliseconds + "ms";

Console.SetOut(currentOut);
return output;
}
}
}
40 changes: 40 additions & 0 deletions Demo/ILGPU.Demo.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<RuntimeIdentifier>browser-wasm</RuntimeIdentifier>
<WasmMainJSPath>main.js</WasmMainJSPath>
<OutputType>Exe</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup>
<_WasmPThreadPoolSize>60</_WasmPThreadPoolSize>
<WasmEnableThreads>true</WasmEnableThreads>
</PropertyGroup>
<ItemGroup>
<Content Include="style.css">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<PackageReference Include="ILGPU" Version="1.3.0" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.3.1" />
<PackageReference Include="Microsoft.NET.WebAssembly.Threading" Version="7.0.0-rc.2.22472.3" />
</ItemGroup>
<ItemGroup>
<Reference Include="ILGPU">
<HintPath>..\..\..\Downloads\ILGPU.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<WasmExtraFilesToDeploy Include="index.html" />
<WasmExtraFilesToDeploy Include="main.js" />
<WasmExtraFilesToDeploy Include="gui.js" />
<WasmExtraFilesToDeploy Include="style.css" />
<WasmExtraFilesToDeploy Include="codemirror/clike.js" />
<WasmExtraFilesToDeploy Include="codemirror/codemirror.js" />
<WasmExtraFilesToDeploy Include="codemirror/codemirror.css" />
<WasmExtraFilesToDeploy Include="codemirror/matchbrackets.js" />
<WasmExtraFilesToDeploy Include="codemirror/show-hint.css" />
<WasmExtraFilesToDeploy Include="codemirror/show-hint.js" />
</ItemGroup>
</Project>
25 changes: 25 additions & 0 deletions Demo/ILGPU.Demo.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.33103.201
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ILGPU.Demo", "ILGPU.Demo.csproj", "{D19F2625-2462-408D-8DBA-93035BEED38B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D19F2625-2462-408D-8DBA-93035BEED38B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D19F2625-2462-408D-8DBA-93035BEED38B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D19F2625-2462-408D-8DBA-93035BEED38B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D19F2625-2462-408D-8DBA-93035BEED38B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {FC144197-6E1A-43BE-871E-48D74F2992C8}
EndGlobalSection
EndGlobal
32 changes: 32 additions & 0 deletions Demo/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.JavaScript;
using System.Threading;
using System.Threading.Tasks;
using ILGPU;
using ILGPU.Runtime;
using ILGPUwebCompiler;
using Microsoft.CodeAnalysis;

public partial class Program
{
static Compiler c = new Compiler();
public static void Main(string[] args)
{
FillOptimizationLevelDropDown();
}

[JSExport]
internal static async Task Compile(string kernel, bool debug, bool assertions, int optimizationLevel)
{
var output = await c.CompileAndRun(CodeBuilder.getCode(kernel, debug, assertions, (ILGPU.OptimizationLevel)optimizationLevel));
Service.SetOutput(output);
}
private static void FillOptimizationLevelDropDown()
{
Service.FillOptimizationLevelDropDown(ILGPU.OptimizationLevel.Debug.ToString(), (int)ILGPU.OptimizationLevel.Debug);
Service.FillOptimizationLevelDropDown(ILGPU.OptimizationLevel.Release.ToString(), (int)ILGPU.OptimizationLevel.Release);
Service.FillOptimizationLevelDropDown(ILGPU.OptimizationLevel.O2.ToString(), (int)ILGPU.OptimizationLevel.O2);
}
}
13 changes: 13 additions & 0 deletions Demo/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"profiles": {
"ILGPUwebCompiler": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:7056;http://localhost:5223",
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/debug?browser={browserInspectUri}"
}
}
}
26 changes: 26 additions & 0 deletions Demo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
## Browser application

## Build

You can build the application from Visual Studio or by dotnet cli

```
dotnet build -c Debug/Release
```

After building the application, the result is in the `bin/$(Configuration)/net7.0/browser-wasm/AppBundle` directory.

## Run

You can build the application from Visual Studio or by dotnet cli

```
dotnet run -c Debug/Release
```

Or you can start any static file server from the AppBundle directory

```
dotnet serve -d:bin/$(Configuration)/net7.0/browser-wasm/AppBundle
```# ILGPUwebCompiler
# ILGPUwebCompiler
23 changes: 23 additions & 0 deletions Demo/Service.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices.JavaScript;
using System.Text;
using System.Threading.Tasks;

namespace ILGPUwebCompiler
{
public partial class Service
{
[JSImport("references", "main.js")]
internal static partial byte[] GetReference(int n);
[JSImport("totalFiles", "main.js")]
internal static partial int GetAmmountOfReferences();

[JSImport("fillOptimizationLevelDropDown", "main.js")]
internal static partial void FillOptimizationLevelDropDown(string ol, int value);

[JSImport("setOutput", "main.js")]
internal static partial void SetOutput(string output);
}
}
Loading