Initial commit

This commit is contained in:
Student committed 2026-10-15 09:59:40 +07:00
1 parent e56ce768d2
commit 57463dc219
1 file changed
+182
+182
View File
@@ -0,0 +1,182 @@
# Xenith PowerShell Activation Script
# Устанавливаем переменную окружения для промпта
$env:VIRTUAL_ENV_PROMPT = "Xenith"
# Функция для получения аргументов командной строки
function Get-Subcommand {
param([string[]]$args)
if ($args.Count -gt 0) { return $args[0] }
return $null
}
# Определяем основные команды и их описания
$main_commands = @{
"new" = "создать новую модель из корпуса"
"train" = "обучить существующую модель"
"gen" = "сгенерировать текст"
"info" = "показать конфигурацию модели"
"gradcheck" = "проверить градиенты численно"
"bench" = "замерить скорость форварда и шага обучения"
"update" = "Автоматическое обновление с гита"
}
# Регистрируем аргументы для Register-ArgumentCompleter
$subcommands = @("new", "train", "gen", "info", "gradcheck", "bench", "update")
# Создаем функцию-обертку для Xenith
function global:Xenith {
& "./bin/Xenith.exe" @args
}
# Настраиваем автодополнение для PowerShell
Register-ArgumentCompleter -CommandName Xenith -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
$commandElements = $commandAst.CommandElements
$subcommand = $null
# Ищем подкоманду
for ($i = 1; $i -lt $commandElements.Count; $i++) {
$element = $commandElements[$i].Value
if ($subcommands -contains $element) {
$subcommand = $element
break
}
}
# Если подкоманда не найдена, предлагаем основные команды
if (-not $subcommand) {
foreach ($cmd in $subcommands) {
[System.Management.Automation.CompletionResult]::new(
$cmd,
$cmd,
'ParameterValue',
$main_commands[$cmd]
)
}
return
}
# Автодополнение в зависимости от подкоманды
switch ($subcommand) {
"new" {
$params = @(
@{Name="corpus"; Description="текст для построения словаря (обязательно)"; Type="File"},
@{Name="out"; Description="файл модели (по умолчанию model.xnh)"; Type="File"},
@{Name="vocab"; Description="размер словаря (по умолчанию 512)"},
@{Name="embd"; Description="размер эмбеддинга (по умолчанию 128)"},
@{Name="layers"; Description="число слоёв (по умолчанию 4)"},
@{Name="heads"; Description="число голов (по умолчанию 4)"},
@{Name="ctx"; Description="максимальный контекст (по умолчанию 128)"},
@{Name="ffn"; Description="размер FFN (по умолчанию 4*embd)"},
@{Name="rope"; Description="база RoPE (по умолчанию 10000)"},
@{Name="seed"; Description="зерно инициализации (по умолчанию 1337)"},
@{Name="untied"; Description="отдельная матрица выхода вместо привязанной к wte"; Type="Switch"},
@{Name="view-vocab"; Description="выводит словарь нейросети"; Type="Switch"}
)
foreach ($param in $params) {
$completionText = "--" + $param.Name
$listItemText = $completionText
$resultType = 'ParameterName'
if ($param.Type -eq "Switch") { $resultType = 'ParameterName' }
[System.Management.Automation.CompletionResult]::new(
$completionText,
$listItemText,
$resultType,
$param.Description
)
}
}
"train" {
$params = @(
@{Name="corpus"; Description="обучающий текст (обязательно)"; Type="File"},
@{Name="out"; Description="куда сохранить (по умолчанию перезапись входного файла)"; Type="File"},
@{Name="steps"; Description="шагов (по умолчанию 1000)"},
@{Name="batch"; Description="батч (по умолчанию 8)"},
@{Name="block"; Description="длина окна (по умолчанию 64)"},
@{Name="lr"; Description="скорость (по умолчанию 3e-4)"},
@{Name="wd"; Description="weight decay (по умолчанию 0.01)"},
@{Name="clip"; Description="клип нормы градиента (по умолчанию 1.0)"},
@{Name="warmup"; Description="прогрев (по умолчанию 100)"},
@{Name="seed"; Description="зерно (по умолчанию 1337)"},
@{Name="ckpt-every"; Description="промежуточное сохранение каждые N шагов"},
@{Name="val-every"; Description="валидация каждые N шагов"},
@{Name="val-tokens"; Description="размер валидации (по умолчанию 20000)"},
@{Name="threads"; Description="потоков (0 = все ядра)"},
@{Name="resume"; Description="продолжить с сохранённого step (Adam-state из файла)"; Type="Switch"}
)
foreach ($param in $params) {
$completionText = "--" + $param.Name
$listItemText = $completionText
$resultType = 'ParameterName'
[System.Management.Automation.CompletionResult]::new(
$completionText,
$listItemText,
$resultType,
$param.Description
)
}
}
"gen" {
$params = @(
@{Name="prompt"; Description="стартовый текст"},
@{Name="n"; Description="сколько токенов (по умолчанию 200)"},
@{Name="temp"; Description="температура, 0 = жадный выбор (по умолчанию 0.8)"},
@{Name="top-k"; Description="top-k (0 = выкл)"},
@{Name="top-p"; Description="top-p (1.0 = выкл)"},
@{Name="seed"; Description="зерно"},
@{Name="no-stream"; Description="не печатать в процессе"; Type="Switch"},
@{Name="batch"; Description="несколько промптов через ;"},
@{Name="show-tokens"; Description="показать id токенов"; Type="Switch"}
)
foreach ($param in $params) {
$completionText = "--" + $param.Name
$listItemText = $completionText
$resultType = 'ParameterName'
[System.Management.Automation.CompletionResult]::new(
$completionText,
$listItemText,
$resultType,
$param.Description
)
}
}
}
}
# Сохраняем старый промпт и устанавливаем новый
if (-not (Test-Path variable:_OLD_VIRTUAL_PS1)) {
$global:_old_fish_prompt = $function:prompt
$global:_OLD_VIRTUAL_PS1 = $true
function global:prompt {
Write-Host "($env:VIRTUAL_ENV_PROMPT) " -NoNewline -ForegroundColor Cyan
& $global:_old_fish_prompt
}
}
Write-Host "Xenith activate" -ForegroundColor Green
# Функция деактивации
function global:deactivate {
Remove-Item function:Xenith -ErrorAction SilentlyContinue
if (Test-Path variable:_old_fish_prompt) {
$function:prompt = $global:_old_fish_prompt
Remove-Item variable:_old_fish_prompt -ErrorAction SilentlyContinue
}
Remove-Item env:VIRTUAL_ENV_PROMPT -ErrorAction SilentlyContinue
Remove-Item variable:_OLD_VIRTUAL_PS1 -ErrorAction SilentlyContinue
# Удаляем зарегистрированное автодополнение
Unregister-ArgumentCompleter -CommandName Xenith -ErrorAction SilentlyContinue
Remove-Item function:deactivate -ErrorAction SilentlyContinue
Write-Host "Xenith deactivated" -ForegroundColor Yellow
}