okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
aff3a132f
main
1"""One precedence for the engine options of a launch (round 0213, #5178 #5132 #4985). 2 3An engine option can come from four places. For each option the first one that has it wins, and a launch builds its 4run config from them once (``strata_cli/launch/runner.py derive_config``): 5 61. **explicit launch values**: what this command line (``--set``, the typed flags, the Advanced table) says. They are 7written to the config's ``"user_args"`` as well as to ``"args"``, because the drafter policy (``drafting.apply``) and 8the server rebuild ``"args"`` at every start and keep only ``"user_args"``. ``"launch_set"`` names them, so a flag 9given once is not remembered as the person's standing choice: leave it out next time and it is gone. 102. **persisted overrides**: the person's own options, ``"user_args"`` of the installed config plus the hand edits found in 11the previous launch config (``user_args.capture`` against ``"args_derived"``, the copy a launch stamps when it writes). 123. **calibrated values**: ``engine calibrate --apply-result`` records them in the run config's ``"calibrated"`` entry 13(settings, model and context they were measured for); a launch puts them over the generated defaults again, never 14over 1 or 2, and drops them when the model or the context is another. 154. **Auto**: what setup and the policies (drafting, cards, memory fit) generate. 16 17``"args"`` of the written config is the result, so the file, the start and ``strata status`` show the same value for 18an option. ``"user_args"`` stays authoritative at every start (``serve/server.py engine_args``). 19""" 20 21from __future__import annotations 22 23from typing import Any ,Mapping 24 25from strata_control import tune_knobs ,user_args 26 27CALIBRATED_KEY = "calibrated" 28EXPLICIT_KEY = "launch_set" 29DERIVED_KEY = "args_derived" # "args" as the launch wrote them: a difference found next time is a hand edit 30 31 32def _max_context (args :list [str ])-> str | None : 33for i ,a in enumerate (args ): 34if a == "--max-context" and i + 1 < len (args ): 35return str (args [i + 1 ]) 36return None 37 38 39def calibration_record (settings :Mapping [str ,Any ],cfg :Mapping [str ,Any ])-> dict : 40"""What ``calibrate --apply-result`` writes into the run config next to the changed ``"args"``.""" 41args = [str (a )for a in cfg .get ("args" )or []] 42return {"settings" : {str (k ):str (v )for k ,v in settings .items ()},"model_name" :cfg .get ("model_name" ), 43"max_context" :_max_context (args ),"images" :"--vision" in args } 44 45 46def _calibration_fits (rec :Any ,cfg :Mapping [str ,Any ])-> bool : 47"""A calibration is valid for the model, context and image setting it was measured with (setup's hardware_key says the same).""" 48if not isinstance (rec ,dict )or not isinstance (rec .get ("settings" ),dict ): 49return False 50args = [str (a )for a in cfg .get ("args" )or []] 51return (rec .get ("model_name" )== cfg .get ("model_name" )and rec .get ("max_context" )== _max_context (args ) 52and bool (rec .get ("images" ))== ("--vision" in args )) 53 54 55def _hand_edits (prev :Mapping [str ,Any ]| None )-> list [str ]: 56"""The person's options in the previous launch config: its ``user_args`` and the changes made to its ``args`` since the launch wrote 57them; the flags that launch was given on its command line are not the person's standing choice. A config from before ``args_derived`` 58has nothing to compare with, so only its explicit ``user_args`` count (none: they come from the installed config anyway).""" 59if not isinstance (prev ,Mapping )or not isinstance (prev .get (DERIVED_KEY ),list ): 60return [] 61mine = user_args .capture ({"args" :prev .get ("args" ),user_args .USER_KEY :prev .get (user_args .USER_KEY ), 62user_args .WRITTEN_KEY :prev .get (user_args .WRITTEN_KEY )}) 63given = {str (f )for f in prev .get (EXPLICIT_KEY )or []} 64return user_args .flat ([g for g in user_args .groups (mine )if user_args .flag_of (g )not in given ]) 65 66 67def _put (mine :list [str ],flag :str ,value :Any ,bool_flags :frozenset [str ])-> list [str ]: 68if value is None or value is False : 69return user_args .set_flag (mine ,flag ,None ) 70rest = [g for g in user_args .groups (mine )if user_args .flag_of (g )!= flag ] 71rest .append ([flag ]if value is True or flag in bool_flags else [flag ,* user_args .value_tokens (flag ,value )]) 72return user_args .flat (rest ) 73 74 75def layer (cfg :dict ,explicit :Mapping [str ,Any ]| None = None ,prev :Mapping [str ,Any ]| None = None , 76bool_flags :frozenset [str ]= tune_knobs .BOOL_FLAGS )-> dict : 77"""Put the four sources over each other in ``cfg`` (in place; ``cfg["args"]`` is the generated layer on entry). 78``explicit``: the launch's own options as ``tune_knobs.apply_to_argv`` changes (value, True for present, None for off). 79``prev``: the config this launch wrote last time (or None). ``bool_flags``: the engine's valueless switches. Returns {"calibrated": bool, "persisted": [...], "explicit": [...]}.""" 80explicit = dict (explicit or {}) 81args = [str (a )for a in cfg .get ("args" )or []] 82# 3. calibrated values over the generated ones 83rec = None 84for source in (prev ,cfg ):# the previous launch config first: apply-result wrote it there 85if _calibration_fits ((source or {}).get (CALIBRATED_KEY ),cfg ): 86rec = source [CALIBRATED_KEY ] 87break 88cfg .pop (CALIBRATED_KEY ,None ) 89if rec : 90args = tune_knobs .apply_to_argv (args , {k :v for k ,v in rec ["settings" ].items ()}) 91cfg [CALIBRATED_KEY ]= rec 92# 2. the person's standing options: the installed config's, then the previous launch's hand edits (the newer wins) 93mine = user_args .merge (user_args .flat (user_args .groups (cfg .get (user_args .USER_KEY ))),_hand_edits (prev )) 94# 1. this command line 95for flag ,value in explicit .items (): 96mine = _put (mine ,flag ,value ,bool_flags ) 97args = tune_knobs .apply_to_argv (args ,explicit ,bool_flags )if explicit else args 98cfg ["args" ]= user_args .merge (args ,mine ) 99if mine : 100cfg [user_args .USER_KEY ]= mine 101else : 102cfg .pop (user_args .USER_KEY ,None ) 103if explicit : 104cfg [EXPLICIT_KEY ]= sorted (explicit ) 105else : 106cfg .pop (EXPLICIT_KEY ,None ) 107return {"calibrated" :bool (rec ),"persisted" : [user_args .flag_of (g )for g in user_args .groups (mine )if user_args .flag_of (g )and user_args .flag_of (g )not in explicit ], 108"explicit" :sorted (explicit )} 109 110 111def stamp (cfg :dict )-> None : 112"""Called by the launch after its last change to ``cfg["args"]``: records them as written, so only a later hand edit differs.""" 113written = [str (a )for a in cfg .get ("args" )or []] 114cfg [DERIVED_KEY ]= list (written )# (the marker: this config was written by a launch, so "args_written" below is the launch's) 115cfg [user_args .WRITTEN_KEY ]= list (written )# replaces the installed config's copy, which describes other arguments 116 117 118def record_calibration (candidate :dict ,before :Mapping [str ,Any ],settings :Mapping [str ,Any ])-> None : 119"""`engine calibrate --apply-result` on a run config (in place on the candidate that already carries the calibrated ``"args"``): records 120the calibrated values with the model and context they were measured for, so a launch that builds its config again keeps them (#5132); 121the hand edits so far are recorded as the person's first, except the options the calibration sets (a calibration the person asks for is 122their newer choice, as for ``tune_apply``), and ``args_written`` is brought up to date so the calibrated values are never taken for a hand edit.""" 123candidate [CALIBRATED_KEY ]= calibration_record (settings ,candidate ) 124if before .get (user_args .WRITTEN_KEY )is not None or before .get (user_args .USER_KEY ): 125mine = user_args .capture (dict (before )) 126mine = user_args .flat ([g for g in user_args .groups (mine )if user_args .flag_of (g )not in settings ]) 127user_args .stamp (candidate ,mine ) 128if user_args .WRITTEN_KEY not in before : 129candidate .pop (user_args .WRITTEN_KEY ,None ) 130if isinstance (candidate .get (DERIVED_KEY ),list ):# a launch's own config: its copies of "args" follow, or the calibrated values would read as hand edits 131stamp (candidate )