repo stringclasses 371 values | file_path stringlengths 29 241 | code stringlengths 100 736k | tokens int64 20 266k |
|---|---|---|---|
imezx/Surround | imezx-Surround-dde33fc/src/init.luau | --!optimize 2
--!native
local Surround = {}
local RunService = game:GetService("RunService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local scheduler = require(ReplicatedStorage:WaitForChild("scheduler"))
local begin_profiler, end_profiler = scheduler.profiler.Begin, scheduler.profiler.End
local Player: Player = game:GetService("Players").LocalPlayer
type Object = {
root: BasePart,
sound: Sound,
baseVolume: number,
max_distance: number,
}
local default_max_distance: number = 15
local throttle: number = 1 / 24
local last_throttle: number = 0
local objects: { Object } = {}
local queued: { Object } = {}
Surround.addObject = function(_object: BasePart, sound: Sound, baseVolume: number?, max_distance: number?)
if not _object or not sound then
return
end
local object: BasePart = _object
if _object:IsA("Model") and _object.PrimaryPart then
object = _object.PrimaryPart
end
if not object:IsA("BasePart") then
return
end
table.insert(objects, {
root = object,
sound = sound,
baseVolume = baseVolume or sound.Volume,
max_distance = max_distance or default_max_distance,
})
end
Surround.removeObject = function(_object: BasePart, sound: Sound)
if not _object or not sound then
return
end
local object: BasePart = _object
if _object:IsA("Model") and _object.PrimaryPart then
object = _object.PrimaryPart
end
for idx: number, obj: Object in objects do
if obj.root == object and obj.sound == sound then
table.remove(objects, idx)
return
end
end
end
RunService.PreRender:Connect(function(dt: number)
if last_throttle <= throttle then
last_throttle += dt
return
end
last_throttle = 0
local characterRoot: BasePart? = Player.Character and Player.Character.PrimaryPart
if not characterRoot then
return
end
begin_profiler("Surround.simulate")
local characterPos: Vector3 = characterRoot.Position
if next(queued) then
local sounds: { [Sound]: number } = {}
for _, object: Object in queued do
local pos: Vector3 = object.root.Position
local distance: number = (pos - characterPos).Magnitude
local volume: number =
math.clamp(object.baseVolume * (1 - distance / object.max_distance), 0, object.baseVolume)
local highest_volume: number = sounds[object.sound] or -1
if volume <= highest_volume then
continue
end
sounds[object.sound] = volume
end
table.clear(queued)
for sound: Sound, volume: number in sounds do
sound.Volume = volume
end
else
for idx: number, object: Object in objects do
if not object.root or not object.sound or not object.root.Parent then
objects[idx] = nil
continue
end
if not object.root:IsDescendantOf(workspace) then
continue
end
table.insert(queued, object)
end
end
end_profiler("Surround.simulate")
end)
return Surround :: typeof(Surround)
| 729 |
imezx/MultiRaycast | imezx-MultiRaycast-c45dd4d/src/init.luau | --@EternityDev
--!strict
--!native
--!optimize 2
local Raycast = {}
Raycast.__index = Raycast
local RunService = game:GetService("RunService")
local Signal = require(script.Signal)
local PreSimulation = RunService.PreSimulation
local sampleActor = script:WaitForChild("Actor")
function Raycast.new(header: string, directory: Instance, raycastParam: RaycastParams?, actors: number?)
if not header then
header = tostring(math.random(99, 1999))
end
if not raycastParam then
raycastParam = RaycastParams.new()
end
local meta = setmetatable({}, Raycast)
meta.filter = raycastParam
meta.origin = Vector3.new()
meta.direction = Vector3.new()
meta.state = "inactive"
meta.inputs = {}
meta.outputs = {}
meta.connections = {}
meta.task = {}
meta._actors = {}
meta.Signal = Signal(`Signal-{header}`)
if not directory:FindFirstChild(`Actors-{header}`) then
Instance.new("Folder", directory).Name = `Actors-{header}`
end
for idx=1,actors or 4 do
local actor = sampleActor:Clone()
meta.inputs[idx] = actor.Input
meta.outputs[idx] = actor.Output.Event
if RunService:IsClient() then
actor.Client.Enabled = true
actor.Server.Enabled = false
else
actor.Client.Enabled = false
actor.Server.Enabled = true
end
table.insert(meta._actors, actor)
actor.Parent = directory:FindFirstChild(`Actors-{header}`)
end
meta:_bind()
return meta
end
function Raycast:updateFilter(raycastParam: RaycastParams)
if not raycastParam then return end
self.filter = raycastParam
end
function Raycast:setOrigin(origin: Vector3)
if not origin then return end
self.origin = origin
end
function Raycast:setDirection(direction: Vector3)
if not direction then return end
self.direction = direction
end
function Raycast:_unbind()
for _, c in self.connections do
c:Disconnect()
end
table.clear(self.connections)
end
function Raycast:_bind()
for idx, output: RBXScriptSignal in self.outputs do
self.connections[idx] = output:Connect(function(...)
self.Signal:Fire(...)
end)
end
end
function Raycast:run(forceRun: boolean?)
if not forceRun then
if self.state == "active" then return end
end
self.state = "active"
local newTask
newTask = task.spawn(function()
while PreSimulation:Wait() do
for _, input: BindableEvent in self.inputs do
input:Fire(self.origin, self.direction, self.filter)
end
end
end)
table.insert(self.task, newTask)
end
function Raycast:stop()
if self.state == "inactive" then return end
for _, t in self.task do
task.cancel(t)
end
table.clear(self.task)
self.state = "inactive"
end
function Raycast:destroy()
self:stop()
self:_unbind()
self.Signal:Destroy()
for _, actor in self._actors do
actor.Parent:Destroy()
break
end
table.clear(self)
setmetatable(self, nil)
end
return Raycast :: typeof(Raycast) | 710 |
imezx/TaskChain | imezx-TaskChain-83b1c84/src/Types.luau | --!strict
--!optimize 2
local promise = require(script.Parent.Parent.promise)
local janitor = require(script.Parent.Parent.janitor)
export type Promise<T...> = promise.TypedPromise<T...>
export type Janitor = janitor.Janitor
export type task = {
type: "call" | "wait" | "promise" | "andThen" | "catch" | "finally" | "track",
payload: any,
}
export type status = "Pending" | "Running" | "Resolved" | "Rejected" | "Destroyed"
export type TaskChain = {
call: (self: TaskChain, func: (...any) -> ...any, ...any) -> TaskChain,
wait: (self: TaskChain, duration: number) -> TaskChain,
promise: (self: TaskChain, promise: Promise) -> TaskChain,
andThen: (self: TaskChain, onSuccess: ((...any) -> ...any)?, onFailure: ((any) -> any)?) -> TaskChain,
track: <T>(self: TaskChain, item: T, cleanupMethod: string | boolean | nil) -> TaskChain,
catch: (self: TaskChain, errorHandler: (err: any) -> any) -> TaskChain,
finally: (self: TaskChain, handler: () -> ()) -> TaskChain,
destroy: (self: TaskChain) -> (),
remove: (self: TaskChain) -> (),
await: (self: TaskChain) -> any?,
fork: (self: TaskChain) -> TaskChain,
_tasks: { task },
_janitor: Janitor,
_promise: Promise,
_status: status,
_isProcessing: boolean,
}
return {
promise = promise,
janitor = janitor,
}
| 374 |
imezx/TaskChain | imezx-TaskChain-83b1c84/src/init.luau | --!optimize 2
local TaskChain = {}
TaskChain.__index = TaskChain
local types = require(script.Types)
--]
local function _processNextTask(self: types.TaskChain)
if self._status == "Destroyed" or not self._isProcessing then
return
end
if #self._tasks == 0 then
self._isProcessing = false
return
end
local taskDescriptor = table.remove(self._tasks, 1)
self._promise = self._promise:andThen(function(...)
if self._status == "Destroyed" then
return types.promise
.new(function(_, _, onCancel)
onCancel(function()
return
end)
end)
:cancel()
end
local results = { ... }
local taskType = taskDescriptor.type
local payload = taskDescriptor.payload
if taskType == "call" then
return payload.func(table.unpack(results), table.unpack(payload.args))
elseif taskType == "wait" then
local waitPromise = types.promise.delay(payload.duration)
self._janitor:Add(waitPromise, "cancel")
return waitPromise:andThen(function()
return table.unpack(results)
end)
elseif taskType == "promise" then
self._janitor:Add(payload.promise, "cancel")
return payload.promise
elseif taskType == "andThen" then
local p = types.promise.resolve(table.unpack(results))
return p:andThen(payload.onSuccess, payload.onFailure)
elseif taskType == "track" then
self._janitor:Add(payload.item, payload.cleanupMethod)
return table.unpack(results)
elseif taskType == "catch" or taskType == "finally" then
return table.unpack(results)
end
end)
_processNextTask(self)
end
--]
function TaskChain.new(): types.TaskChain
local self = setmetatable({
_tasks = {},
_janitor = types.janitor.new(),
_status = "Pending",
_isProcessing = false,
}, TaskChain)
self._promise = types.promise.resolve()
self._janitor:Add(self._promise, "cancel")
return self
end
--]
function TaskChain:call(func: (...any) -> ...any, ...): types.TaskChain
table.insert(self._tasks, {
type = "call",
payload = { func = func, args = { ... } },
})
if not self._isProcessing then
self._isProcessing = true
self._status = "Running"
_processNextTask(self)
end
return self
end
--]
function TaskChain:wait(duration: number?): types.TaskChain
table.insert(self._tasks, {
type = "wait",
payload = { duration = (duration or 0.016666) },
})
if not self._isProcessing then
self._isProcessing = true
self._status = "Running"
_processNextTask(self)
end
return self
end
--]
function TaskChain:promise(promise: types.Promise): types.TaskChain
table.insert(self._tasks, {
type = "promise",
payload = { promise = promise },
})
if not self._isProcessing then
self._isProcessing = true
self._status = "Running"
_processNextTask(self)
end
return self
end
--]
function TaskChain:andThen(onSuccess, onFailure): types.TaskChain
table.insert(self._tasks, {
type = "andThen",
payload = { onSuccess = onSuccess, onFailure = onFailure },
})
if not self._isProcessing then
self._isProcessing = true
self._status = "Running"
_processNextTask(self)
end
return self
end
--]
function TaskChain:track(item, cleanupMethod: string): types.TaskChain
table.insert(self._tasks, {
type = "track",
payload = { item = item, cleanupMethod = cleanupMethod },
})
if not self._isProcessing then
self._isProcessing = true
self._status = "Running"
_processNextTask(self)
end
return self
end
--]
function TaskChain:catch(errorHandler): types.TaskChain
self._promise = self._promise:catch(errorHandler)
self._promise:catch(function()
if self._status ~= "Destroyed" then
self._status = "Rejected"
end
end)
return self
end
--]
function TaskChain:finally(handler): types.TaskChain
self._promise = self._promise:finally(handler)
self._promise:andThen(function()
if self._status == "Running" then
self._status = "Resolved"
end
end)
return self
end
--]
function TaskChain:await(): any?
local value = select(2, self._promise:await())
self:destroy()
return value
end
--]
function TaskChain:fork(): types.TaskChain
local newChain = TaskChain.new()
newChain._promise = self._promise
return newChain
end
--]
function TaskChain:destroy()
if self._status == "Destroyed" then
return
end
self._status = "Destroyed"
self._isProcessing = false
self._tasks = {}
self._janitor:Destroy()
table.clear(self)
setmetatable(self, nil)
end
TaskChain.remove = TaskChain.destroy
return table.freeze(TaskChain)
| 1,143 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/client/init.luau | --!optimize 2
local client = {}
local ContextActionService = game:GetService("ContextActionService")
local CollectionService = game:GetService("CollectionService")
local localPlayer = game:GetService("Players").LocalPlayer
local vide = require("../vide")
local Profiler = require("./profiler")
local client_performance = require("@self/performance")
local remotes = require("@self/remotes/Remotes")
local spawn_app = require("./ui/spawn_app")
local home_app = require("./ui/home")
local unbind_performance_socket = remotes.fromEvent("scheduler.unbind_performance_socket")
local profiler_state = remotes.fromEvent("scheduler.profiler_state")
local server_frame_value = vide.source({})
local version: string, rootScope, root_performance, home_app_ui
Profiler.store("server_frame_value", server_frame_value)
local function onStateChanged(instance: Instance?)
if instance and instance ~= localPlayer then
return
end
if localPlayer:HasTag("__allowedScheduler__") then
script.Parent.profiler:SetAttribute("__state__", true)
else
script.Parent.profiler:SetAttribute("__state__", false)
end
end
client.assign_ver = function(ver: string)
version = ver
end
client.init = function()
if script:HasTag("__init__") then
return
end
script:AddTag("__init__")
CollectionService:GetInstanceAddedSignal("__allowedScheduler__"):Connect(onStateChanged)
CollectionService:GetInstanceRemovedSignal("__allowedScheduler__"):Connect(onStateChanged)
task.defer(onStateChanged)
end
client.toggle_widget = function(_, state: Enum.UserInputState)
if state and state ~= Enum.UserInputState.End then
return
end
-- cleanup
if root_performance then
root_performance()
root_performance = nil
end
if not localPlayer:HasTag("__allowedScheduler__") or rootScope then
home_app_ui = nil
profiler_state:FireServer(false)
unbind_performance_socket:FireServer()
Profiler.reset()
Profiler.Pause()
if rootScope then
rootScope()
rootScope = nil
end
spawn_app.unmount_all()
return
end
if home_app_ui then
return
end
root_performance = client_performance.run(Profiler)
profiler_state:FireServer(true)
Profiler.reset()
Profiler.Resume()
rootScope = vide.root(function()
-- Server Scheduler
home_app_ui = home_app({
env = "Server",
Profiler = Profiler,
profiler_state = profiler_state,
ProfilerState = Profiler.get_stored("server_frame_value"),
Runtime = Profiler.get_stored("server_runtime"),
version = version,
onClose = function()
if home_app_ui then
home_app_ui.Enabled = false
end
end,
onDestroy = function()
home_app_ui = nil
profiler_state:FireServer(false)
unbind_performance_socket:FireServer()
Profiler.reset()
Profiler.Pause()
if not rootScope then
return
end
rootScope()
rootScope = nil
spawn_app.unmount_all()
end,
})
home_app_ui.Parent = game.Players.LocalPlayer:WaitForChild("PlayerGui", 9e9)
end)
end
client.bind_to = function(key_bind: Enum.KeyCode)
if not client then
warn(`please use .client() first.`)
return
end
ContextActionService:UnbindAction("Toggle Scheduler Widget")
ContextActionService:BindAction("Toggle Scheduler Widget", client.toggle_widget, false, key_bind or Enum.KeyCode.F3)
end
return client :: typeof(client)
| 784 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/client/performance.luau | --!optimize 2
local Players = game:GetService("Players")
local RunService = game:GetService("RunService")
local Stats = game:GetService("Stats")
local vide = require("../../vide")
local remotes = require("./remotes/Remotes")
local get_performance_socket = remotes.fromFunction("scheduler.get_performance_socket")
local communicate_frame_time = remotes.fromEvent("scheduler.communicate_frame_time")
local server_frame_time = remotes.fromEvent("scheduler.server_frame_time")
local communicate_run_time = remotes.fromEvent("scheduler.communicate_run_time")
local root, source, cleanup = vide.root, vide.source, vide.cleanup
local open_connections: { [Player | string]: RBXScriptConnection } = {}
local Buffer = remotes.buffer
local localUser: Player = Players.LocalPlayer
local average_heartbeat: number = 0
local average_frames: number = 0
local render_gpu_frame_time: number = 0
local render_cpu_frame_time: number = 0
local counter: number = 0
local acccumulate: number = 0
local UPDATE_EVERY: number = 1
local scope_value = source("")
local store = source({})
local localSocketId = source("")
local memory_usage = source({} :: { number })
local heartbeat_time = source({} :: { number })
local frames_time = source({} :: { number })
local render_gpu_time = source({} :: { number })
local render_cpu_time = source({} :: { number })
local function performance(Profiler)
cleanup(function()
for host: Player | string, socket: RBXScriptConnection in open_connections do
socket:Disconnect()
end
table.clear(open_connections)
end)
local function obtain_store_data(host: Player | string)
local data = host and get_performance_socket:Invoke(3, { to = host, id = 0 }, nil)
if not data or not data.socket then
return
end
localSocketId(data.socket)
local memory = source(0)
local heartbeat_time = source(0)
local frames_time = source(0)
local render_gpu_time = source(0)
local render_cpu_time = source(0)
store()[host] = {
memory = memory,
heartbeat_time = heartbeat_time,
frames_time = frames_time,
render_gpu_time = render_gpu_time,
render_cpu_time = render_cpu_time,
}
store(store())
local socket: RBXScriptConnection
socket = communicate_frame_time.OnClientEvent:Connect(function(_host: Player | string, packet: buffer)
if _host ~= host or type(packet) ~= "buffer" then
return
end
-- socket:Disconnect()
local packet_heartbeat_time: number, packet_frames_time: number, packet_render_gpu_time: number, packet_render_cpu_time: number, packet_memory: number =
buffer.readf64(packet, 0),
buffer.readf64(packet, 8),
buffer.readf64(packet, 16),
buffer.readf64(packet, 24),
buffer.readf64(packet, 32)
heartbeat_time(packet_heartbeat_time)
frames_time(packet_frames_time)
render_gpu_time(packet_render_gpu_time)
render_cpu_time(packet_render_cpu_time)
memory(packet_memory)
Profiler.socket_assign(host, {
memory = packet_memory,
heartbeat_time = packet_heartbeat_time,
frames_time = packet_frames_time,
render_cpu_time = packet_render_cpu_time,
render_gpu_time = packet_render_gpu_time,
})
end)
open_connections[host] = socket
if host == localUser then
communicate_run_time.OnClientEvent:Connect(function(packet: buffer)
if type(packet) ~= "buffer" then
return
end
local parsed_runTime: string = buffer.tostring(packet)
scope_value(parsed_runTime)
local scope_value = Profiler.get_stored("server_runtime")
if not scope_value then
Profiler.store("server_runtime", scope_value)
end
end)
end
end
obtain_store_data("server")
for _, player: Player in Players:GetPlayers() do
obtain_store_data(player)
end
cleanup(Players.PlayerAdded:Connect(obtain_store_data))
cleanup(Players.PlayerRemoving:Connect(function(Player: Player)
if open_connections[Player] then
open_connections[Player]:Disconnect()
open_connections[Player] = nil
end
end))
cleanup(RunService.Heartbeat:Connect(function()
for host: Player | string, socket: RBXScriptConnection in open_connections do
if socket and socket.Connected then
continue
end
store()[host] = nil
store(store())
end
end))
local server_frame_value = Profiler.get_stored("server_frame_value")
cleanup(RunService.Heartbeat:Connect(function(dt: number)
counter += 1
acccumulate += dt
average_heartbeat += Stats.HeartbeatTime
average_frames += Stats.FrameTime
render_gpu_frame_time += Stats.RenderGPUFrameTime
render_cpu_frame_time += Stats.RenderCPUFrameTime
if acccumulate > UPDATE_EVERY then
if next(open_connections) then
local b: buffer = buffer.create(40)
local data_memory: number, data_heartbeat_time: number, data_frames_time: number, data_render_cpu_frame_time: number, data_render_gpu_frame_time: number =
Stats:GetTotalMemoryUsageMb() * 1e3 * 1e3,
average_heartbeat / counter,
average_frames / counter,
render_cpu_frame_time / counter,
render_gpu_frame_time / counter
buffer.writef64(b, 0, data_heartbeat_time)
buffer.writef64(b, 8, data_frames_time)
buffer.writef64(b, 16, data_render_gpu_frame_time)
buffer.writef64(b, 24, data_render_cpu_frame_time)
buffer.writef64(b, 32, data_memory)
memory_usage()[localUser] = data_memory
heartbeat_time()[localUser] = data_heartbeat_time
frames_time()[localUser] = data_frames_time
render_gpu_time()[localUser] = data_render_cpu_frame_time
render_cpu_time()[localUser] = data_render_gpu_frame_time
communicate_frame_time:FireServer(localSocketId(), b)
Profiler.socket_assign(localUser, {
memory = data_memory,
heartbeat_time = data_heartbeat_time,
frames_time = data_frames_time,
render_cpu_time = data_render_cpu_frame_time,
render_gpu_time = data_render_gpu_frame_time,
})
end
average_heartbeat = 0
average_frames = 0
render_gpu_frame_time = 0
render_cpu_frame_time = 0
acccumulate -= UPDATE_EVERY
counter = 0
end
end))
cleanup(server_frame_time.OnClientEvent:Connect(function(packet: buffer)
if type(packet) ~= "buffer" then
return
end
local raw_exported_server_frames = Buffer.read(packet)
if not raw_exported_server_frames then
return
end
server_frame_value(Profiler.merge(raw_exported_server_frames, false))
end))
end
return {
run = function(Profiler)
return root(function()
performance(Profiler)
end)
end,
}
| 1,609 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/client/remotes/Function.luau | --!optimize 2
--!strict
--@EternityDev
local Function = {}
Function.__index = Function
local RunService = game:GetService("RunService")
function Function.new(remote: RemoteFunction)
local meta = setmetatable({
remote = remote,
}, Function)
remote.Destroying:Once(function()
if not meta then return end
Function.Remove(meta)
end)
return meta
end
function Function:Invoke(expireTime: number, ...: any): (...any?)
if not RunService:IsClient() then
return error("Cannot execute InvokeServer on the server.", 2)
end
if not expireTime then return end
local timer, session
local obj = { ... }
local thread: thread = coroutine.running()
timer = task.delay(expireTime or 3, function()
task.cancel(session)
task.spawn(thread, nil)
end)
session = task.spawn(function()
local obj = self.remote:InvokeServer(table.unpack(obj))
task.cancel(timer)
task.spawn(thread, obj)
end)
return coroutine.yield()
end
function Function:Remove()
setmetatable(self, nil)
end
function Function:Destroy()
self.remote:Destroy()
end
return Function | 254 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/client/remotes/Remotes.luau | --!optimize 2
--!strict
--@EternityDev
--Client
local Remotes = {}
if not script.Parent.Parent.Parent:FindFirstChild("Remotes") then
Instance.new("Folder", script.Parent.Parent.Parent).Name = "Remotes"
end
local RemotesDir = script.Parent.Parent.Parent:WaitForChild("Remotes")
local Function = require("./Function")
function Remotes.fromEvent(remoteName: string): RemoteEvent
if not RemotesDir:FindFirstChild(`Remote_{remoteName}`) then
error(`Oops, cant find remote-event for "{remoteName}", make sure you have defined it on server-side.`)
end
return RemotesDir[`Remote_{remoteName}`]
end
function Remotes.fromFunction(remoteName: string)
if not RemotesDir:FindFirstChild(`Remote_{remoteName}`) then
error(`Oops, cant find remote-function for "{remoteName}", make sure you have defined it on server-side.`)
end
return Function.new(RemotesDir[`Remote_{remoteName}`])
end
Remotes.buffer = require("../../util/bufferencoder")
return Remotes
| 237 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/init.luau | --!optimize 2
--!strict
local scheduler = {}
local profiler = require("@self/profiler")
local client = nil
scheduler.profiler = profiler
scheduler.server = function()
local server = require("@self/server")
return server
end
scheduler.client = function()
if client then
return client
end
client = require("@self/client")
client.assign_ver("0.1.4")
return client
end
return scheduler :: typeof(scheduler)
| 96 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/profiler/init.luau | --!optimize 2
--!native
local Profiler = {}
Profiler.isRunning = false
local IsServer: boolean = game:GetService("RunService"):IsServer()
local vide = require("../vide")
local convert_scale = require("./util/convert_scale")
local Signal = require("./util/limesignal")
local socket_changed_signal = Signal.Signal.new()
local lastUpdated: number, profiler_state: boolean = os.clock(), IsServer
type socket_array_map = {
memory: number,
heartbeat_time: number,
frames_time: number,
render_gpu_time: number,
render_cpu_time: number,
}
type socket_transcript_type_inner = {
id: number,
host: string,
memory: string,
cpu: string,
frames: string,
gpu: string,
cpuRender: string,
}
type socket_transcript_type = { socket_transcript_type_inner }
type TimerInfo = {
name: string,
startTime: number,
deductedTime: number,
}
local activeTimers: { [thread]: { TimerInfo } } = {}
local frameSystems: { { Name: string, Duration: number, Color: Color3 } } = {}
local colorCache: { [string]: Color3 } = {}
local sockets: { [Player | string]: socket_array_map } = {}
local stores: { [string]: any } = {}
local timerPool: { TimerInfo } = {}
local function allocTimer(name: string, startTime: number): TimerInfo
local t = table.remove(timerPool)
if t then
t.name = name
t.startTime = startTime
t.deductedTime = 0
return t
end
return {
name = name,
startTime = startTime,
deductedTime = 0,
}
end
local function freeTimer(t: TimerInfo)
table.insert(timerPool, t)
end
local state: (any) -> { any } = vide.source({})
local function generateColor(str: string): Color3
if colorCache[str] then
return colorCache[str]
end
local hash: number = 0
for i: number = 1, #str do
local char: number = string.byte(str, i)
hash = (bit32.lshift(hash, 5) - hash) + char
hash = bit32.band(hash, hash) -- Convert to 32bit integer
end
local hue: number = (hash % 360) / 360
local color: Color3 = Color3.fromHSV(hue, 0.8, 0.95)
colorCache[str] = color
return color
end
Profiler.reset = function()
Profiler.isRunning = false
table.clear(activeTimers)
table.clear(frameSystems)
Profiler.isRunning = true
end
-- Sockets
Profiler.all_sockets = function(): { [Player | string]: socket_array_map? }
return sockets
end
Profiler.socket_assign = function(host: Player | string, new_map: socket_array_map)
sockets[host] = new_map
socket_changed_signal:fire()
end
Profiler.getSocket = function(host: Player | string): socket_array_map?
return sockets[host]
end
-- { id = 1, host = "server", memory = "0.00GB", cpu = "0.0us", gpu = "0.0us", cpuRender = "0.00ms" },
Profiler.sockets_transcript = function(): socket_transcript_type
local idx: number, transcript: socket_transcript_type = 1, {}
for host: Player | string, map: socket_array_map in sockets do
local frame_time: number = 1 / (map.frames_time or 1)
if frame_time ~= frame_time or frame_time == math.huge then
frame_time = 0
end
table.insert(transcript, {
id = idx,
host = type(host) == "string" and host or (host :: Player).Name,
memory = convert_scale("B", map.memory),
cpu = convert_scale("s", map.heartbeat_time or 0),
frames = string.format("%.2f", frame_time),
gpu = convert_scale("s", map.render_gpu_time or 0),
cpuRender = convert_scale("s", map.render_cpu_time or 0),
})
idx += 1
end
table.sort(transcript, function(a: socket_transcript_type_inner, b: socket_transcript_type_inner): boolean
return a.id ~= 1 and true or a.host < b.host
end)
return transcript
end
Profiler.onSocketChanged = socket_changed_signal
-- Profilers
Profiler.RunTime = function(): number
local runTime: number = 0
for _, frame: { Name: string, Duration: number, Color: Color3 } in frameSystems do
runTime += frame.Duration
end
return runTime
end
Profiler.merge = function(map_value: { { Name: string, Duration: number, Color: Color3 } }?, update_state: boolean?)
map_value = map_value or frameSystems
local merged: { [string]: { Name: string, Duration: number, Count: number, Color: Color3 } } = {}
for _, frameData: { Name: string, Duration: number, Color: Color3 } in map_value :: any do
if not merged[frameData.Name] then
merged[frameData.Name] = {
Name = frameData.Name,
Duration = frameData.Duration,
Count = 1,
Color = frameData.Color,
}
else
local system = merged[frameData.Name]
system.Duration += frameData.Duration
system.Count += 1
end
end
local sorted = {}
for _, system in merged do
system.Duration /= system.Count
table.insert(sorted, system)
end
table.sort(sorted, function(a, b)
return a.Name < b.Name
end)
if update_state == nil or update_state then
state(sorted)
end
table.clear(frameSystems)
return sorted
end
Profiler.Begin = function(name: string)
if not Profiler.isRunning or not profiler_state then
return
end
local startTime = os.clock()
local currentThread: thread = coroutine.running()
local threadStack = activeTimers[currentThread]
if not threadStack then
threadStack = {}
activeTimers[currentThread] = threadStack
end
table.insert(threadStack, allocTimer(name, startTime))
-- overhead compensation
local endTime = os.clock()
local overhead = endTime - startTime
if #threadStack > 1 then
threadStack[#threadStack - 1].deductedTime += overhead
end
end
Profiler.End = function(name: string)
if not Profiler.isRunning or not profiler_state then
return
end
local endStart: number = os.clock()
local currentThread: thread = coroutine.running()
local threadTimers: { TimerInfo } = activeTimers[currentThread]
if not threadTimers then
return
end
local lastIndex = #threadTimers
if lastIndex > 0 and threadTimers[lastIndex].name == name then
local timer = threadTimers[lastIndex]
table.remove(threadTimers, lastIndex)
local duration: number = endStart - timer.startTime - timer.deductedTime
if duration < 0 then
duration = 0
end
table.insert(frameSystems, {
Name = name,
Duration = duration,
Color = generateColor(name),
})
freeTimer(timer)
else
for i: number = lastIndex - 1, 1, -1 do
local timer: TimerInfo = threadTimers[i]
if timer.name == name then
table.remove(threadTimers, i)
local duration: number = endStart - timer.startTime - timer.deductedTime
if duration < 0 then
duration = 0
end
table.insert(frameSystems, {
Name = name,
Duration = duration,
Color = generateColor(name),
})
freeTimer(timer)
break
end
end
end
local endFinish = os.clock()
local overhead = endFinish - endStart
if #threadTimers > 0 then
threadTimers[#threadTimers].deductedTime += overhead
end
if #threadTimers == 0 then
activeTimers[currentThread] = nil
end
if endStart - lastUpdated >= 1 then
lastUpdated = endStart
Profiler.merge(nil, true)
end
end
Profiler.Pause = function()
Profiler.isRunning = false
end
Profiler.Resume = function()
Profiler.isRunning = true
end
Profiler.dump_state = function()
return state
end
Profiler.dump_frames = function(): { { Name: string, Duration: number, Color: Color3 } }
return frameSystems
end
-- Misc
Profiler.store = function(key: string, value: any)
stores[key] = value
end
Profiler.get_stored = function(key: string): any?
return stores[key]
end
if not IsServer then
script:GetAttributeChangedSignal("__state__"):Connect(function()
profiler_state = script:GetAttribute("__state__")
end)
profiler_state = script:GetAttribute("__state__")
end
return Profiler :: typeof(Profiler)
| 1,987 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/server/init.luau | --!optimize 2
local server = {}
local HttpService = game:GetService("HttpService")
local RunService = game:GetService("RunService")
local Stats = game:GetService("Stats")
local CollectionService = game:GetService("CollectionService")
local convert_units = require("./util/convert_units")
local remotes = require("@self/remotes/Remotes")
local Buffer = remotes.buffer
local get_performance_socket = remotes.fromFunction("scheduler.get_performance_socket")
local unbind_performance_socket = remotes.fromEvent("scheduler.unbind_performance_socket")
local communicate_frame_time = remotes.fromEvent("scheduler.communicate_frame_time")
local server_frame_time = remotes.fromEvent("scheduler.server_frame_time")
local communicate_run_time = remotes.fromEvent("scheduler.communicate_run_time")
local profiler_state = remotes.fromEvent("scheduler.profiler_state")
local SEND_EVERY: number = 1
server.allowed = function(): { Player }
return CollectionService:GetTagged("__allowedScheduler__")
end
server.allow = function(player: Player)
player:AddTag("__allowedScheduler__")
end
server.disallow = function(player: Player)
player:RemoveTag("__allowedScheduler__")
end
server.init = function(Profiler)
if script:HasTag("__init__") then
return
end
script:AddTag("__init__")
local active_sockets = {}
local _queue = {}
get_performance_socket.remote.OnServerInvoke = function(sender: Player)
local socket_id: string = HttpService:GenerateGUID(false):gsub("-", "")
active_sockets[sender] = socket_id
return {
socket = socket_id,
}
end
unbind_performance_socket.OnServerEvent:Connect(function(sender: Player)
active_sockets[sender] = nil
end)
communicate_frame_time.OnServerEvent:Connect(function(sender: Player, socketId: string, packet: buffer)
if
type(socketId) ~= "string"
or type(packet) ~= "buffer"
or buffer.len(packet) ~= 40
or not active_sockets[sender]
or active_sockets[sender] ~= socketId
then
return
end
_queue[sender] = packet
end)
profiler_state.OnServerEvent:Connect(function(sender: Player, state: boolean)
if not active_sockets[sender] or not sender:HasTag("__allowedScheduler__") or type(state) ~= "boolean" then
return
end
Profiler.reset()
if state == true then
Profiler.Resume()
else
Profiler.Pause()
end
end)
local average_heartbeat: number = 0
local average_frames: number = 0
local render_gpu_frame_time: number = 0
local render_cpu_frame_time: number = 0
local counter: number = 0
local acccumulate: number = 0
RunService.Heartbeat:Connect(function(dt: number)
counter += 1
acccumulate += dt
average_heartbeat += Stats.HeartbeatTime
average_frames += dt
render_gpu_frame_time += Stats.RenderGPUFrameTime
render_cpu_frame_time += Stats.RenderCPUFrameTime
if acccumulate > SEND_EVERY and Profiler.isRunning then
if next(active_sockets) then
local runTime: string = convert_units("s", Profiler.RunTime())
local exported_scheduler: { { Name: string, Duration: number, Color: Color3 } } = Profiler.dump_frames()
local b: buffer = buffer.create(40)
buffer.writef64(b, 0, average_heartbeat / counter)
buffer.writef64(b, 8, average_frames / counter)
buffer.writef64(b, 16, render_gpu_frame_time / counter)
buffer.writef64(b, 24, render_cpu_frame_time / counter)
buffer.writef64(b, 32, Stats:GetTotalMemoryUsageMb() * 1e3 * 1e3)
for socket: Player in active_sockets do
if not socket or not socket.Parent then
active_sockets[socket] = nil
continue
end
communicate_frame_time:FireClient(socket, "server", b)
server_frame_time:FireClient(socket, Buffer.write(exported_scheduler))
communicate_run_time:FireClient(socket, buffer.fromstring(runTime))
end
end
if next(_queue) then
for host: Player, packet: buffer in _queue do
if not host or not host.Parent or buffer.len(packet) ~= 40 then
_queue[host] = nil
continue
end
for socket: Player in active_sockets do
if not socket or not socket.Parent then
active_sockets[socket] = nil
continue
end
if socket == host then
continue
end
communicate_frame_time:FireClient(socket, host, packet)
end
_queue[host] = nil
end
end
average_heartbeat = 0
average_frames = 0
render_gpu_frame_time = 0
render_cpu_frame_time = 0
acccumulate -= SEND_EVERY
counter = 0
end
end)
end
return server :: typeof(server)
| 1,141 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/server/remotes/Function.luau | --!optimize 2
--!strict
--@EternityDev
local Function = {}
Function.__index = Function
local RunService = game:GetService("RunService")
function Function.new(remote: RemoteFunction)
local meta = setmetatable({
remote = remote,
}, Function)
remote.Destroying:Once(function()
if not meta then
return
end
Function.Remove(meta)
end)
return meta
end
function Function:Invoke(expireTime: number, player: Player, ...: any): ...any?
if not RunService:IsServer() then
return error("Cannot execute InvokeClient on the Client.", 2)
end
if not expireTime then
return
end
local timer, session
local obj = { ... }
local thread: thread = coroutine.running()
timer = task.delay(expireTime or 3, function()
task.cancel(session)
task.spawn(thread, nil)
end)
session = task.spawn(function()
if not player or not player.Parent then
task.cancel(timer)
task.spawn(thread, nil)
return
end
local response = self.remote:InvokeClient(player, table.unpack(obj))
task.cancel(timer)
task.spawn(thread, response)
end)
return coroutine.yield()
end
function Function:Remove()
setmetatable(self, nil)
end
function Function:Destroy()
self.remote:Destroy()
end
return Function
| 296 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/server/remotes/Remotes.luau | --!optimize 2
--!strict
--@EternityDev
--Server
local Remotes = {}
if not script.Parent.Parent.Parent:FindFirstChild("Remotes") then
Instance.new("Folder", script.Parent.Parent.Parent).Name = "Remotes"
end
local RemotesDir = script.Parent.Parent.Parent:WaitForChild("Remotes")
local Function = require("./Function")
function Remotes.fromEvent(remoteName: string): RemoteEvent
if not RemotesDir:FindFirstChild(`Remote_{remoteName}`) then
Instance.new("RemoteEvent", RemotesDir).Name = `Remote_{remoteName}`
end
return RemotesDir[`Remote_{remoteName}`]
end
function Remotes.fromFunction(remoteName: string)
if not RemotesDir:FindFirstChild(`Remote_{remoteName}`) then
Instance.new("RemoteFunction", RemotesDir).Name = `Remote_{remoteName}`
end
return Function.new(RemotesDir[`Remote_{remoteName}`])
end
Remotes.buffer = require("../../util/bufferencoder")
return Remotes
| 227 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/ui/home.luau | --!optimize 2
local pebble = require("../../pebble")
local vide = require("../../vide")
local spawn_app = require("./spawn_app")
local scheduler_app = require("./scheduler")
local performance_app = require("./performance")
type HomeProps = {
env: string,
Profiler: any,
profiler_state: RemoteEvent,
version: string,
onClose: () -> (),
onDestroy: () -> (),
}
local create = vide.create
local source = vide.source
local values = vide.values
local cleanup = vide.cleanup
local env_apps = source({
{
env = "Server",
Position = UDim2.fromScale(0.25, 0.5),
menus = source({
scheduler = scheduler_app,
}),
},
{
env = "Client",
Position = UDim2.fromScale(0.5, 0.5),
menus = source({
scheduler = scheduler_app,
performance = performance_app,
}),
},
})
local home_app_ui, performance_app_ui, server_app_ui, client_app_ui
return function(props: HomeProps)
home_app_ui = pebble.widget({
title = "Home",
subtitle = `v{props.version}`,
min_size = Vector2.new(230, 200),
bind_to_close = props.onClose,
pebble.container({
create("UIListLayout")({
Padding = UDim.new(0, 2),
VerticalFlex = Enum.UIFlexAlignment.SpaceEvenly,
HorizontalFlex = Enum.UIFlexAlignment.Fill,
}),
create("ScrollingFrame")({
-- Size = UDim2.fromScale(1, 1),
CanvasSize = UDim2.new(),
AutomaticCanvasSize = Enum.AutomaticSize.Y,
BackgroundTransparency = 1,
ScrollBarThickness = 6,
HorizontalScrollBarInset = Enum.ScrollBarInset.Always,
create("UIFlexItem")({
FlexMode = Enum.UIFlexMode.Fill,
}),
pebble.padding({
x = UDim.new(0, 1),
right = UDim.new(0, 8),
}),
create("UIListLayout")({
FillDirection = Enum.FillDirection.Horizontal,
HorizontalFlex = Enum.UIFlexAlignment.Fill,
Padding = UDim.new(0, 8),
Wraps = true,
}),
values(env_apps, function(value, key)
return pebble.pane({
name = "",
size = UDim2.fromOffset(200, 0),
automaticsize = Enum.AutomaticSize.Y,
create("UIListLayout")({
Padding = UDim.new(0, 8),
}),
pebble.typography({
text = value.env,
wrapped = true,
}),
values(value.menus, function(app_constructor, i)
local menu: string = i()
return pebble.button({
size = UDim2.new(1, 0, 0, 30),
text = menu,
activated = function()
if menu == "scheduler" then
if value.env == "Client" and client_app_ui then
pcall(client_app_ui)
client_app_ui = nil
elseif server_app_ui then
pcall(server_app_ui)
server_app_ui = nil
end
local newApp = spawn_app.spawn_app(app_constructor, {
env = value.env,
Position = value.Position,
ProfilerState = value.env == "Server" and props.Profiler.get_stored(
"server_frame_value"
) or props.Profiler.dump_state(),
Runtime = value.env == "Server"
and props.Profiler.get_stored("server_runtime"),
Pause = function()
if value.env == "Server" then
props.profiler_state:FireServer(false)
else
props.Profiler.Pause()
end
end,
Resume = function()
if value.env == "Server" then
props.profiler_state:FireServer(true)
else
props.Profiler.Resume()
end
end,
onClose = function()
if value.env == "Client" and client_app_ui then
pcall(client_app_ui)
client_app_ui = nil
elseif server_app_ui then
pcall(server_app_ui)
server_app_ui = nil
end
if
not client_app_ui
and not server_app_ui
and not performance_app_ui
and not home_app_ui
then
spawn_app.unmount_all()
props.onDestroy()
end
end,
})
if value.env == "Client" then
client_app_ui = newApp
else
server_app_ui = newApp
end
elseif menu == "performance" then
if performance_app_ui then
pcall(performance_app_ui)
performance_app_ui = nil
end
performance_app_ui = spawn_app.spawn_app(app_constructor, {
performanceData = props.Profiler.sockets_transcript(),
IsVisible = true,
onClose = function()
if performance_app_ui then
pcall(performance_app_ui)
performance_app_ui = nil
end
if
not client_app_ui
and not server_app_ui
and not performance_app_ui
and not home_app_ui
then
spawn_app.unmount_all()
props.onDestroy()
end
end,
})
end
end,
})
end),
})
end),
}),
}),
})
cleanup(home_app_ui)
return home_app_ui
end
| 1,244 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/ui/performance.luau | --!optimize 2
local vide = require("../../vide")
local pebble = require("../../pebble")
local Profiler = require("../profiler")
local create = vide.create
local source = vide.source
local values = vide.values
local cleanup = vide.cleanup
local function parse(data)
local columnDefinitions = {
{ key = "host", displayName = "Host" },
{ key = "memory", displayName = "Memory Usage" },
{ key = "cpu", displayName = "CPU" },
{ key = "frames", displayName = "FPS" },
{ key = "gpu", displayName = "GPU" },
{ key = "cpuRender", displayName = "CPU Render" },
}
local resultTable = {}
local columnMap = {}
for i, def in columnDefinitions do
resultTable[i] = { def.displayName }
columnMap[def.key] = i
end
for _, record in data do
for _, def in columnDefinitions do
local key: string = def.key
local value = record[key]
local columnIndex: number = columnMap[key]
if columnIndex and value ~= nil then
table.insert(resultTable[columnIndex], value)
end
end
end
return resultTable
end
return function(props)
local performanceData = source(parse(props.performanceData))
Profiler.onSocketChanged:disconnectAll()
cleanup(Profiler.onSocketChanged:connect(function()
local parse = parse(Profiler.sockets_transcript())
performanceData(parse)
end))
return pebble.widget({
title = "Performance",
min_size = Vector2.new(450, 250),
size = Vector2.new(550, 250),
bind_to_close = props.onClose,
pebble.container({
Size = UDim2.fromScale(1, 1),
create("UIFlexItem")({
FlexMode = Enum.UIFlexMode.Fill,
}),
pebble.tablesheet({
size = UDim2.fromScale(1, 1),
column_sizes = source({ 100, 80, 100, 200 }),
read_value = function(column, row)
local value = performanceData()[column][row]
return value and value or ""
end,
on_click = function() end,
on_click2 = function() end,
columns = performanceData,
}),
}),
})
end
| 516 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/ui/scheduler.luau | --!optimize 2
local vide = require("../../vide")
local pebble = require("../../pebble")
local stack_bar = require("./stack_bar")
local convert_scale = require("../util/convert_scale")
type SchedulerProps = {
env: string,
Position: UDim2,
ProfilerState: () -> { any },
Runtime: string?,
Pause: () -> (),
Resume: () -> (),
onClose: () -> (),
}
local create = vide.create
local source = vide.source
local derive = vide.derive
local indexes = vide.indexes
local action = vide.action
local cleanup = vide.cleanup
local effect = vide.effect
local function changed(property: string, fn: (...any) -> ())
return action(function(instance)
local cn = instance:GetPropertyChangedSignal(property):Connect(function()
fn(instance[property])
end)
cleanup(function()
cn:Disconnect()
end)
end)
end
local sort_by_options = {
"Name",
"Frame Time",
}
return function(props: SchedulerProps)
local selected: (number?) -> number = source(0)
local sort_by: (number?) -> number = source(2)
-- Derived state for total runtime
local totalRuntime: () -> number = derive(function()
local total: number = 0
for _, system in props.ProfilerState() do
total += system.Duration
end
return total
end)
local function assign_frame(value_accessor, index)
local gui_state = source(Enum.GuiState.Idle)
local _frame: Frame
local b = create("ImageButton")({
Name = function()
return value_accessor().Name
end,
Size = UDim2.new(1, 0, 0, 32),
LayoutOrder = function()
return 1e9 - value_accessor().Duration * 1e8
end,
BackgroundColor3 = function()
return if gui_state() == Enum.GuiState.Press
then pebble.theme.bg[-1]()
elseif gui_state() == Enum.GuiState.Hover then pebble.theme.bg[6]()
else pebble.theme.bg[3]()
end,
Visible = true,
changed("GuiState", gui_state),
MouseButton2Click = function()
props.Pause()
end,
create("Folder")({
(function()
_frame = create("Frame")({
Position = UDim2.new(0, 0, 1, 4),
AnchorPoint = Vector2.new(0, 1),
Size = function()
return UDim2.new(value_accessor().Duration / totalRuntime(), 0, 0, 1)
end,
BackgroundColor3 = pebble.theme.fg_on_bg_high[0],
})
return _frame
end)(),
effect(function()
if not _frame then
return
end
_frame.Size = UDim2.new(value_accessor().Duration / totalRuntime(), 0, 0, 1)
end),
}),
create("UIStroke")({
Color = pebble.theme.bg[-3],
}),
create("UICorner")({
CornerRadius = UDim.new(0, 4),
}),
create("UIListLayout")({
FillDirection = Enum.FillDirection.Horizontal,
VerticalAlignment = Enum.VerticalAlignment.Center,
HorizontalFlex = Enum.UIFlexAlignment.SpaceEvenly,
Padding = UDim.new(0, 8),
}),
pebble.padding({
x = UDim.new(0, 8),
}),
create("Frame")({
Size = UDim2.fromOffset(16, 16),
AnchorPoint = Vector2.new(0.5, 0.5),
BackgroundColor3 = function()
return value_accessor().Color
end,
create("UICorner")({
CornerRadius = UDim.new(1, 0),
}),
}),
pebble.typography({
automaticsize = Enum.AutomaticSize.None,
text = function()
return value_accessor().Name
end,
truncate = Enum.TextTruncate.SplitWord,
xalignment = Enum.TextXAlignment.Left,
disabled = false,
create("UIFlexItem")({
FlexMode = Enum.UIFlexMode.Fill,
GrowRatio = 1,
ShrinkRatio = 1,
}),
}),
pebble.typography({
automaticsize = Enum.AutomaticSize.XY,
text = function()
return convert_scale("s", value_accessor().Duration)
end,
xalignment = Enum.TextXAlignment.Right,
disabled = true,
}),
})
cleanup(b)
return b
end
return pebble.widget({
title = "Scheduler",
subtitle = `host: {props.env}`,
min_size = Vector2.new(200, 300),
bind_to_close = props.onClose,
create("Frame")({
Name = "Elements",
Size = UDim2.fromScale(1, 1),
AutomaticSize = Enum.AutomaticSize.Y,
BackgroundTransparency = 1,
create("UIListLayout")({
VerticalAlignment = Enum.VerticalAlignment.Bottom,
FillDirection = Enum.FillDirection.Vertical,
VerticalFlex = Enum.UIFlexAlignment.SpaceBetween,
Padding = UDim.new(0, 8),
}),
create("Frame")({
Size = UDim2.fromScale(1, 0),
AutomaticSize = Enum.AutomaticSize.Y,
BackgroundTransparency = 1,
pebble.pane({
name = "Overview",
size = UDim2.fromScale(1, 0),
create("UIListLayout")({
FillDirection = Enum.FillDirection.Vertical,
}),
pebble.typography({
text = props.Runtime and function()
return `Runtime: {props.Runtime}`
end or function()
local time: number = totalRuntime()
return `Run time: {convert_scale("s", time)}`
end,
}),
stack_bar({
values = props.ProfilerState,
selected = selected,
}),
pebble.row({
justifycontent = Enum.UIFlexAlignment.Fill,
pebble.button({
text = "Pause all",
activated = props.Pause,
}),
pebble.button({
text = "Resume all",
activated = props.Resume,
}),
}),
}),
}),
pebble.select({
size = UDim2.new(1, 0, 0, 30),
options = sort_by_options,
selected = sort_by,
update_selected = function(new: number)
sort_by(new)
end,
}),
create("ScrollingFrame")({
Name = "Systems",
Size = UDim2.fromScale(1, 0),
CanvasSize = UDim2.new(),
AutomaticCanvasSize = Enum.AutomaticSize.Y,
BackgroundTransparency = 1,
ScrollBarThickness = 6,
VerticalScrollBarInset = Enum.ScrollBarInset.Always,
ScrollBarImageColor3 = pebble.theme.fg_on_bg_low[3],
create("UIFlexItem")({
FlexMode = Enum.UIFlexMode.Fill,
}),
create("UIListLayout")({
FillDirection = Enum.FillDirection.Vertical,
Padding = UDim.new(0, 8),
SortOrder = function()
return if sort_by() == 1 then Enum.SortOrder.Name else Enum.SortOrder.LayoutOrder
end,
}),
pebble.padding({
y = UDim.new(0, 1),
x = UDim.new(0, 1),
}),
indexes(props.ProfilerState, assign_frame),
}),
}),
})
end
| 1,742 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/ui/spawn_app.luau | -- by jabby
--!strict
--!optimize 2
local Players = game:GetService("Players")
local vide = require("../../vide")
local destroy_fn: { [() -> ()]: boolean } = {}
local function unmount_all()
for destroy in destroy_fn do
destroy()
end
table.clear(destroy_fn)
end
local function spawn_app<T>(app, props: T): () -> ()
return vide.root(function(destroy)
local destroy = function()
destroy_fn[destroy] = nil
pcall(destroy)
end
local application = app(props)
application.Parent = Players.LocalPlayer.PlayerGui
vide.cleanup(application)
destroy_fn[destroy] = true
return destroy
end)
end
return {
unmount_all = unmount_all,
spawn_app = spawn_app,
}
| 179 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/ui/stack_bar.luau | --!optimize 2
local vide = require("../../vide")
local create = vide.create
local indexes = vide.indexes
local derive = vide.derive
type stack_bar = {
values: () -> { { Name: string, Color: Color3, Size: UDim2, Duration: number } },
selected: (index: number) -> (),
}
return function(props: stack_bar)
local total: () -> number = derive(function()
local total: number = 0
for _, value in props.values() do
total += value.Duration
end
return total
end)
return create("Frame")({
Name = "Graph",
Size = UDim2.new(1, 0, 0, 32),
indexes(props.values, function(value, index)
return create("Frame")({
Size = function()
local duration = value().Duration
local totalDuration = total()
if totalDuration == 0 then
return UDim2.fromScale(0, 1)
end
return UDim2.fromScale(duration / totalDuration, 1)
end,
BackgroundColor3 = function()
return value().Color
end,
MouseEnter = function()
props.selected(index)
end,
})
end),
create("UIListLayout")({
FillDirection = Enum.FillDirection.Horizontal,
}),
})
end
| 299 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/Enums.luau | --!optimize 2
--[[
## made by anexpia •…• ##
assigns values to specific bytes so that they can be encoded
this is mainly for sending values that cannot be encoded from server to client
like newproxy() objects, or other unique values like tables that you want to be the same everytime
they're sent in a remote.
you probably don't need to use this most of the time, but the option exists and its helpful when
its actually needed
]]
local RS = game:GetService("RunService")
local Settings = require(script.Parent.Settings)
local SyncingEnabled = Settings.serverclientsyncing
local IsSyncOrigin = if SyncingEnabled then RS:IsServer() else true
local nametovalue: {[string]: any} = {}
local bytetovalue: {[number]: any} = {
[2] = true,
[3] = false,
[102] = "",
[103] = 0,
[104] = 1,
[105] = -1,
[106] = math.huge,
[107] = -math.huge,
[108] = 0 / 0,
}
local valuetobyte: {[any]: number} = {
[true] = 2,
[false] = 3,
[""] = 102,
[0] = 103,
[1] = 104,
[-1] = 105,
[math.huge] = 106,
[-math.huge] = 107,
-- no nan since nan will error if in table
}
local freebytes
local currentposition = 0
local function sanitizename(name)
if type(name) ~= "string" then
error(`expected name to be a string, got {typeof(name)}`, 0)
end
if name == "" then
error("name should not be an empty string", 0)
end
return string.gsub(name, "[^%w_]", "_") -- turn everything that isnt %w and _ into _
end
-- Removes the value associated with 'name' from byte registry.
local function removename(name: string)
name = sanitizename(name)
local value = nametovalue[name]
if value then
local oldbyte = valuetobyte[value]
valuetobyte[value] = nil
if bytetovalue[oldbyte] == value then
bytetovalue[oldbyte] = nil
end
if IsSyncOrigin then
table.insert(freebytes, oldbyte)
nametovalue[name] = nil -- not done on client because this is called whenever the attribute is changed, and current value is needed
if SyncingEnabled then
script:SetAttribute(name, nil)
end
end
end
end
if not IsSyncOrigin then
local function attributechanged(name, byte)
removename(name)
byte = byte or script:GetAttribute(name)
if byte then
local value = nametovalue[name]
if not value then
value = newproxy()
nametovalue[name] = value
end
valuetobyte[value] = byte
bytetovalue[byte] = value
else
nametovalue[name] = nil
end
end
script.AttributeChanged:Connect(attributechanged)
for name, value in script:GetAttributes() do
attributechanged(name, value)
end
else
freebytes = {}
end
return {
bytetovalue = bytetovalue,
nametovalue = nametovalue,
valuetobyte = valuetobyte,
--[[
Assigns 2 bytes to the name and returns the value that is encoded as the byte.
Registered names are synced from server to client.
]]
register = function(name: string, predefined: any?): any
name = sanitizename(name)
if valuetobyte[predefined] then
error(`cannot define {name} with the value {predefined} as the value is already defined`, 0)
end
if nametovalue[name] then
if predefined then
local oldvalue = nametovalue[name]
local byte = valuetobyte[oldvalue]
nametovalue[name] = predefined
if byte then
valuetobyte[oldvalue] = nil
valuetobyte[predefined] = byte
bytetovalue[byte] = predefined
end
end
return nametovalue[name]
end
local v = predefined or newproxy()
if IsSyncOrigin then
local byte = table.remove(freebytes)
if not byte then
byte = currentposition - 1
currentposition = byte
end
nametovalue[name] = v
valuetobyte[v] = byte
bytetovalue[byte] = v
if SyncingEnabled then
script:SetAttribute(name, byte)
end
else
nametovalue[name] = v
end
return v
end,
remove = removename,
}
| 1,131 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/Miscellaneous/floatencoder.luau | --!native
--!optimize 2
--!strict
-- read float16 number from buffer
local function readf16(buff: buffer, cursor: number): number
local n: number = buffer.readu16(buff, cursor)
local mantissa: number, exponent: number, sign: number = bit32.extract(n, 0, 10),
bit32.extract(n, 10, 5),
bit32.extract(n, 15, 1)
if mantissa == 0b0000000000 then
if exponent == 0b00000 then return 0
elseif exponent == 0b11111 then
return if sign == 1 then -math.huge else math.huge
end
elseif exponent == 0b11111 then return 0/0 end
local value: number = ((mantissa / 1024) + 1) * 2 ^ (exponent - 15)
if sign == 1 then return -value end
return value
end
-- write number as float16 into buffer
local function writef16(buff: buffer, cursor: number, value: number): ()
if value == 0 then buffer.writeu16(buff, cursor, 0)
elseif value >= 65520 then buffer.writeu16(buff, cursor, 0b0_11111_0000000000)
elseif value <= -65520 then buffer.writeu16(buff, cursor, 0b1_11111_0000000000)
elseif value ~= value then buffer.writeu16(buff, cursor, 0b0_11111_0000000001)
else
local sign: number = 0
if value < 0 then
sign = 1
value = -value
end
local mantissa: number, exponent: number = math.frexp(value)
if exponent < -14 then -- safeguard against tiny exponents like -20
buffer.writeu16(buff, cursor, 0)
return
end
buffer.writeu16(buff, cursor, bit32.bor((mantissa * 2048 - 1023.5), (exponent + 14) * 2^10, (sign) * 2^15))
end
end
return {
writef16 = writef16;
readf16 = readf16;
}
| 503 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/Miscellaneous/init.luau | --!native
--!optimize 2
-- quaternion stuff from https://devforum.roblox.com/t/introducing-luau-buffer-type-beta/2724894/105?u=anexpia
-- modified a bit to be more performant when encoding
local Types = require(script.Parent.Types)
local floatencoder = require(script.floatencoder)
local FP_EPSILON = 1e-6
local I16_PRECISION = 32767 -- int16 range { -32,786, 32,767 }
local BUFF_CFRAME_SIZE = (3*4) + (1 + 3*2) -- i.e. 3x f32, 1x u8 and 3x i16
local cframe_ToAxisAngle = CFrame.identity.ToAxisAngle
local function getNormalisedQuaternion(cframe: CFrame)
local axis_shadowed, angle = cframe_ToAxisAngle(cframe)
local ha = angle / 2
local axis: vector = if vector.magnitude(axis_shadowed) > FP_EPSILON then vector.normalize(axis_shadowed) else (Vector3.xAxis :: any)
axis *= math.sin(ha)
local w = math.cos(ha)
local length = math.sqrt(vector.dot(axis, axis) + w*w)
if length < FP_EPSILON then
return 0, 0, 0, 1
end
axis /= length
return axis.x, axis.y, axis.z, w / length
end
local function compressQuaternion(cframe)
local qx, qy, qz, qw = getNormalisedQuaternion(cframe)
local index = -1
local value = -math.huge
local sign
for i = 1, 4, 1 do
local val = select(i, qx, qy, qz, qw)
local abs = math.abs(val)
if abs > value then
index = i
value = abs
sign = val
end
end
sign = sign >= 0 and 1 or -1
local v0, v1, v2
if index == 1 then
v0 = math.floor(qy * sign * I16_PRECISION + 0.5)
v1 = math.floor(qz * sign * I16_PRECISION + 0.5)
v2 = math.floor(qw * sign * I16_PRECISION + 0.5)
elseif index == 2 then
v0 = math.floor(qx * sign * I16_PRECISION + 0.5)
v1 = math.floor(qz * sign * I16_PRECISION + 0.5)
v2 = math.floor(qw * sign * I16_PRECISION + 0.5)
elseif index == 3 then
v0 = math.floor(qx * sign * I16_PRECISION + 0.5)
v1 = math.floor(qy * sign * I16_PRECISION + 0.5)
v2 = math.floor(qw * sign * I16_PRECISION + 0.5)
elseif index == 4 then
v0 = math.floor(qx * sign * I16_PRECISION + 0.5)
v1 = math.floor(qy * sign * I16_PRECISION + 0.5)
v2 = math.floor(qz * sign * I16_PRECISION + 0.5)
end
return index, v0, v1, v2
end
local function decompressQuaternion(index, v0, v1, v2)
v0 /= I16_PRECISION
v1 /= I16_PRECISION
v2 /= I16_PRECISION
local d = math.sqrt(1 - (v0*v0 + v1*v1 + v2*v2))
if index == 1 then
return d, v0, v1, v2
elseif index == 2 then
return v0, d, v1, v2
elseif index == 3 then
return v0, v1, d, v2
end
return v0, v1, v2, d
end
local function write(buf: buffer, offset: number, input: CFrame)
local pos = input.Position
buffer.writef32(buf, offset, pos.X)
buffer.writef32(buf, offset + 4, pos.Y)
buffer.writef32(buf, offset + 8, pos.Z)
local qi, q0, q1, q2 = compressQuaternion(input)
buffer.writeu8(buf, offset + 12, qi)
buffer.writei16(buf, offset + 13, q0)
buffer.writei16(buf, offset + 15, q1)
buffer.writei16(buf, offset + 17, q2)
end
local function read(buf: buffer, byte: number, offset: number, info: Types.ReadSettings): (CFrame, number)
local x = buffer.readf32(buf, offset)
local y = buffer.readf32(buf, offset + 4)
local z = buffer.readf32(buf, offset + 8)
if info.sanitize_nanandinf then
if (x / x) ~= 1 then x = 0 end
if (y / y) ~= 1 then y = 0 end
if (z / z) ~= 1 then z = 0 end
end
local qi = buffer.readu8(buf, offset + 12)
local q0 = buffer.readi16(buf, offset + 13)
local q1 = buffer.readi16(buf, offset + 15)
local q2 = buffer.readi16(buf, offset + 17)
local qx, qy, qz, qw = decompressQuaternion(qi, q0, q1, q2)
return CFrame.new(x, y, z, qx, qy, qz, qw), offset + BUFF_CFRAME_SIZE
end
return {
readCFrame = read,
writeCFrame = write,
cframesize = BUFF_CFRAME_SIZE,
writef16 = floatencoder.writef16;
readf16 = floatencoder.readf16;
} | 1,298 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/RbxEnumEncoder.luau | --!optimize 2
--[[
## made by anexpia •…• ##
]]
local RS = game:GetService("RunService")
local Settings = require(script.Parent.Settings)
local SyncingEnabled = Settings.serverclientsyncing
local enumitem_to_type = {}
local enumitem_to_value = {}
local exposed = {
enumitem_to_type = enumitem_to_type;
enumitem_to_value = enumitem_to_value;
compact = {},
full = {},
}
for _, enum in Enum:GetEnums() do
local n = tostring(enum)
enumitem_to_type[enum] = n
for _, enumitem in enum:GetEnumItems() do
enumitem_to_type[enumitem] = n
enumitem_to_value[enumitem] = enumitem.Value
end
end
do
-- encode enums as <19> <u8 length> <string>
-- encode enumitems as <20> <u8 length> <string> <u16 value>
local full = exposed.full
local nametoenum = {}
for _, v in Enum:GetEnums() do
nametoenum[tostring(v)] = v
end
-- this is to avoid erroring due to version mismatch when decoding
local enum_FromValue = (Enum.Material :: any).FromValue
@native
function full.encodeEnum(buf: buffer, offset: number, enum: Enum): number
local name = enumitem_to_type[enum]
local length = #name
buffer.writeu8(buf, offset, length); offset += 1
buffer.writestring(buf, offset, name)
return offset + length
end
@native
function full.encodeEnumItem(buf: buffer, offset: number, enumitem: EnumItem): number
offset = full.encodeEnum(buf, offset, enumitem :: any)
buffer.writeu16(buf, offset, enumitem_to_value[enumitem])
return offset + 2
end
@native
function full.decodeEnum(buf: buffer, byte: number, cursor: number): (Enum, number, boolean?)
local length = buffer.readu8(buf, cursor); cursor += 1
local name = buffer.readstring(buf, cursor, length)
return nametoenum[name], cursor + length, true
end
@native
function full.decodeEnumItem(buf: buffer, byte: number, cursor: number): (EnumItem, number, boolean?)
local enum, newcursor = full.decodeEnum(buf, byte, cursor)
local value = buffer.readu16(buf, newcursor)
return enum and enum_FromValue(enum, value), newcursor + 2, true
end
end
do
-- encode enums as <19> <u16 index>
-- encode enumitems as <20> <u16 index>
-- syncing table between client & server is necessary to avoid issues due to version mismatch
local enumarray: { Enum } = {}
local enumitemarray: { EnumItem } = {}
local valuelookup: { [any]: number } = {}
local compact = exposed.compact
local IsSyncOrigin = if SyncingEnabled then RS:IsServer() else true
if IsSyncOrigin then
local tosend1, tosend2
if SyncingEnabled then
tosend1, tosend2 = {}, {}
local request: RemoteFunction = script:FindFirstChild("request")
if request == nil then
request = Instance.new("RemoteFunction")
request.Name = "request"
request.Parent = script
end
request.OnServerInvoke = function(player, v)
return tosend1, tosend2
end
end
do
-- using tostring on index because the enum/enumitem may not exist
-- which will lead to gaps getting created when syncing
local enum_i, enumitem_i = 0, 0
for _, k in Enum:GetEnums() do
enum_i += 1
enumarray[enum_i] = k
valuelookup[k] = enum_i
if tosend1 then tosend1[tostring(enum_i)] = k end
for _, v in k:GetEnumItems() do
enumitem_i += 1
enumitemarray[enumitem_i] = v
valuelookup[v] = enumitem_i
if tosend2 then tosend2[tostring(enumitem_i)] = v end
end
end
end
else
task.spawn(function()
local request = script:WaitForChild("request")
local function addtoarray(toarray, fromdict)
for k, v in fromdict do
k = tonumber(k)
toarray[k] = v
valuelookup[v] = k
end
end
while true do
local success, r1, r2 = pcall(request.InvokeServer, request)
if success and r1 and r2 then
addtoarray(enumarray, r1)
addtoarray(enumitemarray, r2)
break
else
task.wait(3)
end
end
end)
end
@native
function compact.encodeEnum(buf: buffer, offset: number, value: Enum): number
local position = valuelookup[value]
buffer.writeu16(buf, offset, position or 0)
return offset + 2
end
compact.encodeEnumItem = (compact.encodeEnum :: any) :: (buf: buffer, offset: number, value: EnumItem) -> number
@native
function compact.decodeEnum(buf: buffer, byte: number, cursor: number): (Enum, number)
local position = buffer.readu16(buf, cursor)
return enumarray[position], cursor + 2
end
@native
function compact.decodeEnumItem(buf: buffer, byte: number, cursor: number): (EnumItem, number)
local position = buffer.readu16(buf, cursor)
return enumitemarray[position], cursor + 2
end
end
function exposed.getBehaviorFromSetting(operationsettings): (typeof(exposed.full), "full" | "compact")
local value = operationsettings.rbxenum_behavior or Settings.rbxenum_behavior
local enumbehavior = exposed[value]
if enumbehavior == nil then
error(`{value} is an invalid value for rbx_enumbehavior, options are 'full' / 'compact'`, 0)
end
return enumbehavior, value
end
return exposed
| 1,388 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/Read.luau | --!native
--!optimize 2
--!nolint LocalShadow
--[[ ## made by anexpia •…• ## ]]
local Encoder = script.Parent
local Datatypes = require(Encoder.ReadDatatypes)
local RbxEnumEncoder = require(Encoder.RbxEnumEncoder)
local Settings = require(Encoder.Settings)
local Types = require(Encoder.Types)
type ReadSettings = Types.ReadSettings
local defaultwritingtable = {}
--[[
Decodes the buffer created by encoder.write()
<em>param</em> - buff : the buffer to decode
<em>param</em> - readstart : reading starts from the offset given.
<em>param</em> - readsettings : {
. <strong>allowdeduplication: boolean</strong> -- if the buffer was written with deduplication enabled
. <strong>references: {any}</strong> -- table of values that couldn't be encoded which is returned by encoder.write()
. <strong>shiftseed: number</strong> -- the type bytes of values are unshuffled using the seed.
. <strong>rbxenum_behavior: "full" | "compact"</strong> -- override for the default setting.
. <strong>sanitize_nanandinf: boolean</strong> -- override for the default setting.
}
]]
return function(buff: buffer, readstart: number?, readsettings: ReadSettings?): { [any]: any }
local readsettings: ReadSettings = readsettings or Settings
local shiftseed = readsettings.shiftseed
local dedupenabled = readsettings.allowdeduplication
local cursor = readstart or 0
local isdoingdeduplication_old = false
do
local firstbyte = buffer.readu8(buff, cursor)
if shiftseed then
math.randomseed(shiftseed)
firstbyte = (firstbyte - math.random(1, 127)) % 128
math.randomseed(shiftseed)
end
if firstbyte == 101 then
return {}
elseif firstbyte > 1 then
error(`expected '0', '1', or '101' for first byte, got {firstbyte}`)
end
isdoingdeduplication_old = firstbyte == 0
if isdoingdeduplication_old then dedupenabled = false end
end
local enumbehavior = RbxEnumEncoder.getBehaviorFromSetting(readsettings)
local sanitize_nanandinf = readsettings.sanitize_nanandinf
if sanitize_nanandinf == nil then sanitize_nanandinf = Settings.sanitize_nanandinf end
Datatypes.adjustforsettings(enumbehavior, sanitize_nanandinf)
local deduplicationindex = 0
local deduplicationtable = if dedupenabled then {} else nil
local currenttable = {}
local maintable = currenttable
local writingtable = defaultwritingtable
local formedtables = {currenttable}
local formedcount = 0
local lastwasdictkey = false
local dictkey = nil
local currentindex = 0
local info: Types.decodeinfo = {
sanitize_nanandinf = sanitize_nanandinf,
references = readsettings.references,
deduplicationtable = deduplicationtable,
tables = formedtables,
}
while cursor <= (buffer.len(buff) - 1) do
local byte = buffer.readu8(buff, cursor)
cursor += 1
local isdictkey = byte > 127
if isdictkey then
byte = (255 - byte)
end
if shiftseed then
byte = (byte - math.random(1, 127)) % 128
end
local value: any, canbededuplicated: boolean?
local func = Datatypes[byte]
if func then
value, cursor, canbededuplicated = func(buff, byte, cursor, info)
elseif byte == 1 then
formedcount += 1
if currentindex > 0 then
table.move(writingtable, 1, currentindex, 1, currenttable)
currentindex = 0
end
currenttable = formedtables[formedcount]
if currenttable == nil then
currenttable = {}
formedtables[formedcount] = currenttable
end
lastwasdictkey = false
dictkey = nil
continue
elseif byte == 0 then
if isdoingdeduplication_old then
isdoingdeduplication_old = false
currenttable = {}
deduplicationtable = currenttable
info.deduplicationtable = deduplicationtable
continue
else
if shiftseed then math.randomseed(os.time()) end
if currentindex > 0 then
table.move(writingtable, 1, currentindex, 1, currenttable)
end
table.clear(writingtable)
return maintable
end
elseif byte == 101 then value = {}
elseif byte ~= 4 then -- not nil
error(`{byte} is not a type byte`)
end
if dedupenabled and canbededuplicated then
deduplicationindex += 1
deduplicationtable[deduplicationindex] = value
end
if lastwasdictkey then
lastwasdictkey = false
if dictkey ~= nil then
currenttable[dictkey] = value
dictkey = nil
end
elseif isdictkey then
dictkey = value
lastwasdictkey = true
else
currentindex += 1
writingtable[currentindex] = value
end
end
if shiftseed then math.randomseed(os.time()) end
error("buffer is not terminated with '0' byte", 0)
end
| 1,240 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/BrickColor.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
type datatypedecodinginfo = Types.datatypedecodinginfo
local brickcolorbyte = 30
return {
[brickcolorbyte] = @native function(buff: buffer, byte: number, cursor: number): (BrickColor, number)
return BrickColor.new(buffer.readu16(buff, cursor)), cursor + 2
end;
} :: datatypedecodinginfo | 127 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/CFrame.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
local Miscellaneous = require(Module.Miscellaneous)
type datatypedecodinginfo = Types.datatypedecodinginfo
local cframebyte = 17
return {
[cframebyte] = Miscellaneous.readCFrame
} :: datatypedecodinginfo | 97 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/Color3.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
local Miscellaneous = require(Module.Miscellaneous)
local color3always6bytes = Settings.color3always6bytes
local readf16 = Miscellaneous.readf16
type datatypedecodinginfo = Types.datatypedecodinginfo
local u8colorbyte = 23
local f16colorbyte = 24
local writebytesign
return {
[u8colorbyte] = @native function(buff: buffer, byte: number, cursor: number): (Color3, number)
local r, g, b = buffer.readu8(buff, cursor), buffer.readu8(buff, cursor + 1), buffer.readu8(buff, cursor + 2)
return Color3.fromRGB(r, g, b), cursor + 3
end;
[f16colorbyte] = @native function(buff: buffer, byte: number, cursor: number): (Color3, number)
local r, g, b = readf16(buff, cursor), readf16(buff, cursor + 2), readf16(buff, cursor + 4)
return Color3.new(r, g, b), cursor + 6
end;
} :: datatypedecodinginfo | 290 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/ColorSequence.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
type datatypedecodinginfo = Types.datatypedecodinginfo
local colorbyte = 25
local uI16_max = (2 ^ 16) - 1
return {
[colorbyte] = @native function(buff: buffer, byte: number, cursor: number): (ColorSequence, number)
local length = buffer.readu8(buff, cursor); cursor += 1
local tbl = table.create(length)
for i = 1, length do
local time = math.clamp(buffer.readu16(buff, cursor) / uI16_max, 0, 1)
local r, g, b = buffer.readu8(buff, cursor + 2), buffer.readu8(buff, cursor + 3), buffer.readu8(buff, cursor + 4); cursor += 5
tbl[i] = ColorSequenceKeypoint.new(time, Color3.fromRGB(r, g, b))
end
return ColorSequence.new(tbl), cursor
end;
} :: datatypedecodinginfo | 266 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/ContentAndFont.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
type datatypedecodinginfo = Types.datatypedecodinginfo
local contentbyte = 33
local fontbyte = 34
local writebytesign
local FromValue = (Enum.FontWeight :: any).FromValue -- localizing it to silence errors 😭
return {
[contentbyte] = @native function(buff: buffer, byte: number, cursor: number): (Content, number)
local length = buffer.readu8(buff, cursor); cursor += 1
if length == 0 then
return Content.none, cursor
elseif length == 1 then
local num = buffer.readf64(buff, cursor)
return Content.fromAssetId(num), cursor + 8
else
length -= 1
local uri = buffer.readstring(buff, cursor, length)
return Content.fromUri(uri), cursor + length
end
end;
[fontbyte] = @native function(buff: buffer, byte: number, cursor: number): (Font, number)
local length = buffer.readu8(buff, cursor); cursor += 1
if length == 0 then
local num = buffer.readf64(buff, cursor); cursor += 8
local weightv, stylev = buffer.readu16(buff, cursor), buffer.readu8(buff, cursor + 2)
return Font.fromId(num, FromValue(Enum.FontWeight, weightv), FromValue(Enum.FontStyle, stylev)), cursor + 3
else
length -= 1
local familyname = buffer.readstring(buff, cursor, length); cursor += length
if familyname == "" then familyname = "Arimo" end
local weightv, stylev = buffer.readu16(buff, cursor), buffer.readu8(buff, cursor + 2)
-- not using FromName because familyname can be empty
return Font.new(`rbxasset://fonts/families/{familyname}.json`, FromValue(Enum.FontWeight, weightv), FromValue(Enum.FontStyle, stylev)), cursor + 3
end
end;
} :: datatypedecodinginfo | 494 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/DateTime.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Types = require(Module.Types)
type datatypedecodinginfo = Types.datatypedecodinginfo
local datetimebyte = 35
return {
[datetimebyte] = @native function(buff: buffer, byte: number, cursor: number): (DateTime, number)
local unixmillis = buffer.readf64(buff, cursor)
return DateTime.fromUnixTimestampMillis(unixmillis), cursor + 8
end;
} :: datatypedecodinginfo | 129 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/NumberRange.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
type datatypedecodinginfo = Types.datatypedecodinginfo
local numberbyte = 21
local writebytesign
return {
[numberbyte] = @native function(buff: buffer, byte: number, cursor: number): (NumberRange, number)
local min = buffer.readf32(buff, cursor)
local max = buffer.readf32(buff, cursor + 4)
return NumberRange.new(min, max), cursor + 8
end;
} :: datatypedecodinginfo | 152 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/NumberSequence.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
local Miscellaneous = require(Module.Miscellaneous)
type datatypedecodinginfo = Types.datatypedecodinginfo
local readf16 = Miscellaneous.readf16
local numberbyte = 22
local writebytesign
local uI16_max = (2 ^ 16) - 1
return {
[numberbyte] = @native function(buff: buffer, byte: number, cursor: number): (NumberSequence, number)
local length = buffer.readu8(buff, cursor); cursor += 1
local tbl = table.create(length)
for i = 1, length do
local time = math.clamp(buffer.readu16(buff, cursor) / uI16_max, 0, 1)
local value = buffer.readf32(buff, cursor + 2)
local envelope = readf16(buff, cursor + 6); cursor += 8
tbl[i] = NumberSequenceKeypoint.new(time, value, envelope)
end
return NumberSequence.new(tbl), cursor
end;
} :: datatypedecodinginfo | 271 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/PhysicalProperties.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
type datatypedecodinginfo = Types.datatypedecodinginfo
local physpropsbyte = 29
local writebytesign
return {
[physpropsbyte] = @native function(buff: buffer, byte: number, cursor: number): (PhysicalProperties, number)
local Density = buffer.readf32(buff, cursor)
local Friction = buffer.readf32(buff, cursor + 4)
local Elasticity = buffer.readf32(buff, cursor + 8)
local FrictionWeight = buffer.readf32(buff, cursor + 12)
local ElasticityWeight = buffer.readf32(buff, cursor + 16)
return PhysicalProperties.new(Density, Friction, Elasticity, FrictionWeight, ElasticityWeight),
cursor + 20
end;
} :: datatypedecodinginfo | 220 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/Ray.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
type datatypedecodinginfo = Types.datatypedecodinginfo
local raybyte = 18
local writebytesign
return {
[raybyte] = @native function(buff: buffer, byte: number, cursor: number, info: Types.decodeinfo): (Ray, number)
local ox = buffer.readf32(buff, cursor); cursor += 4
local oy = buffer.readf32(buff, cursor); cursor += 4
local oz = buffer.readf32(buff, cursor); cursor += 4
local dx = buffer.readf32(buff, cursor); cursor += 4
local dy = buffer.readf32(buff, cursor); cursor += 4
local dz = buffer.readf32(buff, cursor); cursor += 4
if info.sanitize_nanandinf then
if (ox / ox) ~= 1 then ox = 0 end
if (oy / oy) ~= 1 then oy = 0 end
if (oz / oz) ~= 1 then oz = 0 end
if (dx / dx) ~= 1 then dx = 0 end
if (dy / dy) ~= 1 then dy = 0 end
if (dz / dz) ~= 1 then dz = 0 end
end
return Ray.new(Vector3.new(ox, oy, oz), Vector3.new(dx, dy, dz)), cursor
end;
} :: datatypedecodinginfo | 357 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/Rect.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
type datatypedecodinginfo = Types.datatypedecodinginfo
local rectbyte = 28
local writebytesign
return {
[rectbyte] = @native function(buff: buffer, byte: number, cursor: number): (Rect, number)
local xmin = buffer.readf32(buff, cursor)
local ymin = buffer.readf32(buff, cursor + 4)
local xmax = buffer.readf32(buff, cursor + 8)
local ymax = buffer.readf32(buff, cursor + 12)
return Rect.new(xmin, ymin, xmax, ymax), cursor + 16
end;
} :: datatypedecodinginfo | 185 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/UDim.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
type datatypedecodinginfo = Types.datatypedecodinginfo
local udimbyte = 26
local writebytesign
return {
[udimbyte] = @native function(buff: buffer, byte: number, cursor: number): (UDim, number)
local scale = buffer.readf32(buff, cursor)
local offset = buffer.readi32(buff, cursor + 4)
return UDim.new(scale, offset), cursor + 8
end;
} :: datatypedecodinginfo | 154 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/UDim2.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
type datatypedecodinginfo = Types.datatypedecodinginfo
local udim2byte = 27
local writebytesign
return {
[udim2byte] = @native function(buff: buffer, byte: number, cursor: number): (UDim2, number)
local xscale = buffer.readf32(buff, cursor)
local xoffset = buffer.readi32(buff, cursor + 4)
local yscale = buffer.readf32(buff, cursor + 8)
local yoffset = buffer.readi32(buff, cursor + 12)
return UDim2.new(xscale, xoffset, yscale, yoffset), cursor + 16
end;
} :: datatypedecodinginfo | 201 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/Vector2.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
type datatypedecodinginfo = Types.datatypedecodinginfo
local vectorbyte = 16
local vectorint16byte = 32
local writebytesign
return {
[vectorbyte] = @native function(buff: buffer, byte: number, cursor: number, info: Types.decodeinfo): (Vector2, number)
local x = buffer.readf32(buff, cursor)
local y = buffer.readf32(buff, cursor + 4)
if info.sanitize_nanandinf then
if (x / x) ~= 1 then x = 0 end
if (y / y) ~= 1 then y = 0 end
end
return Vector2.new(x, y), cursor + 8
end;
[vectorint16byte] = @native function(buff: buffer, byte: number, cursor: number): (Vector2int16, number)
local x = buffer.readi16(buff, cursor)
local y = buffer.readi16(buff, cursor + 2)
return Vector2int16.new(x, y), cursor + 4
end;
} :: datatypedecodinginfo | 291 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/Vector3.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
type datatypedecodinginfo = Types.datatypedecodinginfo
local vectorbyte = 15
local vectorint16byte = 31
local writebytesign
return {
[vectorbyte] = @native function(buff: buffer, byte: number, cursor: number, info: Types.decodeinfo): (vector, number, boolean?)
local x = buffer.readf32(buff, cursor)
local y = buffer.readf32(buff, cursor + 4)
local z = buffer.readf32(buff, cursor + 8)
-- need to check if deduplication is possible as if nan exists, the vector
-- cannot be deduplicated during writing process, thus would cause value positions to get shifted
local candeduplicate = x == x and y == y and z == z
if info.sanitize_nanandinf then
if (x / x) ~= 1 then x = 0 end
if (y / y) ~= 1 then y = 0 end
if (z / z) ~= 1 then z = 0 end
end
return vector.create(x, y, z), cursor + 12, candeduplicate
end;
[vectorint16byte] = @native function(buff: buffer, byte: number, cursor: number): (Vector3int16, number)
local x = buffer.readi16(buff, cursor)
local y = buffer.readi16(buff, cursor + 2)
local z = buffer.readi16(buff, cursor + 4)
return Vector3int16.new(x, y, z), cursor + 6
end;
} :: datatypedecodinginfo | 402 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/buffer.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
type datatypedecodinginfo = Types.datatypedecodinginfo
local bufferu8byte = 12
local bufferu16byte = 13
local bufferu32byte = 14
@native
local function readbuffer(buff: buffer, byte: number, cursor: number, info: Types.decodeinfo): (buffer, number)
local length
if byte == bufferu8byte then length = buffer.readu8(buff, cursor); cursor += 1
elseif byte == bufferu16byte then length = buffer.readu16(buff, cursor); cursor += 2
else length = buffer.readu32(buff, cursor); cursor += 4 end
local value = buffer.create(length)
buffer.copy(value, 0, buff, cursor, length)
return value, cursor + length
end
return {
[bufferu8byte] = readbuffer;
[bufferu16byte] = readbuffer;
[bufferu32byte] = readbuffer;
} :: datatypedecodinginfo | 262 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/init.luau | --[[
## made by anexpia •…• ##
originally this also had write functions for each datatype
but i found that it was slower than having if conditions
so now it only contains read functions and thats it
]]
local bytetofunction = {}
local bytetodatatype = {}
for _, t in script:GetChildren() do
local name = t.Name
if t.Name == "template" then continue end
for num, func in require(t) do
if bytetodatatype[num] then
warn(`The modules {name} and {bytetodatatype[num]} are using the same byte {num}`)
continue
end
bytetofunction[num] = func
bytetodatatype[num] = name
end
end
table.clear(bytetodatatype)
bytetodatatype = nil :: any
local enumbyte = 19
local enumitembyte = 20
-- math.huge -math.huge nan
local f106, f107, f108 = bytetofunction[106], bytetofunction[107], bytetofunction[108]
local f103 = bytetofunction[103] -- returns 0
function bytetofunction.adjustforsettings(enumbehavior, sanitize_nanandinf: boolean?)
bytetofunction[enumbyte] = enumbehavior.decodeEnum
bytetofunction[enumitembyte] = enumbehavior.decodeEnumItem
if sanitize_nanandinf then
for i = 106, 108 do
bytetofunction[i] = f103
end
else
bytetofunction[106], bytetofunction[107], bytetofunction[108] = f106, f107, f108
end
end
return bytetofunction
| 389 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/number.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
local Enums = require(Module.Enums)
type datatypedecodinginfo = Types.datatypedecodinginfo
local u8numbyte = 5
local n_u8numbyte = 8
local u16numbyte = 6
local n_u16numbyte = 9
local u32numbyte = 7
local n_u32numbyte = 10
local floatnumbyte = 11
local t = {
[u8numbyte] = @native function(buff: buffer, byte: number, cursor: number): (number, number, boolean?)
return buffer.readu8(buff, cursor), cursor + 1
end;
[n_u8numbyte] = @native function(buff: buffer, byte: number, cursor: number): (number, number, boolean?)
return -buffer.readu8(buff, cursor), cursor + 1
end;
[u16numbyte] = @native function(buff: buffer, byte: number, cursor: number): (number, number, boolean?)
return buffer.readu16(buff, cursor), cursor + 2, true
end;
[n_u16numbyte] = @native function(buff: buffer, byte: number, cursor: number): (number, number, boolean?)
return -buffer.readu16(buff, cursor), cursor + 2, true
end;
[u32numbyte] = @native function(buff: buffer, byte: number, cursor: number): (number, number, boolean?)
return buffer.readu32(buff, cursor), cursor + 4, true
end;
[n_u32numbyte] = @native function(buff: buffer, byte: number, cursor: number): (number, number, boolean?)
return -buffer.readu32(buff, cursor), cursor + 4, true
end;
[floatnumbyte] = @native function(buff: buffer, byte: number, cursor: number): (number, number, boolean?)
return buffer.readf64(buff, cursor), cursor + 8, true
end
}
return t | 476 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/string.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
type datatypedecodinginfo = Types.datatypedecodinginfo
local stringu8byte = 54
local stringu16byte = 55
local stringu32byte = 56
local writebytesign
return {
[stringu8byte] = @native function(buff: buffer, byte: number, cursor: number): (string, number, boolean?)
local length = buffer.readu8(buff, cursor); cursor += 1
return buffer.readstring(buff, cursor, length), cursor + length, true
end;
[stringu16byte] = @native function(buff: buffer, byte: number, cursor: number): (string, number, boolean?)
local length = buffer.readu16(buff, cursor); cursor += 2
return buffer.readstring(buff, cursor, length), cursor + length, true
end;
[stringu32byte] = @native function(buff: buffer, byte: number, cursor: number): (string, number, boolean?)
local length = buffer.readu32(buff, cursor); cursor += 4
return buffer.readstring(buff, cursor, length), cursor + length, true
end;
} :: datatypedecodinginfo | 296 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/table_and_deduplicate.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local ByteToValue = require(Module.Enums).bytetovalue
local Types = require(Module.Types)
type datatypedecodinginfo = Types.datatypedecodinginfo
local tblu8byte = 51
local tblu16byte = 52
local tblu32byte = 53
local dedupu8byte = 57
local dedupu16byte = 58
local dedupu32byte = 59
local referenceu8byte = 60
local referenceu16byte = 61
local referenceu32byte = 62
local customvaluebyte = 99
@native
local function readtable(buff: buffer, byte: number, cursor: number, info: Types.decodeinfo)
local index
if byte == tblu8byte then index = buffer.readu8(buff, cursor); cursor += 1
elseif byte == tblu16byte then index = buffer.readu16(buff, cursor); cursor += 2
else index = buffer.readu32(buff, cursor); cursor += 4 end
local formedtables = info.tables
local f = formedtables[index]
if f then return f, cursor
else
local value = {}
formedtables[index] = value
return value, cursor
end
end
@native
local function readdeduplicate(buff: buffer, byte: number, cursor: number, info: Types.decodeinfo)
local index
if byte == dedupu8byte then index = buffer.readu8(buff, cursor); cursor += 1
elseif byte == dedupu16byte then index = buffer.readu16(buff, cursor); cursor += 2
else index = buffer.readu32(buff, cursor); cursor += 4 end
return info.deduplicationtable[index], cursor
end
@native
local function readreference(buff: buffer, byte: number, cursor: number, info: Types.decodeinfo)
local index
if byte == referenceu8byte then index = buffer.readu8(buff, cursor); cursor += 1
elseif byte == referenceu16byte then index = buffer.readu16(buff, cursor); cursor += 2
else index = buffer.readu32(buff, cursor); cursor += 4 end
local references = info.references
if references then
return references[index], cursor
else
error('Missing references table when decoding buffer that contains value references.')
end
end
local t = {
[tblu8byte] = readtable;
[tblu16byte] = readtable;
[tblu32byte] = readtable;
[dedupu8byte] = readdeduplicate;
[dedupu16byte] = readdeduplicate;
[dedupu32byte] = readdeduplicate;
[referenceu8byte] = readreference;
[referenceu16byte] = readreference;
[referenceu32byte] = readreference;
[customvaluebyte] = @native function(buff: buffer, byte: number, cursor: number)
return ByteToValue[-buffer.readu8(buff, cursor)], cursor + 1
end,
} :: datatypedecodinginfo
-- doing those here so theres no cost for indexing ByteToValue
for byte, v in ByteToValue do
if byte > 0 then
-- this runs somehow faster with native .... ok i guess
t[byte] = @native function(buff, byte, cursor) return v, cursor end
end
end
return t | 792 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/ReadDatatypes/template.luau | --!nolint LocalUnused
--!nolint ImportUnused
--!optimize 2
local Module = script.Parent.Parent
local Settings = require(Module.Settings)
local Types = require(Module.Types)
type datatypedecodinginfo = Types.datatypedecodinginfo
local templatebyte = -1
local writebytesign
return {
[templatebyte] = @native function(buff: buffer, byte: number, cursor: number): (any, number, boolean?)
error('Byte read function should be changed for the template.', 0)
end;
} :: datatypedecodinginfo | 128 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/Settings.luau | local Encoder = script.Parent
-- explanation for each of the settings exists in the main module
local t = {
color3always6bytes = false;
rbxenum_behavior = "full" :: "full" | "compact";
serverclientsyncing = false;
sanitize_nanandinf = false;
}
for att, value in Encoder:GetAttributes() do
if t[att] ~= nil then
if type(value) == type(t[att]) then t[att] = value
else warn(`[BUFFERENCODER] {typeof(value)} is not a valid type for the setting {att}`) end
end
end
return t | 141 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/Types.luau | type anyTable = { [any]: any }
export type encodeinfo = {
valuepositionlookup: anyTable;
settings: WriteSettings,
scanlist: { anyTable },
referencelist: { any },
allocatedsize: number;
}
export type decodeinfo = {
sanitize_nanandinf: boolean?,
references: { any }?;
deduplicationtable: { any };
tables: { anyTable };
}
export type WriteSettings = {
allowdeduplication: boolean?,
allowreferences: boolean?,
shiftseed: number?,
rbxenum_behavior: "full" | "compact" | nil,
color3always6bytes: boolean?,
}
export type ReadSettings = {
allowdeduplication: boolean?,
references: { any }?,
shiftseed: number?,
rbxenum_behavior: "full" | "compact" | nil,
sanitize_nanandinf: boolean?,
}
export type datatypedecodinginfo = {
[number]: (buff: buffer, byte: number, cursor: number, info: decodeinfo) -> (any, number, boolean?),
}
return 0
| 239 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/Write.luau | --!native
--!optimize 2
--!nolint LocalShadow
--[[ ## made by anexpia •…• ## ]]
-- [[ byte tags, if negative then its a dict key ]]
-- 0 -> at end: terminate, at start: deduplication table
-- 1 -> stop and start new table
-- 2 -> boolean: true
-- 3 -> boolean: false
-- 4 -> nil
-- 5 to 11 -> number
-- 12 to 14 -> buffer
-- 15 -> v3 (3 f32)
-- 16 -> v2 (2 f32)
-- 17 -> cframe
-- 18 -> ray (6 f32)
-- 19 -> enum < polymorphic - depends on setting 'rbxenum_behavior' >
-- 20 -> enumitem < polymorphic - depends on setting 'rbxenum_behavior' >
-- 21 -> numberrange (2 f32)
-- 22 -> numbersequence
-- 23 -> color3 (u8)
-- 24 -> color3 (f16)
-- 25 -> colorsequence
-- 26 -> udim (1 int32 1 f32)
-- 27 -> udim2 (2 int32 2 f32)
-- 28 -> rect (4 f32)
-- 29 -> physicalproperties (really long)
-- 30 -> brickcolor (int16)
-- 31 -> vector3int16 (3 i16)
-- 32 -> vector2int16 (2 i16)
-- 33 -> content (depends)
-- 34 -> font (depends)
-- 35 -> datetime (f64)
-- 51 -> table position (u8)
-- 52 -> table position (u16)
-- 53 -> table position (u32)
-- 54 -> u8 length string
-- 55 -> u16 length string
-- 56 -> u32 length string
-- 57 -> value deduplicate (u8)
-- 58 -> value deduplicate (u16)
-- 59 -> value deduplicate (u32)
-- 60 -> reference (u8)
-- 61 -- reference (u16)
-- 62 -- reference (u32)
-- 99 -> 2 byte custom value || <99> <-index>
-- 101 -> empty table
-- 102 -> empty string
-- 103 -> 0
-- 104 -> 1
-- 105 -> -1
-- 106 -> math.huge
-- 107 -> -math.huge
-- 108 -> nan
local uI16_max = (2 ^ 16) - 1
local Enums = require(script.Parent.Enums)
local Miscellaneous = require(script.Parent.Miscellaneous)
local RbxEnumEncoder = require(script.Parent.RbxEnumEncoder)
local Settings = require(script.Parent.Settings)
local Types = require(script.Parent.Types)
type encodeinfo = Types.encodeinfo
type WriteSettings = Types.WriteSettings
local valuetobyte = Enums.valuetobyte
local writef16 = Miscellaneous.writef16
local writeCFrame = Miscellaneous.writeCFrame
local CFrameSize = Miscellaneous.cframesize
-- shift the byte associated with a value/datatype by the number given
local tryshift = function(v: number, shiftseed: number?): number
if shiftseed then return (v + math.random(1, 127)) % 128
else return v end
end
-- write the byte associated with a given value or datatype
local function writebytesign(buff: buffer, cursor: number, value: number, isdict: boolean?, shiftseed: number?)
if shiftseed then value = (value + math.random(1, 127)) % 128 end
if isdict then value = 255 - value end
buffer.writeu8(buff, cursor, value)
end
-- expand the size of the writingbuffer
local function expandbuffertosize(buff: buffer, newsize: number, info: encodeinfo): buffer
if newsize > info.allocatedsize then
newsize //= 1/1.375
info.allocatedsize = newsize
local newbuff = buffer.create(newsize)
buffer.copy(newbuff, 0, buff)
return newbuff
end
return buff
end
-- write every value into the buffer
local function write(
buff: buffer,
cursor: number,
info: encodeinfo
): (buffer, number)
local writesettings = info.settings
local shiftseed: number?, dedupallowed = writesettings.shiftseed, writesettings.allowdeduplication
local color3always6bytes = writesettings.color3always6bytes
if color3always6bytes == nil then color3always6bytes = Settings.color3always6bytes end
local enumbehavior, enumbehaviortype = RbxEnumEncoder.getBehaviorFromSetting(writesettings)
local fullrbxenum: boolean = enumbehaviortype == 'full'
local scancount: number = 1
local deduplicatedcount: number = 0
local referencecount: number = 0
local valuepositionlookup = info.valuepositionlookup
local scanlist = info.scanlist
local referencelist = info.referencelist
for _, tbl in scanlist do
buff = expandbuffertosize(buff, cursor + 1, info)
writebytesign(buff, cursor, 1, nil, shiftseed); cursor += 1
local arraywritelength: number = rawlen(tbl)
local isdoingdict: boolean = arraywritelength == 0
local iternum: number = if isdoingdict then 2 else 1
local lastkey: number = 0
for k, v in next, tbl do
if (not isdoingdict) then
local diff: number = (k - lastkey) - 1
if diff > 0 then
buff = expandbuffertosize(buff, cursor + diff, info)
if shiftseed then
for i = 0, diff - 1 do
buffer.writeu8(buff, cursor + i, (4 + math.random(1, 127)) % 128)
end
else buffer.fill(buff, cursor, 4, diff) end
cursor += diff
end
lastkey = k
end
for i = 1, iternum do
local isdict: boolean = isdoingdict and i == 1
local value: any = if isdict then k else v
local valuebyte: number? = valuetobyte[value]
if valuebyte then
if valuebyte <= 0 then
buff = expandbuffertosize(buff, cursor + 2, info)
writebytesign(buff, cursor, 99, isdict, shiftseed)
buffer.writeu8(buff, cursor + 1, -valuebyte); cursor += 2
else
buff = expandbuffertosize(buff, cursor + 1, info)
writebytesign(buff, cursor, valuebyte, isdict, shiftseed); cursor += 1
end
continue
end
local t: string = typeof(value)
local candeduplicate: boolean = dedupallowed and (t == 'string' or t == 'Vector3' or t == 'number' or (fullrbxenum and (t == 'EnumItem' or t == 'Enum')))
if candeduplicate then
if value ~= value then
-- nan shouldnt be deduplicated, whether in a vector or as a number
if t == 'number' then
buff = expandbuffertosize(buff, cursor + 1, info)
writebytesign(buff, cursor, 108, isdict, shiftseed); cursor += 1
else
local value: Vector3 = value
-- vector in this case
buff = expandbuffertosize(buff, cursor + 13, info)
writebytesign(buff, cursor, 15, isdict, shiftseed); cursor += 1
buffer.writef32(buff, cursor, value.X); cursor += 4
buffer.writef32(buff, cursor, value.Y); cursor += 4
buffer.writef32(buff, cursor, value.Z); cursor += 4
end
continue
end
if t == 'number' then
local value: number = value
-- numbers below 256 that arent float values shouldnt be deduplicated
local abs = math.abs(value)
if not (abs > 0xFF or abs % 1 ~= 0) then
-- encoding here to avoid rechecking later
buff = expandbuffertosize(buff, cursor + 5, info)
writebytesign(buff, cursor, if value < 0 then 8 else 5, isdict, shiftseed)
buffer.writeu8(buff, cursor + 1, abs); cursor += 2
continue
end
end
local added: number? = valuepositionlookup[value]
if added then
if added <= 0xFF then -- u8
buff = expandbuffertosize(buff, cursor + 2, info)
writebytesign(buff, cursor, 57, isdict, shiftseed)
buffer.writeu8(buff, cursor + 1, added); cursor += 2
elseif added <= 0xFFFF then -- u16
buff = expandbuffertosize(buff, cursor + 3, info)
writebytesign(buff, cursor, 58, isdict, shiftseed)
buffer.writeu16(buff, cursor + 1, added); cursor += 3
else -- u32
buff = expandbuffertosize(buff, cursor + 5, info)
writebytesign(buff, cursor, 59, isdict, shiftseed)
buffer.writeu32(buff, cursor + 1, added); cursor += 5
end
continue
else
deduplicatedcount += 1
valuepositionlookup[value] = deduplicatedcount
end
end
if t == "nil" then
buff = expandbuffertosize(buff, cursor + 1, info)
writebytesign(buff, cursor, 4, isdict, shiftseed); cursor += 1
elseif t == "number" then
local value: number = value
if value ~= value then
buff = expandbuffertosize(buff, cursor + 1, info)
writebytesign(buff, cursor, 108, isdict, shiftseed); cursor += 1
else
local abs = math.abs(value)
if (value % 1) ~= 0 or abs > 0xFFFFFFFF then -- float64
buff = expandbuffertosize(buff, cursor + 9, info)
writebytesign(buff, cursor, 11, isdict, shiftseed)
buffer.writef64(buff, cursor + 1, value); cursor += 9
else
local offset = if value < 0 then 3 else 0
if abs <= 0xFF then -- uint8
buff = expandbuffertosize(buff, cursor + 2, info)
writebytesign(buff, cursor, 5 + offset, isdict, shiftseed)
buffer.writeu8(buff, cursor + 1, abs); cursor += 2
elseif abs <= 0xFFFF then -- uint16
buff = expandbuffertosize(buff, cursor + 3, info)
writebytesign(buff, cursor, 6 + offset, isdict, shiftseed)
buffer.writeu16(buff, cursor + 1, abs); cursor += 3
else
buff = expandbuffertosize(buff, cursor + 5, info)
writebytesign(buff, cursor, 7 + offset, isdict, shiftseed)
buffer.writeu32(buff, cursor + 1, abs); cursor += 5
end
end
end
elseif t == "string" then
local value: string = value
local len: number = #value
if len <= 0xFF then -- not zero-terminated since no benefit in making it zero-terminated
buff = expandbuffertosize(buff, cursor + len + 2, info)
writebytesign(buff, cursor, 54, isdict, shiftseed)
buffer.writeu8(buff, cursor + 1, len); cursor += 2
elseif len <= 0xFFFF then
buff = expandbuffertosize(buff, cursor + len + 3, info)
writebytesign(buff, cursor, 55, isdict, shiftseed)
buffer.writeu16(buff, cursor + 1, len); cursor += 3
else
buff = expandbuffertosize(buff, cursor + len + 5, info)
writebytesign(buff, cursor, 56, isdict, shiftseed)
buffer.writeu32(buff, cursor + 1, len); cursor += 5
end
buffer.writestring(buff, cursor, value); cursor += len
elseif t == "table" then
local value: {[any]: any} = value
local scanpos: number? = valuepositionlookup[value]
if (not scanpos) and (next(value) ~= nil) then
scanpos = scancount + 1
scancount = scanpos :: any
valuepositionlookup[value] = scanpos
scanlist[scanpos] = value
end
if scanpos then
if scanpos <= 0xFF then
buff = expandbuffertosize(buff, cursor + 2, info)
writebytesign(buff, cursor, 51, isdict, shiftseed)
buffer.writeu8(buff, cursor + 1, scanpos); cursor += 2
elseif scanpos <= 0xFFFF then
buff = expandbuffertosize(buff, cursor + 3, info)
writebytesign(buff, cursor, 52, isdict, shiftseed)
buffer.writeu16(buff, cursor + 1, scanpos); cursor += 3
else
buff = expandbuffertosize(buff, cursor + 5, info)
writebytesign(buff, cursor, 53, isdict, shiftseed)
buffer.writeu32(buff, cursor + 1, scanpos); cursor += 5
end
else
buff = expandbuffertosize(buff, cursor + 1, info)
writebytesign(buff, cursor, 101, isdict, shiftseed); cursor += 1
end
elseif t == "buffer" then
local value: buffer = value
local length: number = buffer.len(value)
if length <= 0xFF then
buff = expandbuffertosize(buff, cursor + 2 + length, info)
writebytesign(buff, cursor, 12, isdict, shiftseed)
buffer.writeu8(buff, cursor + 1, length)
cursor += 2
elseif length <= 0xFFFF then
buff = expandbuffertosize(buff, cursor + 3 + length, info)
writebytesign(buff, cursor, 13, isdict, shiftseed)
buffer.writeu16(buff, cursor + 1, length)
cursor += 3
else
buff = expandbuffertosize(buff, cursor + 5 + length, info)
writebytesign(buff, cursor, 14, isdict, shiftseed)
buffer.writeu32(buff, cursor + 1, length)
cursor += 5
end
buffer.copy(buff, cursor, value)
cursor += length
elseif t == "Vector3" then
local value: Vector3 = value
buff = expandbuffertosize(buff, cursor + 13, info)
writebytesign(buff, cursor, 15, isdict, shiftseed); cursor += 1
buffer.writef32(buff, cursor, value.X); cursor += 4
buffer.writef32(buff, cursor, value.Y); cursor += 4
buffer.writef32(buff, cursor, value.Z); cursor += 4
elseif t == "Vector2" then
local value: Vector2 = value
buff = expandbuffertosize(buff, cursor + 9, info)
writebytesign(buff, cursor, 16, isdict, shiftseed); cursor += 1
buffer.writef32(buff, cursor, value.X); cursor += 4
buffer.writef32(buff, cursor, value.Y); cursor += 4
elseif t == "CFrame" then
local value: CFrame = value
buff = expandbuffertosize(buff, cursor + CFrameSize + 1, info)
writebytesign(buff, cursor, 17, isdict, shiftseed); cursor += 1
writeCFrame(buff, cursor, value); cursor += CFrameSize
elseif t == "Ray" then
local value: Ray = value
buff = expandbuffertosize(buff, cursor + 25, info)
writebytesign(buff, cursor, 18, isdict, shiftseed); cursor += 1
local pos: Vector3, dir: Vector3 = value.Origin, value.Direction
buffer.writef32(buff, cursor, pos.X); cursor += 4
buffer.writef32(buff, cursor, pos.Y); cursor += 4
buffer.writef32(buff, cursor, pos.Z); cursor += 4
buffer.writef32(buff, cursor, dir.X); cursor += 4
buffer.writef32(buff, cursor, dir.Y); cursor += 4
buffer.writef32(buff, cursor, dir.Z); cursor += 4
elseif t == "Enum" then
local value: Enum = value
local size: number = 3 -- <u8> 19 | <u16> position
if fullrbxenum then
size = 2 + #RbxEnumEncoder.enumitem_to_type[value]
-- <u8> byte | <u8> length | string
end
buff = expandbuffertosize(buff, cursor + size, info)
writebytesign(buff, cursor, 19, isdict, shiftseed)
cursor = enumbehavior.encodeEnum(buff, cursor + 1, value)
elseif t == "EnumItem" then
local value: EnumItem = value
local size: number = 3 -- <u8> 20 | <u16> position
if fullrbxenum then
size = 4 + #RbxEnumEncoder.enumitem_to_type[value]
-- <u8> 20 | <u8> length | string | <u16> value
end
buff = expandbuffertosize(buff, cursor + size, info)
writebytesign(buff, cursor, 20, isdict, shiftseed)
cursor = enumbehavior.encodeEnumItem(buff, cursor + 1, value)
elseif t == "NumberRange" then
local value: NumberRange = value
buff = expandbuffertosize(buff, cursor + 9, info)
writebytesign(buff, cursor, 21, isdict, shiftseed); cursor += 1
buffer.writef32(buff, cursor, value.Min); cursor += 4
buffer.writef32(buff, cursor, value.Max); cursor += 4
elseif t == "NumberSequence" then
local value: NumberSequence = value
local keypoints: {NumberSequenceKeypoint} = value.Keypoints
buff = expandbuffertosize(buff, cursor + 2 + #keypoints * 8, info)
writebytesign(buff, cursor, 22, isdict, shiftseed);
buffer.writeu8(buff, cursor + 1, #keypoints); cursor += 2
for _, k in keypoints do
buffer.writeu16(buff, cursor, math.round(k.Time * uI16_max))
buffer.writef32(buff, cursor + 2, k.Value)
writef16(buff, cursor + 6, k.Envelope); cursor += 8
end
elseif t == "Color3" then
local value: Color3 = value
local r: number, g: number, b: number = value.R, value.G, value.B
if color3always6bytes or (math.max(r, g, b) > 1 or math.min(r, g, b) < 0) then
buff = expandbuffertosize(buff, cursor + 7, info)
-- one or more of values is out of 1 byte limit, so this encodes as 2 bytes each
writebytesign(buff, cursor, 24, isdict, shiftseed)
writef16(buff, cursor + 1, r)
writef16(buff, cursor + 3, g)
writef16(buff, cursor + 5, b)
cursor += 7
else
buff = expandbuffertosize(buff, cursor + 4, info)
writebytesign(buff, cursor, 23, isdict, shiftseed)
buffer.writeu8(buff, cursor + 1, math.round(r * 255))
buffer.writeu8(buff, cursor + 2, math.round(g * 255))
buffer.writeu8(buff, cursor + 3, math.round(b * 255))
cursor += 4
end
elseif t == "ColorSequence" then
local value: ColorSequence = value
local keypoints: {ColorSequenceKeypoint} = value.Keypoints
buff = expandbuffertosize(buff, cursor + 2 + #keypoints * 5, info)
writebytesign(buff, cursor, 25, isdict, shiftseed)
buffer.writeu8(buff, cursor + 1, #keypoints); cursor += 2
for _, k in keypoints do
local color = k.Value
-- colors in colorsequences are always limited to 0-1
buffer.writeu16(buff, cursor, math.round(k.Time * uI16_max))
buffer.writeu8(buff, cursor + 2, math.round(color.R * 255))
buffer.writeu8(buff, cursor + 3, math.round(color.G * 255))
buffer.writeu8(buff, cursor + 4, math.round(color.B * 255))
cursor += 5
end
elseif t == "UDim" then
local value: UDim = value
buff = expandbuffertosize(buff, cursor + 9, info)
writebytesign(buff, cursor, 26, isdict, shiftseed)
buffer.writef32(buff, cursor + 1, value.Scale)
buffer.writei32(buff, cursor + 5, value.Offset)
cursor += 9
elseif t == "UDim2" then
local value: UDim2 = value
buff = expandbuffertosize(buff, cursor + 17, info)
local x: UDim, y: UDim = value.X, value.Y
writebytesign(buff, cursor, 27, isdict, shiftseed)
buffer.writef32(buff, cursor + 1, x.Scale)
buffer.writei32(buff, cursor + 5, x.Offset)
buffer.writef32(buff, cursor + 9, y.Scale)
buffer.writei32(buff, cursor + 13, y.Offset)
cursor += 17
elseif t == "Rect" then
local value: Rect = value
buff = expandbuffertosize(buff, cursor + 17, info)
local min: Vector2, max: Vector2 = value.Min, value.Max
writebytesign(buff, cursor, 28, isdict, shiftseed)
buffer.writef32(buff, cursor + 1, min.X)
buffer.writef32(buff, cursor + 5, min.Y)
buffer.writef32(buff, cursor + 9, max.X)
buffer.writef32(buff, cursor + 13, max.Y)
cursor += 17
elseif t == "PhysicalProperties" then
local value: PhysicalProperties = value
buff = expandbuffertosize(buff, cursor + 21, info)
writebytesign(buff, cursor, 29, isdict, shiftseed)
buffer.writef32(buff, cursor + 1, value.Density)
buffer.writef32(buff, cursor + 5, value.Friction)
buffer.writef32(buff, cursor + 9, value.Elasticity)
buffer.writef32(buff, cursor + 13, value.FrictionWeight)
buffer.writef32(buff, cursor + 17, value.ElasticityWeight)
cursor += 21
elseif t == "BrickColor" then
local value: BrickColor = value
buff = expandbuffertosize(buff, cursor + 3, info)
writebytesign(buff, cursor, 30, isdict, shiftseed)
buffer.writeu16(buff, cursor + 1, value.Number)
cursor += 3
elseif t == "Vector3int16" then
local value: Vector3int16 = value
buff = expandbuffertosize(buff, cursor + 7, info)
writebytesign(buff, cursor, 31, isdict, shiftseed)
buffer.writei16(buff, cursor + 1, value.X)
buffer.writei16(buff, cursor + 3, value.Y)
buffer.writei16(buff, cursor + 5, value.Z)
cursor += 7
elseif t == "Vector2int16" then
local value: Vector2int16 = value
buff = expandbuffertosize(buff, cursor + 5, info)
writebytesign(buff, cursor, 32, isdict, shiftseed)
buffer.writei16(buff, cursor + 1, value.X)
buffer.writei16(buff, cursor + 3, value.Y)
cursor += 5
elseif t == "Content" then
local value: Content = value
if value.SourceType == Enum.ContentSourceType.Uri then
local uri: string = value.Uri :: string
local num: string? = string.match(uri, "%d+$")
if num then
buff = expandbuffertosize(buff, cursor + 10, info)
writebytesign(buff, cursor, 33, isdict, shiftseed)
buffer.writeu8(buff, cursor + 1, 1)
buffer.writef64(buff, cursor + 2, tonumber(num) :: number)
cursor += 10
else
-- im going to make a guess and say that the content links are NOT going past 254 bytes in length 😨
local len: number = #uri
if len > 254 then
error("content uri length cannot be more than 254 bytes.", 0)
end
buff = expandbuffertosize(buff, cursor + 2 + len, info)
writebytesign(buff, cursor, 33, isdict, shiftseed)
buffer.writeu8(buff, cursor + 1, len + 1); cursor += 2
buffer.writestring(buff, cursor , uri)
cursor += len
end
continue
else
buff = expandbuffertosize(buff, cursor + 2, info)
writebytesign(buff, cursor, 33, isdict, shiftseed)
buffer.writeu8(buff, cursor + 1, 0); cursor += 2
end
elseif t == "Font" then
local value: Font = value
local family: string = value.Family
local num: string? = string.match(family, "%d+$")
if num then
buff = expandbuffertosize(buff, cursor + 13, info)
writebytesign(buff, cursor, 34, isdict, shiftseed)
buffer.writeu8(buff, cursor + 1, 0)
buffer.writef64(buff, cursor + 2, tonumber(num) :: number)
cursor += 10
else
local familyname: string = string.match(family, "/(%w+).json$") or ""
local length: number = #familyname
-- same here
if length > 254 then
error("font name length cannot be more than 254 bytes.", 0)
end
buff = expandbuffertosize(buff, cursor + 5 + length, info)
writebytesign(buff, cursor, 34, isdict, shiftseed)
buffer.writeu8(buff, cursor + 1, length + 1); cursor += 2
buffer.writestring(buff, cursor, familyname)
cursor += length
end
buffer.writeu16(buff, cursor, RbxEnumEncoder.enumitem_to_value[value.Weight])
buffer.writeu8(buff, cursor + 2, RbxEnumEncoder.enumitem_to_value[value.Style]); cursor += 3
elseif t == "DateTime" then
local value: DateTime = value
buff = expandbuffertosize(buff, cursor + 9, info)
writebytesign(buff, cursor, 35, isdict, shiftseed)
buffer.writef64(buff, cursor + 1, value.UnixTimestampMillis); cursor += 9
else
if referencelist then
local referenceposition: number = valuepositionlookup[value]
if not referenceposition then
referenceposition = referencecount + 1
referencecount = referenceposition :: any
valuepositionlookup[value] = referenceposition
referencelist[referenceposition] = value
end
if referenceposition <= 0xFF then
buff = expandbuffertosize(buff, cursor + 2, info)
writebytesign(buff, cursor, 60, isdict, shiftseed)
buffer.writeu8(buff, cursor + 1, referenceposition); cursor += 2
elseif referenceposition <= 0xFFFF then
buff = expandbuffertosize(buff, cursor + 3, info)
writebytesign(buff, cursor, 61, isdict, shiftseed)
buffer.writeu16(buff, cursor + 1, referenceposition); cursor += 3
else
buff = expandbuffertosize(buff, cursor + 5, info)
writebytesign(buff, cursor, 62, isdict, shiftseed)
buffer.writeu32(buff, cursor + 1, referenceposition); cursor += 5
end
elseif isdict then break
else
buff = expandbuffertosize(buff, cursor + 1, info)
writebytesign(buff, cursor, 4, isdict, shiftseed); cursor += 1
end
end
end
if k == arraywritelength then iternum = 2; isdoingdict = true end
end
end
return buff, cursor
end
local writingbuffer = buffer.create(256)
local writingbuffersize = 256
type BenchmarkerProfiler = {
Begin: (name: string) -> nil;
End: () -> nil;
}
--[[
returns the table given encoded as a buffer, and the size of buffer
<em>param</em> - value : the table to encode
<em>param</em> - writeoffset : writing starts from the offset given.
<em>param</em> - writesettings : {
. <strong>allowdeduplication: boolean</strong> -- attempt to deduplicate repeated values if enabled to reduce buffer size
. <strong>allowreferences: boolean</strong> -- if enabled, return a table containing the values it couldn't encode alongside the buffer.
. <strong>shiftseed: number</strong> -- the type bytes of values are shuffled using the seed.
. <strong>rbxenum_behavior: "full" | "compact"</strong> -- override for the default setting.
. <strong>color3always6bytes: boolean</strong> -- override for the default setting.
}
]]
return function(
value: { [any]: any },
writeoffset: number?,
writesettings: WriteSettings?,
Profiler: BenchmarkerProfiler?
): (buffer, { any }?)
if type(value) == "table" then
local writesettings: WriteSettings = writesettings or (Settings :: any)
local shiftseed = writesettings.shiftseed
if shiftseed then math.randomseed(shiftseed) end
local referencelist = if writesettings.allowreferences then {} else nil
if next(value) == nil then
local b = buffer.create(1)
buffer.writeu8(b, 0, tryshift(101, shiftseed))
if shiftseed then math.randomseed(os.time()) end
return b, referencelist
end
local cursor: number = writeoffset or 0
local info: encodeinfo = {
valuepositionlookup = {[value] = 1},
scanlist = {value},
referencelist = referencelist,
settings = writesettings,
allocatedsize = writingbuffersize;
}
local buff = writingbuffer
if Profiler then
Profiler.Begin("Write")
end
buff, cursor = write(buff, cursor, info)
buff = expandbuffertosize(buff, cursor + 1, info)
writebytesign(buff, cursor, 0, nil, shiftseed)
if Profiler then
Profiler.End()
Profiler.Begin("Finish")
end
writingbuffer = buff
writingbuffersize = info.allocatedsize
local truncatedbuffer = buffer.create(cursor + 2)
buffer.copy(truncatedbuffer, 0, buff, 0, cursor + 1)
if shiftseed then math.randomseed(os.time()) end
if Profiler then
Profiler.End()
end
return truncatedbuffer, referencelist
else
error(`Expected a table to be encoded into a buffer, got {typeof(value)}`, 0)
end
end
| 7,360 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/bufferencoder/init.luau | --[[
## made by anexpia •…• ##
v---v---v---v---v---v currently supported types v---v---v---v---v---v
[x] -> datatype has deduplication
deduplication means that if the value exists in more than one table, it will be encoded only once
this reduces buffer size and time it takes to encode the value
luau types
> string [x]
> number [x]
> boolean
> nil
> table
> buffer
> vector [x]
roblox types
> Enum [x]? only if rbxenum_behavior is 'full'
> EnumItem [x]? only if rbxenum_behavior is 'full'
> BrickColor
> Color3
> ColorSequence
> NumberSequence
> NumberRange
> CFrame
> Ray
> Vector3int16
> Vector2
> Vector2int16
> Rect
> UDim
> UDim2
> PhysicalProperties
> Content
> Font
> DateTime
can also encode custom values into 2 bytes
> this is done by using enums.register(name, value)
> value is optional, itll give you a newproxy() if you dont give it a value
> max 255 values
v---v---v---v---v---v---v---v settings v---v---v---v---v---v---v---v
> color3always6bytes: boolean >> default false
this toggles if color3 components are always saved as float16 numbers
> rbxenum_behavior: string ( 'full' | 'compact' ) >> default 'compact'
this has 2 behaviors currently.
> "full"
encodes the enums as <19> <u8 length> <string>
enumitems are <20> <u8 length> <string> <u16 value>
this should be used for data saving as this guarantees the enumitems stay the same as long as roblox doesn't do anything weird
* encoded values are deduplicated if allowed, so if the same enum & enumitem are encoded multiple times
it will not cost the same to encode it each time
> "compact" *default behavior*
this should ONLY BE USED for sending the enums & enumitems in temporary sessions!!! (like in remotes)
the order of the enum & enumitem table is not guaranteed to be consistent between
every session thus you will definitely encounter bugs if you use this for saving data
* no deduplication since there's no benefit, as this saves both enums and enumitems as 3 bytes,
> serverclientsyncing: boolean
determines whether to sync enumitems and custom values between client and server
> sanitize_nanandinf: boolean
determines whether to turn NaN and math.huge into 0 when reading buffer content
this only sanitizes them for Numbers, Vectors, Rays, and CFrames
]]
return {
read = require(script.Read);
write = require(script.Write);
enums = require(script.Enums)
} | 681 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/convert_scale.luau | --!optimize 2
-- jabby_util
local function convert_scale(unit: string, value: number): string
local s = math.sign(value)
value = math.abs(value)
local prefixes = {
[4] = "T",
[3] = "G",
[2] = "M",
[1] = "k",
[0] = "",
[-1] = "m",
[-2] = "μ",
[-3] = "n",
[-4] = "p",
}
local order = 0
while value >= 1000 do
order += 1
value /= 1000
end
while value ~= 0 and value < 1 do
order -= 1
value *= 1000
end
local format = "%.01f"
if value >= 100 then
format = "%.01f"
value = math.floor(value)
elseif value >= 10 then
format = "%.01f"
value = math.floor(value * 1e1) / 1e1
elseif value >= 1 then
format = "%.02f"
value = math.floor(value * 1e2) / 1e2
end
return string.format(format, value * s) .. prefixes[math.clamp(order, -4, 4)] .. unit
end
return convert_scale
| 305 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/convert_units.luau | --!optimize 2
-- jabby_util
local function convert_units(unit: string, value: number): string
local s = math.sign(value)
value = math.abs(value)
local prefixes = {
[4] = "T",
[3] = "G",
[2] = "M",
[1] = "k",
[0] = " ",
[-1] = "m",
[-2] = "u",
[-3] = "n",
[-4] = "p",
}
local order = 0
while value >= 1000 do
order += 1
value /= 1000
end
while value ~= 0 and value < 1 do
order -= 1
value *= 1000
end
if value >= 100 then
value = math.floor(value)
elseif value >= 10 then
value = math.floor(value * 1e1) / 1e1
elseif value >= 1 then
value = math.floor(value * 1e2) / 1e2
end
return value * s .. prefixes[order] .. unit
end
return convert_units
| 264 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/limesignal/init.luau | --!optimize 2
--!strict
--!native
--$Packages
local ThreadPool = require("@self/threadpool")
--$Types
export type Connection<T...> = {
disconnect: (self: Connection<T...>) -> (),
reconnect: (self: Connection<T...>) -> (),
connected: boolean,
}
export type Event<T...> = {
connect: (self: Event<T...>, fn: (T...) -> ()) -> Connection<T...>,
connectOnce: (self: Event<T...>, fn: (T...) -> ()) -> Connection<T...>,
disconnectAll: (self: Event<T...>) -> (),
wait: (self: Event<T...>) -> T...,
from: (emitter: (event: Event<T...>, T...) -> ()) -> Event<T...>,
}
export type Bindable<T...> = {
new: () -> Bindable<T...>,
wrap: (signal: RBXScriptSignal<T...>) -> Bindable<T...>,
fire: (self: Bindable<T...>, T...) -> (),
Destroy: (self: Bindable<T...>) -> (), -- why PascalCase? because it does call Destroy method on RBXScriptConnection if it exists
RBXScriptConnection: RBXScriptConnection?,
event: Event<T...>,
}
export type Signal<T...> = {
new: () -> Signal<T...>,
wrap: (signal: RBXScriptSignal<T...>) -> Signal<T...>,
connect: (self: Signal<T...>, fn: (T...) -> ()) -> Connection<T...>,
connectOnce: (self: Signal<T...>, fn: (T...) -> ()) -> Connection<T...>,
disconnectAll: (self: Signal<T...>) -> (),
wait: (self: Signal<T...>) -> T...,
fire: (self: Signal<T...>, T...) -> (),
Destroy: (self: Signal<T...>) -> (),
RBXScriptConnection: RBXScriptConnection?,
}
local Connection = {} :: Connection<...any>
(Connection :: any).__index = Connection
local function disconnect(self)
if not self.connected then
return
end
self.connected = false
local next = (self :: any)._next
local prev = (self :: any)._prev
if next then
next._prev = prev
end
if prev then
prev._next = next
end
local signal = (self :: any)._signal
if signal._head == self then
signal._head = next
end
end
Connection.disconnect = disconnect -- i know this is annoying but this is only for micro optimization
function reconnect(self)
if self.connected then
return
end
self.connected = true
local signal = (self :: any)._signal
local head = signal._head
if head then
head._prev = self
end
signal._head = self;
(self :: any)._next = head;
(self :: any)._prev = false
end
Connection.reconnect = reconnect
--$Lime
local Bindable = {} :: Bindable<...any>
(Bindable :: any).__index = Bindable
local Event = {} :: Event<...any>
(Event :: any).__index = Event
local Signal = {} :: Signal<...any>
(Signal :: any).__index = Signal
local rbxConnect, rbxDisconnect
do
local bindable = Instance.new("BindableEvent")
rbxConnect = bindable.Event.Connect
rbxDisconnect = bindable.Event:Connect(function() end).Disconnect
bindable:Destroy()
end
local function connect<T...>(self, fn)
local head = (self :: any)._head
local cn = setmetatable({
connected = true,
_signal = self,
_fn = fn,
_next = head,
_prev = false,
}, Connection)
if head then
head._prev = cn
end
(self :: any)._head = cn :: any
return cn :: any
end
Signal.connect = connect
Event.connect = connect :: any
local function once<T...>(self, fn)
local cn
cn = connect(self, function(...: any)
disconnect(cn)
fn(...)
end)
return cn
end
Signal.connectOnce = once
Event.connectOnce = once :: any
local function wait<T...>(self): T...
local thread = coroutine.running()
local cn
cn = connect(self, function(...)
disconnect(cn)
task.spawn(thread, ...)
end)
return coroutine.yield()
end
Signal.wait = wait
Event.wait = wait :: any
local function fire<T...>(self, ...)
local event = (self :: any).event or self
local cn = event._head
while cn do
-- local thread
-- if #freeThreads > 0 then
-- thread = freeThreads[#freeThreads]
-- freeThreads[#freeThreads] = nil
-- else
-- thread = coroutine.create(yielder)
-- coroutine.resume(thread)
-- end
-- task.spawn(thread, cn._fn, thread, ...)
-- now we spawn in shared threadpool!
ThreadPool.spawn(cn._fn, ...)
cn = cn._next
end
end
Signal.fire = fire
Bindable.fire = fire :: any
local function disconnectAll<T...>(self)
local cn = (self :: any)._head
while cn do
disconnect(cn)
cn = cn._next
end
end
Event.disconnectAll = disconnectAll
Signal.disconnectAll = disconnectAll
local function Destroy<T...>(self)
disconnectAll((self :: any).event or self)
local cn = self.RBXScriptConnection
if cn then
rbxDisconnect(cn)
self.RBXScriptConnection = nil :: any
end
end
Signal.Destroy = Destroy
Bindable.Destroy = Destroy :: any
function Event.from(emitter)
return setmetatable({ _emitter = emitter, _head = false }, Event) :: any
end
function Bindable.new()
local event = setmetatable({ _head = false }, Event)
return setmetatable({ event = event }, Bindable) :: any
end
function Bindable.wrap(signal)
local wrapper = Bindable.new()
wrapper.RBXScriptConnection = rbxConnect(signal, function(...)
fire(wrapper :: any, ...)
end)
return wrapper
end
function Signal.new()
return setmetatable({ _head = false }, Signal) :: any
end
function Signal.wrap(signal)
local wrapper = Signal.new()
wrapper.RBXScriptConnection = rbxConnect(signal, function(...)
fire(wrapper, ...)
end)
return wrapper
end
local function createEmitter(): <T...>(event: Event<T...>, T...) -> ()
local function emitter(event, ...)
if not event._emitter or event._emitter ~= emitter then
error("Emitted an invalid event")
end
fire(event, ...)
end
return emitter :: any
end
return {
Signal = Signal,
Event = Event,
Bindable = Bindable,
createEmitter = createEmitter,
}
| 1,490 |
imezx/Scheduler | imezx-Scheduler-43e0719/src/util/limesignal/threadpool.luau | -- source credit to https://github.com/lukadev-0/util.luau/blob/main/packages/threadpool/init.luau
local threadpool = {}
local freeThreads: { thread } = {}
local function run<T...>(f: (T...) -> (), thread: thread, ...)
f(...)
table.insert(freeThreads, thread)
end
local function yielder()
while true do
run(coroutine.yield())
end
end
--[=[
Executes the given function in a separate thread, threads are pooled and reused.
별도의 스레드에서 지정된 함수를 실행하며 스레드는 풀링되어 재사용됩니다.
```lua
ThreadPool.spawn(function()
task.wait(2)
print("Hello Caveful Games!")
end)
```
]=]
function threadpool.spawn<T...>(f: (T...) -> (), ...: T...)
local thread
if #freeThreads > 0 then
thread = freeThreads[#freeThreads]
freeThreads[#freeThreads] = nil
else
thread = coroutine.create(yielder)
coroutine.resume(thread)
end
task.spawn(thread, f, thread, ...)
end
return threadpool
| 263 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Debug.luau | --!optimize 2
local Types = require("./Types")
local GradClip = require("./GradClip")
local Anomaly = require("./Util/Anomaly")
type Tensor = Types.Tensor
local Debug = {}
function Debug.checkTensor(t: Tensor, name: string?): boolean
if Anomaly.hasBadValues(t) then
warn(`Gradien.Debug: tensor '{name or "?"}' has NaN/Inf/invalid values`)
return false
end
return true
end
function Debug.checkGradients(params: { Tensor }, label: string?): (boolean, number?)
for i, p in params do
local g = p._grad
if g and Anomaly.hasBadValues(g) then
warn(`Gradien.Debug: bad gradient in param {i} ({label or ""})`)
return false, i
end
end
return true, nil
end
function Debug.wrapOptimizer(
opt,
params: { Tensor },
cfgs: { maxGradNorm: number?, clipValue: number?, warnOnNaN: boolean?, label: string? }?
)
local cfg = cfgs or {}
local maxGradNorm = cfg.maxGradNorm
local clipValue = cfg.clipValue
local warnOnNaN = cfg.warnOnNaN
if type(warnOnNaN) ~= "boolean" then
warnOnNaN = true
end
local label = cfg.label or "wrapped optimizer"
local wrapped = {}
function wrapped:zeroGrad()
opt:zeroGrad()
end
function wrapped:step()
if maxGradNorm then
GradClip.clipNorm(params, maxGradNorm)
end
if clipValue then
GradClip.clipValue(params, clipValue)
end
if warnOnNaN then
Debug.checkGradients(params, label)
end
opt:step()
end
return wrapped
end
function Debug.checkModel(model, label: string?)
local params = model:parameters()
Debug.checkGradients(params, label)
for i, p in params do
Debug.checkTensor(p, `{label or "model"}.param{i}`)
end
end
return Debug
| 449 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/GradClip.luau | --!native
--!optimize 2
local GC = {}
function GC.clipValue(params, clip)
task.desynchronize()
for _, p in params do
if p._grad then
for i = 1, #p._grad._storage do
p._grad._storage[i] = math.clamp(p._grad._storage[i], -clip, clip)
end
end
end
task.synchronize()
end
function GC.clipNorm(params, maxNorm)
task.desynchronize()
local total = 0
for _, p in params do
if p._grad then
for i = 1, #p._grad._storage do
total += p._grad._storage[i] ^ 2
end
end
end
total = math.sqrt(total)
if total > maxNorm then
local scale = maxNorm / (total + 1e-9)
for _, p in params do
if p._grad then
for i = 1, #p._grad._storage do
p._grad._storage[i] *= scale
end
end
end
end
task.synchronize()
end
return GC
| 253 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Initializer.luau | --!native
--!optimize 2
local Types = require("./Types")
local Initializer = {}
local function _randn(): number
local u1 = math.random()
local u2 = math.random()
if u1 <= 1e-7 then
u1 = 1e-7
end
return math.sqrt(-2 * math.log(u1)) * math.cos(2 * math.pi * u2)
end
function Initializer.xavierUniform(W: Types.Tensor)
task.desynchronize()
local fanIn = W._shape[2]
local fanOut = W._shape[1]
local bound = math.sqrt(6 / (fanIn + fanOut))
for i = 1, #W._storage do
W._storage[i] = (math.random() * 2 - 1) * bound
end
task.synchronize()
end
function Initializer.kaimingUniform(W: Types.Tensor)
task.desynchronize()
local fanIn = W._shape[2]
local bound = math.sqrt(6 / fanIn)
for i = 1, #W._storage do
W._storage[i] = (math.random() * 2 - 1) * bound
end
task.synchronize()
end
function Initializer.heUniform(W: Types.Tensor)
Initializer.kaimingUniform(W)
end
-- N(0, 2 / fanIn)
function Initializer.heNormal(W: Types.Tensor)
task.desynchronize()
local fanIn = W._shape[2]
local std = math.sqrt(2 / fanIn)
for i = 1, #W._storage do
W._storage[i] = _randn() * std
end
task.synchronize()
end
-- U(-sqrt(3 / fanIn), sqrt(3 / fanIn))
function Initializer.lecunUniform(W: Types.Tensor)
task.desynchronize()
local fanIn = W._shape[2]
local bound = math.sqrt(3 / fanIn)
for i = 1, #W._storage do
W._storage[i] = (math.random() * 2 - 1) * bound
end
task.synchronize()
end
-- N(0, 1 / fanIn)
function Initializer.lecunNormal(W: Types.Tensor)
task.desynchronize()
local fanIn = W._shape[2]
local std = math.sqrt(1 / fanIn)
for i = 1, #W._storage do
W._storage[i] = _randn() * std
end
task.synchronize()
end
function Initializer.zeros(B: Types.Tensor)
task.desynchronize()
for i = 1, #B._storage do
B._storage[i] = 0
end
task.synchronize()
end
return Initializer
| 585 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Metrics.luau | --!native
--!optimize 2
local Types = require("./Types")
local M = {}
function M.accuracy(logits: Types.Tensor, targets: Types.Tensor): number
task.desynchronize()
local C, B = logits._shape[1], logits._shape[2]
local correct = 0
for j = 1, B do
local best = -1 / 0
local arg = 1
for i = 1, C do
local v = logits._storage[(i - 1) * B + j]
if v > best then
best = v
arg = i
end
end
if arg == targets[j] then
correct += 1
end
end
task.synchronize()
return correct / B
end
function M.topk(logits: Types.Tensor, targets: Types.Tensor, k: number): number
task.desynchronize()
local C, B = logits._shape[1], logits._shape[2]
local hit = 0
for j = 1, B do
local arr = {}
for i = 1, C do
arr[i] = logits._storage[(i - 1) * B + j]
end
table.sort(arr, function(a, b)
return a > b
end)
local thresh = arr[math.min(k, C)]
local t = targets[j]
local ok = false
for i = 1, C do
if logits._storage[(i - 1) * B + j] >= thresh and i == t then
ok = true
end
end
if ok then
hit += 1
end
end
task.synchronize()
return hit / B
end
function M.mse(pred: Types.Tensor, target: Types.Tensor): number
task.desynchronize()
local s = 0
for i = 1, #pred._storage do
local d = pred._storage[i] - target._storage[i]
s += d * d
end
task.synchronize()
return s / pred._shape[#pred._shape]
end
function M.prf1(pred: Types.Tensor, target: Types.Tensor, C: number): (number, number, number)
task.desynchronize()
local yhat: { number }, B: number
if type(pred) == "table" and pred._storage ~= nil then
local Cx, Bb = pred._shape[1], pred._shape[2]
B = Bb
yhat = table.create(B, 1)
for j = 1, B do
local best, arg = -1 / 0, 1
for i = 1, Cx do
local v = pred._storage[(i - 1) * B + j]
if v > best then
best, arg = v, i
end
end
yhat[j] = arg
end
else
yhat = pred
B = #yhat
end
local tpC: { number }, fpC: { number }, fnC: { number } = {}, {}, {}
for c = 1, C do
tpC[c] = 0
fpC[c] = 0
fnC[c] = 0
end
for j = 1, B do
local p, t = yhat[j], target[j]
if p and t and p >= 1 and p <= C and t >= 1 and t <= C then
if p == t then
tpC[p] += 1
else
fpC[p] += 1
fnC[t] += 1
end
end
end
local sumP, sumR, sumF = 0, 0, 0
for c = 1, C do
local pc = tpC[c] / (tpC[c] + fpC[c] + 1e-9)
local rc = tpC[c] / (tpC[c] + fnC[c] + 1e-9)
local fc = 2 * pc * rc / (pc + rc + 1e-9)
sumP += pc
sumR += rc
sumF += fc
end
task.synchronize()
return sumP / C, sumR / C, sumF / C
end
function M.confusion(pred: Types.Tensor, target: Types.Tensor, C: number): { { number } }
task.desynchronize()
local yhat: { number }, B: number
if type(pred) == "table" and pred._storage ~= nil then
local Cx, Bb = pred._shape[1], pred._shape[2]
B = Bb
yhat = table.create(B, 1)
for j = 1, B do
local best, arg = -1 / 0, 1
for i = 1, Cx do
local v = pred._storage[(i - 1) * B + j]
if v > best then
best, arg = v, i
end
end
yhat[j] = arg
end
else
yhat = pred
B = #yhat
end
local mat: { { number } } = {}
for i = 1, C do
mat[i] = table.create(C, 0)
for j = 1, C do
mat[i][j] = 0
end
end
for j = 1, B do
local t, p = target[j], yhat[j]
if t >= 1 and t <= C and p >= 1 and p <= C then
mat[t][p] += 1
end
end
task.synchronize()
return mat
end
return M
| 1,276 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/State.luau | --!native
--!optimize 2
local Types = require("./Types")
local Util = require("./Util")
local State = {}
local assert = Util.Assert
local function mapParamsToIndices(params: { Types.Tensor }): { [Types.Tensor]: string }
local map = {}
for i, p in params do
map[p] = `{i}`
end
return map
end
--@param params { Types.Tensor }
--@return Snapshot
function State.dump(params: { Types.Tensor }): Types.Snapshot
task.desynchronize()
local n = #params
local out: Types.Snapshot = table.create(n)
for i = 1, n do
local t = params[i]
assert(t and t._storage and t._shape, `State.dump: expected Tensor at params[{i}]`)
local shp = table.clone(t._shape)
local dat = table.create(#t._storage, 0)
for k = 1, #t._storage do
dat[k] = t._storage[k]
end
out[i] = { shape = shp, dtype = t._dtype or "f32", data = dat }
end
task.synchronize()
return out
end
function State.load(params: { Types.Tensor }, snap: Types.Snapshot): boolean
if snap == nil then
return false
end
task.desynchronize()
local changed = false
if #params ~= #snap then
warn(`Gradien: Model parameter count mismatch (Model: {#params}, Snapshot: {#snap})`)
end
for i = 1, math.min(#params, #snap) do
local t = params[i]
local s = snap[i]
local data = s and (s.data or s.values)
if t and data then
if #t._storage ~= #data then
warn(`Gradien: Layer {i} size mismatch (Model: {#t._storage}, Snapshot: {#data})`)
end
local n = math.min(#t._storage, #data)
for k = 1, n do
t._storage[k] = data[k] :: number
end
changed = true
end
end
task.synchronize()
return changed
end
function State.dumpModel(model: Types.Module): Types.Snapshot
return State.dump(model:parameters())
end
function State.loadModel(model: Types.Module, snap: Types.Snapshot): boolean
return State.load(model:parameters(), snap)
end
-- Serializes optimizer state by converting Tensor Keys -> Index Strings
function State.dumpOptimizer(optim: Types.Optimizer, modelParams: { Types.Tensor }): Types.OptimizerState?
if optim and type(optim.getState) == "function" then
local rawState = optim:getState()
if not rawState then
return nil
end
local serialized = table.clone(rawState)
local paramMap = mapParamsToIndices(modelParams)
for k, v in rawState do
if type(v) == "table" then
local isTensorMap = false
local newTable = {}
for tk, tv in v do
if type(tk) == "table" and tk._storage then
isTensorMap = true
local idx = paramMap[tk]
if idx then
newTable[idx] = tv
end
else
newTable[tk] = tv
end
end
if isTensorMap then
serialized[k] = newTable
end
end
end
return serialized
end
return nil
end
function State.loadOptimizer(optim: Types.Optimizer, snap: Types.OptimizerState?, modelParams: { Types.Tensor }): ()
if not snap then
return
end
if optim and type(optim.setState) == "function" then
local restored = table.clone(snap)
for k, v in snap do
if type(v) == "table" then
local reconstructed = {}
local wasParamMap = false
for idxStr, val in v do
local idx = tonumber(idxStr)
if idx and modelParams[idx] then
wasParamMap = true
reconstructed[modelParams[idx]] = val
else
reconstructed[idxStr] = val
end
end
if wasParamMap then
restored[k] = reconstructed
end
end
end
optim:setState(restored)
end
end
function State.dumpTrainer(trainer: Types.Trainer): Types.TrainerSnapshot
local params = trainer.model:parameters()
return {
model = State.dumpModel(trainer.model),
optimizer = State.dumpOptimizer(trainer.optimizer, params),
step = trainer.step or nil,
epoch = trainer.epoch or nil,
bestMetric = trainer.bestMetric,
}
end
function State.loadTrainer(trainer: Types.Trainer, snap: Types.TrainerSnapshot)
if not snap then
error("State.loadTrainer: no snapshot provided")
end
State.loadModel(trainer.model, snap.model)
if snap.optimizer then
local params = trainer.model:parameters()
State.loadOptimizer(trainer.optimizer, snap.optimizer, params)
end
trainer.step = snap.step or trainer.step or 0
trainer.epoch = snap.epoch or trainer.epoch or 0
trainer.bestMetric = snap.bestMetric
end
function State.toBuffer(snap: Types.Snapshot): buffer
return Util.Buffer.write(snap)
end
function State.fromBuffer(b: buffer): Types.Snapshot?
return Util.Buffer.read(b)
end
return State
| 1,205 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Tensor.luau | --!native
--!optimize 2
local Tensor = {}
local Util = require("./Util")
local Types = require("./Types")
local Tape -- lazy-load
local TensorMethods = {}
local function attachMethods(t)
for name, fn in TensorMethods do
t[name] = fn
end
end
export type Tensor = Types.Tensor
local sizeFromShape = Util.sizeFromShape
local assert = Util.Assert
local sqrt = math.sqrt
local log = math.log
local cos = math.cos
local sin = math.sin
local floor = math.floor
local pi = math.pi
local random = math.random
local function computeStrides(shape: { number }): { number }
task.desynchronize()
local rank = #shape
local strides = table.create(rank)
local acc: number = 1
for i = rank, 1, -1 do
strides[i] = acc
acc *= shape[i]
end
task.synchronize()
return strides
end
local function newTensor(
storage: { number },
shape: { number },
dtype: Types.DType?,
requiresGrad: boolean?,
sizeOverride: number?
): Tensor
local shapeClone = table.clone(shape)
local strides = computeStrides(shapeClone)
local t: Types.Tensor = {
_storage = storage,
_shape = shapeClone,
_dtype = dtype or "f64",
_requiresGrad = requiresGrad == true,
_size = sizeOverride or #storage,
_strides = strides,
_parents = nil,
_backprop = nil,
_grad = nil,
}
attachMethods(t :: any)
return t :: any
end
local function ensureSize(t: Types.Tensor): number
local size = t._size
if not size then
size = #t._storage
t._size = size
end
return size
end
local function is_contiguous(self: Tensor): boolean
if not self._strides then
return true
end
local computed = computeStrides(self._shape)
for i = 1, #self._strides do
if self._strides[i] ~= computed[i] then
return false
end
end
return true
end
local function contiguous(self: Tensor): Tensor
if is_contiguous(self) then
return self
end
local size = ensureSize(self)
local out = newTensor(self._storage, self._shape, self._dtype, self._requiresGrad, size)
return out
end
local function ensureStrides(t: Types.Tensor): { number }
local strides = t._strides
if not strides then
strides = computeStrides(t._shape)
t._strides = strides
end
return strides
end
function Tensor.zeros(shape: { number }, dtype: Types.DType?, requiresGrad: boolean?): Tensor
dtype = dtype or "f64"
local n = sizeFromShape(shape)
return newTensor(table.create(n, 0), shape, dtype, requiresGrad, n)
end
function Tensor.ones(shape: { number }, dtype: Types.DType?, requiresGrad: boolean?): Tensor
dtype = dtype or "f64"
local n = sizeFromShape(shape)
return newTensor(table.create(n, 1), shape, dtype, requiresGrad, n)
end
function Tensor.empty(shape: { number }, dtype: Types.DType?, requiresGrad: boolean?): Tensor
dtype = dtype or "f64"
local n = sizeFromShape(shape)
return newTensor(table.create(n), shape, dtype, requiresGrad, n)
end
function Tensor.fromArray(data: { number }, shape: { number }, dtype: Types.DType?, requiresGrad: boolean?): Tensor
local n = sizeFromShape(shape)
assert(#data == n, ("Tensor.fromArray: got %d elements, expected %d"):format(#data, n))
dtype = dtype or "f64"
return newTensor(table.clone(data), shape, dtype, requiresGrad, n)
end
function Tensor.randn(shape: { number }, dtype: Types.DType?, requiresGrad: boolean?): Tensor
dtype = dtype or "f64"
local n = sizeFromShape(shape)
local storage = table.create(n)
task.desynchronize()
for i = 1, n, 2 do
local u1 = random()
local u2 = random()
local radius = sqrt(-2 * log(u1))
local theta = 2 * pi * u2
local z0 = radius * cos(theta)
local z1 = radius * sin(theta)
storage[i] = z0
if i + 1 <= n then
storage[i + 1] = z1
end
end
task.synchronize()
return newTensor(storage, shape, dtype, requiresGrad, n)
end
local function reshape(self: Tensor, newShape: { number }): Tensor
local size = ensureSize(self)
assert(sizeFromShape(newShape) == size, "reshape: element count mismatch")
local out = newTensor(self._storage, newShape, self._dtype, self._requiresGrad, size)
if not self._requiresGrad then
return out
end
if not Tape then
Tape = require("./autograd/Tape") :: any
end
return Tape.makeNode(out, { self }, function(gy: Types.Tensor)
if self._requiresGrad then
self._grad = self._grad or Tensor.zeros(self._shape, self._dtype, false)
task.desynchronize()
local gs, ys = (self._grad :: Types.Tensor)._storage, gy._storage
for i = 1, #ys do
gs[i] += ys[i]
end
task.synchronize()
end
end)
end
local function expand(self: Tensor, newShape: { number }): Tensor
local rank = #self._shape
local newRank = #newShape
assert(newRank >= rank, "expand: new rank must be >= old rank")
local expansionStrides = table.create(newRank, 0)
local oldShapeExpanded = table.create(newRank, 1)
local oldStrides = ensureStrides(self)
local oldStridesExpanded = table.create(newRank, 0)
for i = 1, rank do
oldShapeExpanded[newRank - rank + i] = self._shape[i]
oldStridesExpanded[newRank - rank + i] = oldStrides[i]
end
for i = 1, newRank do
if oldShapeExpanded[i] == 1 and newShape[i] > 1 then
expansionStrides[i] = 0
elseif oldShapeExpanded[i] == newShape[i] then
expansionStrides[i] = oldStridesExpanded[i]
else
error("expand: incompatible shapes")
end
end
local outSize = sizeFromShape(newShape)
local outStorage = table.create(outSize)
task.desynchronize()
local src = self._storage
local coord = table.create(newRank, 0)
for flatOut = 1, outSize do
local srcOffset = 0
for d = 1, newRank do
srcOffset += coord[d] * expansionStrides[d]
end
outStorage[flatOut] = src[srcOffset + 1]
for d = newRank, 1, -1 do
local val = coord[d] + 1
if val < newShape[d] then
coord[d] = val
break
end
coord[d] = 0
end
end
task.synchronize()
local out = newTensor(outStorage, newShape, self._dtype, self._requiresGrad, outSize)
if not self._requiresGrad then
return out
end
if not Tape then
Tape = require("./autograd/Tape") :: any
end
local dtype = self._dtype
local shapeCopy = table.clone(self._shape)
return Tape.makeNode(out, { self }, function(gy: Types.Tensor)
if not self._requiresGrad then
return
end
self._grad = self._grad or Tensor.zeros(shapeCopy, dtype, false)
task.desynchronize()
local gs = (self._grad :: Types.Tensor)._storage
local gys = gy._storage
local coordBack = table.create(newRank, 0)
for flatOut = 1, outSize do
local srcOffset = 0
for d = 1, newRank do
srcOffset += coordBack[d] * expansionStrides[d]
end
gs[srcOffset + 1] += gys[flatOut]
for d = newRank, 1, -1 do
local val = coordBack[d] + 1
if val < newShape[d] then
coordBack[d] = val
break
end
coordBack[d] = 0
end
end
task.synchronize()
end)
end
local function slice(self: Tensor, dim: number, startIdx: number, endIdx: number?, step: number?): Tensor
local shape = self._shape
local rank = #shape
assert(dim >= 1 and dim <= rank, "slice: dim out of range")
local sizeDim = shape[dim]
local s = startIdx
local e = endIdx or sizeDim
local st = step or 1
assert(st > 0, "slice: step must be > 0")
assert(s >= 1 and s <= sizeDim, "slice: startIdx out of bounds")
assert(e >= 1 and e <= sizeDim, "slice: endIdx out of bounds")
assert(e >= s, "slice: endIdx must be >= startIdx")
local length = floor((e - s) / st) + 1
local outShape = table.clone(shape)
outShape[dim] = length
local outSize = sizeFromShape(outShape)
local inStrides = ensureStrides(self)
local outStorage = table.create(outSize)
local indexMap = self._requiresGrad and table.create(outSize) or nil
task.desynchronize()
local coord = table.create(rank, 1)
local srcStorage = self._storage
for flatOut = 1, outSize do
local posDim = s + (coord[dim] - 1) * st
local flatIn0 = 0
for d = 1, rank do
local cd = coord[d]
if d == dim then
cd = posDim
end
flatIn0 += (cd - 1) * inStrides[d]
end
local storageIndex = flatIn0 + 1
outStorage[flatOut] = srcStorage[storageIndex]
if indexMap then
indexMap[flatOut] = storageIndex
end
for d = rank, 1, -1 do
local val = coord[d] + 1
if val <= outShape[d] then
coord[d] = val
break
end
coord[d] = 1
end
end
task.synchronize()
local out = newTensor(outStorage, outShape, self._dtype, self._requiresGrad, outSize)
if not self._requiresGrad then
return out
end
if not Tape then
Tape = require("./autograd/Tape") :: any
end
local shapeCopy = table.clone(shape)
local mapCopy = indexMap
local dtype = self._dtype
return Tape.makeNode(out, { self }, function(gy: Types.Tensor)
if not self._requiresGrad then
return
end
self._grad = self._grad or Tensor.zeros(shapeCopy, dtype, false)
task.desynchronize()
local gsrc = (self._grad :: Types.Tensor)._storage
local gys = gy._storage
if mapCopy then
for i = 1, #gys do
local dest = mapCopy[i]
if dest then
gsrc[dest] += gys[i]
end
end
end
task.synchronize()
end)
end
local function transpose(self: Tensor, dim1: number?, dim2: number?): Tensor
local shape = self._shape
local rank = #shape
local d1 = dim1
local d2 = dim2
if d1 == nil and d2 == nil then
assert(rank == 2, "transpose: default dims only valid for rank-2 tensors")
d1, d2 = 1, 2
else
assert(d1 ~= nil and d2 ~= nil, "transpose: both dim1 and dim2 must be provided")
end
assert(d1 >= 1 and d1 <= rank, "transpose: dim1 out of range")
assert(d2 >= 1 and d2 <= rank, "transpose: dim2 out of range")
assert(d1 ~= d2, "transpose: dim1 and dim2 must be different")
local perm = table.create(rank)
for i = 1, rank do
perm[i] = i
end
perm[d1], perm[d2] = perm[d2], perm[d1]
local outShape = table.create(rank)
for i = 1, rank do
outShape[i] = shape[perm[i]]
end
local size = ensureSize(self)
local outSize = size
local outStrides = computeStrides(outShape)
local dst = table.create(outSize)
local indexMap = self._requiresGrad and table.create(outSize) or nil
task.desynchronize()
local coordIn = table.create(rank, 1)
for flatIn = 1, size do
local flatOut0 = 0
for outDim = 1, rank do
local inDim = perm[outDim]
local c = coordIn[inDim]
flatOut0 += (c - 1) * outStrides[outDim]
end
local outIndex = flatOut0 + 1
dst[outIndex] = self._storage[flatIn]
if indexMap then
indexMap[outIndex] = flatIn
end
for d = rank, 1, -1 do
local val = coordIn[d] + 1
if val <= shape[d] then
coordIn[d] = val
break
end
coordIn[d] = 1
end
end
task.synchronize()
local out = newTensor(dst, outShape, self._dtype, self._requiresGrad, outSize)
if not self._requiresGrad then
return out
end
if not Tape then
Tape = require("./autograd/Tape") :: any
end
local shapeCopy = table.clone(shape)
local mapCopy = indexMap
local dtype = self._dtype
return Tape.makeNode(out, { self }, function(gy: Types.Tensor)
if not self._requiresGrad then
return
end
self._grad = self._grad or Tensor.zeros(shapeCopy, dtype, false)
task.desynchronize()
local gsrc = (self._grad :: Types.Tensor)._storage
local gys = gy._storage
if mapCopy then
for i = 1, #gys do
local srcIdx = mapCopy[i]
if srcIdx then
gsrc[srcIdx] += gys[i]
end
end
end
task.synchronize()
end)
end
local function narrow(self: Tensor, dim: number, startIdx: number, length: number): Tensor
assert(length >= 1, "narrow: length must be >= 1")
local endIdx = startIdx + length - 1
return slice(self, dim, startIdx, endIdx, 1)
end
local function sum(self: Tensor, dim: number?): Tensor
if dim then
error("Tensor.sum with dim not implemented yet")
end
local s = 0
local storage = self._storage
task.desynchronize()
for i = 1, #storage do
s += storage[i]
end
task.synchronize()
local out = newTensor({ s }, { 1 }, self._dtype, self._requiresGrad, 1)
if not self._requiresGrad then
return out
end
if not Tape then
Tape = require("./autograd/Tape") :: any
end
return Tape.makeNode(out, { self }, function(gy: Types.Tensor)
if self._requiresGrad then
self._grad = self._grad or Tensor.zeros(self._shape, self._dtype, false)
local g = gy._storage[1]
task.desynchronize()
local gs = (self._grad :: Types.Tensor)._storage
for i = 1, #gs do
gs[i] += g
end
task.synchronize()
end
end)
end
local function detach(self: Tensor): Tensor
return newTensor(self._storage, self._shape, self._dtype, false, ensureSize(self))
end
local function noGrad(self: Tensor): ()
self._requiresGrad = false
self._grad = nil
end
local function backward(self: Tensor, grad: Tensor?)
if not self._requiresGrad then
error("Tensor does not require grad")
end
if not Tape then
Tape = require("./autograd/Tape") :: any
end
if not grad then
if self._size == 1 then
grad = Tensor.ones(self._shape, self._dtype, false)
else
error("backward: grad must be provided for non-scalar tensors")
end
end
Tape.backwardFrom(self, grad)
end
TensorMethods.reshape = reshape
Tensor.reshape = reshape
TensorMethods.expand = expand
Tensor.expand = expand
TensorMethods.is_contiguous = is_contiguous
Tensor.is_contiguous = is_contiguous
TensorMethods.contiguous = contiguous
Tensor.contiguous = contiguous
TensorMethods.slice = slice
Tensor.slice = slice
TensorMethods.transpose = transpose
Tensor.transpose = transpose
TensorMethods.narrow = narrow
Tensor.narrow = narrow
TensorMethods.sum = sum
Tensor.sum = sum
TensorMethods.detach = detach
Tensor.detach = detach
TensorMethods.noGrad = noGrad
Tensor.noGrad = noGrad
TensorMethods.backward = backward
Tensor.backward = backward
return Tensor
| 3,943 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Trainer.luau | --!native
--!optimize 2
local Tape = require("./autograd/Tape")
local Types = require("./Types")
local Losses = require("./nn/Losses")
local Metrics = require("./Metrics")
local Util = require("./Util")
local Trainer = {}
Trainer.__index = Trainer
local assert = Util.Assert
local function asArrayCallbacks(raw: Types.Callbacks?, default: { Types.CallbackFn }?): { Types.CallbackFn }
if type(raw) ~= "table" then
return default or {}
end
if not next(raw) then
return raw :: { Types.CallbackFn }
end
local tbl = raw :: Types.CallbackTable
local out: { Types.CallbackFn } = {}
if tbl.onStep then
local fn = tbl.onStep
table.insert(out, function(event: Types.TrainerEvent, ctx: Types.CallbackContext)
if event == "step_end" then
fn(ctx)
end
end)
end
if tbl.onEpochEnd then
local fn = tbl.onEpochEnd
table.insert(out, function(event: Types.TrainerEvent, ctx: Types.CallbackContext)
if event == "epoch_end" then
fn(ctx)
end
end)
end
if tbl.onBest then
local fn = tbl.onBest
table.insert(out, function(event: Types.TrainerEvent, ctx: Types.CallbackContext)
if event == "best" then
fn(ctx)
end
end)
end
return out
end
local function fireCallbacks(callbacks: { Types.CallbackFn }, event: Types.TrainerEvent, ctx: Types.CallbackContext)
for _, cb in callbacks do
cb(event, ctx)
end
end
local function runSimple(cfg: Types.SimpleConfig): ()
task.desynchronize()
local model = cfg.model
local opt = cfg.optimizer(model:parameters())
local lossFn = cfg.loss
local loader = cfg.loader
local metricFn = cfg.metric
local steps = cfg.steps or 100
local reportEvery = cfg.reportEvery or 10
local onMetric = cfg.onMetric
local callbacks = asArrayCallbacks(cfg.callbacks, nil)
local bestMetric: number? = nil
for step = 1, steps do
opt:zeroGrad()
local X, Y = loader()
local out = model:forward(X)
local lossValue, grad = lossFn(out, Y)
Tape.backwardFrom(out, grad)
opt:step()
local metricValue: number? = nil
if metricFn and (step % reportEvery == 0) then
local m = metricFn(out, Y)
metricValue = m
if onMetric then
onMetric(m)
end
if bestMetric == nil or m > bestMetric then
bestMetric = m
if #callbacks > 0 then
fireCallbacks(callbacks, "best", {
epoch = 1,
step = step,
loss = lossValue,
metric = m,
model = model,
optimizer = opt,
})
end
end
end
if #callbacks > 0 then
fireCallbacks(callbacks, "step_end", {
epoch = 1,
step = step,
loss = lossValue,
metric = metricValue,
model = model,
optimizer = opt,
})
end
end
task.synchronize()
end
--@param cfg { model: Module, optimizerFactory: (({ Tensor }) -> Optimizer)?, optimizer: Optimizer?, loss: LossFn, metric: ((Tensor, Tensor) -> number)?, reportEvery: number?, callbacks: Callbacks? }
--@return Trainer
function Trainer.new(cfg: Types.TrainerConfig)
local model = cfg.model
local params = model:parameters()
local opt: Types.Optimizer
if cfg.optimizerFactory then
opt = cfg.optimizerFactory(params)
else
assert(cfg.optimizer, "Trainer.new: provide optimizerFactory OR optimizer instance")
opt = cfg.optimizer :: Types.Optimizer
end
local self = setmetatable({
model = model,
optimizer = opt,
loss = cfg.loss,
metric = cfg.metric,
reportEvery = cfg.reportEvery or 10,
lrScheduler = cfg.lrScheduler,
callbacks = asArrayCallbacks(cfg.callbacks, {}),
bestMetric = nil,
step = 0,
epoch = 1,
}, Trainer)
return self
end
--@param makeLoader () -> () -> (Tensor?, Tensor?)
--@param opts { epochs: number?, stepsPerEpoch: number?, onMetric: ((number, number, number) -> ())? }
function Trainer:fit(makeLoader: () -> () -> (Types.Tensor?, Types.Tensor?), opts: Types.FitOptions?)
local fitOpts = (opts or {}) :: Types.FitOptions
local epochs = fitOpts.epochs or self.epoch or 1
local stepsPerEpoch = fitOpts.stepsPerEpoch
local onMetric = fitOpts.onMetric
for epoch = 1, epochs do
self.epoch = epoch
local loader = makeLoader()
local lastLoss: number? = nil
local lastMetric: number? = nil
local stepsThisEpoch = 0
while true do
local X, Y = loader()
if not X then
break
end
self.step += 1
stepsThisEpoch += 1
self.optimizer:zeroGrad()
local out = self.model:forward(X)
local lossValue, grad = self.loss(out, Y)
Tape.backwardFrom(out, grad)
self.optimizer:step()
if self.lrScheduler then
local newLr = self.lrScheduler(self.step)
if type(newLr) == "number" then
if type(self.optimizer.setLr) == "function" then
self.optimizer:setLr(newLr)
elseif type(self.optimizer.setLR) == "function" then
self.optimizer:setLR(newLr)
end
end
end
lastLoss = lossValue
local metricValue: number? = nil
if self.metric and self.reportEvery > 0 and (self.step % self.reportEvery == 0) then
local m = self.metric(out, Y)
metricValue = m
lastMetric = m
if onMetric then
onMetric(epoch, self.step, m)
end
if self.bestMetric == nil or m > (self.bestMetric :: number) then
self.bestMetric = m
fireCallbacks(self.callbacks, "best", {
epoch = epoch,
step = self.step,
loss = lossValue,
metric = m,
model = self.model,
optimizer = self.optimizer,
})
end
end
fireCallbacks(self.callbacks, "step_end", {
epoch = epoch,
step = self.step,
loss = lossValue,
metric = metricValue,
model = self.model,
optimizer = self.optimizer,
})
if stepsPerEpoch and stepsThisEpoch >= stepsPerEpoch then
break
end
end
fireCallbacks(self.callbacks, "epoch_end", {
epoch = epoch,
step = self.step,
loss = lastLoss,
metric = lastMetric,
model = self.model,
optimizer = self.optimizer,
})
end
end
--@param cfg Types.TrainerConfig
--@param opts { smoothing: number?, loss: Types.LossFn?, metric: ((Types.Tensor, any) -> number)? }?
function Trainer.newClassification(
cfg: Types.TrainerConfig,
opts: {
smoothing: number?,
loss: Types.LossFn?,
metric: ((Types.Tensor, any) -> number)?,
}?
)
local cfgOpts = (opts or {}) :: {
smoothing: number?,
loss: Types.LossFn?,
metric: ((Types.Tensor, any) -> number)?,
}
local smoothing = cfgOpts.smoothing
local lossFn = cfgOpts.loss or cfg.loss
if not lossFn then
lossFn = function(logits, target)
return Losses.cross_entropy_backward(logits, target, smoothing)
end
end
local metricFn = cfgOpts.metric or cfg.metric
if not metricFn then
metricFn = function(logits, target)
return Metrics.accuracy(logits, target)
end
end
return Trainer.new({
model = cfg.model,
optimizerFactory = cfg.optimizerFactory,
optimizer = cfg.optimizer,
loss = lossFn,
metric = metricFn,
reportEvery = cfg.reportEvery,
lrScheduler = cfg.lrScheduler,
callbacks = cfg.callbacks,
})
end
function Trainer:run(loader: () -> (Types.Tensor?, Types.Tensor?), opts: Types.FitOptions?)
local function makeLoader()
return loader
end
self:fit(makeLoader, opts)
end
setmetatable(Trainer, {
__call = function(_, cfg: Types.SimpleConfig)
return runSimple(cfg)
end,
})
return Trainer
| 1,961 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Types.luau | --!strict
export type DType = "f64" | "f32" | "i32" | "u8"
export type Shape = { number }
export type Storage = { number }
export type Tensor = {
_storage: Storage,
_shape: Shape,
_dtype: DType,
_requiresGrad: boolean,
_size: number,
_strides: { number }?,
_parents: { Tensor }?,
_backprop: ((grad: Tensor) -> ())?,
_grad: Tensor?,
}
export type Module<TIn = Tensor, TOut = Tensor> = {
forward: (self: Module<TIn, TOut>, x: TIn) -> TOut,
parameters: (self: Module<TIn, TOut>) -> { Tensor },
}
export type OptimizerState = {
lr: number,
b1: number,
b2: number,
eps: number,
t: number,
m: { [Tensor]: { [number]: number } },
v: { [Tensor]: { [number]: number } },
}
export type Optimizer = {
step: (self: Optimizer) -> (),
zeroGrad: (self: Optimizer) -> (),
getState: (self: Optimizer) -> OptimizerState?,
setState: (self: Optimizer, state: OptimizerState?) -> (),
}
export type LossFn = (pred: Tensor, target: Tensor) -> (number, Tensor)
export type Dataset = {
size: (self: Dataset) -> number,
at: (self: Dataset, i: number) -> (Tensor, Tensor),
batch: (self: Dataset, indices: { number }) -> (Tensor, Tensor),
slice: (self: Dataset, i: number, j: number) -> (Tensor, Tensor),
}
export type BatchIter = () -> ({ number }, { number }) | nil
export type Snapshot = { SnapshotTensor }
export type TrainerSnapshot = {
model: Snapshot,
optimizer: OptimizerState?,
step: number?,
epoch: number?,
bestMetric: number?,
}
export type SnapshotTensor = {
shape: { number },
dtype: DType,
data: { number },
}
export type TrainerEvent = "step_end" | "epoch_end" | "best"
export type CallbackContext = {
epoch: number,
step: number?,
loss: number?,
metric: number?,
model: Module,
optimizer: Optimizer,
}
export type CallbackFn = (TrainerEvent, CallbackContext) -> ()
export type CallbackTable = {
onStep: ((CallbackContext) -> ())?,
onEpochEnd: ((CallbackContext) -> ())?,
onBest: ((CallbackContext) -> ())?,
}
export type Callbacks = { CallbackFn } | CallbackTable
export type SimpleConfig = {
model: Module,
optimizer: (params: { Tensor }) -> Optimizer,
loss: LossFn,
loader: () -> (Tensor, Tensor),
metric: ((Tensor, Tensor) -> number)?,
steps: number?,
reportEvery: number?,
onMetric: ((number) -> ())?,
callbacks: Callbacks?,
}
export type TrainerConfig = {
model: Module,
optimizerFactory: (({ Tensor }) -> Optimizer)?,
optimizer: Optimizer?,
loss: LossFn,
metric: ((Tensor, Tensor) -> number)?,
reportEvery: number?,
lrScheduler: ((number) -> number)?,
callbacks: Callbacks?,
}
export type FitOptions = {
epochs: number?,
stepsPerEpoch: number?,
onMetric: ((number, number, number) -> ())?, -- (epoch, step, metric)
}
export type Trainer = {
step: number,
epoch: number,
model: Module,
optimizer: Optimizer,
loss: LossFn,
metric: ((Tensor, Tensor) -> number)?,
lrScheduler: ((number) -> number)?,
reportEvery: number?,
callbacks: { CallbackFn },
bestMetric: number?,
}
export type Sample = {
name: string,
total: number,
self: number,
count: number,
avg: number,
selfAvg: number,
min: number,
max: number,
last: number,
percent: number,
}
export type Stat = {
name: string,
total: number,
selfTime: number,
count: number,
min: number,
max: number,
last: number,
}
export type Marker = {
name: string,
start: number,
child: number,
}
export type Callable = (...any) -> ...any
return nil
| 946 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Util/Anomaly.luau | --!native
--!optimize 2
local Types = require("../Types")
local Anomaly = {}
function Anomaly.hasBadValues(t: Types.Tensor)
for i = 1, #t._storage do
local v = t._storage[i]
if v ~= v or v == math.huge or v == -math.huge then
return true
end
end
return false
end
function Anomaly.hasNaN(t: Types.Tensor)
for i = 1, #t._storage do
local v = t._storage[i]
if v ~= v then
return true
end
end
return false
end
function Anomaly.hasInf(t: Types.Tensor)
for i = 1, #t._storage do
local v = t._storage[i]
if v == math.huge or v == -math.huge then
return true
end
end
return false
end
return Anomaly
| 205 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Util/Assert.luau | --!optimize 2
--@Eternity_Devs
return function<T>(condition: T, errorMessage: string, level: number?): T
if not (condition :: any) then
error(errorMessage, level or 2)
end
return condition
end
| 58 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Util/Buffer/Dedicated.luau | --!native
--!native
--!optimize 2
--@Eternity_Devs
--from Warp lib
local DedicatedBuffer = {}
local create = buffer.create
local copy = buffer.copy
local writei8 = buffer.writei8
local writei16 = buffer.writei16
local writei32 = buffer.writei32
local writeu8 = buffer.writeu8
local writeu16 = buffer.writeu16
local writeu32 = buffer.writeu32
local writef32 = buffer.writef32
local writef64 = buffer.writef64
local writestring = buffer.writestring
local default: { [string]: number } = {
point = 0,
next = 0,
size = 128,
bufferSize = 128,
}
local function copyMethod(self: any, offset: number, b: buffer?, src: buffer?, srcOffset: number?, count: number?)
if not b then
copy(create(count or default.size), offset, src or self.buffer, srcOffset, count)
else
copy(b, offset, src or self.buffer, srcOffset, count)
end
end
local function alloc(self: any, byte: number)
local need = self.next + byte
if need > self.size then
local newSize = self.size
repeat
newSize = math.floor(newSize * 1.25 + 0.5)
until newSize < need and not (newSize < need) or newSize >= need
if newSize < need then
newSize = need
end
local newBuffer: buffer = create(newSize)
copy(newBuffer, 0, self.buffer, 0, self.next)
self.buffer = newBuffer
self.size = newSize
end
self.point = self.next
self.next += byte
end
local function build(self: any): buffer
local p: number = self.next > self.point and self.next or self.point
local buildBuffer: buffer = create(p)
copy(buildBuffer, 0, self.buffer, 0, p)
return buildBuffer
end
local function buildAndRemove(self: any): (buffer, any?)
local p: number = self.next > self.point and self.next or self.point
local buildBuffer: buffer = create(p)
local ref = #self.ref > 0 and table.clone(self.ref) or nil
copy(buildBuffer, 0, self.buffer, 0, p)
self:remove()
return buildBuffer, ref
end
local function wi8(self: any, val: number, allocBytes: number?)
if not val then
return
end
self:alloc(allocBytes or 1)
writei8(self.buffer, self.point, val)
end
local function wi16(self: any, val: number, allocBytes: number?)
if not val then
return
end
self:alloc(allocBytes or 2)
writei16(self.buffer, self.point, val)
end
local function wi32(self: any, val: number, allocBytes: number?)
if not val then
return
end
self:alloc(allocBytes or 4)
writei32(self.buffer, self.point, val)
end
local function wu8(self: any, val: number, allocBytes: number?)
if not val then
return
end
self:alloc(allocBytes or 1)
writeu8(self.buffer, self.point, val)
end
local function wu16(self: any, val: number, allocBytes: number?)
if not val then
return
end
self:alloc(allocBytes or 2)
writeu16(self.buffer, self.point, val)
end
local function wu32(self: any, val: number, allocBytes: number?)
if not val then
return
end
self:alloc(allocBytes or 4)
writeu32(self.buffer, self.point, val)
end
local function wf32(self: any, val: number, allocBytes: number?)
if not val then
return
end
self:alloc(allocBytes or 4)
writef32(self.buffer, self.point, val)
end
local function wf64(self: any, val: number, allocBytes: number?)
if not val then
return
end
self:alloc(allocBytes or 8)
writef64(self.buffer, self.point, val)
end
local function wstring(self: any, val: string)
if not val then
return
end
self:alloc(#val)
writestring(self.buffer, self.point, val)
end
local function wType(self: any, ref: number)
writeu8(self.buffer, self.point, ref)
self.point += 1
end
local function wRef(self: any, value: any)
if not value then
return
end
table.insert(self.ref, value)
local index = #self.ref
self:alloc(2)
writeu16(self.buffer, self.point, index)
end
local function pack(self: any, data: any)
local dataType: string = typeof(data)
if dataType == "nil" then
self:wi8(0)
elseif dataType == "Instance" then
self:wi8(-1)
self:wRef(data)
elseif dataType == "table" then
local count = 0
for _ in data do
count += 1
end
local isArray: boolean = (#data == count)
if isArray then
self:wi8(-2)
self:wu16(count)
for i = 1, count do
self:pack(data[i])
end
else
self:wi8(-3)
self:wu16(count)
for k, v in data do
self:pack(k)
self:pack(v)
end
end
elseif dataType == "EnumItem" then
self:wi8(-4)
local enumName: string = `{data.EnumType}`
self:wi8(#enumName)
self:wstring(enumName)
self:wu16(data.Value)
elseif dataType == "BrickColor" then
self:wi8(-5)
self:wi16(data.Number)
elseif dataType == "Enum" then
self:wi8(-6)
local enumName: string = data.Name
self:wi8(#enumName)
self:wstring(enumName)
elseif dataType == "number" then
if math.floor(data) == data then
if data >= 0 and data <= 255 then
self:wi8(1)
self:wu8(data)
elseif data >= -32768 and data <= 32767 then
self:wi8(2)
self:wi16(data)
elseif data >= -2147483648 and data <= 2147483647 then
self:wi8(3)
self:wi32(data)
else
self:wi8(4)
self:wf64(data)
end
else
self:wi8(4)
self:wf64(data)
end
elseif dataType == "boolean" then
self:wi8(data and 5 or 6)
elseif dataType == "string" then
local length = #data
if length <= 255 then
self:wi8(7)
self:wu8(length)
elseif length <= 65535 then
self:wi8(8)
self:wu16(length)
else
self:wi8(9)
self:wi32(length)
end
self:wstring(data)
elseif dataType == "Vector3" then
self:wi8(10)
self:wf32(data.X)
self:wf32(data.Y)
self:wf32(data.Z)
elseif dataType == "Vector2" then
self:wi8(11)
self:wf32(data.X)
self:wf32(data.Y)
elseif dataType == "CFrame" then
self:wi8(12)
for _, v in { data:GetComponents() } do
self:wf32(v)
end
elseif dataType == "Color3" then
self:wi8(13)
local r = math.clamp(math.floor(data.R * 255 + 0.5), 0, 255)
local g = math.clamp(math.floor(data.G * 255 + 0.5), 0, 255)
local b = math.clamp(math.floor(data.B * 255 + 0.5), 0, 255)
self:wu8(r)
self:wu8(g)
self:wu8(b)
else
warn(`Unsupported data type: {dataType} value: {data}`)
end
end
local function flush(self: any)
self.point = default.point
self.next = default.next
self.size = default.size
self.buffer = create(default.bufferSize)
table.clear(self.ref)
end
local function remove(self: any)
self:flush()
table.clear(self)
end
local methods = {
copy = copyMethod,
alloc = alloc,
build = build,
buildAndRemove = buildAndRemove,
wi8 = wi8,
wi16 = wi16,
wi32 = wi32,
wu8 = wu8,
wu16 = wu16,
wu32 = wu32,
wf32 = wf32,
wf64 = wf64,
wstring = wstring,
wType = wType,
wRef = wRef,
pack = pack,
flush = flush,
remove = remove,
}
for name, fn in methods do
DedicatedBuffer[name] = fn
end
function DedicatedBuffer.new()
local obj = {
point = default.point,
next = default.next,
size = default.size,
buffer = create(default.bufferSize),
ref = {},
}
for name, fn in methods do
obj[name] = fn
end
return obj
end
export type DedicatedType = typeof(DedicatedBuffer.new())
return DedicatedBuffer.new :: typeof(DedicatedBuffer.new)
| 2,160 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Util/Buffer/init.luau | --!native
--!native
--!optimize 2
--@Eternity_Devs
--from Warp lib & extended
local assert = require("./Assert")
local Buffer = {}
Buffer.__index = Buffer
local Dedicated = require(script.Dedicated)
local tostring = buffer.tostring
local fromstring = buffer.fromstring
local readu8 = buffer.readu8
local readi8 = buffer.readi8
local readu16 = buffer.readu16
local readi16 = buffer.readi16
local readi32 = buffer.readi32
local readf32 = buffer.readf32
local readf64 = buffer.readf64
local readstring = buffer.readstring
local writeu8 = buffer.writeu8
local writei32 = buffer.writei32
local writef32 = buffer.writef32
local writef64 = buffer.writef64
local len = buffer.len
local create = buffer.create
local dtypeInfo = {
f64 = {
bytes = 8,
read = readf64,
write = writef64,
},
f32 = {
bytes = 4,
read = readf32,
write = writef32,
},
i32 = {
bytes = 4,
read = readi32,
write = writei32,
},
u8 = {
bytes = 1,
read = readu8,
write = writeu8,
},
}
local function ensureDType(dtype: string?)
local info = dtypeInfo[dtype or "f64"]
assert(info, `Buffer: unsupported dtype {dtype}`)
return info
end
local function readValue(b: buffer, position: number, ref: { any }?): (any, number)
local typeByte = readi8(b, position)
position += 1
if typeByte == 0 then -- nil
return nil, position
elseif typeByte == -1 then -- Instance
if type(ref) ~= "table" then
return nil, position + 1 -- still consume the index (compat if kept u8)
end
local idx = readu16(b, position)
local value = ref[idx]
if typeof(value) == "Instance" then
return value, position + 2
end
return nil, position + 2
elseif typeByte == -2 then -- array
local length = readu16(b, position)
position += 2
local array = {}
for _ = 1, length do
local value
value, position = readValue(b, position, ref)
table.insert(array, value)
end
return array, position
elseif typeByte == -3 then -- dictionary
local length = readu16(b, position)
position += 2
local dict = {}
for _ = 1, length do
local key, value
key, position = readValue(b, position, ref)
value, position = readValue(b, position, ref)
dict[key] = value
end
return dict, position
elseif typeByte == -4 then -- EnumItem
local length = readu8(b, position)
local enumName = readstring(b, position + 1, length)
local enumVal = readu16(b, position + 1 + length)
return Enum[enumName]:FromValue(enumVal), position + 3 + length
elseif typeByte == -5 then -- BrickColor
local value = readi16(b, position)
return BrickColor.new(value), position + 2
elseif typeByte == -6 then -- Enum
local length = readu8(b, position)
local enumName = readstring(b, position + 1, length)
return Enum[enumName], position + 1 + length
elseif typeByte == 1 then -- int u8
local value = readu8(b, position)
return value, position + 1
elseif typeByte == 2 then -- int i16
local value = readi16(b, position)
return value, position + 2
elseif typeByte == 3 then -- int i32
local value = readi32(b, position)
return value, position + 4
elseif typeByte == 4 then -- f64
local value = readf64(b, position)
return value, position + 8
elseif typeByte == 5 then
return true, position
elseif typeByte == 6 then
return false, position
elseif typeByte == 7 then -- string u8
local length = readu8(b, position)
local value = readstring(b, position + 1, length)
return value, position + length + 1
elseif typeByte == 8 then -- string u16
local length = readu16(b, position)
local value = readstring(b, position + 2, length)
return value, position + length + 2
elseif typeByte == 9 then -- string i32
local length = readi32(b, position)
local value = readstring(b, position + 4, length)
return value, position + length + 4
elseif typeByte == 10 then -- Vector3
local x = readf32(b, position)
local y = readf32(b, position + 4)
local z = readf32(b, position + 8)
return Vector3.new(x, y, z), position + 12
elseif typeByte == 11 then -- Vector2
local x = readf32(b, position)
local y = readf32(b, position + 4)
return Vector2.new(x, y), position + 8
elseif typeByte == 12 then -- CFrame
local components = {}
for i = 1, 12 do
table.insert(components, readf32(b, position + (i - 1) * 4))
end
return CFrame.new(unpack(components)), position + 48
elseif typeByte == 13 then -- Color3
local r = readu8(b, position)
local g = readu8(b, position + 1)
local channelB = readu8(b, position + 2)
return Color3.fromRGB(r, g, channelB), position + 3
end
error(`Unsupported type marker: {typeByte}`)
end
function Buffer.new(): Dedicated.DedicatedType
return Dedicated()
end
function Buffer.convert(b: buffer): string
return tostring(b)
end
function Buffer.revert(s: string): buffer
return fromstring(s)
end
function Buffer.write(data: any): (buffer, any?)
local newBuffer = Dedicated()
newBuffer:pack(data)
return newBuffer:buildAndRemove()
end
function Buffer.read(b: buffer, ref: { any }?): any?
local position = 0
local result = {}
while position < len(b) do
local value
value, position = readValue(b, position, ref)
table.insert(result, value)
end
ref = nil
return result
end
function Buffer.writeDenseArray(data: { number }, dtype: string?, existing: buffer?): buffer
local info = ensureDType(dtype)
local count = #data
local totalBytes = count * info.bytes
local buf = existing
if not buf or len(buf) ~= totalBytes then
buf = create(totalBytes)
end
local offset = 0
for i = 1, count do
info.write(buf, offset, data[i])
offset += info.bytes
end
return buf
end
function Buffer.readDenseArray(buf: buffer, dtype: string?, out: { number }?): { number }
local info = ensureDType(dtype)
local bytes = info.bytes
local count = math.floor(len(buf) / bytes)
local dest = out
if not dest or #dest ~= count then
dest = table.create(count)
end
local offset = 0
for i = 1, count do
dest[i] = info.read(buf, offset)
offset += bytes
end
return dest
end
function Buffer.copyDenseToColumn(
buf: buffer,
dtype: string?,
target: { number },
column: number,
batch: number,
length: number?
)
local info = ensureDType(dtype)
local bytes = info.bytes
local elements = length or math.floor(len(buf) / bytes)
local offset = 0
local idx = column
for _ = 1, elements do
target[idx] = info.read(buf, offset)
offset += bytes
idx += batch
end
end
return Buffer :: typeof(Buffer)
| 1,870 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Util/GradStats.luau | --!native
--!optimize 2
local Types = require("../Types")
local GradStats = {}
local function stats(t: Types.Tensor): (number, number, number, number)
local n = #t._storage
if n == 0 then
return 0, 0, 0, 0
end
task.desynchronize()
local minv, maxv = math.huge, -math.huge
local sum, sumsq = 0, 0
for i = 1, n do
local v = t._storage[i]
if v < minv then
minv = v
end
if v > maxv then
maxv = v
end
sum += v
sumsq += v * v
end
local mean = sum / n
local var = math.max(sumsq / n - mean * mean, 0)
local std = math.sqrt(var)
task.synchronize()
return minv, maxv, mean, std
end
function GradStats.forModel(model: Types.Module): { { min: number, max: number, mean: number, std: number, n: number } }
local ps = model:parameters()
local out = {}
for i, p in ps do
if p._grad then
local minv, maxv, mean, std = stats(p._grad)
out[i] = {
min = minv,
max = maxv,
mean = mean,
std = std,
n = #p._grad._storage,
}
end
end
return out
end
return GradStats
| 350 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Util/Hooks.luau | --!optimize 2
local Hooks = {}
function Hooks.addForwardHook(module, fn)
local orig = module.forward
module.___fwd = orig
module.forward = function(self, ...)
local out = orig(self, ...)
fn(self, out)
return out
end
end
function Hooks.removeForwardHook(module)
if module.___fwd then
module.forward = module.___fwd
module.___fwd = nil
end
end
return Hooks
| 103 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Util/ModelStats.luau | --!native
--!optimize 2
local function bytesPer(dtype: string?): number
if dtype == "f64" then return 8 end
if dtype == "u8" then return 1 end
return 4
end
local function count(model): (number, number)
local ps = model:parameters()
local total, bytes = 0, 0
task.desynchronize()
for i = 1, #ps do
local t = ps[i]
local n = #t._storage
total += n
bytes += n * bytesPer(t._dtype)
end
task.synchronize()
return total, bytes
end
local function fmtBytes(n: number): string
local units = { "B", "KB", "MB", "GB", "TB" }
local i = 1
while n >= 1024 and i < #units do
n /= 1024; i += 1
end
return string.format("%.2f %s", n, units[i])
end
return {
count = count,
formatBytes = fmtBytes,
summary = function(model, printOut: boolean?): (number, string)
local p, b = count(model)
local fmt = fmtBytes(b)
if printOut then
print(`params={p} (~{fmt})`)
end
return p, fmt
end,
}
| 293 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Util/Parallel.luau | --!native
--!optimize 2
local Parallel = {}
function Parallel.with(fn: () -> ...any): ...any
task.desynchronize()
local res = { fn() }
task.synchronize()
return table.unpack(res)
end
function Parallel.withSafe(fn: () -> ...any): (boolean, ...any)
task.desynchronize()
local res = { pcall(fn) }
task.synchronize()
return table.unpack(res)
end
return Parallel
| 93 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Util/Profiler.luau | --!native
--!optimize 2
local Types = require("../Types")
local assert = require("./Assert")
local Profiler = {}
local fmt = string.format
local stats: { [string]: Types.Stat } = {}
local stack: { Types.Marker } = {}
local enabled: boolean = true
local function ensureStat(name: string): Types.Stat
local stat = stats[name]
if not stat then
stat = {
name = name,
total = 0,
selfTime = 0,
count = 0,
min = math.huge,
max = 0,
last = 0,
}
stats[name] = stat
end
return stat
end
local function clamp(value: number): number
if value < 0 or value ~= value then
return 0
end
return value
end
local function formatTime(value: number, precision: number): string
local absValue, unit, scaled = math.abs(value)
if absValue >= 1 then
unit = "s"
scaled = value
elseif absValue >= 1e-3 then
unit = "ms"
scaled = value * 1e3
elseif absValue >= 1e-6 then
unit = "us"
scaled = value * 1e6
else
unit = "ns"
scaled = value * 1e9
end
local prec = math.max(0, precision)
local spec = `%.{prec}f{unit}`
return fmt(spec, scaled, unit)
end
function Profiler.reset(): ()
table.clear(stats)
table.clear(stack)
end
function Profiler.flush(): ()
table.clear(stack)
end
function Profiler.isEnabled(): boolean
return enabled
end
function Profiler.setEnabled(flag: boolean): ()
if flag == enabled then
return
end
enabled = flag
if not enabled then
table.clear(stack)
end
end
function Profiler.start(name: string): ()
if not enabled then
return
end
table.insert(stack, {
name = name,
start = os.clock(),
child = 0,
})
end
function Profiler.stop(name: string?): number?
if not enabled then
return nil
end
local depth = #stack
if depth == 0 then
-- error("Profiler.stop called without matching Profiler.start", 2)
return nil
end
local marker = stack[depth]
stack[depth] = nil
if name and marker.name ~= name then
error(`Profiler.stop mismatch (expected '{marker.name}', got '{name}')`, 2)
end
local elapsed = clamp(os.clock() - marker.start)
local exclusive = clamp(elapsed - marker.child)
local stat = ensureStat(marker.name)
stat.total += elapsed
stat.selfTime += exclusive
stat.count += 1
if elapsed < stat.min then
stat.min = elapsed
end
if elapsed > stat.max then
stat.max = elapsed
end
stat.last = elapsed
if depth > 1 then
stack[depth - 1].child += elapsed
end
return elapsed
end
local function callWithProfiling(name: string, fn: Types.Callable, ...: any): (number, ...any)
assert(type(fn) == "function", "Profiler: expected callable")
if not enabled then
local results = table.pack(pcall(fn, ...))
if not results[1] then
error(results[2], 0)
end
return 0, table.unpack(results, 2, results.n)
end
local packed = table.pack(pcall(function(...)
Profiler.start(name)
return fn(...)
end, ...))
local elapsed = Profiler.stop(name) or 0
if not packed[1] then
error(packed[2], 0)
end
return elapsed, table.unpack(packed, 2, packed.n)
end
function Profiler.scope(name: string, fn: Types.Callable, ...: any): (number, ...any)
return callWithProfiling(name, fn, ...)
end
function Profiler.wrap(fn: Types.Callable, name: string?)
assert(type(fn) == "function", "Profiler.wrap expects a function")
local label = name or "Profiler.wrap"
return function(...)
return select(2, callWithProfiling(label, fn, ...))
end
end
function Profiler.instrument(target: any, methods: { string } | string, opts: { prefix: string? }?)
assert(type(target) == "table", "Profiler.instrument expects a table target")
local names
if type(methods) == "string" then
names = { methods }
else
names = methods
end
local prefix = if opts and opts.prefix then opts.prefix else `{target}`
local originals = {}
for _, key in names do
local fn = target[key]
assert(type(fn) == "function", `Profiler.instrument: '{key}' is not a function`)
originals[key] = fn
target[key] = function(...)
return select(2, callWithProfiling(`${prefix}.{key}`, fn, ...))
end
end
return function()
for key, original in originals do
target[key] = original
end
end
end
local function copyStat(stat: Types.Stat, total: number): Types.Sample
local minv = if stat.min == math.huge then 0 else stat.min
local count = stat.count
local avg = if count > 0 then stat.total / count else 0
local selfAvg = if count > 0 then stat.selfTime / count else 0
local pct = if total > 0 then (stat.total / total) * 100 else 0
return {
name = stat.name,
total = stat.total,
self = stat.selfTime,
count = count,
avg = avg,
selfAvg = selfAvg,
min = minv,
max = stat.max,
last = stat.last,
percent = pct,
}
end
local function collectTotals(): (number, number)
local total = 0
local n = 0
task.desynchronize()
for _, stat in stats do
total += stat.total
n += 1
end
task.synchronize()
return total, n
end
function Profiler.snapshot(): ({ Types.Sample }, number)
local total, count = collectTotals()
local out = table.create(count)
local i = 1
task.desynchronize()
for _, stat in stats do
out[i] = copyStat(stat, total)
i += 1
end
task.synchronize()
return out, total
end
function Profiler.get(name: string): Types.Sample?
local stat = stats[name]
if not stat then
return nil
end
local total = 0
task.desynchronize()
for _, s in stats do
total += s.total
end
task.synchronize()
return copyStat(stat, total)
end
type ReportOptions = {
sortBy: ("total" | "self" | "avg" | "selfAvg" | "max" | "count" | "last" | "min" | "percent")?,
limit: number?,
precision: number?,
print: boolean?,
}
local function sortEntries(entries: { Types.Sample }, key: string)
table.sort(entries, function(a, b)
local av = (a :: any)[key] or 0
local bv = (b :: any)[key] or 0
if av == bv then
return a.name < b.name
end
return av > bv
end)
end
function Profiler.report(opts: ReportOptions?): ({ Types.Sample }, number)
local options: ReportOptions = opts or {}
local sortBy = options.sortBy or "total"
local precision = options.precision or 4
local entries, total = Profiler.snapshot()
sortEntries(entries, sortBy)
local limit = options.limit
if limit and limit < #entries then
for i = limit + 1, #entries do
entries[i] = nil
end
end
if options.print ~= false then
print(fmt("[Profiler] total %s (%d sections)", formatTime(total, precision), #entries))
print(fmt("%-24s %12s %12s %12s %8s %12s %12s", "section", "total", "self", "avg", "count", "min", "max"))
for _, entry in entries do
local totalStr = formatTime(entry.total, precision)
local selfStr = formatTime(entry.self, precision)
local avgStr = formatTime(entry.avg, precision)
local minStr = formatTime(entry.min, precision)
local maxStr = formatTime(entry.max, precision)
print(
fmt(
"%-24s %12s %12s %12s %8d %12s %12s (%5.1f%%)",
entry.name,
totalStr,
selfStr,
avgStr,
entry.count,
minStr,
maxStr,
entry.percent
)
)
end
end
return entries, total
end
function Profiler.withEnabled(flag: boolean, fn: Types.Callable, ...: any): ...any
assert(type(fn) == "function", "Profiler.withEnabled expects a function")
local prev = enabled
Profiler.setEnabled(flag)
local packed = table.pack(pcall(fn, ...))
Profiler.setEnabled(prev)
if not packed[1] then
error(packed[2], 0)
end
return table.unpack(packed, 2, packed.n)
end
Profiler.push = Profiler.start
Profiler.pop = Profiler.stop
Profiler.time = Profiler.scope
return Profiler
| 2,081 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Util/RNG.luau | --!native
--!optimize 2
local RNG = {}
local _rng = Random.new()
function RNG.seed(s: number)
_rng = Random.new(math.floor(s))
return s
end
function RNG.uniform(a: number?, b: number?, rng: Random?)
a = a or 0
b = b or 1
return (rng or _rng):NextNumber(a, b)
end
function RNG.randint(lo: number, hi: number, rng: Random?)
-- inclusive
return lo + math.floor((rng or _rng):NextNumber(0, 1) * (hi - lo + 1))
end
function RNG.generator()
return {
randint = function(_, lo: number, hi: number, rng: Random?): number
return RNG.randint(lo, hi, rng)
end,
random = function(_, rng: Random?): number
return RNG.uniform(0, 1, rng)
end,
uniform = function(_, a: number?, b: number?, rng: Random?): number
return RNG.uniform(a, b, rng)
end,
}
end
return RNG
| 241 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Util/RunningNorm.luau | --!native
--!optimize 2
local function update(self, x: number)
self.n += 1
local d = x - self.mean
self.mean += d / self.n
self.m2 += d * (x - self.mean)
end
local function var(self): number
if self.n < 2 then
return 1.0
end
return self.m2 / (self.n - 1)
end
local function std(self): number
return math.sqrt(var(self)) + self.eps
end
local function normalize(self, x: number): number
return (x - self.mean) / std(self)
end
local function new(eps: number?)
return {
n = 0,
mean = 0.0,
m2 = 0.0,
eps = eps or 1e-8,
update = update,
var = var,
std = std,
normalize = normalize,
}
end
return new
| 210 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Util/Visual2D.luau | --!native
--!optimize 2
local assert = require("./Assert")
local Visual2D = {}
local RunService = game:GetService("RunService")
local HttpService = game:GetService("HttpService")
export type Tensor = { _storage: { number }, _shape: { number }, _grad: { _storage: { number } }? }
export type RenderOptions = {
parent: Instance?,
size: UDim2?,
position: UDim2?,
anchorPoint: Vector2?,
layerSizeHints: { number }?,
maxNeuronsPerLayer: number?,
maxLinesPerEdge: number?,
padding: number?,
colSpacing: number?,
rowMinGap: number?,
nodeRadius: number?,
lineMin: number?,
lineMax: number?,
updateInterval: number?,
mode: string?,
palette: { Color3 }?,
name: string?,
getActivations: ((model: any) -> { { number } })?,
showLayerBoxes: boolean?,
showLabels: boolean?,
backgroundColor: Color3?,
}
export type RenderHandle = {
container: GuiObject,
setMode: (self: RenderHandle, mode: string) -> (),
update: (self: RenderHandle) -> (),
setAutoUpdate: (self: RenderHandle, on: boolean) -> (),
destroy: (self: RenderHandle) -> (),
}
local function clamp(v: number, lo: number, hi: number): number
if v < lo then
return lo
elseif v > hi then
return hi
else
return v
end
end
local function ema(prev: number, x: number, alpha: number): number
return alpha * x + (1 - alpha) * prev
end
local function pickEven(N: number, k: number): { number }
k = math.min(k, N)
local out = table.create(k)
for i = 1, k do
local idx = math.floor((i - 0.5) * (N / k)) + 1
if idx > N then
idx = N
end
out[i] = idx
end
return out
end
local function newFrame(
parent: Instance,
name: string,
size: UDim2,
pos: UDim2,
ap: Vector2,
bg: Color3?,
transp: number?
): Frame
local f = Instance.new("Frame")
f.Name = name
f.AnchorPoint = ap
f.Size = size
f.Position = pos
f.BackgroundColor3 = bg or Color3.new(0, 0, 0)
f.BackgroundTransparency = (transp ~= nil) and transp or 1
f.BorderSizePixel = 0
f.Parent = parent
return f
end
local function newText(parent: Instance, text: string, pos: UDim2, ap: Vector2, color: Color3): TextLabel
local t = Instance.new("TextLabel")
t.AnchorPoint = ap
t.BackgroundTransparency = 1
t.Size = UDim2.fromOffset(200, 20)
t.Position = pos
t.Font = Enum.Font.GothamMedium
t.TextScaled = true
t.Text = text
t.TextColor3 = color
t.TextStrokeTransparency = 0.75
t.TextXAlignment = Enum.TextXAlignment.Center
t.Parent = parent
return t
end
local function newCircle(parent: Instance, center: Vector2, radius: number, color: Color3): Frame
local f = Instance.new("Frame")
f.Name = "Node"
f.AnchorPoint = Vector2.new(0.5, 0.5)
f.Position = UDim2.fromOffset(center.X, center.Y)
f.Size = UDim2.fromOffset(radius * 2, radius * 2)
f.BackgroundColor3 = color
f.BorderSizePixel = 0
f.ZIndex = 2
local uic = Instance.new("UICorner")
uic.CornerRadius = UDim.new(1, 0)
uic.Parent = f
local uis = Instance.new("UIStroke")
uis.Parent = f
f.Parent = parent
return f
end
local function newLine(parent: Instance, p1: Vector2, p2: Vector2, thickness: number, color: Color3): Frame
local dx, dy = p2.X - p1.X, p2.Y - p1.Y
local len = math.max(1, math.sqrt(dx * dx + dy * dy))
local mid = Vector2.new((p1.X + p2.X) / 2, (p1.Y + p2.Y) / 2)
local angle = math.deg(math.atan2(dy, dx))
local f = Instance.new("Frame")
f.Name = "Line"
f.AnchorPoint = Vector2.new(0.5, 0.5)
f.Position = UDim2.fromOffset(mid.X, mid.Y)
f.Size = UDim2.fromOffset(len, thickness)
f.Rotation = angle
f.BackgroundColor3 = color
f.BorderSizePixel = 0
f.Parent = parent
return f
end
local function collectWeightMats(params: { Tensor }): { Tensor }
local Ws = {}
for _, t in ipairs(params) do
if t._shape and #t._shape == 2 then
table.insert(Ws, t)
end
end
return Ws
end
local function inferSizes(params: { Tensor }): { number }
local Ws = collectWeightMats(params)
local L = #Ws
if L == 0 then
return {}
end
local sizes = table.create(L + 1)
sizes[1] = Ws[1]._shape[2]
for i = 1, L do
table.insert(sizes, Ws[i]._shape[1])
end
return sizes
end
local function posByIndex(nodePicks, nodePos, sizes, layerIdx: number, neuronIndex: number): Vector2
local pickList = nodePicks[layerIdx]
local posList = nodePos[layerIdx]
for k = 1, #pickList do
if pickList[k] == neuronIndex then
return posList[k]
end
end
local L = #posList
local approx = math.clamp(math.floor((neuronIndex - 1) / math.max(1, sizes[layerIdx]) * L) + 1, 1, L)
return posList[approx]
end
function Visual2D.render(model: any, parent: Instance, opt: RenderOptions?): RenderHandle
opt = opt or {}
assert(parent ~= nil, "Visual2D.render: parent (ScreenGui/BillboardGui/SurfaceGui/Frame) is required")
local NAME = opt.name or ("NNViz2D_" .. HttpService:GenerateGUID(false))
local canvasSize = opt.size or UDim2.fromScale(1, 1)
local canvasPos = opt.position or UDim2.fromScale(0.5, 0.5)
local canvasAP = opt.anchorPoint or Vector2.new(0.5, 0.5)
local padding = opt.padding or 24
local nodeR = opt.nodeRadius or 5
local lineMin = opt.lineMin or 1
local lineMax = opt.lineMax or 6
local rowMinGap = opt.rowMinGap or 6
local maxNodes = opt.maxNeuronsPerLayer or 48
local maxLinesPerEdge = opt.maxLinesPerEdge or 256
local updateEvery = opt.updateInterval or 0.7
local currentMode = (opt.mode == "grads") and "grads" or "weights"
local palette = opt.palette
or { Color3.fromRGB(80, 160, 255), Color3.fromRGB(120, 120, 120), Color3.fromRGB(255, 160, 80) }
local showBoxes = (opt.showLayerBoxes ~= false)
local showLabels = (opt.showLabels ~= false)
local container: Frame
if parent:IsA("ScreenGui") or parent:IsA("BillboardGui") or parent:IsA("SurfaceGui") then
container =
newFrame(parent, NAME, canvasSize, canvasPos, canvasAP, opt.backgroundColor or Color3.new(0, 0, 0), 1)
elseif parent:IsA("GuiObject") then
container =
newFrame(parent, NAME, canvasSize, canvasPos, canvasAP, opt.backgroundColor or Color3.new(0, 0, 0), 1)
else
error("Visual2D.render: parent must be a ScreenGui/BillboardGui/SurfaceGui/Frame")
end
local params = (model.parameters and model:parameters()) or {}
local sizes = opt.layerSizeHints or inferSizes(params)
if #sizes < 2 then
local msg = newText(
container,
"Visual2D: no layers found",
UDim2.fromScale(0.5, 0.5),
Vector2.new(0.5, 0.5),
Color3.fromRGB(255, 120, 120)
)
msg.TextSize = 16
return {
container = container,
setMode = function() end,
update = function() end,
setAutoUpdate = function() end,
destroy = function(self)
self.container:Destroy()
end,
}
end
local L = #sizes
local absW = container.AbsoluteSize.X > 0 and container.AbsoluteSize.X
or (canvasSize.X.Offset > 0 and canvasSize.X.Offset or 900)
local absH = container.AbsoluteSize.Y > 0 and container.AbsoluteSize.Y
or (canvasSize.Y.Offset > 0 and canvasSize.Y.Offset or 320)
local innerW = math.max(1, absW - padding * 2)
local innerH = math.max(1, absH - padding * 2)
local colSpacing = opt.colSpacing or (innerW / math.max(1, L - 1))
local colX = table.create(L)
for li = 1, L do
colX[li] = padding + (li - 1) * colSpacing
end
local layerFrames: { Frame } = {}
local labelFrames: { TextLabel } = {}
local nodeFolders: { Frame } = {}
local nodePicks: { { number } } = {}
local nodePos: { { Vector2 } } = {}
for li = 1, L do
local n = sizes[li]
local picks = pickEven(n, math.min(maxNodes, n))
nodePicks[li] = picks
local count = #picks
local totalHeight = math.max(count * (2 * nodeR + rowMinGap) - rowMinGap, 1)
local topY = padding + (innerH - totalHeight) / 2
local lf = newFrame(
container,
("Layer_%d"):format(li),
UDim2.fromOffset(1, 1),
UDim2.fromOffset(0, 0),
Vector2.new(0, 0),
nil,
1
)
layerFrames[li] = lf
if showBoxes then
local box = newFrame(
container,
("ColBox_%d"):format(li),
UDim2.fromOffset(40, innerH),
UDim2.fromOffset(colX[li] - 20, padding),
Vector2.new(0, 0),
(li == 1 and palette[1]) or (li == L and palette[3]) or palette[2],
0.92
)
box.BackgroundTransparency = 0.92
end
if showLabels then
local tag = (li == 1 and ("Input " .. n)) or (li == L and ("Output " .. n)) or ("Hidden " .. n)
local lbl = newText(
container,
tag,
UDim2.fromOffset(colX[li], padding * 0.5),
Vector2.new(0.5, 0),
(li == 1 and palette[1]) or (li == L and palette[3]) or palette[2]
)
labelFrames[li] = lbl
end
-- nodes
local nf = newFrame(
container,
("Nodes_%d"):format(li),
UDim2.fromOffset(1, 1),
UDim2.fromOffset(0, 0),
Vector2.new(0, 0),
nil,
1
)
nf.ZIndex = 2
nodeFolders[li] = nf
local posList = table.create(count)
for idx = 1, count do
local j = picks[idx]
local y = topY + (idx - 1) * (2 * nodeR + rowMinGap) + nodeR
posList[idx] = Vector2.new(colX[li], y)
local node = newCircle(nf, posList[idx], nodeR, Color3.fromRGB(210, 210, 210))
node.Name = ("n_%d"):format(j)
end
nodePos[li] = posList
end
local Ws = collectWeightMats(params)
local edgeSpecs = {} :: {
{
W: Tensor,
mode: string,
inPick: { number },
outPick: { number },
pointsIn: { Vector2 },
pointsOut: { Vector2 },
lines: { Frame },
emaMax: number,
}
}
local linkCount = math.min(#Ws, L - 1)
for li = 1, linkCount do
local W = Ws[li]
local fullInPick = nodePicks[li] or {}
local fullOutPick = nodePicks[li + 1] or {}
local targetSide = math.floor(math.sqrt(maxLinesPerEdge))
local strideIn = math.max(1, math.floor(#fullInPick / math.max(1, targetSide)))
local strideOut = math.max(1, math.floor(#fullOutPick / math.max(1, targetSide)))
local selIn, selOut = {}, {}
for k = 1, #fullInPick, strideIn do
table.insert(selIn, fullInPick[k])
end
for k = 1, #fullOutPick, strideOut do
table.insert(selOut, fullOutPick[k])
end
local lineFolder = newFrame(
container,
("Lines_%d"):format(li),
UDim2.fromOffset(1, 1),
UDim2.fromOffset(0, 0),
Vector2.new(0, 0),
nil,
1
)
local _pairs = {}
for oi = 1, #selOut do
for ij = 1, #selIn do
if #_pairs >= maxLinesPerEdge then
break
end
local p1 = posByIndex(nodePicks, nodePos, sizes, li, selIn[ij])
local p2 = posByIndex(nodePicks, nodePos, sizes, li + 1, selOut[oi])
local f = newLine(lineFolder, p1, p2, lineMin, Color3.fromRGB(180, 180, 180))
table.insert(_pairs, { iOut = selOut[oi], jIn = selIn[ij], line = f })
end
if #_pairs >= maxLinesPerEdge then
break
end
end
table.insert(edgeSpecs, {
W = W,
pairs = _pairs,
emaMax = 1.0,
})
end
local function getValueField(t: Tensor, idx: number, useGrad: boolean): number
if useGrad and t._grad and t._grad._storage then
return math.abs(t._grad._storage[idx] or 0)
end
return t._storage[idx] or 0
end
local autoConn: RBXScriptConnection? = nil
local handle: RenderHandle
handle = {
container = container,
setMode = function(self, m: string)
if m == "grads" or m == "weights" then
currentMode = m
end
end,
update = function(self)
for _, spec in ipairs(edgeSpecs) do
local W = spec.W
local inDim = W._shape[2]
local useGrad = (currentMode == "grads")
local curMax = 1e-12
for _, pr in ipairs(spec.pairs) do
local idx = (pr.iOut - 1) * inDim + pr.jIn
local v = getValueField(W, idx, useGrad)
local a = math.abs(v)
if a > curMax then
curMax = a
end
end
spec.emaMax = ema(spec.emaMax, curMax, 0.2)
local denom = spec.emaMax + 1e-12
for _, pr in ipairs(spec.pairs) do
local idx = (pr.iOut - 1) * inDim + pr.jIn
local val = getValueField(W, idx, useGrad)
local mag = clamp(math.abs(val) / denom, 0, 1)
local thick = lineMin + (lineMax - lineMin) * mag
local color = (useGrad and Color3.fromRGB(255, 220, 90))
or ((val >= 0) and Color3.fromRGB(90, 180, 255) or Color3.fromRGB(255, 120, 120))
local f = pr.line
f.Size = UDim2.fromOffset(f.Size.X.Offset, thick)
f.BackgroundColor3 = color
end
end
if opt.getActivations then
local acts = opt.getActivations(model)
if type(acts) == "table" then
for li = 1, #sizes do
local layerActs = acts[li]
if layerActs then
local nf = nodeFolders[li]
local picks = nodePicks[li]
for idx = 1, #picks do
local j = picks[idx]
local node = nf:FindFirstChild(("n_%d"):format(j)) :: Frame
if node then
local a = layerActs[j] or 0
local s = clamp(math.abs(a), 0, 1)
node.BackgroundColor3 = (a >= 0) and Color3.fromRGB(150, 220, 255)
or Color3.fromRGB(255, 160, 160)
node.BackgroundTransparency = 1 - (0.15 + 0.75 * s)
local r = nodeR + 3 * s
node.Size = UDim2.fromOffset(r * 2, r * 2)
end
end
end
end
end
end
end,
setAutoUpdate = function(self, on: boolean)
if autoConn then
autoConn:Disconnect()
autoConn = nil
end
if on then
local acc = 0.0
autoConn = RunService.PreSimulation:Connect(function(dt)
acc += dt
if acc >= updateEvery then
acc = 0.0
self:update()
end
end)
end
end,
destroy = function(self)
if autoConn then
autoConn:Disconnect()
autoConn = nil
end
self.container:Destroy()
end,
}
handle:update()
handle:setAutoUpdate(true)
return handle
end
return Visual2D
| 4,289 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Util/Visual3D.luau | --!native
--!optimize 2
local Visual3D = {}
local Workspace = game:GetService("Workspace")
local RunService = game:GetService("RunService")
local HttpService = game:GetService("HttpService")
local Types = require("../Types")
type Tensor = Types.Tensor
type Module = Types.Module
export type RenderOptions = {
layerSizeHints: { number }?,
maxNeuronsPerLayer: number?,
maxBeamsPerEdge: number?,
layerSpacing: number?,
boxDepth: number?,
unitHeight: number?,
updateInterval: number?,
mode: string?,
palette: { Color3 }?,
name: string?,
getActivations: ((model: any) -> { { number } })?,
showNeuronValues: boolean?,
valueEvery: number?,
valueDecimals: number?,
valueColor: Color3?,
valueSize: Vector2?,
sparsity: number?,
}
export type RenderHandle = {
folder: Folder,
setMode: (self: RenderHandle, mode: string) -> (),
update: (self: RenderHandle) -> (),
destroy: (self: RenderHandle) -> (),
setAutoUpdate: (self: RenderHandle, on: boolean) -> (),
setSparsity: (self: RenderHandle, th: number) -> (),
setValuesVisible: (self: RenderHandle, on: boolean) -> (),
}
type BeamObj = {
beam: Beam,
iOut: number,
jIn: number,
_cWidth: number,
_cColor: Color3,
_cEnabled: boolean,
}
type NodeObj = {
part: BasePart,
label: TextLabel?,
idx: number,
_cColor: Color3,
_cTrans: number,
_cSize: Vector3,
_cText: string?,
}
local function fmtVal(a: number, digits: number): string
local aa = math.abs(a)
if aa < 1e-3 and aa ~= 0 then
return `{string.format("%.2e", a)}`
end
return string.format("%." .. digits .. "f", a)
end
local function newPart(parent: Instance, cf: CFrame, size: Vector3, color: Color3, name: string): BasePart
local p = Instance.new("Part")
p.Name = name
p.Anchored = true
p.CanCollide = false
p.CastShadow = false
p.Material = Enum.Material.SmoothPlastic
p.Color = color
p.CFrame = cf
p.Size = size
p.Parent = parent
return p
end
local function label(part: BasePart, text: string)
local bb = Instance.new("BillboardGui")
bb.Name = "Label"
bb.AlwaysOnTop = true
bb.Size = UDim2.fromScale(6, 2)
bb.StudsOffset = Vector3.new(0, part.Size.Y * 0.6 + 0.75, 0)
local tl = Instance.new("TextLabel")
tl.Size = UDim2.fromScale(1, 1)
tl.BackgroundTransparency = 1
tl.Text = text
tl.TextScaled = true
tl.Font = Enum.Font.GothamMedium
tl.TextColor3 = Color3.new(1, 1, 1)
tl.TextStrokeTransparency = 0.6
tl.Parent = bb
bb.Parent = part
end
local function labelVal(node: BasePart, valueDigits: number, valueColor: Color3, valueSize: Vector2)
local bb = Instance.new("BillboardGui")
bb.Name = "Val"
bb.AlwaysOnTop = true
bb.LightInfluence = 0
bb.Size = UDim2.fromScale(valueSize.X, valueSize.Y)
bb.StudsOffset = Vector3.new(0, 0, 0.28)
local tl = Instance.new("TextLabel")
tl.BackgroundTransparency = 1
tl.Size = UDim2.fromScale(1, 1)
tl.TextScaled = true
tl.Font = Enum.Font.GothamMedium
tl.TextColor3 = valueColor
tl.TextStrokeTransparency = 0.35
tl.Text = fmtVal(0, valueDigits)
tl.Parent = bb
bb.Parent = node
return tl
end
local function ema(prev: number, x: number, alpha: number): number
return alpha * x + (1 - alpha) * prev
end
local function pickEven(N: number, k: number): { number }
k = math.min(k, N)
local out = table.create(k)
for i = 1, k do
local idx = math.floor((i - 0.5) * (N / k)) + 1
if idx > N then
idx = N
end
out[i] = idx
end
return out
end
local function collectWeightMats(params: { Tensor }): { Tensor }
local Ws = {}
for _, t in ipairs(params) do
if t._shape and #t._shape == 2 then
table.insert(Ws, t)
end
end
return Ws
end
local function inferSizes(params: { Tensor }): { number }
local Ws = collectWeightMats(params)
local L = #Ws
if L == 0 then
return {}
end
local sizes = table.create(L + 1)
sizes[1] = Ws[1]._shape[2]
for i = 1, L do
table.insert(sizes, Ws[i]._shape[1])
end
return sizes
end
local function sizesFromActs(getActsFn, model)
local acts = getActsFn(model)
local L = type(acts) == "table" and #acts or 0
if L > 1 then
local s = table.create(L)
for i = 1, L do
s[i] = #acts[i]
end
return s
end
return {}
end
function Visual3D.render(model: any, origin: CFrame, opts: RenderOptions?): RenderHandle
local opt = opts or {}
local maxNeurons = opt.maxNeuronsPerLayer or 48
local maxBeamsPerEdge = opt.maxBeamsPerEdge or 256
local spacing = opt.layerSpacing or 10
local boxDepth = opt.boxDepth or 2
local unitH = opt.unitHeight or 0.12
local updateEvery = opt.updateInterval or 0.8
local sparsity = opt.sparsity or 0
local mode = (opt.mode == "grads") and "grads" or "weights"
local palette = opt.palette
or { Color3.fromRGB(80, 160, 255), Color3.fromRGB(120, 120, 120), Color3.fromRGB(255, 160, 80) }
local name = opt.name or `NNViz_{HttpService:GenerateGUID(false)}`
local getActs = opt.getActivations
local showVals = (typeof(getActs) == "function" and opt.showNeuronValues == true)
local valueEvery = opt.valueEvery or 1
local valueDigits = opt.valueDecimals or 2
local valueColor = opt.valueColor or Color3.fromRGB(235, 235, 245)
local valueSize = opt.valueSize or Vector2.new(0.5, 0.15)
local folder = Instance.new("Folder")
folder.Name = name
folder.Parent = Workspace
local params = model:parameters() :: { Tensor }
local sizes = opt.layerSizeHints or (getActs and sizesFromActs(getActs, model)) or inferSizes(params)
local L = #sizes
if L < 2 then
local p = newPart(folder, origin, Vector3.new(5, 1, 2), Color3.fromRGB(255, 90, 90), "Error")
label(p, "Visual3D: < 2 layers detected")
return {
folder = folder,
setMode = function() end,
update = function() end,
destroy = function(self)
self.folder:Destroy()
end,
setAutoUpdate = function() end,
setSparsity = function() end,
setValuesVisible = function() end,
}
end
local layerParts: { BasePart } = table.create(L)
local nodeCache: { { NodeObj } } = table.create(L)
local neuronPicks: { { number } } = table.create(L)
local nodePinsByLayer: { [number]: { [number]: Attachment } } = {}
for li = 1, L do
local n = sizes[li]
local height = math.max(1, n * unitH)
local color = (li == 1) and palette[1] or ((li == L) and palette[3] or palette[2])
local p = newPart(
folder,
origin * CFrame.new((li - 1) * spacing, height / 2, 0),
Vector3.new(3, height, boxDepth),
color,
`Layer_{li}`
)
local tag = (li == 1 and `Input {n}`) or (li == L and `Output {n}`) or `Hidden {n}`
label(p, tag)
layerParts[li] = p
local nf = Instance.new("Folder")
nf.Name = `Nodes_{li}`
nf.Parent = folder
local picks = pickEven(n, math.min(maxNeurons, n))
neuronPicks[li] = picks
local layerNodes = table.create(#picks)
nodeCache[li] = layerNodes
local pins = {}
nodePinsByLayer[li] = pins
for k = 1, #picks do
local j = picks[k]
local y = -p.Size.Y / 2 + (j - 0.5) * (p.Size.Y / n)
local node = Instance.new("Part")
node.Name = `n_{j}`
node.Shape = Enum.PartType.Ball
node.Anchored = true
node.CanCollide = false
node.CastShadow = false
node.Material = Enum.Material.SmoothPlastic
node.Color = Color3.fromRGB(200, 200, 200)
node.Size = Vector3.new(0.35, 0.35, 0.35)
node.CFrame = p.CFrame * CFrame.new(0, y, 0.6 + 0.5)
node.Parent = nf
local lbl: TextLabel? = nil
if showVals and ((k - 1) % valueEvery == 0) then
lbl = labelVal(node, valueDigits, valueColor, valueSize)
end
local pin = Instance.new("Attachment")
pin.Name = `pin_{j}`
pin.Parent = node
pins[j] = pin
layerNodes[k] = {
part = node,
label = lbl,
idx = j,
_cColor = Color3.new(1, 1, 1),
_cTrans = 0,
_cSize = Vector3.new(1, 1, 1),
_cText = nil,
}
end
end
local Ws = collectWeightMats(params)
local beamSpecs = {} :: { { W: Tensor, objects: { BeamObj }, emaMax: number } }
local linkCount = math.min(#Ws, L - 1)
for li = 1, linkCount do
local W = Ws[li]
local fullInPick = neuronPicks[li] or {}
local fullOutPick = neuronPicks[li + 1] or {}
local targetSide = math.floor(math.sqrt(maxBeamsPerEdge))
local strideIn = math.max(1, math.floor(#fullInPick / math.max(1, targetSide)))
local strideOut = math.max(1, math.floor(#fullOutPick / math.max(1, targetSide)))
local bf = Instance.new("Folder")
bf.Name = `Beams_{li}`
bf.Parent = folder
local objects: { BeamObj } = {}
local total = 0
for oi = 1, #fullOutPick, strideOut do
if total >= maxBeamsPerEdge then
break
end
for ij = 1, #fullInPick, strideIn do
if total >= maxBeamsPerEdge then
break
end
local iOut = fullOutPick[oi]
local jIn = fullInPick[ij]
local pinIn = nodePinsByLayer[li] and nodePinsByLayer[li][jIn]
local pinOut = nodePinsByLayer[li + 1] and nodePinsByLayer[li + 1][iOut]
if pinIn and pinOut then
local b = Instance.new("Beam")
b.FaceCamera = true
b.Transparency = NumberSequence.new(0.15)
b.Attachment0 = pinIn
b.Attachment1 = pinOut
b.Width0 = 0.01
b.Width1 = 0.01
b.Color = ColorSequence.new(Color3.fromRGB(180, 180, 180))
b.Parent = bf
table.insert(objects, {
beam = b,
iOut = iOut,
jIn = jIn,
_cWidth = 0.01,
_cColor = Color3.new(1, 1, 1),
_cEnabled = true,
})
total += 1
end
end
end
table.insert(beamSpecs, { W = W, objects = objects, emaMax = 1.0 })
end
local function getValueField(t: Tensor, idx: number, useGrad: boolean): number
if useGrad and t._grad and t._grad._storage then
return math.abs(t._grad._storage[idx] or 0)
end
return t._storage[idx] or 0
end
local autoConn: RBXScriptConnection? = nil
local currentMode = mode
local handle: RenderHandle
handle = {
folder = folder,
setMode = function(self, m: string)
if m == "grads" or m == "weights" then
currentMode = m
end
end,
setSparsity = function(_, th: number)
sparsity = math.clamp(th, 0, 0.5)
end,
setValuesVisible = function(_, on: boolean)
if not getActs then
return
end
showVals = on
for _, layerList in nodeCache do
for _, obj in layerList do
if obj.label and obj.label.Parent and obj.label.Parent:IsA("BillboardGui") then
obj.label.Parent.Enabled = on
end
end
end
end,
update = function(self)
task.desynchronize()
local useGrad = (currentMode == "grads")
for _, spec in ipairs(beamSpecs) do
local W = spec.W
local inDim = W._shape[2]
local curMax = 1e-12
for _, obj in ipairs(spec.objects) do
local idx = (obj.iOut - 1) * inDim + obj.jIn
local v = getValueField(W, idx, useGrad)
local a = math.abs(v)
if a > curMax then
curMax = a
end
end
spec.emaMax = ema(spec.emaMax, curMax, 0.2)
local denom = spec.emaMax + 1e-12
for _, obj in ipairs(spec.objects) do
local idx = (obj.iOut - 1) * inDim + obj.jIn
local val = getValueField(W, idx, useGrad)
local mag = math.clamp(math.abs(val) / denom, 0, 1)
local keep = (mag >= sparsity)
obj._cEnabled = keep
if keep then
local w = 0.01 + 0.015 * mag
obj._cWidth = w
if useGrad then
obj._cColor = Color3.fromRGB(255, 220, 90)
else
if val >= 0 then
obj._cColor = Color3.fromRGB(90, 180, 255)
else
obj._cColor = Color3.fromRGB(255, 120, 120)
end
end
end
end
end
local actResults = nil
if getActs then
local acts = getActs(model)
if type(acts) == "table" then
actResults = acts
for li = 1, #nodeCache do
local layerActs = acts[li]
local layerNodes = nodeCache[li]
if layerActs and layerNodes then
for _, nodeObj in ipairs(layerNodes) do
local j = nodeObj.idx
local a = layerActs[j] or 0
local s = math.clamp(math.abs(a), 0, 1)
if a >= 0 then
nodeObj._cColor = Color3.fromRGB(150, 220, 255)
else
nodeObj._cColor = Color3.fromRGB(255, 160, 160)
end
nodeObj._cTrans = 1 - (0.15 + 0.75 * s)
local sz = 0.30 + 0.25 * s
nodeObj._cSize = Vector3.new(sz, sz, sz)
if showVals and nodeObj.label then
nodeObj._cText = fmtVal(a, valueDigits)
end
end
end
end
end
end
task.synchronize()
for _, spec in ipairs(beamSpecs) do
for _, obj in ipairs(spec.objects) do
obj.beam.Enabled = obj._cEnabled
if obj._cEnabled then
local w = obj._cWidth
obj.beam.Width0 = w
obj.beam.Width1 = w
obj.beam.Color = ColorSequence.new(obj._cColor)
end
end
end
if getActs and actResults then
for li = 1, #nodeCache do
local layerNodes = nodeCache[li]
for _, nodeObj in ipairs(layerNodes) do
nodeObj.part.Color = nodeObj._cColor
nodeObj.part.Transparency = nodeObj._cTrans
nodeObj.part.Size = nodeObj._cSize
if nodeObj._cText and nodeObj.label then
nodeObj.label.Text = nodeObj._cText
end
end
end
end
end,
setAutoUpdate = function(self, on: boolean)
if autoConn then
autoConn:Disconnect()
autoConn = nil
end
if on then
local t = 0.0
autoConn = RunService.PreSimulation:Connect(function(dt: number)
t += dt
if t >= updateEvery then
t = 0.0
self:update()
end
end)
end
end,
destroy = function(self)
if autoConn then
autoConn:Disconnect()
autoConn = nil
end
self.folder:Destroy()
end,
}
handle:update()
task.synchronize()
handle:setAutoUpdate(true)
return handle
end
return Visual3D
| 4,295 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/Util/init.luau | --!native
--!optimize 2
local Util = {}
local Types = require("./Types")
local function isModule(m: any): boolean
return type(m) == "table" and type(m.forward) == "function" and type(m.parameters) == "function"
end
local function applyRecursive(m: any, fn: (any) -> ())
if isModule(m) then
fn(m)
end
if type(m) == "table" then
if type(m._layers) == "table" then
for _, sub in m._layers do
applyRecursive(sub, fn)
end
end
for _, v in m do
if v ~= m and isModule(v) then
applyRecursive(v, fn)
end
end
end
end
--@param shape {number}
--@return number
function Util.sizeFromShape(shape: { number }): number
task.desynchronize()
local n = 1
for _, d in shape do
n *= d
end
task.synchronize()
return n
end
function Util.train(m: Types.Module)
applyRecursive(m, function(mm)
(mm :: any)._train = true
end)
end
function Util.eval(m: Types.Module)
applyRecursive(m, function(mm)
(mm :: any)._train = false
end)
end
function Util.apply(m: Types.Module, fn: (Types.Module) -> ())
applyRecursive(m, function(mm)
fn(mm :: Types.Module)
end)
end
function Util.to(m: Types.Module, dtype: Types.DType)
applyRecursive(m, function(mm)
for _, p in mm:parameters() do
p._dtype = dtype
end
end)
end
function Util.shape(x: Types.Tensor): (number, number?)
return x._shape[1], x._shape[2]
end
Util.ModelStats = require("@self/ModelStats")
Util.Visual2D = require("@self/Visual2D")
Util.Visual3D = require("@self/Visual3D")
Util.RunningNorm = require("@self/RunningNorm")
Util.Anomaly = require("@self/Anomaly")
Util.RNG = require("@self/RNG")
Util.Hooks = require("@self/Hooks")
Util.Parallel = require("@self/Parallel")
Util.GradStats = require("@self/GradStats")
Util.Buffer = require("@self/Buffer")
Util.Profiler = require("@self/Profiler")
Util.Assert = require("@self/Assert")
return Util
| 533 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/autograd/Tape.luau | --!native
--!optimize 2
local Tensor = require("../Tensor")
local BLAS = require("../ops/BLAS")
local Types = require("../Types")
local Tape = {}
local gradEnabled = true
local function withTape(t: Types.Tensor, parents: { Types.Tensor }, back: (grad: Types.Tensor) -> ()): Types.Tensor
if not gradEnabled then
t._parents = nil
t._backprop = nil
t._requiresGrad = false
return t
end
t._parents = parents
t._backprop = back
t._requiresGrad = false
for _, p in parents do
if p._requiresGrad then
t._requiresGrad = true
break
end
end
return t
end
--@param out any @Tensor
--@param parents {any}
--@param back fun(grad: any)
function Tape.makeNode(out: Types.Tensor, parents: { Types.Tensor }, back: (grad: Types.Tensor) -> ()): Types.Tensor
return withTape(out, parents, back)
end
-- y = ReLU(x)
--@param x @Tensor
function Tape.relu(x: Types.Tensor): Types.Tensor
task.desynchronize()
local y = Tensor.zeros(x._shape, x._dtype, x._requiresGrad)
for i = 1, #x._storage do
local v = x._storage[i]
y._storage[i] = (v > 0) and v or 0
end
task.synchronize()
return withTape(y, { x }, function(gy)
if x._requiresGrad then
task.desynchronize()
if not x._grad then
x._grad = Tensor.zeros(x._shape, x._dtype)
end
if x._grad then
for i = 1, #x._grad._storage do
x._grad._storage[i] += (x._storage[i] > 0 and 1 or 0) * gy._storage[i]
end
end
task.synchronize()
end
end)
end
-- y = A @ B
--@param x @Tensor
function Tape.matmul(A: Types.Tensor, B: Types.Tensor): Types.Tensor
local Y = BLAS.matmul(A, B)
return withTape(Y, { A, B }, function(gY: Types.Tensor)
-- dA = gY @ B^T ; dB = A^T @ gY
task.desynchronize()
local M, K = A._shape[1], A._shape[2]
local _, N = B._shape[1], B._shape[2]
if A._requiresGrad then
if not A._grad then
A._grad = Tensor.zeros({ M, K }, A._dtype)
end
local BT
Tape.noGrad(function()
BT = Tensor.transpose(B)
end)
local dA = BLAS.matmul(gY, BT)
if A._grad then
local dst = A._grad._storage
local src = dA._storage
for idx = 1, #dst do
dst[idx] += src[idx]
end
end
end
if B._requiresGrad then
if not B._grad then
B._grad = Tensor.zeros({ K, N }, B._dtype)
end
local AT
Tape.noGrad(function()
AT = Tensor.transpose(A)
end)
local dB = BLAS.matmul(AT, gY)
if B._grad then
local dst = B._grad._storage
local src = dB._storage
for idx = 1, #dst do
dst[idx] += src[idx]
end
end
end
task.synchronize()
end)
end
function Tape.backwardFrom(y: Types.Tensor, grad: Types.Tensor)
task.desynchronize()
local pending: { [Types.Tensor]: number } = {}
local visitStack = { y }
local seen = {}
while #visitStack > 0 do
local node = table.remove(visitStack)
if not seen[node] then
seen[node] = true
if node._parents then
for _, parent in node._parents do
if parent._requiresGrad then
pending[parent] = (pending[parent] or 0) + 1
table.insert(visitStack, parent)
end
end
end
end
end
y._grad = grad
local ready = { y }
while #ready > 0 do
local node = table.remove(ready)
if node._requiresGrad then
local g = node._grad
if not g then
g = Tensor.zeros(node._shape, node._dtype)
node._grad = g
end
if node._backprop then
node._backprop(g)
end
if node._parents then
for _, parent in node._parents do
if parent._requiresGrad then
local remaining = pending[parent]
if remaining then
remaining -= 1
if remaining == 0 then
pending[parent] = nil
if parent._backprop or parent._parents then
table.insert(ready, parent)
end
else
pending[parent] = remaining
end
else
if parent._backprop or parent._parents then
table.insert(ready, parent)
end
end
end
end
end
end
end
task.synchronize()
end
function Tape.noGrad(fn: () -> ()): ()
gradEnabled = false
fn()
gradEnabled = true
end
function Tape.grad(f: (...any) -> Types.Tensor, inputs: { Types.Tensor }): { Types.Tensor? }
local oldReq: { boolean } = {}
for i, x in inputs do
oldReq[i] = x._requiresGrad
x._requiresGrad = true
x._grad = nil
end
local y = f(table.unpack(inputs))
if y == nil or y._shape == nil then
error("Autograd.grad: f must return a Tensor")
end
Tape.backwardFrom(y, Tensor.ones(y._shape))
local out: { Types.Tensor? } = {}
for i, x in inputs do
out[i] = x._grad
x._requiresGrad = oldReq[i]
end
return out
end
return Tape
| 1,390 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/classic/GaussianNB.luau | --!native
--!optimize 2
local Util = require("../Util")
local assert = Util.Assert
return function(C: number)
local mu = {}
local var = {}
local prior = table.create(C, 0)
local fitted = false
local self
self = {
fit = function(_, X, y: { number })
local D, N = X._shape[1], X._shape[2]
task.desynchronize()
for c = 1, C do
mu[c] = table.create(D, 0)
var[c] = table.create(D, 0)
prior[c] = 0
end
for n = 1, N do
prior[y[n]] += 1
end
for c = 1, C do
if prior[c] == 0 then
prior[c] = 1
end
end
for c = 1, C do
for d = 1, D do
local s = 0
for n = 1, N do
if y[n] == c then
s += X._storage[(d - 1) * N + n]
end
end
mu[c][d] = s / prior[c]
end
end
for c = 1, C do
for d = 1, D do
local s = 0
for n = 1, N do
if y[n] == c then
local dx = X._storage[(d - 1) * N + n] - mu[c][d]
s += dx * dx
end
end
var[c][d] = math.max(s / prior[c], 1e-6)
end
end
for c = 1, C do
prior[c] = prior[c] / N
end
task.synchronize()
fitted = true
end,
predict = function(_, X)
assert(fitted, "GaussianNB: fit first")
local D, N = X._shape[1], X._shape[2]
local out = table.create(N, 1)
task.desynchronize()
for n = 1, N do
local best = -1 / 0
local arg = 1
for c = 1, C do
local logp = math.log(prior[c])
for d = 1, D do
local m = mu[c][d]
local v = var[c][d]
local x = X._storage[(d - 1) * N + n]
logp += -0.5 * math.log(2 * math.pi * v) - (x - m) * (x - m) / (2 * v)
end
if logp > best then
best = logp
arg = c
end
end
out[n] = arg
end
task.synchronize()
return out
end,
}
return self
end
| 678 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/classic/KMeans.luau | --!native
--!optimize 2
local Tensor = require("../Tensor")
local Util = require("../Util")
local assert = Util.Assert
return function(K: number, iters: number)
iters = iters or 20
local centers: any = nil
local function initPlusPlus(X)
local D, N = X._shape[1], X._shape[2]
local C = Tensor.zeros({ D, K })
local first = math.random(1, N)
for i = 1, D do
C._storage[(i - 1) * K + 1] = X._storage[(i - 1) * N + first]
end
local dist = table.create(N, math.huge)
task.desynchronize()
for c = 2, K do
for n = 1, N do
local best = dist[n]
for cc = 1, c - 1 do
local s = 0
for d = 1, D do
local dx = X._storage[(d - 1) * N + n] - C._storage[(d - 1) * K + cc]
s += dx * dx
end
if s < best then
best = s
end
end
dist[n] = best
end
local sum = 0
for n = 1, N do
sum += dist[n]
end
local r = math.random() * math.max(sum, 1e-9)
local acc = 0
local pick = N
for n = 1, N do
acc += dist[n]
if acc >= r then
pick = n
break
end
end
for d = 1, D do
C._storage[(d - 1) * K + c] = X._storage[(d - 1) * N + pick]
end
end
task.synchronize()
return C
end
local self
self = {
fit = function(_, X)
local D, N = X._shape[1], X._shape[2]
centers = initPlusPlus(X)
local labels = table.create(N, 1)
task.desynchronize()
for _ = 1, iters do
for n = 1, N do
local best = math.huge
local li = 1
for k = 1, K do
local s = 0
for d = 1, D do
local dx = X._storage[(d - 1) * N + n] - centers._storage[(d - 1) * K + k]
s += dx * dx
end
if s < best then
best = s
li = k
end
end
labels[n] = li
end
local counts = table.create(K, 0)
local newC = Tensor.zeros({ D, K })
for n = 1, N do
local k = labels[n]
counts[k] += 1
for d = 1, D do
newC._storage[(d - 1) * K + k] += X._storage[(d - 1) * N + n]
end
end
for k = 1, K do
local c = math.max(counts[k], 1)
for d = 1, D do
newC._storage[(d - 1) * K + k] /= c
end
end
centers = newC
end
task.synchronize()
return centers
end,
predict = function(_, X)
assert(centers, "KMeans: fit first")
local D, N = X._shape[1], X._shape[2]
local labels = table.create(N, 1)
task.desynchronize()
for n = 1, N do
local best = math.huge
local li = 1
for k = 1, K do
local s = 0
for d = 1, D do
local dx = X._storage[(d - 1) * N + n] - centers._storage[(d - 1) * K + k]
s += dx * dx
end
if s < best then
best = s
li = k
end
end
labels[n] = li
end
task.synchronize()
return labels
end,
centers = function(_)
return centers
end,
}
return self
end
| 1,035 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/classic/KNN.luau | --!native
--!optimize 2
local Types = require("../Types")
local Util = require("../Util")
local assert = Util.Assert
--@class KNN
--@field X any
--@field y {number}
--@field k integer
local function predict(self, Q: Types.Tensor): { number }
task.desynchronize()
local D, N = self.X._shape[1], self.X._shape[2]
local B = Q._shape[2]
local out = table.create(B, 1)
for j = 1, B do
local distIdx = table.create(N)
for n = 1, N do
local s = 0.0
for i = 1, D do
local a = self.X._storage[(i - 1) * N + n]
local b = Q._storage[(i - 1) * B + j]
local d = a - b
s += d * d
end
distIdx[n] = { s, n }
end
table.sort(distIdx, function(a, b)
return a[1] < b[1]
end)
local votes = {}
local K = math.min(self.k, N)
for r = 1, K do
local label = self.y[distIdx[r][2]]
votes[label] = (votes[label] or 0) + 1
end
local best, arg = -1, 1
for lbl, cnt in votes do
if cnt > best then
best, arg = cnt, lbl
end
end
out[j] = arg
end
task.synchronize()
return out
end
local function new(X: Types.Tensor, y: { number }, k: number?)
assert(#y == X._shape[2], "KNN: y length must equal N")
return {
X = X,
y = y,
k = k or 5,
predict = predict,
}
end
return new
| 442 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/classic/LinearRegression.luau | --!native
--!optimize 2
local Tape = require("../autograd/Tape")
local Losses = require("../nn/Losses")
local Linear = require("../nn/Linear")
local SGD = require("../optim/SGD")
return function(inF: number)
local model = Linear(inF, 1)
local self
self = {
fit = function(_, X, Y, epochs: number, lr: number)
local opt = SGD(model:parameters(), lr or 1e-2)
for _ = 1, epochs do
opt:zeroGrad()
local pred = model:forward(X)
local _, grad = Losses.mse_backward(pred, Y)
Tape.backwardFrom(pred, grad)
opt:step()
end
end,
predict = function(_, X)
return model:forward(X)
end,
parameters = function(_)
return model:parameters()
end,
}
return self
end
| 207 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/classic/LogisticRegression.luau | --!native
--!optimize 2
local Tensor = require("../Tensor")
local Tape = require("../autograd/Tape")
local Losses = require("../nn/Losses")
local Linear = require("../nn/Linear")
local Adam = require("../optim/Adam")
return function(inF: number)
local model = Linear(inF, 1)
local self
self = {
fit = function(_, X, targets: { number }, epochs: number, lr: number)
local opt = Adam(model:parameters(), lr or 1e-3)
for _ = 1, epochs do
opt:zeroGrad()
local logits = model:forward(X)
local _, grad = Losses.bceWithLogits_backward(logits, targets)
Tape.backwardFrom(logits, grad)
opt:step()
end
end,
predictProba = function(_, X)
local logits = model:forward(X)
local out = Tensor.zeros(logits._shape)
task.desynchronize()
for i = 1, #logits._storage do
out._storage[i] = 1 / (1 + math.exp(-logits._storage[i]))
end
task.synchronize()
return out
end,
predict = function(self, X, threshold: number?)
threshold = threshold or 0.5
local p = self:predictProba(X)
local r = table.create(p._shape[2], 0)
task.desynchronize()
for j = 1, #r do
r[j] = (p._storage[j] >= threshold) and 1 or 0
end
task.synchronize()
return r
end,
parameters = function(_)
return model:parameters()
end,
}
return self
end
| 388 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/classic/MultinomialNB.luau | --!native
--!optimize 2
local Util = require("../Util")
local assert = Util.Assert
return function(C: number, alpha: number)
alpha = alpha or 1.0
local classCount = table.create(C, 0)
local featureCount = {}
local fitted = false
local self
self = {
fit = function(_, X, y)
local D, N = X._shape[1], X._shape[2]
task.desynchronize()
for c = 1, C do
featureCount[c] = table.create(D, 0)
classCount[c] = 0
end
for n = 1, N do
local c = y[n]
classCount[c] += 1
for d = 1, D do
featureCount[c][d] += math.max(0, X._storage[(d - 1) * N + n])
end
end
task.synchronize()
fitted = true
end,
predict = function(_, X)
assert(fitted, "MultinomialNB: fit first")
local D, N = X._shape[1], X._shape[2]
local out = table.create(N, 1)
task.desynchronize()
for n = 1, N do
local best = -1 / 0
local arg = 1
for c = 1, C do
local sum = 0
for d = 1, D do
sum += featureCount[c][d]
end
local logp = math.log((classCount[c] + alpha) / (N + C * alpha))
for d = 1, D do
local p = (featureCount[c][d] + alpha) / (sum + D * alpha)
local x = math.max(0, X._storage[(d - 1) * N + n])
if p > 0 then
logp += x * math.log(p)
end
end
if logp > best then
best = logp
arg = c
end
end
out[n] = arg
end
task.synchronize()
return out
end,
}
return self
end
| 500 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/classic/Ridge.luau | --!native
--!optimize 2
local Tensor = require("../Tensor")
local Tape = require("../autograd/Tape")
local Losses = require("../nn/Losses")
local Linear = require("../nn/Linear")
local SGD = require("../optim/SGD")
return function(inF: number, wd: number)
wd = wd or 1e-2
local model = Linear(inF, 1)
local self
self = {
fit = function(_, X, Y, epochs: number, lr: number)
local opt = SGD(model:parameters(), lr or 1e-2, 0.9, true)
for _ = 1, epochs do
opt:zeroGrad()
local pred = model:forward(X)
local _, grad = Losses.mse_backward(pred, Y)
local W = model.W
if not W._grad then
W._grad = Tensor.zeros(W._shape)
end
task.desynchronize()
for i = 1, #W._storage do
W._grad._storage[i] += 2 * wd * W._storage[i]
end
task.synchronize()
Tape.backwardFrom(pred, grad)
opt:step()
end
end,
predict = function(_, X)
return model:forward(X)
end,
parameters = function(_)
return model:parameters()
end,
}
return self
end
| 310 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/classic/SoftmaxRegression.luau | --!native
--!optimize 2
local Linear = require("../nn/Linear")
local Losses = require("../nn/Losses")
local Tape = require("../autograd/Tape")
local Tensor = require("../Tensor")
local Types = require("../Types")
local Adam = require("../optim/Adam")
local Util = require("../Util")
local assert = Util.Assert
local function slice(
N: number,
X: Types.Tensor,
D: number,
y: { number },
startIdx: number,
size: number
): (Types.Tensor, { number })
local B = math.min(size, N - startIdx + 1)
local XB = Tensor.zeros({ D, B }, X._dtype, X._requiresGrad)
local yB = table.create(B, 1)
task.desynchronize()
for j = 1, B do
local srcj = startIdx + j - 1
for i = 1, D do
XB._storage[(i - 1) * B + j] = X._storage[(i - 1) * N + srcj]
end
yB[j] = y[srcj]
end
task.synchronize()
return XB, yB
end
local function forward(self, X: Types.Tensor): Types.Tensor
return self.fc:forward(X)
end
local function parameters(self): { Types.Tensor }
return self.fc:parameters()
end
local function fit(self, X: Types.Tensor, y: { number }, lr: number, epochs: number, batch: number, smoothing: number)
lr, epochs, batch = lr or 1e-2, epochs or 5, batch or 64
smoothing = smoothing or 0
local D, N = X._shape[1], X._shape[2]
assert(#y == N, "y length must equal N")
task.desynchronize()
local opt = Adam(parameters(self), lr)
for _ = 1, epochs do
for s = 1, N, batch do
local XB, yB = slice(N, X, D, y, s, batch)
opt:zeroGrad()
local logits = forward(self, XB)
local _, dlogits = Losses.cross_entropy_backward(logits, yB, smoothing)
Tape.backwardFrom(logits, dlogits)
opt:step()
end
end
task.synchronize()
end
local function new(inDim: number, classes: number): Types.Module<Types.Tensor, Types.Tensor>
return {
fc = Linear(inDim, classes),
forward = forward,
parameters = parameters,
fit = fit,
}
end
return new
| 560 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/data/DataLoader.luau | --!native
--!optimize 2
local Types = require("../Types")
return function(
dataset: Types.Dataset,
batchSize: number,
shuffle: boolean,
generator: { randint: (a: number, b: number) -> number }?,
drop_last: boolean?
)
local N = dataset:size()
generator = generator or {
randint = function(a: number, b: number)
return math.random(a, b)
end,
}
local order = table.create(N, 0)
for i = 1, N do
order[i] = i
end
if shuffle then
for i = N, 2, -1 do
local j = generator.randint(1, i)
order[i], order[j] = order[j], order[i]
end
end
local idx = 1
return function()
if idx > N or (drop_last and (N - idx + 1) < batchSize) then
return nil
end
local last = math.min(idx + batchSize - 1, N)
local count = last - idx + 1
local batchIdx = table.create(count)
for i = 1, count do
batchIdx[i] = order[idx + i - 1]
end
idx = last + 1
if dataset.batch then
return dataset:batch(batchIdx)
elseif dataset.slice and not shuffle then
return dataset:slice(batchIdx[1], batchIdx[#batchIdx])
end
return dataset:at(batchIdx[1])
end
end
| 343 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/data/KFold.luau | --!native
--!optimize 2
local Types = require("../Types")
return function(N: number, K: number): Types.BatchIter
local order: { number } = {}
for i = 1, N do
order[i] = i
end
for i = N, 2, -1 do
local j = math.random(i)
order[i], order[j] = order[j], order[i]
end
local fold = 1
return function()
if fold > K then
return nil
end
local size = math.floor(N / K)
local s = (fold - 1) * size + 1
local e = (fold == K) and N or (s + size - 1)
local test: { number } = {}
for i = s, e do
table.insert(test, order[i])
end
local train: { number } = {}
for i = 1, N do
if i < s or i > e then
table.insert(train, order[i])
end
end
fold += 1
return train, test
end
end
| 252 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/data/Split.luau | --!native
--!optimize 2
--@param N number -- total items
--@param testRatio number? -- fraction in test split (default 0.2)
--@param stratify {number}? -- optional class per item (1..C), length N
--@param rng Random.new? -- optional RNG for deterministic splits
--@return {number}, {number} -- trainIdx, testIdx (1-based indices into your data)
return function(N: number, testRatio: number?, stratify: { number }?, rng: Random?): ({ number }, { number })
rng = rng or Random.new()
testRatio = testRatio or 0.2
local idx = table.create(N, 0)
for i = 1, N do
idx[i] = i
end
if stratify then
local by = {}
for i = 1, N do
local c = stratify[i]
if not by[c] then
by[c] = {}
end
table.insert(by[c], i)
end
local train, test = {}, {}
for _, arr in by do
for i = #arr, 2, -1 do
local j = rng:NextInteger(1, i)
arr[i], arr[j] = arr[j], arr[i]
end
local cut = math.floor(#arr * (1 - testRatio :: number))
for i = 1, #arr do
if i <= cut then
table.insert(train, arr[i])
else
table.insert(test, arr[i])
end
end
end
return train, test
end
for i = N, 2, -1 do
local j = rng:NextInteger(1, i)
idx[i], idx[j] = idx[j], idx[i]
end
local cut = math.floor(N * (1 - testRatio :: number))
local train = {}
local test = {}
for i = 1, N do
if i <= cut then
table.insert(train, idx[i])
else
table.insert(test, idx[i])
end
end
return train, test
end
| 470 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/data/TensorDataset.luau | --!native
--!optimize 2
local Tensor = require("../Tensor")
local Types = require("../Types")
return function(X: Types.Tensor, Y: Types.Tensor): Types.Dataset
local D, N = X._shape[1], X._shape[2]
local function colSlice(startIdx: number, endIdx: number): (Types.Tensor, Types.Tensor)
local B = endIdx - startIdx + 1
local XB = Tensor.zeros({ D, B }, X._dtype, X._requiresGrad)
for d = 1, D do
local base = (d - 1) * N
for b = 1, B do
XB._storage[(d - 1) * B + b] = X._storage[base + (startIdx + b - 1)]
end
end
local yB = table.create(B, 1)
for b = 1, B do
yB[b] = Y[startIdx + b - 1]
end
return XB, yB
end
local function colGather(indices: { number }): (Types.Tensor, Types.Tensor)
local B = #indices
local XB = Tensor.zeros({ D, B }, X._dtype, X._requiresGrad)
for d = 1, D do
local base = (d - 1) * N
for b = 1, B do
XB._storage[(d - 1) * B + b] = X._storage[base + indices[b]]
end
end
local yB = table.create(B, 1)
for b = 1, B do
yB[b] = Y[indices[b]]
end
return XB, yB
end
return {
size = function(self): number
return N
end,
at = function(self, i: number): (Types.Tensor, Types.Tensor)
return colSlice(i, i)
end,
slice = function(self, i: number, j: number): (Types.Tensor, Types.Tensor)
return colSlice(i, j)
end,
batch = function(self, indices: { number }): (Types.Tensor, Types.Tensor)
return colGather(indices)
end,
}
end
| 495 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/experimental/models/QIMHNN.luau | --!native
--!optimize 2
-- Quantum-Inspired Metaheuristic Neural Network (QIMHNN)
local Types = require("../../Types")
local Tensor = require("../../Tensor")
local Tape = require("../../autograd/Tape")
local Util = require("../../Util")
local Utils = require("../../models/Utils")
local LayerNorm = require("../../nn/LayerNorm")
local Dropout = require("../../nn/Dropout")
local Linear = require("../../nn/Linear")
local Sequential = require("../../nn/Sequential")
local assert = Util.Assert
local sizeFromShape = Util.sizeFromShape
local function sameShape(a: { number }, b: { number }): boolean
if #a ~= #b then
return false
end
for i = 1, #a do
if a[i] ~= b[i] then
return false
end
end
return true
end
local function ensureScratchTensor(buf: Types.Tensor?, shape: { number }): Types.Tensor
if not buf or not sameShape(buf._shape, shape) then
return Tensor.zeros(shape, "f64", false)
end
task.desynchronize()
for i = 1, #buf._storage do
buf._storage[i] = 0
end
task.synchronize()
return buf
end
export type QILayerConfig = {
inDim: number,
outDim: number,
useSuperposition: boolean?,
useInterference: boolean?,
useEntanglement: boolean?,
quantumAmplitude: number?, -- amp for |z|
initScale: number?,
}
local function QILayer(config: QILayerConfig): Types.Module<Types.Tensor, Types.Tensor>
assert(config.inDim and config.inDim > 0, "QILayer: inDim required")
assert(config.outDim and config.outDim > 0, "QILayer: outDim required")
local useSuperposition = config.useSuperposition ~= false
local useInterference = config.useInterference ~= false
local useEntanglement = config.useEntanglement ~= false
local quantumAmplitude = config.quantumAmplitude or 0.1
local initScale = config.initScale or 0.1
local interferenceAlpha = 0.1
local entangleBeta = 0.1
local eps = 1e-8
local W_real = Tensor.zeros({ config.outDim, config.inDim }, "f64", true)
local W_imag = Tensor.zeros({ config.outDim, config.inDim }, "f64", true) -- used when superposition OR interference enabled
local b = Tensor.zeros({ config.outDim, 1 }, "f64", true)
local entanglement = if useEntanglement then Tensor.zeros({ config.outDim, config.outDim }, "f64", true) else nil
task.desynchronize()
local fanIn, fanOut = config.inDim, config.outDim
local bound = initScale * math.sqrt(2 / (fanIn + fanOut))
for i = 1, #W_real._storage do
W_real._storage[i] = (math.random() * 2 - 1) * bound
W_imag._storage[i] = (math.random() * 2 - 1) * bound * 0.5
end
if entanglement then
for i = 1, #entanglement._storage do
entanglement._storage[i] = (math.random() * 2 - 1) * initScale * 0.1
end
end
task.synchronize()
return {
W_real = W_real,
W_imag = W_imag,
b = b,
entanglement = entanglement,
quantumAmplitude = quantumAmplitude,
useSuperposition = useSuperposition,
useInterference = useInterference,
useEntanglement = useEntanglement,
_scratch = {},
forward = function(self, x: Types.Tensor): Types.Tensor
local B = x._shape[2]
local outF = config.outDim
local scratch = self._scratch
-- linear
local z_real = Tape.matmul(self.W_real, x)
local hasImag = (self.useSuperposition or self.useInterference)
local z_imag: Types.Tensor? = nil
if hasImag then
z_imag = Tape.matmul(self.W_imag, x)
end
-- y_sup: superposition amplitude mix
local y_sup = ensureScratchTensor(scratch.y_sup, { outF, B })
scratch.y_sup = y_sup
task.desynchronize()
for i = 1, outF do
for j = 1, B do
local idx = (i - 1) * B + j
local zr = z_real._storage[idx]
if self.useSuperposition and z_imag then
local zi = z_imag._storage[idx]
local mag = math.sqrt(zr * zr + zi * zi + eps)
y_sup._storage[idx] = zr + self.quantumAmplitude * mag
else
y_sup._storage[idx] = zr
end
end
end
task.synchronize()
-- scale by 1 + alpha * cos(phase), phase = atan2(zi, zr)
local y_int = ensureScratchTensor(scratch.y_int, { outF, B })
scratch.y_int = y_int
task.desynchronize()
for i = 1, outF do
for j = 1, B do
local idx = (i - 1) * B + j
local scale = 1
if self.useInterference then
local zr = z_real._storage[idx]
local zi = if z_imag then z_imag._storage[idx] else 0
local phase = math.atan2(zi, zr)
scale = 1 + interferenceAlpha * math.cos(phase)
end
y_int._storage[idx] = y_sup._storage[idx] * scale
end
end
task.synchronize()
local stored_y_int: Types.Tensor = nil
if self.useEntanglement and self.entanglement then
stored_y_int = ensureScratchTensor(scratch.stored_y_int, { outF, B })
scratch.stored_y_int = stored_y_int
task.desynchronize()
for i = 1, #stored_y_int._storage do
stored_y_int._storage[i] = y_int._storage[i]
end
task.synchronize()
end
-- residual E @ y_int
local y_preBias = y_int
local entangled: Types.Tensor = nil
if self.useEntanglement and self.entanglement then
entangled = Tape.matmul(self.entanglement, y_int)
task.desynchronize()
for i = 1, #y_preBias._storage do
y_preBias._storage[i] = y_preBias._storage[i] + entangleBeta * entangled._storage[i]
end
task.synchronize()
end
-- bias
task.desynchronize()
for i = 1, outF do
local bi = self.b._storage[i]
for j = 1, B do
y_preBias._storage[(i - 1) * B + j] += bi
end
end
task.synchronize()
local stored_z_real = z_real
local stored_z_imag = z_imag
-- local stored_y_sup = y_sup
local usedImag = hasImag
local parents: { Types.Tensor } = { self.W_real, self.b, x }
if self.useSuperposition or self.useInterference then
table.insert(parents, self.W_imag)
end
if self.useEntanglement and self.entanglement then
table.insert(parents, self.entanglement)
end
return Tape.makeNode(y_preBias, parents, function(gy: Types.Tensor)
-- gy is dL/d(y_preBias)
local outF = config.outDim
local inF = config.inDim
local B = gy._shape[2]
if self.b._requiresGrad then
if not self.b._grad then
self.b._grad = Tensor.zeros({ outF, 1 })
end
task.desynchronize()
for i = 1, outF do
local acc = 0
for j = 1, B do
acc += gy._storage[(i - 1) * B + j]
end
self.b._grad._storage[i] += acc
end
task.synchronize()
end
-- y_preBias = y_int + beta * (E @ y_int)
local gy_int = gy -- start with gy
if self.useEntanglement and self.entanglement then
-- dE += beta * gy @ y_int^T
if self.entanglement._requiresGrad then
if not self.entanglement._grad then
self.entanglement._grad = Tensor.zeros({ outF, outF })
end
local yIntT: Types.Tensor = nil
Tape.noGrad(function()
yIntT = Tensor.transpose(stored_y_int)
end)
local dEnt
Tape.noGrad(function()
dEnt = Tape.matmul(gy, yIntT)
end)
task.desynchronize()
for i = 1, #self.entanglement._grad._storage do
self.entanglement._grad._storage[i] += entangleBeta * dEnt._storage[i]
end
task.synchronize()
end
-- E: gy_int = gy + beta * (E^T @ gy)
local ET
Tape.noGrad(function()
ET = Tensor.transpose(self.entanglement)
end)
local add
Tape.noGrad(function()
add = Tape.matmul(ET, gy)
end)
local tmp = ensureScratchTensor(scratch.gy_int_tmp, { outF, B })
scratch.gy_int_tmp = tmp
task.desynchronize()
for i = 1, #tmp._storage do
tmp._storage[i] = gy._storage[i] + entangleBeta * add._storage[i]
end
task.synchronize()
gy_int = tmp
end
local gz_real = ensureScratchTensor(scratch.gz_real, { outF, B })
scratch.gz_real = gz_real
local gz_imag = nil
if usedImag then
gz_imag = ensureScratchTensor(scratch.gz_imag, { outF, B })
scratch.gz_imag = gz_imag
end
task.desynchronize()
for i = 1, outF do
for j = 1, B do
local idx = (i - 1) * B + j
local zr = stored_z_real._storage[idx]
local zi = if stored_z_imag then stored_z_imag._storage[idx] else 0
local denom = zr * zr + zi * zi + eps
local mag = math.sqrt(denom)
local ysup = if self.useSuperposition then (zr + self.quantumAmplitude * mag) else zr
local M = 1
local phase = 0
if self.useInterference then
phase = math.atan2(zi, zr)
M = 1 + interferenceAlpha * math.cos(phase)
end
-- gy wrt y_sup and wrt M
local gyij = gy_int._storage[idx]
local gy_sup = gyij * M
local gM = gyij * ysup
local gzR_phase, gzI_phase = 0, 0
if self.useInterference then
local gphase = -interferenceAlpha * gM * math.sin(phase)
-- d phase/dzr = -zi/denom ; d phase/dzi = zr/denom
gzR_phase = gphase * (-zi / denom)
gzI_phase = gphase * (zr / denom)
end
-- superposition path
local gzR_sup, gzI_sup = 0, 0
if self.useSuperposition then
gzR_sup = gy_sup * (1 + self.quantumAmplitude * (zr / mag))
gzI_sup = gy_sup * (self.quantumAmplitude * (zi / mag))
else
gzR_sup = gy_sup
gzI_sup = 0
end
local totalR = gzR_sup + gzR_phase
gz_real._storage[idx] = gz_real._storage[idx] + totalR
if gz_imag then
local totalI = gzI_sup + gzI_phase
gz_imag._storage[idx] = gz_imag._storage[idx] + totalI
end
end
end
task.synchronize()
local xT
Tape.noGrad(function()
xT = Tensor.transpose(x)
end)
-- dW_real += gz_real @ x^T
if self.W_real._requiresGrad then
if not self.W_real._grad then
self.W_real._grad = Tensor.zeros({ outF, inF })
end
local dW
Tape.noGrad(function()
dW = Tape.matmul(gz_real, xT)
end)
task.desynchronize()
for i = 1, #self.W_real._grad._storage do
self.W_real._grad._storage[i] += dW._storage[i]
end
task.synchronize()
end
-- dW_imag
if gz_imag and self.W_imag._requiresGrad then
if not self.W_imag._grad then
self.W_imag._grad = Tensor.zeros({ outF, inF })
end
local dWi
Tape.noGrad(function()
dWi = Tape.matmul(gz_imag, xT)
end)
task.desynchronize()
for i = 1, #self.W_imag._grad._storage do
self.W_imag._grad._storage[i] += dWi._storage[i]
end
task.synchronize()
end
-- dx = W_real^T @ gz_real + (if used) W_imag^T @ gz_imag
local dx: Types.Tensor = nil
if x._requiresGrad then
dx = ensureScratchTensor(scratch.dx, { inF, B })
scratch.dx = dx
local WT
Tape.noGrad(function()
WT = Tensor.transpose(self.W_real)
end)
local dxr
Tape.noGrad(function()
dxr = Tape.matmul(WT, gz_real)
end)
task.desynchronize()
for i = 1, #dx._storage do
dx._storage[i] = dxr._storage[i]
end
task.synchronize()
if gz_imag then
local WIT
Tape.noGrad(function()
WIT = Tensor.transpose(self.W_imag)
end)
local dxi
Tape.noGrad(function()
dxi = Tape.matmul(WIT, gz_imag)
end)
task.desynchronize()
for i = 1, #dx._storage do
dx._storage[i] += dxi._storage[i]
end
task.synchronize()
end
if not x._grad then
x._grad = Tensor.zeros({ inF, B })
end
task.desynchronize()
for i = 1, #x._grad._storage do
x._grad._storage[i] += dx._storage[i]
end
task.synchronize()
end
return nil -- no grad
end)
end,
parameters = function(self): { Types.Tensor }
local params = { self.W_real, self.b }
if self.useSuperposition or self.useInterference then
table.insert(params, 2, self.W_imag)
end
if self.entanglement then
table.insert(params, self.entanglement)
end
return params
end,
}
end
export type QIMHNNConfig = {
inputDim: number,
outputDim: number,
hiddenDims: { number }?,
activation: Utils.ActivationName?,
finalActivation: Utils.ActivationName?,
useSuperposition: boolean?,
useInterference: boolean?,
useEntanglement: boolean?,
quantumAmplitude: number?,
dropout: number?,
layerNorm: boolean?,
}
return function(config: QIMHNNConfig): Types.Module<Types.Tensor, Types.Tensor>
assert(config.inputDim, "QIMHNN: inputDim is required")
assert(config.outputDim, "QIMHNN: outputDim is required")
local hidden = if config.hiddenDims and #config.hiddenDims > 0
then table.clone(config.hiddenDims)
else { math.max(config.inputDim, config.outputDim) }
local dropProb = math.clamp(config.dropout or 0, 0, 0.95)
local layers = {}
local trainables: { any } = {}
local inDim = config.inputDim
for _, hiddenDim in ipairs(hidden) do
assert(hiddenDim > 0, "QIMHNN: hidden dimensions must be positive")
local qiLayer = QILayer({
inDim = inDim,
outDim = hiddenDim,
useSuperposition = config.useSuperposition,
useInterference = config.useInterference,
useEntanglement = config.useEntanglement,
quantumAmplitude = config.quantumAmplitude or 0.1,
})
table.insert(layers, qiLayer)
table.insert(trainables, qiLayer)
if config.layerNorm then
local norm = LayerNorm(hiddenDim)
table.insert(layers, norm)
table.insert(trainables, norm)
end
table.insert(layers, Utils.makeActivationModule(config.activation))
if dropProb > 0 then
local drop = Dropout(dropProb)
table.insert(layers, drop)
table.insert(trainables, drop)
end
inDim = hiddenDim
end
local head = Linear(inDim, config.outputDim)
table.insert(layers, head)
table.insert(trainables, head)
if config.finalActivation then
table.insert(layers, Utils.makeActivationModule(config.finalActivation))
end
local seq = Sequential(layers)
return {
forward = function(_, x: Types.Tensor): Types.Tensor
return seq:forward(x)
end,
act = function(_, x: Types.Tensor): Types.Tensor
return seq:forward(x)
end,
parameters = function(_): { Types.Tensor }
return seq:parameters()
end,
train = function(_, mode: boolean?)
Utils.trainAll(trainables, mode)
end,
}
end
| 4,108 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/experimental/nn/KAN.luau | --!native
--!optimize 2
local Tensor = require("../../Tensor")
local Tape = require("../../autograd/Tape")
local Types = require("../../Types")
local Linear = require("../../nn/Linear")
local Activations = require("../../nn/Activations")
local function RBF(x: Types.Tensor, grid: Types.Tensor, h: number): Types.Tensor
-- x: {B, In}
-- grid: {G} (centers)
-- out: {B, In, G}
local B, In = x._shape[1], x._shape[2]
local G = grid._shape[1]
local out = Tensor.zeros({ B, In, G }, x._dtype, x._requiresGrad or grid._requiresGrad)
local xs = x._storage
local gs = grid._storage
local os = out._storage
task.desynchronize()
for b = 1, B do
for i = 1, In do
local idx_x = (b - 1) * In + i
local val = xs[idx_x]
for g = 1, G do
local c = gs[g]
local dist = (val - c) / h
local rbf = math.exp(-dist * dist)
-- out: {B, In, G}
-- index: (b-1)*In*G + (i-1)*G + g
local idx_o = ((b - 1) * In + (i - 1)) * G + g
os[idx_o] = rbf
end
end
end
task.synchronize()
return Tape.makeNode(out, { x, grid }, function(gy)
if x._requiresGrad then
if not x._grad then
x._grad = Tensor.zeros(x._shape, x._dtype, false)
end
task.desynchronize()
local x_grad = x._grad :: Types.Tensor
local dxs = x_grad._storage
local gys = gy._storage
for b = 1, B do
for i = 1, In do
local idx_x = (b - 1) * In + i
local val = xs[idx_x]
local acc = 0
for g = 1, G do
local idx_o = ((b - 1) * In + (i - 1)) * G + g
local gy_val = gys[idx_o]
local c = gs[g]
local dist = (val - c) / h
local rbf = os[idx_o] -- exp term
-- d/dx exp(-((x-c)/h)^2) = exp(...) * -2((x-c)/h) * 1/h
local grad_val = rbf * (-2 * dist / h)
acc += gy_val * grad_val
end
dxs[idx_x] += acc
end
end
task.synchronize()
end
end)
end
local function KANLayer(in_features: number, out_features: number, grid_size: number?, spline_order: number?)
grid_size = grid_size or 5
spline_order = spline_order or 3
local h = 1.0 / (grid_size :: number)
local base_linear = Linear(in_features, out_features)
local spline_linear = Linear(in_features * (grid_size :: number), out_features)
local grid = Tensor.fromArray({}, { grid_size :: number }, "f64", false)
local step = 2.0 / ((grid_size :: number) - 1)
for i = 1, grid_size :: number do
grid._storage[i] = -1 + (i - 1) * step
end
return {
forward = function(x: Types.Tensor)
local input_shape = x._shape
local rank = #input_shape
local flattened_dim = 1
for i = 1, rank - 1 do
flattened_dim *= input_shape[i]
end
local x_flat = Tensor.reshape(x, { flattened_dim, in_features })
local x_silu = Activations.SiLU(x_flat)
local base_out = base_linear:forward(x_silu)
local x_rbf = RBF(x_flat, grid, h) -- {N, In, G}
local x_rbf_flat = Tensor.reshape(x_rbf, { flattened_dim, in_features * (grid_size :: number) })
local spline_out = spline_linear:forward(x_rbf_flat)
local out = Tensor.zeros(base_out._shape, base_out._dtype, true)
task.desynchronize()
local os, bs, ss = out._storage, base_out._storage, spline_out._storage
for i = 1, #os do
os[i] = bs[i] + ss[i]
end
task.synchronize()
out = Tape.makeNode(out, { base_out, spline_out }, function(gy)
local gys = gy._storage
if base_out._requiresGrad then
if not base_out._grad then
base_out._grad = Tensor.zeros(base_out._shape)
end
local gbs = base_out._grad._storage
task.desynchronize()
for i = 1, #gys do
gbs[i] += gys[i]
end
task.synchronize()
end
if spline_out._requiresGrad then
if not spline_out._grad then
spline_out._grad = Tensor.zeros(spline_out._shape)
end
local gss = spline_out._grad._storage
task.desynchronize()
for i = 1, #gys do
gss[i] += gys[i]
end
task.synchronize()
end
end)
local out_shape = table.clone(input_shape)
out_shape[rank] = out_features
return Tensor.reshape(out, out_shape)
end,
parameters = function(_)
local p = {}
for _, v in base_linear:parameters() do
table.insert(p, v)
end
for _, v in spline_linear:parameters() do
table.insert(p, v)
end
return p
end,
}
end
return KANLayer
| 1,359 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/experimental/nn/Mamba.luau | --!native
--!optimize 2
local Tensor = require("../../Tensor")
local Tape = require("../../autograd/Tape")
local Types = require("../../Types")
local Scan = require("../../ops/Scan")
local Initializer = require("../../Initializer")
local BLAS = require("../../ops/BLAS")
local Math = require("../../ops/Math")
local Activations = require("../../nn/Activations")
local function ensureGrad(t: Types.Tensor): Types.Tensor?
if not t._grad then
t._grad = Tensor.zeros(t._shape, t._dtype, false)
end
return t._grad
end
local function depthwiseConv1d(x: Types.Tensor, weight: Types.Tensor): Types.Tensor
-- x: {B, L, D}
if not Tensor.is_contiguous(x) then
x = Tensor.contiguous(x)
end
if not Tensor.is_contiguous(weight) then
weight = Tensor.contiguous(weight)
end
local B, L, D = x._shape[1], x._shape[2], x._shape[3]
local K = weight._shape[3]
local y = Tensor.zeros({ B, L, D }, x._dtype, x._requiresGrad or weight._requiresGrad)
task.desynchronize()
local xs = x._storage
local ws = weight._storage
local ys = y._storage
for b = 0, B - 1 do
local b_offset = b * L * D
for l = 0, L - 1 do
local l_offset = b_offset + l * D
for d = 0, D - 1 do
local sum = 0
for k = 0, K - 1 do
if l - k >= 0 then
local x_idx = b_offset + (l - k) * D + d + 1
local w_idx = d * K + k + 1
sum += xs[x_idx] * ws[w_idx]
end
end
ys[l_offset + d + 1] = sum
end
end
end
task.synchronize()
return Tape.makeNode(y, { x, weight }, function(gy)
if not x._requiresGrad and not weight._requiresGrad then
return
end
local gx = x._requiresGrad and ensureGrad(x)
local gw = weight._requiresGrad and ensureGrad(weight)
local gys = gy._storage
task.desynchronize()
local gxs = gx and gx._storage
local gws = gw and gw._storage
for b = 0, B - 1 do
local b_offset = b * L * D
for l = 0, L - 1 do
local l_offset = b_offset + l * D
for d = 0, D - 1 do
local gy_val = gys[l_offset + d + 1]
if gy_val == 0 then
continue
end
for k = 0, K - 1 do
if l - k >= 0 then
local x_idx = b_offset + (l - k) * D + d + 1
local w_idx = d * K + k + 1
if gxs then
gxs[x_idx] += gy_val * ws[w_idx]
end
if gws then
gws[w_idx] += gy_val * xs[x_idx]
end
end
end
end
end
end
task.synchronize()
end)
end
local function linear(x: Types.Tensor, weight: Types.Tensor, bias: Types.Tensor?): Types.Tensor
local inFeat = weight._shape[2]
local outFeat = weight._shape[1]
local xShape, xShape_len = x._shape, #x._shape
local lastDim = xShape[xShape_len]
if lastDim ~= inFeat then
error(`Linear: input dimension mismatch. Expected {inFeat}, got {lastDim}`)
end
local flattenedDim = 1
for i = 1, xShape_len - 1 do
flattenedDim *= xShape[i]
end
local xFlat = Tensor.reshape(x, { flattenedDim, inFeat })
local wT = Tensor.transpose(weight, 1, 2)
local outFlat = BLAS.matmul(xFlat, wT)
if bias then
local outWithBias = Tensor.empty(outFlat._shape, outFlat._dtype, outFlat._requiresGrad or bias._requiresGrad)
local b_storage = bias._storage
local out_storage = outFlat._storage
local res_storage = outWithBias._storage
local outSize = #out_storage
task.desynchronize()
for i = 0, outSize - 1 do
local c = (i % outFeat) + 1
res_storage[i + 1] = out_storage[i + 1] + b_storage[c]
end
task.synchronize()
if outWithBias._requiresGrad then
outFlat = Tape.makeNode(outWithBias, { outFlat, bias }, function(gy)
if outFlat._requiresGrad then
local gout = ensureGrad(outFlat)
local gys = gy._storage
local gos = gout._storage
task.desynchronize()
for i = 1, #gys do
gos[i] += gys[i]
end
task.synchronize()
end
if bias._requiresGrad then
local gb = ensureGrad(bias)
local gys = gy._storage
local gbs = gb._storage
task.desynchronize()
for i = 0, #gys - 1 do
local c = (i % outFeat) + 1
gbs[c] += gys[i + 1]
end
task.synchronize()
end
end)
else
outFlat = outWithBias
end
end
local outShape = table.clone(xShape)
outShape[#outShape] = outFeat
return Tensor.reshape(outFlat, outShape)
end
local function MambaBlock(dModel: number, dState: number?, dConv: number?, expand: number?)
dState = dState or 16
dConv = dConv or 4
expand = expand or 2
local dInner = dModel * (expand :: number)
local dtRank = math.ceil(dModel / 16)
local inProj = Tensor.empty({ dInner * 2, dModel }, "f64", true)
Initializer.xavierUniform(inProj)
local convWeight = Tensor.empty({ dInner, 1, dConv :: number }, "f64", true)
Initializer.kaimingUniform(convWeight)
local A_log = Tensor.empty({ dInner, dState :: number }, "f64", true)
Initializer.kaimingUniform(A_log)
local D = Tensor.ones({ dInner }, "f64", true)
local xProj = Tensor.empty({ dtRank + (dState :: number) * 2, dInner }, "f64", true)
local dtProj = Tensor.empty({ dInner, dtRank }, "f64", true)
Initializer.xavierUniform(xProj)
Initializer.xavierUniform(dtProj)
local outProj = Tensor.empty({ dModel, dInner }, "f64", true)
Initializer.xavierUniform(outProj)
return {
forward = function(_, u: Types.Tensor): Types.Tensor
local _B_size, _L_size, D_size = u._shape[1], u._shape[2], u._shape[3]
local xz = linear(u, inProj)
local x = Tensor.slice(xz, 3, 1, dInner)
local z = Tensor.slice(xz, 3, dInner + 1, dInner * 2)
local x_conv = depthwiseConv1d(x, convWeight)
local x_act = Activations.SiLU(x_conv)
local x_dbl = linear(x_act, xProj)
local dt_rank = Tensor.slice(x_dbl, 3, 1, dtRank)
local B_ssm = Tensor.slice(x_dbl, 3, dtRank + 1, dtRank + (dState :: number))
local C_ssm = Tensor.slice(x_dbl, 3, dtRank + (dState :: number) + 1, dtRank + (dState :: number) * 2)
local dt = linear(dt_rank, dtProj)
dt = Activations.Softplus(dt)
local A = Math.scalarMul(Math.exp(A_log), -1)
local y = Scan.selectiveScan(x_act, dt, A, B_ssm, C_ssm, D)
local z_act = Activations.SiLU(z)
local y_gated = Math.mul(y, z_act)
local out = linear(y_gated, outProj)
if D_size == dModel then
return Math.add(out, u)
end
return out
end,
parameters = function()
return { inProj, convWeight, A_log, D, xProj, dtProj, outProj }
end,
}
end
return MambaBlock
| 1,997 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/experimental/optim/Metaheuristic.luau | --!native
--!optimize 2
-- Metaheuristic Optimizer for QIMHNN
local Types = require("../../Types")
local Tensor = require("../../Tensor")
local Util = require("../../Util")
local assert = Util.Assert
export type MetaheuristicConfig = {
lr: number,
swarmSize: number?,
inertia: number?,
cognitive: number?,
social: number?,
gradScale: number?,
mutationRate: number?,
mutationStrength: number?,
}
return function(params: { Types.Tensor }, config: MetaheuristicConfig): Types.Optimizer
assert(config.lr and config.lr > 0, "MetaheuristicOptimizer: lr required")
local lr = config.lr
local _swarmSize = config.swarmSize or 10
local inertia = config.inertia or 0.9
local cognitive = config.cognitive or 1.5
local social = config.social or 1.5
local gradScale = config.gradScale or 0.1
local mutationRate = config.mutationRate or 0.05
local mutationStrength = config.mutationStrength or 0.01
local velocities: { Types.Tensor } = {}
local personalBest: { Types.Tensor } = {}
local globalBest: { Types.Tensor } = {}
local personalBestScore: { number } = {}
local globalBestScore: { number } = {}
for i, param in ipairs(params) do
local v = Tensor.zeros(param._shape, param._dtype, false)
local pb = Tensor.zeros(param._shape, param._dtype, false)
local gb = Tensor.zeros(param._shape, param._dtype, false)
local pStore = param._storage
local vStore = v._storage
local pbStore = pb._storage
local gbStore = gb._storage
task.desynchronize()
for j = 1, #pStore do
vStore[j] = (math.random() * 2 - 1) * 0.001
pbStore[j] = pStore[j]
gbStore[j] = pStore[j]
end
task.synchronize()
velocities[i] = v
personalBest[i] = pb
globalBest[i] = gb
personalBestScore[i] = math.huge
globalBestScore[i] = math.huge
end
return {
step = function()
for i, param in ipairs(params) do
local grad = param._grad
if grad then
local gStore = grad._storage
local gradNormSq = 0
task.desynchronize()
for j = 1, #gStore do
local g = gStore[j]
gradNormSq += g * g
end
task.synchronize()
local score = gradNormSq
if score < personalBestScore[i] then
personalBestScore[i] = score
local pb = personalBest[i]
local pStore = param._storage
local pbStore = pb._storage
task.desynchronize()
for j = 1, #pStore do
pbStore[j] = pStore[j]
end
task.synchronize()
end
if score < globalBestScore[i] then
globalBestScore[i] = score
local gb = globalBest[i]
local pStore = param._storage
local gbStore = gb._storage
task.desynchronize()
for j = 1, #pStore do
gbStore[j] = pStore[j]
end
task.synchronize()
end
end
end
for i, param in ipairs(params) do
local grad = param._grad
if grad then
local v = velocities[i]
local pb = personalBest[i]
local gb = globalBest[i]
local pStore = param._storage
local gStore = grad._storage
local vStore = v._storage
local pbStore = pb._storage
local gbStore = gb._storage
task.desynchronize()
for j = 1, #pStore do
local r1 = math.random()
local r2 = math.random()
local g = gStore[j]
local current = pStore[j]
local vj = vStore[j]
local pbj = pbStore[j]
local gbj = gbStore[j]
vj = inertia * vj
+ cognitive * r1 * (pbj - current)
+ social * r2 * (gbj - current)
- gradScale * g
local newVal = current + lr * vj
if mutationRate > 0 and math.random() < mutationRate then
newVal += (math.random() * 2 - 1) * mutationStrength
end
vStore[j] = vj
pStore[j] = newVal
end
task.synchronize()
end
end
end,
zeroGrad = function()
for _, param in ipairs(params) do
local grad = param._grad
if grad then
local gStore = grad._storage
task.desynchronize()
for i = 1, #gStore do
gStore[i] = 0
end
task.synchronize()
end
end
end,
getState = function()
return nil
end,
setState = function(_self, _state)
return
end,
}
end
| 1,189 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/experimental/optim/SwarmPSO.luau | --!native
--!optimize 2
-- multi-particle PSO Optimizer for QIMHNN
local Types = require("../../Types")
local Tensor = require("../../Tensor")
local Util = require("../../Util")
local assert = Util.Assert
export type SwarmPSOConfig = {
swarmSize: number,
inertia: number?,
cognitive: number?,
social: number?,
lr: number?,
mutationRate: number?,
mutationStrength: number?,
evalFn: (number) -> number,
}
local function copyTensorData(src: Types.Tensor, dst: Types.Tensor)
assert(#src._storage == #dst._storage, "SwarmPSO: tensor size mismatch in copyTensorData")
task.desynchronize()
for i = 1, #src._storage do
dst._storage[i] = src._storage[i]
end
task.synchronize()
end
local function swapTensorStorage(a: Types.Tensor, b: Types.Tensor)
local tmp = a._storage
a._storage = b._storage
b._storage = tmp
end
return function(params: { Types.Tensor }, config: SwarmPSOConfig): Types.Optimizer
assert(config and type(config) == "table", "SwarmPSO: config table required")
assert(config.swarmSize and config.swarmSize > 0, "SwarmPSO: swarmSize > 0 required")
assert(config.evalFn, "SwarmPSO: evalFn callback is required")
local swarmSize = config.swarmSize
local inertia = config.inertia or 0.7
local cognitive = config.cognitive or 1.5
local social = config.social or 1.5
local lr = config.lr or 1.0
local mutationRate = config.mutationRate or 0.0
local mutationStrength = config.mutationStrength or 0.0
local evalFn = config.evalFn
local positions: { { Types.Tensor } } = {}
local velocities: { { Types.Tensor } } = {}
local pbest: { { Types.Tensor } } = {}
local pbestScore: { number } = {}
local gbest: { Types.Tensor } = {}
local gbestScore = math.huge
for p = 1, swarmSize do
local posForParticle: { Types.Tensor } = {}
local velForParticle: { Types.Tensor } = {}
local pbestForParticle: { Types.Tensor } = {}
for _, param in ipairs(params) do
local pos = Tensor.zeros(param._shape, param._dtype, false)
copyTensorData(param, pos)
local vel = Tensor.zeros(param._shape, param._dtype, false)
task.desynchronize()
for j = 1, #vel._storage do
vel._storage[j] = (math.random() * 2 - 1) * 0.001
end
task.synchronize()
local pb = Tensor.zeros(param._shape, param._dtype, false)
copyTensorData(param, pb)
table.insert(posForParticle, pos)
table.insert(velForParticle, vel)
table.insert(pbestForParticle, pb)
end
positions[p] = posForParticle
velocities[p] = velForParticle
pbest[p] = pbestForParticle
pbestScore[p] = math.huge
end
for _, param in ipairs(params) do
local gb = Tensor.zeros(param._shape, param._dtype, false)
copyTensorData(param, gb)
table.insert(gbest, gb)
end
for i, param in ipairs(params) do
param._storage = gbest[i]._storage
end
return {
step = function()
for p = 1, swarmSize do
local posForParticle = positions[p]
for i, param in ipairs(params) do
local pos = posForParticle[i]
swapTensorStorage(param, pos)
end
local loss = evalFn(p)
assert(type(loss) == "number", "SwarmPSO: evalFn must return a number (loss)")
for i, param in ipairs(params) do
local pos = posForParticle[i]
swapTensorStorage(param, pos)
end
if loss < pbestScore[p] then
pbestScore[p] = loss
local pbForParticle = pbest[p]
for i = 1, #params do
local pos = posForParticle[i]
local pb = pbForParticle[i]
copyTensorData(pos, pb)
end
end
if loss < gbestScore then
gbestScore = loss
for i = 1, #params do
local pos = posForParticle[i]
local gb = gbest[i]
copyTensorData(pos, gb)
end
end
end
for p = 1, swarmSize do
local posForParticle = positions[p]
local velForParticle = velocities[p]
local pbForParticle = pbest[p]
for i = 1, #params do
local pos = posForParticle[i]
local vel = velForParticle[i]
local pb = pbForParticle[i]
local gb = gbest[i]
task.desynchronize()
for j = 1, #pos._storage do
local x = pos._storage[j]
local vj = vel._storage[j]
local pbestVal = pb._storage[j]
local gbestVal = gb._storage[j]
local r1 = math.random()
local r2 = math.random()
vj = inertia * vj + cognitive * r1 * (pbestVal - x) + social * r2 * (gbestVal - x)
vj *= lr
local newX = x + vj
if mutationRate > 0 and math.random() < mutationRate then
newX += (math.random() * 2 - 1) * mutationStrength
end
vel._storage[j] = vj
pos._storage[j] = newX
end
task.synchronize()
end
end
for i, param in ipairs(params) do
param._storage = gbest[i]._storage
if param._grad then
task.desynchronize()
for j = 1, #param._grad._storage do
param._grad._storage[j] = 0
end
task.synchronize()
end
end
end,
zeroGrad = function()
for _, param in ipairs(params) do
if param._grad then
task.desynchronize()
for i = 1, #param._grad._storage do
param._grad._storage[i] = 0
end
task.synchronize()
end
end
end,
getState = function()
return nil
end,
setState = function(_self, _state)
return
end,
}
end
| 1,494 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/experimental/rl/Feudal.luau | --!native
--!optimize 2
local Types = require("../../Types")
local Tensor = require("../../Tensor")
local Linear = require("../../nn/Linear")
local LSTM = require("../../nn/LSTM")
local Softmax = require("../../nn/Softmax")
local Util = require("../../Util")
local Activations = require("../../nn/Activations")
local assert = Util.Assert
local function cosineSimilarity(u: Types.Tensor, v: Types.Tensor)
-- u, v: {D, B}
local dot = Tensor.zeros({ 1, u._shape[2] }, u._dtype, u._requiresGrad or v._requiresGrad)
local B = u._shape[2]
local D = u._shape[1]
task.desynchronize()
local u_store = u._storage
local v_store = v._storage
local out_store = dot._storage
for b = 1, B do
local sum_uv, sum_uu, sum_vv = 0, 0, 0
for i = 1, D do
local idx = (i - 1) * B + b
local val_u = u_store[idx]
local val_v = v_store[idx]
sum_uv += val_u * val_v
sum_uu += val_u * val_u
sum_vv += val_v * val_v
end
local norm_u = math.sqrt(sum_uu) + 1e-8
local norm_v = math.sqrt(sum_vv) + 1e-8
out_store[b] = sum_uv / (norm_u * norm_v)
end
task.synchronize()
return dot
end
return function(cfg: {
inputDim: number,
actionDim: number,
hiddenDim: number,
goalDim: number?,
horizon: number?,
gammaW: number?,
gammaM: number?,
lr: number?,
optimizerFactory: (params: { number }) -> Types.Optimizer,
})
assert(cfg.inputDim, "Feudal: inputDim required")
assert(cfg.actionDim, "Feudal: actionDim required")
assert(cfg.hiddenDim, "Feudal: hiddenDim required")
local inputDim = cfg.inputDim
local actionDim = cfg.actionDim
local hiddenDim = cfg.hiddenDim
local goalDim = cfg.goalDim or hiddenDim
local horizon = cfg.horizon or 10
local _gammaW = cfg.gammaW or 0.99
local _gammaM = cfg.gammaM or 0.99
local _lr = cfg.lr or 1e-3
local optimizerFactory = cfg.optimizerFactory
assert(optimizerFactory, "Feudal: optimizerFactory required")
local perceptor = Linear(inputDim, hiddenDim)
local mgrLinear1 = Linear(hiddenDim, hiddenDim)
local mgrLSTM = LSTM(hiddenDim, hiddenDim)
local mgrGoalHead = Linear(hiddenDim, goalDim)
local mgrValueHead = Linear(hiddenDim, 1)
local wkrLinear1 = Linear(hiddenDim + goalDim, hiddenDim)
local wkrLSTM = LSTM(hiddenDim, hiddenDim)
local wkrActionHead = Linear(hiddenDim, actionDim)
local wkrValueHead = Linear(hiddenDim, 1)
local params = {}
local function collectParams(mod)
for _, p in ipairs(mod:parameters()) do
table.insert(params, p)
end
end
collectParams(perceptor)
collectParams(mgrLinear1)
collectParams(mgrLSTM)
collectParams(mgrGoalHead)
collectParams(mgrValueHead)
collectParams(wkrLinear1)
collectParams(wkrLSTM)
collectParams(wkrActionHead)
collectParams(wkrValueHead)
local optimizer = optimizerFactory(params)
local mgrH, mgrC
local wkrH, wkrC
local currentGoal
local lastMgrUpdateStep = 0
local stepCount = 0
local startState
local workerBuffer = {} -- {s, g, a, r_ext, r_int, ns, done}
local managerBuffer = {} -- {s, g, r_sum, ns, done}
local Agent = {}
function Agent:reset(batchSize: number)
batchSize = batchSize or 1
mgrH = Tensor.zeros({ hiddenDim, batchSize }, "f64", true)
mgrC = Tensor.zeros({ hiddenDim, batchSize }, "f64", true)
wkrH = Tensor.zeros({ hiddenDim, batchSize }, "f64", true)
wkrC = Tensor.zeros({ hiddenDim, batchSize }, "f64", true)
currentGoal = Tensor.zeros({ goalDim, batchSize }, "f64", true)
startState = nil
stepCount = 0
lastMgrUpdateStep = 0
table.clear(workerBuffer)
table.clear(managerBuffer)
end
function Agent:act(state: Types.Tensor)
-- state: {inputDim, B}
local B = state._shape[2]
local z_raw = perceptor:forward(state)
local z = Activations.ReLU(z_raw)
if stepCount - lastMgrUpdateStep >= horizon or stepCount == 0 then
local mgr_z = mgrLinear1:forward(z)
mgr_z = Activations.Tanh(mgr_z)
local h_new, c_new = mgrLSTM:forward(mgr_z, mgrH, mgrC)
mgrH, mgrC = h_new, c_new
local g = mgrGoalHead:forward(h_new)
local g_norm = Tensor.zeros(g._shape, g._dtype, true)
task.desynchronize()
local g_store = g._storage
local gn_store = g_norm._storage
for b = 1, B do
local sum_sq = 0
for i = 1, goalDim do
local val = g_store[(i - 1) * B + b]
sum_sq += val * val
end
local scale = 1 / (math.sqrt(sum_sq) + 1e-8)
for i = 1, goalDim do
local idx = (i - 1) * B + b
gn_store[idx] = g_store[idx] * scale
end
end
task.synchronize()
currentGoal = g_norm
lastMgrUpdateStep = stepCount
startState = state:detach()
end
-- z: {hiddenDim, B}, goal: {goalDim, B}
local combinedInput = Tensor.zeros({ hiddenDim + goalDim, B }, state._dtype, true)
task.desynchronize()
local z_store = z._storage
local g_store = currentGoal._storage
local c_store = combinedInput._storage
for b = 1, B do
for i = 1, hiddenDim do
c_store[(i - 1) * B + b] = z_store[(i - 1) * B + b]
end
for i = 1, goalDim do
c_store[(hiddenDim + i - 1) * B + b] = g_store[(i - 1) * B + b]
end
end
task.synchronize()
local wz = wkrLinear1:forward(combinedInput)
local wh_new, wc_new = wkrLSTM:forward(wz, wkrH, wkrC)
wkrH, wkrC = wh_new, wc_new
local logits = wkrActionHead:forward(wh_new)
local P = Softmax.forward(logits)
local action = 1
task.desynchronize()
local r = math.random()
local cum = 0.0
for i = 1, actionDim do
cum += P._storage[i]
if r <= cum then
action = i
break
end
end
task.synchronize()
stepCount += 1
return action, currentGoal
end
function Agent:observe(transition: {
state: Types.Tensor,
action: number,
reward: number,
nextState: Types.Tensor,
done: boolean,
})
local s = transition.state
local a = transition.action
local r = transition.reward
local ns = transition.nextState
local d = transition.done
local z = Activations.ReLU(perceptor:forward(s))
local z_next = Activations.ReLU(perceptor:forward(ns))
local dz = Tensor.zeros(z._shape, z._dtype, false)
task.desynchronize()
local zs, zns, dzs = z._storage, z_next._storage, dz._storage
for i = 1, #zs do
dzs[i] = zns[i] - zs[i]
end
task.synchronize()
local cosim = cosineSimilarity(dz, currentGoal)
local r_int = cosim._storage[1]
table.insert(workerBuffer, {
s = s,
g = currentGoal,
a = a,
r_ext = r,
r_int = r_int,
ns = ns,
d = d,
})
if d or (stepCount - lastMgrUpdateStep == 0) then
local r_mgr, workerBuffer_len = 0, #workerBuffer
for i = workerBuffer_len - (stepCount - lastMgrUpdateStep), workerBuffer_len do
if workerBuffer[i] then
r_mgr += workerBuffer[i].r_ext
end
end
table.insert(managerBuffer, {
s = startState,
g = currentGoal,
r = r_mgr,
ns = ns,
d = d,
})
end
end
function Agent:trainStep()
optimizer:zeroGrad()
local _loss = Tensor.zeros({ 1 }, "f64", true)
table.clear(workerBuffer)
table.clear(managerBuffer)
return { loss = 0 }
end
return Agent
end
| 2,149 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/extra/RND.luau | --!native
--!optimize 2
local Tape = require("../autograd/Tape")
local Tensor = require("../Tensor")
local Types = require("../Types")
local function step(self, s: Types.Tensor): number
self.opt:zeroGrad()
local g = self.target:forward(s) :: Types.Tensor -- {E,1}
local f = self.predictor:forward(s) :: Types.Tensor -- {E,1}
local loss = 0
local grad = Tensor.zeros(f._shape)
task.desynchronize()
for i = 1, #f._storage do
local d = f._storage[i] - g._storage[i]
loss += d * d
grad._storage[i] = 2 * d
end
task.synchronize()
Tape.backwardFrom(f, grad)
self.opt:step()
local r = loss
if self.norm then
self.norm:update(r)
r = self.norm:normalize(r)
end
return r
end
local function new(
target: Types.Module<Types.Tensor, Types.Tensor>,
predictor: Types.Module<Types.Tensor, Types.Tensor>,
optimizer: Types.Optimizer,
norm: {
update: (self: { update: (x: number) -> (), normalize: (x: number) -> number }, x: number) -> number,
normalize: (self: { update: (x: number) -> number, normalize: (x: number) -> number }, x: number) -> number,
}?
)
return {
target = target,
predictor = predictor,
opt = optimizer,
norm = norm,
step = step,
}
end
return { new = new }
| 359 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/init.luau | --[[
Gradien (by @Eternity_Devs)
A strictly-typed, optimized parallel-first ML & DL library for Roblox.
Version 1.4.0-rc5
]]
--!strict
local Gradien = {}
Gradien.Autograd = require("@self/autograd/Tape")
Gradien.Init = require("@self/Initializer")
Gradien.Metrics = require("@self/Metrics")
Gradien.GradClip = require("@self/GradClip")
Gradien.Trainer = require("@self/Trainer")
Gradien.State = require("@self/State")
Gradien.Types = require("@self/Types")
Gradien.Util = require("@self/Util")
Gradien.Tensor = require("@self/Tensor")
Gradien.Debug = require("@self/Debug")
Gradien.Tokenizers = require("@self/tokenizers")
Gradien.Experimental = {
Models = {
QIMHNN = require("@self/experimental/models/QIMHNN"),
},
NN = {
MambaBlock = require("@self/experimental/nn/Mamba"),
KAN = require("@self/experimental/nn/KAN"),
},
Optim = {
Metaheuristic = require("@self/experimental/optim/Metaheuristic"),
SwarmPSO = require("@self/experimental/optim/SwarmPSO"),
},
RL = {
Feudal = require("@self/experimental/rl/Feudal"),
},
}
Gradien.Models = {
MLP = require("@self/models/MLP"),
ResMLP = require("@self/models/ResMLP"),
ConvNet = require("@self/models/ConvNet"),
TransformerEncoder = require("@self/models/TransformerEncoder"),
SequenceClassifier = require("@self/models/SequenceClassifier"),
AutoEncoder = require("@self/models/AutoEncoder"),
Utils = require("@self/models/Utils"),
}
Gradien.Ops = {
Math = require("@self/ops/Math"),
BLAS = require("@self/ops/BLAS"),
Reduce = require("@self/ops/Reduce"),
Conv2d = require("@self/ops/Conv2d"),
Pool = require("@self/ops/Pool"),
Softmax = require("@self/ops/Softmax"),
AvgPool2d = require("@self/ops/AvgPool2d"),
Scan = require("@self/ops/Scan"),
ConvTranspose2d = require("@self/ops/ConvTranspose2d"),
}
Gradien.NN = {
Linear = require("@self/nn/Linear"),
NoisyLinear = require("@self/nn/NoisyLinear"),
Activations = require("@self/nn/Activations"),
LayerNorm = require("@self/nn/LayerNorm"),
BatchNorm1d = require("@self/nn/BatchNorm1d"),
BatchNorm2d = require("@self/nn/BatchNorm2d"),
Embedding = require("@self/nn/Embedding"),
Attention = require("@self/nn/Attention"),
RMSNorm = require("@self/nn/RMSNorm"),
RNN = require("@self/nn/RNN"),
GRU = require("@self/nn/GRU"),
LSTM = require("@self/nn/LSTM"),
Sequential = require("@self/nn/Sequential"),
Dropout = require("@self/nn/Dropout"),
Fused = require("@self/nn/Fused"),
Softmax = require("@self/nn/Softmax"),
Losses = require("@self/nn/Losses"),
Functional = require("@self/nn/Functional"),
GatedMLP = require("@self/nn/GatedMLP"),
DropPath = require("@self/nn/DropPath"),
Residual = require("@self/nn/Residual"),
SwiGLU = require("@self/nn/SwiGLU"),
Conv2d = require("@self/nn/Conv2d"),
MaxPool2d = require("@self/nn/MaxPool2d"),
AvgPool2d = require("@self/nn/AvgPool2d"),
ConvTranspose2d = require("@self/nn/ConvTranspose2d"),
GroupNorm = require("@self/nn/GroupNorm"),
Flatten = require("@self/nn/Flatten"),
}
Gradien.Optim = {
SGD = require("@self/optim/SGD"),
Adam = require("@self/optim/Adam"),
AdamW = require("@self/optim/AdamW"),
EMA = require("@self/optim/EMA"),
RMSProp = require("@self/optim/RMSProp"),
Adagrad = require("@self/optim/Adagrad"),
Adafactor = require("@self/optim/Adafactor"),
Accumulated = require("@self/optim/Accumulated"),
Schedulers = require("@self/optim/Schedulers"),
Lion = require("@self/optim/Lion"),
Lookahead = require("@self/optim/Lookahead"),
Sophia = require("@self/optim/Sophia"),
Muon = require("@self/optim/Muon"),
}
Gradien.RL = {
Replay = require("@self/rl/Replay"),
UniformReplay = require("@self/rl/UniformReplay"),
PrioritizedReplay = require("@self/rl/PrioritizedReplay"),
DQL = require("@self/rl/DQL"),
DoubleDQN = require("@self/rl/DoubleDQN"),
C51DQN = require("@self/rl/C51DQN"),
BDQ = require("@self/rl/BDQ"),
Dueling = require("@self/rl/Dueling"),
NStep = require("@self/rl/NStep"),
LambdaBuffer = require("@self/rl/LambdaBuffer"),
A2C = require("@self/rl/A2C"),
PPO = require("@self/rl/PPO"),
MultiAgent = require("@self/rl/MultiAgent"),
}
Gradien.Classic = {
SoftmaxRegression = require("@self/classic/SoftmaxRegression"),
LinearRegression = require("@self/classic/LinearRegression"),
Ridge = require("@self/classic/Ridge"),
LogisticRegression = require("@self/classic/LogisticRegression"),
KMeans = require("@self/classic/KMeans"),
KNN = require("@self/classic/KNN"),
GaussianNB = require("@self/classic/GaussianNB"),
MultinomialNB = require("@self/classic/MultinomialNB"),
}
Gradien.Preprocess = {
StandardScaler = require("@self/preprocess/StandardScaler"),
MinMaxScaler = require("@self/preprocess/MinMaxScaler"),
OneHot = require("@self/preprocess/OneHot"),
PCA = require("@self/preprocess/PCA"),
SinusoidalPE = require("@self/preprocess/SinusoidalPE"),
}
Gradien.Data = {
TensorDataset = require("@self/data/TensorDataset"),
DataLoader = require("@self/data/DataLoader"),
Split = require("@self/data/Split"),
KFold = require("@self/data/KFold"),
}
Gradien.Extra = {
RND = require("@self/extra/RND"),
}
Gradien.Tools = {
Gradcheck = require("@self/tools/Gradcheck"),
}
return Gradien
| 1,552 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/models/AutoEncoder.luau | --!native
--!optimize 2
local Types = require("../Types")
local Utils = require("./Utils")
local Util = require("../Util")
local Linear = require("../nn/Linear")
local LayerNorm = require("../nn/LayerNorm")
local Dropout = require("../nn/Dropout")
local Sequential = require("../nn/Sequential")
local assert = Util.Assert
export type AutoEncoderConfig = {
inputDim: number,
latentDim: number,
hiddenDims: { number }?,
activation: Utils.ActivationName?,
dropout: number?,
layerNorm: boolean?,
finalActivation: Utils.ActivationName?,
weightInit: ((number, number) -> number)?,
}
local AutoEncoder = {}
AutoEncoder.__index = AutoEncoder
local function buildStack(
inDim: number,
hiddenDims: { number },
outDim: number,
activation: Utils.ActivationName?,
dropProb: number,
useLayerNorm: boolean?,
init: ((number, number) -> number)?
): (Types.Module<Types.Tensor, Types.Tensor>, { any })
local layers = {}
local trainables: { any } = {}
local function insert(m)
table.insert(layers, m)
table.insert(trainables, m)
end
local current = inDim
for _, hidden in ipairs(hiddenDims) do
insert(Linear(current, hidden, init))
if useLayerNorm then
insert(LayerNorm(hidden))
end
insert(Utils.makeActivationModule(activation))
if dropProb > 0 then
insert(Dropout(dropProb))
end
current = hidden
end
insert(Linear(current, outDim, init))
return Sequential(layers), trainables
end
function AutoEncoder.new(cfg: AutoEncoderConfig): Types.Module<Types.Tensor, Types.Tensor>
assert(cfg.inputDim and cfg.latentDim, "AutoEncoder: inputDim and latentDim required")
local hidden = if cfg.hiddenDims and #cfg.hiddenDims > 0
then table.clone(cfg.hiddenDims)
else {
math.max(cfg.inputDim, cfg.latentDim * 2),
}
local revHidden = table.clone(hidden)
for i = 1, math.floor(#revHidden / 2) do
local j = #revHidden - i + 1
revHidden[i], revHidden[j] = revHidden[j], revHidden[i]
end
local drop = math.clamp(cfg.dropout or 0, 0, 0.95)
local encoder, encTrain =
buildStack(cfg.inputDim, hidden, cfg.latentDim, cfg.activation, drop, cfg.layerNorm, cfg.weightInit)
local decoder, decTrain =
buildStack(cfg.latentDim, revHidden, cfg.inputDim, cfg.activation, drop, cfg.layerNorm, cfg.weightInit)
local finalAct = if cfg.finalActivation then Utils.makeActivationModule(cfg.finalActivation) else nil
local trainables: { any } = {}
for _, m in ipairs(encTrain) do
table.insert(trainables, m)
end
for _, m in ipairs(decTrain) do
table.insert(trainables, m)
end
if finalAct then
table.insert(trainables, finalAct)
end
local self = setmetatable({
_encoder = encoder,
_decoder = decoder,
_finalAct = finalAct,
_trainables = trainables,
}, AutoEncoder)
return self
end
function AutoEncoder:encode(x: Types.Tensor): Types.Tensor
return self._encoder:forward(x)
end
function AutoEncoder:decode(z: Types.Tensor): Types.Tensor
local out = self._decoder:forward(z)
if self._finalAct then
out = self._finalAct:forward(out)
end
return out
end
function AutoEncoder:forward(x: Types.Tensor): Types.Tensor
local z = self:encode(x)
return self:decode(z)
end
function AutoEncoder:parameters(): { Types.Tensor }
local params = {}
Utils.collectParams(params, self._encoder)
Utils.collectParams(params, self._decoder)
return params
end
function AutoEncoder:train(mode: boolean?)
Utils.trainAll(self._trainables, mode)
end
return setmetatable({
new = function(cfg: AutoEncoderConfig): Types.Module<Types.Tensor, Types.Tensor>
return AutoEncoder.new(cfg)
end,
}, {
__call = function(_, cfg: AutoEncoderConfig): Types.Module<Types.Tensor, Types.Tensor>
return AutoEncoder.new(cfg)
end,
})
| 941 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/models/ConvNet.luau | --!native
--!optimize 2
local Types = require("../Types")
local Utils = require("./Utils")
local Util = require("../Util")
local Conv2d = require("../nn/Conv2d")
local BatchNorm2d = require("../nn/BatchNorm2d")
local MaxPool2d = require("../nn/MaxPool2d")
local AvgPool2d = require("../nn/AvgPool2d")
local Dropout = require("../nn/Dropout")
local Flatten = require("../nn/Flatten")
local Linear = require("../nn/Linear")
local Sequential = require("../nn/Sequential")
local assert = Util.Assert
export type PoolConfig = {
kind: "max" | "avg",
size: number?,
stride: number?,
}
export type ConvBlockConfig = {
outChannels: number,
kernelSize: number?,
activation: Utils.ActivationName?,
useBatchNorm: boolean?,
pool: PoolConfig?,
dropout: number?,
}
export type ConvNetConfig = {
inChannels: number,
inputHeight: number,
inputWidth: number,
numClasses: number,
blocks: { ConvBlockConfig }?,
headDims: { number }?,
activation: Utils.ActivationName?,
dropout: number?,
headDropout: number?,
finalActivation: Utils.ActivationName?,
weightInit: ((number, number) -> number)?,
}
local function defaultBlocks(): { ConvBlockConfig }
return {
{ outChannels = 32, kernelSize = 3, pool = { kind = "max", size = 2 } },
{ outChannels = 64, kernelSize = 3, pool = { kind = "max", size = 2 } },
{ outChannels = 128, kernelSize = 3, pool = { kind = "max", size = 2 } },
}
end
local function applyConvSize(size: number, kernel: number): number
local nextSize = size - kernel + 1
assert(nextSize > 0, "ConvNet: spatial dimension collapsed (conv)")
return nextSize
end
local function applyPoolSize(size: number, cfg: PoolConfig): number
local k = cfg.size or 2
local stride = cfg.stride or k
local nextSize = math.floor((size - k) / stride) + 1
assert(nextSize > 0, "ConvNet: spatial dimension collapsed (pool)")
return nextSize
end
return function(config: ConvNetConfig): Types.Module<Types.Tensor, Types.Tensor>
assert(config.inChannels and config.inputHeight and config.inputWidth, "ConvNet: input spec required")
assert(config.numClasses, "ConvNet: numClasses required")
local blocks = if config.blocks and #config.blocks > 0 then config.blocks else defaultBlocks()
local H, W = config.inputHeight, config.inputWidth
local C = config.inChannels
for _, block: ConvBlockConfig in ipairs(blocks) do
local kernel = block.kernelSize or 3
H = applyConvSize(H, kernel)
W = applyConvSize(W, kernel)
if block.pool then
H = applyPoolSize(H, block.pool)
W = applyPoolSize(W, block.pool)
end
C = block.outChannels
end
local flattenDim = C * H * W
assert(flattenDim > 0, "ConvNet: invalid flatten dimension")
local convLayers = {}
local trainables: { any } = {}
local inChannels = config.inChannels
for _, block: ConvBlockConfig in ipairs(blocks) do
local kernel = block.kernelSize or 3
local conv = Conv2d(inChannels, block.outChannels, kernel, kernel)
table.insert(convLayers, conv)
table.insert(trainables, conv)
if block.useBatchNorm ~= false then
local bn = BatchNorm2d(block.outChannels)
table.insert(convLayers, bn)
table.insert(trainables, bn)
end
local blockActivation: Utils.ActivationName?
if block.activation ~= nil then
blockActivation = block.activation
elseif config.activation ~= nil then
blockActivation = config.activation
else
blockActivation = nil
end
table.insert(convLayers, Utils.makeActivationModule(blockActivation))
if block.pool then
local poolCfg = block.pool
local size = poolCfg.size or 2
local stride = poolCfg.stride or size
local poolModule = if poolCfg.kind == "avg"
then AvgPool2d(size, size, stride)
else MaxPool2d(size, size, stride)
table.insert(convLayers, poolModule)
table.insert(trainables, poolModule)
end
local dropProb = block.dropout or config.dropout or 0
if dropProb > 0 then
local drop = Dropout(math.clamp(dropProb, 0, 0.95))
table.insert(convLayers, drop)
table.insert(trainables, drop)
end
inChannels = block.outChannels
end
local featureExtractor = Sequential(convLayers)
local flatten = Flatten()
table.insert(trainables, flatten)
local headLayers = {}
local headDims = config.headDims or { 256 }
local headDrop = math.clamp(config.headDropout or config.dropout or 0, 0, 0.95)
local lastDim = flattenDim
for _, hidden in ipairs(headDims) do
assert(hidden > 0, "ConvNet: head hidden dims must be positive")
local lin = Linear(lastDim, hidden, config.weightInit)
table.insert(headLayers, lin)
table.insert(trainables, lin)
table.insert(headLayers, Utils.makeActivationModule(config.activation))
if headDrop > 0 then
local drop = Dropout(headDrop)
table.insert(headLayers, drop)
table.insert(trainables, drop)
end
lastDim = hidden
end
local classifier = Linear(lastDim, config.numClasses, config.weightInit)
table.insert(headLayers, classifier)
table.insert(trainables, classifier)
if config.finalActivation then
table.insert(headLayers, Utils.makeActivationModule(config.finalActivation))
end
local head = Sequential(headLayers)
return {
forward = function(_, x: Types.Tensor): Types.Tensor
local h = featureExtractor:forward(x)
h = flatten:forward(h)
return head:forward(h)
end,
parameters = function(_): { Types.Tensor }
local params = {}
Utils.collectParams(params, featureExtractor)
Utils.collectParams(params, head)
return params
end,
train = function(_, mode: boolean?)
Utils.trainAll(trainables, mode)
end,
}
end
| 1,420 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/models/MLP.luau | --!native
--!optimize 2
local Types = require("../Types")
local Utils = require("./Utils")
local Util = require("../Util")
local Linear = require("../nn/Linear")
local LayerNorm = require("../nn/LayerNorm")
local Dropout = require("../nn/Dropout")
local Sequential = require("../nn/Sequential")
local assert = Util.Assert
export type MLPConfig = {
inputDim: number,
outputDim: number,
hiddenDims: { number }?,
activation: Utils.ActivationName?,
finalActivation: Utils.ActivationName?,
dropout: number?,
layerNorm: boolean?,
weightInit: ((number, number) -> number)?,
}
return function(config: MLPConfig): Types.Module<Types.Tensor, Types.Tensor>
assert(config.inputDim, "MLP: inputDim is required")
assert(config.outputDim, "MLP: outputDim is required")
local hidden = if config.hiddenDims and #config.hiddenDims > 0
then table.clone(config.hiddenDims)
else {
math.max(config.inputDim, config.outputDim),
}
local dropProb = math.clamp(config.dropout or 0, 0, 0.95)
local layers = {}
local trainables: { any } = {}
local inDim = config.inputDim
for _, hiddenDim in ipairs(hidden) do
assert(hiddenDim > 0, "MLP: hidden dimensions must be positive")
local linear = Linear(inDim, hiddenDim, config.weightInit)
table.insert(layers, linear)
table.insert(trainables, linear)
if config.layerNorm then
local norm = LayerNorm(hiddenDim)
table.insert(layers, norm)
table.insert(trainables, norm)
end
table.insert(layers, Utils.makeActivationModule(config.activation))
if dropProb > 0 then
local drop = Dropout(dropProb)
table.insert(layers, drop)
table.insert(trainables, drop)
end
inDim = hiddenDim
end
local head = Linear(inDim, config.outputDim, config.weightInit)
table.insert(layers, head)
table.insert(trainables, head)
if config.finalActivation then
table.insert(layers, Utils.makeActivationModule(config.finalActivation))
end
local seq = Sequential(layers)
return {
forward = function(_, x: Types.Tensor): Types.Tensor
return seq:forward(x)
end,
parameters = function(_): { Types.Tensor }
return seq:parameters()
end,
train = function(_, mode: boolean?)
Utils.trainAll(trainables, mode)
end,
}
end
| 544 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/models/ResMLP.luau | --!native
--!optimize 2
local Types = require("../Types")
local Utils = require("./Utils")
local Util = require("../Util")
local Linear = require("../nn/Linear")
local LayerNorm = require("../nn/LayerNorm")
local Dropout = require("../nn/Dropout")
local Sequential = require("../nn/Sequential")
local assert = Util.Assert
export type ResMLPConfig = {
inputDim: number,
outputDim: number,
embedDim: number?,
hiddenDim: number?,
numBlocks: number?,
activation: Utils.ActivationName?,
dropout: number?,
layerNorm: boolean?,
finalLayerNorm: boolean?,
weightInit: ((number, number) -> number)?,
}
type Block = {
norm: Types.Module<Types.Tensor, Types.Tensor>?,
ff: Types.Module<Types.Tensor, Types.Tensor>,
trainables: { any },
}
local function buildBlock(
embedDim: number,
hiddenDim: number,
activation: Utils.ActivationName?,
dropProb: number,
useLayerNorm: boolean?,
init: ((number, number) -> number)?
): Block
local norm = if useLayerNorm then LayerNorm(embedDim) else nil
local layers = {}
local trainables: { any } = {}
local function insertModule(m)
table.insert(layers, m)
table.insert(trainables, m)
end
insertModule(Linear(embedDim, hiddenDim, init))
insertModule(Utils.makeActivationModule(activation))
if dropProb > 0 then
insertModule(Dropout(dropProb))
end
insertModule(Linear(hiddenDim, embedDim, init))
if dropProb > 0 then
insertModule(Dropout(dropProb))
end
local ff = Sequential(layers)
if norm then
table.insert(trainables, norm)
end
return {
norm = norm,
ff = ff,
trainables = trainables,
}
end
local function buildModel(config: ResMLPConfig)
assert(config.inputDim and config.outputDim, "ResMLP: inputDim and outputDim required")
local embedDim = config.embedDim or config.inputDim
local hiddenDim = config.hiddenDim or (embedDim * 4)
local blocks = math.max(1, config.numBlocks or 4)
local dropout = math.clamp(config.dropout or 0, 0, 0.95)
local inputProj = if config.inputDim ~= embedDim then Linear(config.inputDim, embedDim, config.weightInit) else nil
local outputHead = Linear(embedDim, config.outputDim, config.weightInit)
local finalNorm = if config.finalLayerNorm then LayerNorm(embedDim) else nil
local stack = table.create(blocks)
for i = 1, blocks do
stack[i] = buildBlock(embedDim, hiddenDim, config.activation, dropout, config.layerNorm, config.weightInit)
end
local trainables: { any } = {}
if inputProj then
table.insert(trainables, inputProj)
end
for _, block in ipairs(stack) do
for _, m in ipairs(block.trainables) do
table.insert(trainables, m)
end
end
if finalNorm then
table.insert(trainables, finalNorm)
end
table.insert(trainables, outputHead)
local function forward(_, x: Types.Tensor): Types.Tensor
local h = x
if inputProj then
h = inputProj:forward(h)
end
for _, block in ipairs(stack) do
local y = h
if block.norm then
y = block.norm:forward(y)
end
y = block.ff:forward(y)
h = Utils.addTensors(h, y)
end
if finalNorm then
h = finalNorm:forward(h)
end
return outputHead:forward(h)
end
local function parameters(_): { Types.Tensor }
local params = {}
if inputProj then
Utils.collectParams(params, inputProj)
end
for _, block in ipairs(stack) do
if block.norm then
Utils.collectParams(params, block.norm)
end
Utils.collectParams(params, block.ff)
end
if finalNorm then
Utils.collectParams(params, finalNorm)
end
Utils.collectParams(params, outputHead)
return params
end
local function train(_, mode: boolean?)
Utils.trainAll(trainables, mode)
end
local module = {
forward = forward,
parameters = parameters,
train = train,
}
return module
end
return setmetatable({
new = function(config: ResMLPConfig)
return buildModel(config)
end,
}, {
__call = function(_, config: ResMLPConfig)
return buildModel(config)
end,
})
| 1,011 |
imezx/Gradien | imezx-Gradien-eaf9c89/src/models/SequenceClassifier.luau | --!native
--!optimize 2
local Types = require("../Types")
local Utils = require("./Utils")
local Tensor = require("../Tensor")
local GRU = require("../nn/GRU")
local LSTM = require("../nn/LSTM")
local RNN = require("../nn/RNN")
local Dropout = require("../nn/Dropout")
local LayerNorm = require("../nn/LayerNorm")
local Linear = require("../nn/Linear")
export type SequenceClassifierConfig = {
inputDim: number,
hiddenDim: number,
numLayers: number?,
numClasses: number,
cell: "gru" | "lstm" | "rnn"?,
dropout: number?,
layerNorm: boolean?,
finalActivation: Utils.ActivationName?,
}
type CellType = "gru" | "lstm" | "rnn"
type LSTMState = { h: Types.Tensor, c: Types.Tensor }
local function makeCell(cellType: CellType, inputDim: number, hiddenDim: number)
if cellType == "lstm" then
return LSTM(inputDim, hiddenDim)
elseif cellType == "rnn" then
return RNN(inputDim, hiddenDim)
end
return GRU(inputDim, hiddenDim)
end
local function sliceTimeStep(x: Types.Tensor, t: number, inputDim: number, batch: number): Types.Tensor
local step = Tensor.slice(x, 2, t, t)
return Tensor.reshape(step, { inputDim, batch })
end
local function initStates(self, batch: number, dtype: Types.DType, requiresGrad: boolean)
local states = table.create(#self._cells)
for i = 1, #self._cells do
if self._cellType == "lstm" then
states[i] = {
h = Tensor.zeros({ self._hiddenDim, batch }, dtype, requiresGrad),
c = Tensor.zeros({ self._hiddenDim, batch }, dtype, requiresGrad),
}
else
states[i] = Tensor.zeros({ self._hiddenDim, batch }, dtype, requiresGrad)
end
end
return states
end
local function forward(self, x: Types.Tensor): Types.Tensor
assert(#x._shape == 3, "SequenceClassifier: expected input shape {features, time, batch}")
local inputDim, timeSteps, batch = x._shape[1], x._shape[2], x._shape[3]
assert(inputDim == self._inputDim, "SequenceClassifier: inputDim mismatch")
local states = initStates(self, batch, x._dtype, x._requiresGrad)
local last
for t = 1, timeSteps do
local step = sliceTimeStep(x, t, inputDim, batch)
local layerInput: Types.Tensor = step
for layerIdx, cell in ipairs(self._cells) do
if self._cellType == "lstm" then
local state = states[layerIdx] :: LSTMState
local nextH, nextC = cell:forward(layerInput, state.h, state.c)
states[layerIdx] = { h = nextH, c = nextC }
layerInput = nextH
else
local prev = states[layerIdx] :: Types.Tensor
local nextH = cell:forward(layerInput, prev)
states[layerIdx] = nextH
layerInput = nextH
end
local drop = self._dropoutBetween[layerIdx]
if drop and layerIdx < #self._cells then
layerInput = drop:forward(layerInput)
end
end
last = layerInput
end
assert(last, "SequenceClassifier: sequence length must be >= 1")
local out = last
if self._norm then
out = self._norm:forward(out)
end
if self._finalDropout then
out = self._finalDropout:forward(out)
end
out = self._head:forward(out)
if self._finalAct then
out = self._finalAct:forward(out)
end
return out
end
local function parameters(self): { Types.Tensor }
local params = {}
for _, cell in ipairs(self._cells) do
Utils.collectParams(params, cell)
end
if self._norm then
Utils.collectParams(params, self._norm)
end
Utils.collectParams(params, self._head)
return params
end
local function train(self, mode: boolean?)
Utils.trainAll(self._trainables, mode)
end
local function SequenceClassifier(cfg: SequenceClassifierConfig): Types.Module<Types.Tensor, Types.Tensor>
assert(cfg.inputDim and cfg.hiddenDim and cfg.numClasses, "SequenceClassifier: missing config fields")
local numLayers = math.max(1, cfg.numLayers or 1)
local cellType = (cfg.cell or "gru") :: CellType
local layers = table.create(numLayers)
local inDim = cfg.inputDim
for i = 1, numLayers do
layers[i] = makeCell(cellType, inDim, cfg.hiddenDim)
inDim = cfg.hiddenDim
end
local dropoutBetween = {}
local dropProb = math.clamp(cfg.dropout or 0, 0, 0.95)
if dropProb > 0 and numLayers > 1 then
for i = 1, numLayers - 1 do
dropoutBetween[i] = Dropout(dropProb)
end
end
local finalDropout = if dropProb > 0 then Dropout(dropProb) else nil
local norm = if cfg.layerNorm then LayerNorm(cfg.hiddenDim) else nil
local head = Linear(cfg.hiddenDim, cfg.numClasses)
local finalAct = if cfg.finalActivation then Utils.makeActivationModule(cfg.finalActivation) else nil
local trainables: { any } = {}
for _, cell in ipairs(layers) do
table.insert(trainables, cell)
end
for _, drop in ipairs(dropoutBetween) do
table.insert(trainables, drop)
end
if finalDropout then
table.insert(trainables, finalDropout)
end
if norm then
table.insert(trainables, norm)
end
table.insert(trainables, head)
if finalAct then
table.insert(trainables, finalAct)
end
return {
_inputDim = cfg.inputDim,
_hiddenDim = cfg.hiddenDim,
_cells = layers,
_cellType = cellType,
_dropoutBetween = dropoutBetween,
_finalDropout = finalDropout,
_norm = norm,
_head = head,
_finalAct = finalAct,
_trainables = trainables,
forward = forward,
parameters = parameters,
train = train,
}
end
return {
new = SequenceClassifier,
}
| 1,430 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.