Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1353,6 +1353,7 @@ SET(LIBDASCRIPT_COMPILER_SRC
src/ast/ast_escape_analysis.cpp
src/ast/ast_cfg.cpp
src/ast/ast_dse.cpp
src/ast/ast_sink.cpp
src/ast/ast_cse.cpp
src/ast/ast_devirtualize.cpp
src/ast/ast_inline.cpp
Expand Down
3 changes: 2 additions & 1 deletion ci/test_ci_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,8 @@ def test_the_fast_math_cell_runs_the_per_pr_lane_narrowed_and_no_nightly_step(se
self.assertIn(" if(DAS_FAST_MATH)\n"
" set(_aot_subset_test_dirs ${_DAS_FAST_MATH_AOT_DIRS})\n", tests_cmake)
self.assertIn("set(_DAS_FAST_MATH_AOT_DIRS ${PROJECT_SOURCE_DIR}/tests/language"
" ${PROJECT_SOURCE_DIR}/tests/math)\n", tests_cmake)
" ${PROJECT_SOURCE_DIR}/tests/optimization\n"
" ${PROJECT_SOURCE_DIR}/tests/math)\n", tests_cmake)

with open(os.path.join(os.path.dirname(HERE), "tests", "aot", "CMakeLists.txt"), encoding="utf-8") as f:
aot_cmake = f.read()
Expand Down
5 changes: 5 additions & 0 deletions doc/source/reference/language/options.rst
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,11 @@ Optimization
- bool
- false
- Disables the fastcall optimization.
* - ``disable_sink``
- bool
- false
- Disables the sink pass, which moves a local with a pure initializer into the one ``if`` arm
that reads it, so an inlined check builds its message only when the check fails.
* - ``max_fast_call_depth``
- int
- 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ Keeps the ``unsafe { }`` scope in the AST after inference, which ``foldUnsafe``
Allows float optimizations with major bit differences (x*0, x-x, reciprocal division, NaN-compare flips, reassociation); also stamps JIT fast-math flags. Doubles stay bit-exact unless enabled.
Disables the dead-store-elimination optimizer pass. Host-side counterpart of ``options disable_dse`` (the option overrides the policy).
Disables the common-subexpression-elimination optimizer pass. Host-side counterpart of ``options disable_cse`` (the option overrides the policy).
Disables the sink pass, which moves a local with a pure initializer into the one ``if`` arm that reads it. Host-side counterpart of ``options disable_sink`` (the option overrides the policy).
Disables ``[inline]`` splicing - annotated calls stay regular calls. The declaration-level contract checks (body shape, recursion through the inline graph, taking the address) still run; call-site splice checks do not apply, since nothing splices. Host-side counterpart of ``options disable_inline`` (the option overrides the policy).
Disables automatic inlining: block-literal call sites stay regular calls and invoke-of-literal sites stay invokes. ``[inline]`` splicing is unaffected. Host-side counterpart of ``options disable_auto_inline`` (the option overrides the policy).
Heuristic best-effort inlining of plain calls and operator sites (default ON, optimized builds only): small same-module non-generic callees splice, silently declining anything unspliceable. Cross-module inlining stays the explicit ``[inline]`` contract. Host-side counterpart of ``options auto_inline_functions`` (the option overrides the policy). ``disable_auto_inline`` overrides.
Expand Down
2 changes: 1 addition & 1 deletion include/daScript/ast/ast_serializer.h
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ namespace das {
AstSerializer & serializeModule ( Module & module, bool already_exists );

static constexpr uint32_t getVersion () {
return 288; // 288: a function records the [no_capture_string] contract
return 289; // 289: the policies record disable_sink
}

void serializeProgram ( ProgramPtr program, ModuleGroup & libGroup ) noexcept;
Expand Down
3 changes: 2 additions & 1 deletion include/daScript/daScriptC.h
Original file line number Diff line number Diff line change
Expand Up @@ -821,7 +821,8 @@ typedef enum das_bool_policy {
DAS_POLICY_AUTO_INLINE_FUNCTIONS, // Heuristic best-effort inlining of plain calls and operator sites of small same-module [inline]-shaped functions (default ON; silent declines; optimized builds only; cross-module inlining stays the explicit [inline] contract)
DAS_POLICY_DISABLE_TEMP_STRING_RECLAIM, // Disable the temp-string reclaim pass (fresh-string call results riding the 1-slot dispose queue)
DAS_POLICY_JIT_ENABLED, // Enable JIT compilation of [jit] functions. The flag alone is not enough: the host must also register the "just_in_time" extra module (see das_fileaccess_add_extra_module) so the LLVM JIT backend is compiled in
DAS_POLICY_JIT_DLL_MODE // With JIT: cache generated code as per-script DLLs under .cache/daslang/ in the working directory (default: on). Off = codegen in-memory every run, no cache writes. The cache path needs a DLL build of daslang; a static-linked host always codegens in-memory regardless of this flag
DAS_POLICY_JIT_DLL_MODE, // With JIT: cache generated code as per-script DLLs under .cache/daslang/ in the working directory (default: on). Off = codegen in-memory every run, no cache writes. The cache path needs a DLL build of daslang; a static-linked host always codegens in-memory regardless of this flag
DAS_POLICY_DISABLE_SINK // Disable the pass that sinks a pure local into the one `if` arm reading it
} das_bool_policy;

// Integer policy fields (stack size, heap limits).
Expand Down
1 change: 1 addition & 0 deletions include/daScript/simulate/code_of_policies.h
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ namespace das {
/*option*/ bool fast_math = false; // allow VALUE-SAFE float optimizations with bit differences (reassociation, FMA contraction, signed-zero laxity); inf/NaN semantics are preserved — no rcp division, no nan-compare flips (JIT stamps reassoc|nsz|contract only). doubles stay bit-exact unless this is on
/*option*/ bool disable_dse = false; // disable the dead-store-elimination pass
/*option*/ bool disable_cse = false; // disable the common-subexpression-elimination pass
/*option*/ bool disable_sink = false; // disable the pass that sinks a pure local into the one `if` arm reading it
/*option*/ bool disable_inline = false; // disable the [inline] function inliner (calls stay regular calls; declaration-level contract checks - shape, recursion, @@ - still lint)
/*option*/ bool disable_auto_inline = false; // disable automatic inlining of block-literal call sites and invoke-of-literal devirtualization ([inline] splicing is unaffected)
/*option*/ bool auto_inline_functions = true; // heuristic best-effort inlining of plain calls and operator sites of small same-module [inline]-shaped functions (default ON; silent declines; optimized builds only; disable_auto_inline overrides)
Expand Down
17 changes: 9 additions & 8 deletions modules/dasLLAMA/dasllama/dasllama_image.das
Original file line number Diff line number Diff line change
Expand Up @@ -1177,33 +1177,34 @@ def count_meta_fields(var t) : int {
//! name + full type name + byte size in order, recursing into struct fields and array-element
//! structs — any meta-closure shape change refuses by name; IMAGE_VERSION covers behavior.
def layout_fingerprint(var t) : uint64 {
var d = ""
layout_describe(t, d)
let d = build_string() $(var w) {
layout_describe(t, w)
}
return hash(d)
}

def private layout_describe(var t; var d : string&) {
def private layout_describe(var t; var d : StringBuilderWriter) {
apply(t) $(name : string; var field) {
d += "{name}:{typeinfo typename(field)}:{typeinfo sizeof(field)};"
d |> write("{name}:{typeinfo typename(field)}:{typeinfo sizeof(field)};")
static_if (typeinfo is_struct(field)) {
layout_describe(field, d)
d += "^" // close the nesting so sibling boundaries stay unambiguous
d |> write("^") // close the nesting so sibling boundaries stay unambiguous
} static_elif (typeinfo is_dim(field)) {
layout_describe(field[0], d) // one element's shape stands for the table
d += "^"
d |> write("^")
} static_elif (typeinfo is_array(field)) {
layout_describe_elem(field, d)
}
}
}

// an array field's ELEMENT struct also serializes element-wise — its shape is load-bearing
def private layout_describe_elem(var a : array<auto(TT)>; var d : string&) {
def private layout_describe_elem(var a : array<auto(TT)>; var d : StringBuilderWriter) {
static_if (typeinfo is_struct(type<TT>)) {
unsafe { //! the zeroed value: a nested carrier's initializer chain overflows the init script's stack, and only the type is read
var tmp : TT
layout_describe(tmp, d)
d += "^"
d |> write("^")
delete tmp
}
}
Expand Down
23 changes: 17 additions & 6 deletions modules/dasLLAMA/dasllama/dasllama_spm.das
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ module dasllama_spm shared public

require dasllama/dasllama_lint public
require daslib/fio
require daslib/array_boost // nolint:STYLE030 — temp_array is [template]; STYLE030 misses template-fn refs
require daslib/array_boost
require dasllama/dasllama_gguf
require dasllama/dasllama_bpe
require strings
Expand Down Expand Up @@ -332,15 +332,16 @@ def unigram_unk_score(tk : SpmTokenizer) : float {
return lo - UNIGRAM_UNK_PENALTY
}

def private spm_piece_of(d : array<uint8> const#; i, n : int) : string {
[temp_string_result]
def private spm_piece_of(d : array<uint8> | #; i, n : int) : string {
return "" if (n <= 0)
unsafe {
return string(temp_array(addr<uint8?>(d[i]), n, type<uint8>))
}
}

// the next codepoint boundary after byte position i
def private cpt_end(d : array<uint8> const#; i, n : int) : int {
def private cpt_end(d : array<uint8> | #; i, n : int) : int {
var j = i + 1
while (j < n && (int(d[j]) & 0xC0) == 0x80) {
j++
Expand All @@ -351,7 +352,7 @@ def private cpt_end(d : array<uint8> const#; i, n : int) : int {
// the Viterbi lattice over byte positions: best[j] the highest score reaching j, back_len /
// back_id the piece that got there; ties go to the earliest candidate (the reference's strict >);
// a byte piece or a reserved control piece never matches text, as in the reference's trie
def private unigram_lattice(tk : SpmTokenizer; d : array<uint8> const#; unk_id : int64; reserved : array<int64>;
def private unigram_lattice(tk : SpmTokenizer; d : array<uint8> | #; unk_id : int64; reserved : array<int64>;
var best : array<float>; var back_len : array<int>; var back_id : array<int64>) {
let n = length(d)
let unk_score = unigram_unk_score(tk)
Expand Down Expand Up @@ -402,8 +403,17 @@ def unigram_encode(tk : SpmTokenizer; text : string; unk_id : int64; byte_fallba
if (unk_id < 0l || unk_id >= long_length(tk.vocab)) {
panic("dasLLAMA spm: unigram encode with no unknown piece (id {unk_id} of {length(tk.vocab)})")
}
let input = tk.add_space_prefix ? " {text}" : text
peek_data(input) $(d : array<uint8> const#) {
var inscope d : array<uint8>
d |> reserve(length(text) + 1)
if (tk.add_space_prefix) {
d |> push(uint8(' '))
}
peek_data(text) $(t : array<uint8> const#) {
for (b in t) {
d |> push(b)
}
}
{
var inscope best : array<float>
var inscope back_len : array<int>
var inscope back_id : array<int64>
Expand All @@ -421,6 +431,7 @@ def unigram_encode(tk : SpmTokenizer; text : string; unk_id : int64; byte_fallba
rev_len |> push(back_len[p])
p -= back_len[p]
}
ids |> reserve(length(d))
var k = length(rev) - 1
while (k >= 0) {
if (rev[k] == unk_id && byte_fallback) {
Expand Down
2 changes: 1 addition & 1 deletion modules/dasLLAMA/dasllama/dasllama_whisper.das
Original file line number Diff line number Diff line change
Expand Up @@ -754,7 +754,7 @@ def private stream_whisper_model(path : string; enc_q8, dec_q8 : bool; img, tag
}
var wrote = false
fmap(f) $(var bytes : array<uint8>#) {
var st = WhisperStaging()
var inscope st = WhisperStaging()
var recs : table<string; WTensorRec>
var encJobs, decJobs : array<WFillJob>
whisper_index(bytes, int64(stat(path).size), st, recs, encJobs, decJobs)
Expand Down
6 changes: 5 additions & 1 deletion modules/dasLLAMA/tests/test_model_image.das
Original file line number Diff line number Diff line change
Expand Up @@ -4645,7 +4645,7 @@ def test_devw_bake_tables(t : T?) {
}
}

[test(description = "`layout_fingerprint` is deterministic per type and moves on field reorder, retype, add, nesting and array element shape, the Model closure fingerprints nonzero, and a flipped fingerprint byte at header offset 48 declines the image load")]
[test(description = "`layout_fingerprint` is deterministic per type and moves on field reorder, retype, add, nesting and array element shape, the Model closure fingerprints nonzero with its description written once, and a flipped fingerprint byte at header offset 48 declines the image load")]
def test_layout_fingerprint(t : T?) {
t |> run("the fingerprint moves on any field-shape change and holds on none") @(t : T?) {
if (!arm_on(t, "mechanics")) {
Expand All @@ -4670,6 +4670,10 @@ def test_layout_fingerprint(t : T?) {
let mfp = layout_fingerprint(m)
to_log(LOG_INFO, "image fingerprint: Model meta closure = {mfp}\n")
t |> success(mfp != 0ul, "the real Model closure fingerprints (no recursion trap)")
let s0 = string_heap_bytes_allocated()
t |> equal(layout_fingerprint(m), mfp, "deterministic on the real closure")
let s1 = string_heap_bytes_allocated()
t |> success(s1 <= s0 + 262144ul, "the description is written once, not copied per field ({s0} -> {s1} bytes)")
delete m
}
t |> run("a corrupted fingerprint byte refuses the image at parse") @(t : T?) {
Expand Down
19 changes: 19 additions & 0 deletions modules/dasLLAMA/tests/test_tokenizer.das
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,25 @@ def test_tokenizer_spm_byte_pieces_by_name(t : T?) {
}
}

[test(description = "A unigram encode leaves no string behind: the lattice frees each candidate piece it looks up, so twenty encodes of a sentence keep the string heap where one left it")]
def test_tokenizer_unigram_encode_no_garbage(t : T?) {
var pieces <- ["<unk>", "<s>", "</s>", " ", "a", "b", " a", "ab", " ab"]
var tk <- spm_vocab(pieces)
tk.max_token_length = 3
tk.add_space_prefix = true
let reserved : array<int64>
let text = "ab ab ba ab ab ba ab ab ba ab ab ba"
var warm <- unigram_encode(tk, text, 0l, false, reserved)
delete warm
let before = string_heap_bytes_allocated()
for (_ in range(20)) {
var ids <- unigram_encode(tk, text, 0l, false, reserved)
delete ids
}
t |> equal(before, string_heap_bytes_allocated(), "the string heap after twenty encodes")
delete tk
}

[test(description = "On the Mistral v0.3 vocab, newline and tab byte pieces resolve to 781 and 780 past the control tokens, and sample texts encode to the exact ids llama-tokenize gives and decode back")]
def test_tokenizer_mistral_v03_byte_pieces(t : T?) {
t |> run("Mistral v0.3: byte pieces past 768 control tokens, llama-tokenize's ids") @(t : T?) {
Expand Down
26 changes: 26 additions & 0 deletions src/ast/ARCHITECTURE_EFFECTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,29 @@ a null pointer is undefined behavior, not a raise); `ExprAsVariant`, `ExprAssert
(its target is unknown) always raise. Only a pass that deletes
an evaluation asks, and only through `droppable`, which wants `noSideEffects` and no `mayRaise` together. CSE does not: it reuses the first
evaluation, which still raises.

## Sinking a pure local into the branch that reads it {#sink-pure-let}

`optimizationSink` (`ast_sink.cpp`) moves a `let` of one variable into the `if` right after it, when
that `if` reads the variable in one arm only and nothing after the `if` reads it. The local is then
computed only on the path that uses it. The common case is an inlined check: the inliner binds the
message argument to a local ahead of the body's `if`, so a check that passes still builds its
message; once sunk, it builds it only when it fails.

Moving an evaluation later, and onto one path, is the same question as deleting it on the others, so
the pass asks `droppable` of the initializer: no side effect, and no raise, since a raise that
happens today on every path must not vanish on the paths that no longer evaluate it. The `if`
condition must be `droppable` too: the initializer now runs after it, and a condition that writes
what the initializer reads would change its value. A reference local, an `inscope` or collected
local (its cleanup sits in the block's final list) and a move out of storage (the move zeroes the
source at a different time) stay where they are. No arm can declare the moved local's name: infer
refuses a local that shadows another, and the optimizer's own locals carry unique names. `options
disable_sink` turns the pass off.

The pass is one visitor. A block's pre-visit finds its let-if pairs and registers each `if`'s arms,
which are blocks themselves; the walk counts every use of a candidate's variable, and the uses inside
each of its arms; and the block's post-visit moves a let whose uses all sit in one arm - none in the
condition, the other arm or after the `if`. A local lives in its own block, so by the post-visit
every use of it has been counted. It runs no side-effect walk of its own: it
reads the flags that walk left at the start of dead-store elimination, the pass right before it.
A node built since then is never `droppable`, so a stale flag can only keep a let in place.
4 changes: 4 additions & 0 deletions src/ast/ast_optimize.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include "daScript/ast/ast.h"
#include "daScript/ast/ast_expressions.h"
#include "daScript/ast/ast_visitor.h"
#include "ast_sink.h"

namespace das {

Expand Down Expand Up @@ -45,6 +46,9 @@ namespace das {
last = program->optimizationDeadStores(optimizationRound); if ( program->failed() ) break; noteChange(last);
if ( log ) logs << "DEAD STORES:" << (last ? "optimized" : "nothing") << "\n";
if ( logPass ) logs << *program;
last = optimizationSink(program, optimizationRound); if ( program->failed() ) break; noteChange(last);
if ( log ) logs << "SINK:" << (last ? "optimized" : "nothing") << "\n";
if ( logPass ) logs << *program;
// this is here again for a reason
last = program->optimizationUnused(logs, optimizationRound); if ( program->failed() ) break; noteChange(last);
if ( log ) logs << "REMOVE UNUSED:" << (last ? "optimized" : "nothing") << "\n";
Expand Down
Loading
Loading