Skip to content

Ability to selectively disable memoization #6508

Open

Description

@Danila-Bain

Short context

From what I understand, Typst’s memoization mechanism is an optimization technique that caches the result of every in-document function call during compilation to speed up recompilation.

However, in some applications — particularly data visualization — this approach can lead to excessive memory usage and even worsened performance (see details below). These cases often involve numerous small function calls, where memoization provides little benefit. In fact, only the top-level function (e.g. "render the entire plot") typically benefits from caching, while most changes (e.g. color, axis limits) trigger widespread recalculations anyway.

As detailed below, the memory consumption in such cases can become significant, to the point where users are forced to move their plots into separate documents (which is not always sufficient, for larger plots). This workaround is inconvenient and undermines the benefits of integrating data visualization directly within the main document.

For a concrete example, see this related discussion: lilaq-project/lilaq#79

Suggested Changes

To address this issue, I propose several potential directions:

  • Allow disabling memoization on specific functions:
    Introduce a way to mark a function as non-memoized:

    #let square(x) = x * x // memoized by default
    
    #let square1 = square.with(memoization: false) // or: incremental: false
    
    #let square2 = square.unmemoized()
  • Introduce a dedicated syntax for non-memoized functions:
    This may be equivalent to the previous suggestion, but with cleaner syntax:

    #let square1(x) := x * x
    #let square2 = (x) :=> x * x
  • Allow disabling memoization for function bodies selectively:
    For example, using a wrapper like blackbox to prevent memoization of inner expressions:

    #let square(x) = blackbox(x * x)
  • Add non-memoizing variants of iteration functions (map, fold, etc.):
    This may be similar to the previous suggestion, but more specialized. This option may offer a less intrusive but still helpful solution, especially when mapping small functions over large arrays, which is main source of the issue that I can think of so far:

    #let square(x) = x * x
    
    #let squares = range(10).map_uncached(square)
  • Disable memoization for functions whose execution time is below a threshold:
    This would require runtime profiling and substantial bookkeeping, which may significantly impact overall performance. Still, it’s an idea worth considering, especially if implemented in a way that’s opt-in or scoped.

  • Disable memoization for short numerical functions:
    That is, automatically skip memoization for functions that meet two criteria:

    1. Short — based on character count or token length.
    2. Numerical — consisting solely of numerical operations and not dependent on context.
      This heuristic could help reduce memory usage for common cases without needing explicit annotations.

I understand that disabling memoization may be non-trivial within Typst’s current architecture. However, I hope some form of this feature can be introduced without impacting performance for code that continues to use memoization as-is, which absolutely should be a default behavior.

Use case: colormesh plotting

Here we explore the example of generating a raster gray-scale image for function $f(x, y) = x^2 + y^2 \mod 1$. This is relatively cheap function that has values between 0 and 1, making conversion to a color as simple as multiplying by 255 and converting to an integer. I consider this example rather minimal, because it involves only a few computations to produce actual image. In practice, however, more processing is usually required, such as normalization and scaling, color mapping, data limits calculation, nan filtering, etc. This additional processing multiplies the memory consumption proportionally to the number of used operations, which makes us reach memory limit much earlier than in the following examples.

I should also note, that this example applies not only to colormesh plots, but also for regular plots, such as line plots, scatter plots, or histograms. Although they typically require less data points, even for them memory usage might become problematic quite quickly, especially for complex parametric plots or detailed histograms)

Generation of data from a function

#set page(width: auto, height: auto, margin: 2mm)

#let f(x, y) = calc.fract(x*x + y*y)

#let width = 200 
#let height = width

#let linspace(a, b, n) = range(n).map((i) => a + i*(b - a)/(n - 1))
#let x = linspace(-10, 10, width)
#let y = linspace(-10, 10, height)

#let z_values = x.map((x) => y.map(y => f(x, y)))
#let z_flat_values = z_values.flatten()
#let z_flat_colors = z_flat_values.map((z) => int(z*255))

#image(bytes(z_flat_colors), format: (encoding: "luma8", width: width, height: height))

Here a report on a memory usage of a single typst compile command for this implementation, provided by a /usr/bin/time utility:

size # of pixels Elapsed Time (s) Max Memory (MB) Max Memory (B / pixel)
10 x 10 100 0.53 27 2170
25 x 25 625 0.53 30 4869
50 x 50 2500 0.57 39 4895
100 x 100 10000 0.59 76 5092
250 x 250 62500 1.02 333 5131
300 x 300 90000 1.22 463 5079
500 x 500 250000 2.45 1245 5107
600 x 600 360000 3.32 1766 5065
700 x 700 490000 4.27 2416 5112
800 x 800 640000 5.29 3126 5076
900 x 900 810000 7.10 3903 5017
1000 x 1000 1000000 31.42 4643 4840

Note that here and in the following tables, Max Memory (MB) is absolute, but Max Memory (B / pexel) is relative to a base memory usage, corresponding to a memory usage for zero-sized image.

As we can see, the compilation of a 900x900 image takes 3.9GB of memory, while the output file is only 640KB, which is completely unreasonable amount, taking around 5KB per single pixel. As mentioned before, in actual application it is even worse.

Data loading from JSON

Now we compare data generation and loading data from json. Comparing to in-document data generation this is incovenient, but often json data may come from numerical experiments written in other languages, so this source of the data is also expected to be common in Typst.

Loading z_flat_colors

This is the case when we pre-calculated as much as we could, so only thing is left is to convert array of colors to bytes and call image:

size # of pixels Elapsed Time (s) Max Memory (MB) Max Memory (B / pixel)
10 x 10 100 0.56 29 14868
25 x 25 625 0.54 29 2896
50 x 50 2500 0.52 28 575
100 x 100 10000 0.54 29 181
250 x 250 62500 0.55 30 47
300 x 300 90000 0.55 30 33
500 x 500 250000 0.57 35 33
600 x 600 360000 0.57 39 35
700 x 700 490000 0.58 44 36
800 x 800 640000 0.59 50 37
900 x 900 810000 0.68 57 38

So, by loading data from json file, we get very reasonable compilation time and memory usage. So, image or bytes functions are not to blame, it is data processing, that causes memory explosion. I guess, that we cannot really improve memory consumption here.

Loading 2-dimensional array of colors:

size # of pixels Elapsed Time (s) Max Memory (MB) Max Memory (B / pixel)
10 x 10 100 0.51 28 13762
25 x 25 625 0.51 28 1454
50 x 50 2500 0.51 29 691
100 x 100 10000 0.52 29 182
250 x 250 62500 0.53 32 74
300 x 300 90000 0.52 33 69
500 x 500 250000 0.56 43 64
600 x 600 360000 0.58 52 72
700 x 700 490000 0.59 62 74
800 x 800 640000 0.72 72 74
900 x 900 810000 3.13 82 71
1000 x 1000 1000000 2.00 92 68

Comparing to the previous example, memory usage is doubled, I guess it is due creating a copy of the whole data when flattening.

Loading z_flat_values from json, computing colors with z_flat_values.map((z) => int(z*255))

size # of pixels Elapsed Time (s) Max Memory (MB) Max Memory (B / pixel)
10 x 10 100 0.53 28 14172
25 x 25 625 0.53 29 2870
50 x 50 2500 0.56 30 1010
100 x 100 10000 0.53 34 725
250 x 250 62500 0.63 63 606
300 x 300 90000 0.69 81 627
500 x 500 250000 0.92 180 642
600 x 600 360000 1.08 250 648
700 x 700 490000 1.30 331 649
800 x 800 640000 1.53 427 654
900 x 900 810000 1.94 527 647
1000 x 1000 1000000 5.36 601 601

Comparing to loading z_flat_colors from json, memory consuption is increased by a factor of 20, which is surprising, because we only added a map with function (z) => int(z*255), so I expected the increase in 4 times, one copy of loaded data, one copy for multiplying with 255, one copy for conversion to int, and one copy for the resulting array.

Also, if we swap single map((z) => int(z*255)) into two separate mappings map((z) => z*255) and map((z => int(z)) memory usage increases to around 1000 B / pixel, which I do not understand also.

Loading z_values from json

size # of pixels Elapsed Time (s) Max Memory (MB) Max Memory (B / pixel)
10 x 10 100 0.51 29 16465
25 x 25 625 0.52 28 1730
50 x 50 2500 0.52 30 1163
100 x 100 10000 0.54 34 749
250 x 250 62500 0.62 66 647
300 x 300 90000 0.66 87 692
500 x 500 250000 0.92 187 672
600 x 600 360000 1.12 265 692
700 x 700 490000 1.29 346 683
800 x 800 640000 1.63 450 692
900 x 900 810000 1.98 554 682
1000 x 1000 1000000 5.48 630 632

This one is similar to the previous one, but with added cost for extra flattening.

Summary

As we can see, loading data from json helps a lot, but 600MB for a 1000x1000 image is also not ideal, and will significantly limit the number of images that can be used in the document. Also, with more processing, memory consumption increases.

Overall, saving raw data to json does not help enough. Also, saving color values as json does not make much sense anyway.

Code for colormesh experiments

Typst file for memory consumption benchmarking

For the following file, compiling it with

/usr/bin/time -f "%e %M" typst compile image.typ --input width=200 --input method=map

returns a compilation time in seconds and max memory usage in KB. Option --input width determines the size of the image. Option --input method can be set to write_json_flat_colors, write_json_2d_colors, write_json_flat_values, or write_json_2d_values to print corresponding json file content. Option --input method can be set to read_json_flat_colors, read_json_2d_colors, read_json_flat_values, or read_json_2d_values to compile document using data in json file, which is provided by --input data.

// image.typ

#set page(width: auto, height: auto, margin: 2mm)

#let f(x, y) = calc.fract(x*x + y*y)

#let width = int(sys.inputs.at("width", default: 50))
#let height = width
#let method = sys.inputs.at("method", default: none)

#{
if method == none {

} else if method in ("map", "write_json_flat_values", "write_json_flat_colors", "write_json_2d_values", "write_json_2d_colors") {
  let linspace(a, b, n) = range(n).map((i) => a + i*(b - a)/(n - 1))
  let x = linspace(-10, 10, width)
  let y = linspace(-10, 10, height)
  let z_values = x.map((x) => y.map(y => f(x, y)))
  let z_flat_values = z_values.flatten()
  let z_flat_colors = z_flat_values.map((z) => int(z*255))

  if method == "map" {
    image(bytes(z_flat_colors), format: (encoding: "luma8", width: width, height: height))
  } else if method == "write_json_flat_colors" {
    metadata(json.encode(z_flat_colors))
  } else if method == "write_json_flat_values" {
    metadata(json.encode(z_flat_values))
  } else if method == "write_json_2d_values" {
    metadata(json.encode(z_values))
  } else if method == "write_json_2d_colors" {
    metadata(json.encode(z_values.map((z) => z.map((z) => int(z*255)))))
  }
} else if sys.inputs.at("method") == "read_json_flat_colors" {
  let z = json(sys.inputs.at("data"))
  image(bytes(z), format: (encoding: "luma8", width: width, height: height))
} else if sys.inputs.at("method") == "read_json_flat_values" {
  let z = json(sys.inputs.at("data"))
  image(bytes(z.map((z) => int(z * 255))), format: (encoding: "luma8", width: width, height: height))
} else if sys.inputs.at("method") == "read_json_2d_values" {
  let z = json(sys.inputs.at("data"))
  image(bytes(z.flatten().map((z) => int(z*255))), format: (encoding: "luma8", width: width, height: height))
} else if sys.inputs.at("method") == "read_json_2d_colors" {
  let z = json(sys.inputs.at("data"))
  image(bytes(z.flatten()), format: (encoding: "luma8", width: width, height: height))
}
}
Bash script for generating markdown tables

I do not know bash script well, so this script works, but may not be pretty, sorry for that.

#!/bin/bash

OUTPUT=$( { /usr/bin/time -f "%e %M" typst compile image.typ; } 2>&1 1>/dev/null )
BASE_ELAPSED=$(echo "$OUTPUT" | awk '{print $1}')
BASE_MEMORY=$(echo "$OUTPUT" | awk '{print $2}')
echo "BASE_MEMORY: $BASE_MEMORY"

VALUES=(10 25 50 100 250 300 500 600 700 800 900 1000)

echo "map:"
echo "| size | # of pixels | Elapsed Time (s) | Max Memory (MB) | Max Memory (B / pixel) |"
echo "|------|-------------|------------------|-----------------|------------------------|"
for value in "${VALUES[@]}"; do
    OUTPUT=$( { /usr/bin/time -f "%e %M" typst compile image.typ --input width=$value --input method=map; } 2>&1 1>/dev/null )
    ELAPSED=$(echo "$OUTPUT" | awk '{print $1}')
    MEMORY=$(echo "$OUTPUT" | awk '{print $2}')
    echo "| $value x $value | $((value*value)) | $ELAPSED |  $((MEMORY/1024)) | $(((MEMORY - BASE_MEMORY) * 1024 / (value*value))) |"
    # echo $((MEMORY - BASE_MEMORY))
done

JSON_VARIANTS=("flat_colors" "2d_colors" "flat_values" "2d_values")

for VARIANT in "${JSON_VARIANTS[@]}"; do
  echo $VARIANT
  echo "| size | # of pixels | Elapsed Time (s) | Max Memory (MB) | Max Memory (B / pixel) |"
  echo "|------|-------------|------------------|-----------------|------------------------|"
  for value in "${VALUES[@]}"; do
    DATA=$(echo $VARIANT)_$value.json

    OUTPUT=`typst query image.typ metadata --one --field value --input width=$value --input method=write_json_$VARIANT`
    OUTPUT=$(echo "$OUTPUT" | sed 's/^.\(.*\).$/\1/') # strip quotes
    echo -e $OUTPUT > $DATA

    OUTPUT=$( { /usr/bin/time -f "%e %M" typst compile image.typ --input width=$value --input method=read_json_$VARIANT --input data=$DATA; } 2>&1 1>/dev/null )

    ELAPSED=$(echo "$OUTPUT" | awk '{print $1}')
    MEMORY=$(echo "$OUTPUT" | awk '{print $2}')
    echo "| $value x $value | $((value*value)) | $ELAPSED |  $((MEMORY/1024)) | $(((MEMORY - BASE_MEMORY) * 1024 / (value*value))) |"

    rm "$(echo $VARIANT)_$value.json"
  done
done

range vs map

Consider two implementations of the code, that creates a 10000-element array in the for loop:

// range.typ

#set page(width: auto, height: auto, margin: 2mm)
#let iterations = int(sys.inputs.iterations)
#{
  for i in range(iterations) {
    let arr = range(i, 10000*iterations, step: iterations)
  }
}

and

// map.typ

#set page(width: auto, height: auto, margin: 2mm)
#let iterations = int(sys.inputs.iterations)
#{
  for i in range(iterations) {
    let arr = range(10000).map((x) => i + iterations*x)
  }
}

They should produce the same arrays in the for loop. The first implementation uses range function, while the second implementation uses map over smaller range.

There are results for the memory consumption for those implementations:

range.typ:

iterations Elapsed Time (s) Max Memory (MB) Max Memory (KB / iteration) relative to 0 iterations
10 0.65 27 12
20 0.64 27 18
30 0.64 27 5
40 0.65 27 7
50 0.65 27 4
60 0.66 27 5
70 0.65 27 9
80 0.65 27 3
90 0.65 27 3
100 0.65 27 6

As we see, range function is basically free here, although for each iteration, produced arrays are disjoint.

map.typ:

iterations Elapsed Time (s) Max Memory (MB) Max Memory (KB / iteration) relative to 0 iterations
10 0.91 196 17329
20 1.13 365 17331
30 1.41 541 17547
40 1.65 704 17332
50 1.95 892 17712
60 2.15 1056 17560
70 2.42 1218 17432
80 2.61 1382 17343
90 2.92 1545 17274
100 3.25 1757 17718

Here, the memory usage is proportional to the number of iterations, using 17MB per iteration, which is unacceptable amount for a computation of this size.

Bash script for generating markdown tables
#!/bin/bash

OUTPUT=$( { /usr/bin/time -f "%e %M" typst compile range.typ --input iterations=0; } 2>&1 1>/dev/null )
BASE_ELAPSED=$(echo "$OUTPUT" | awk '{print $1}')
BASE_MEMORY=$(echo "$OUTPUT" | awk '{print $2}')
echo "BASE_MEMORY: $BASE_MEMORY"

FILES=("range.typ" "map.typ")

for FILE in "${FILES[@]}"; do

  echo $FILE 

  echo "| iterations | Elapsed Time (s) | Max Memory (MB) | Max Memory (KB / iteration) relative to 0 iterations |"
  echo "|------------|------------------|-----------------|-----------------------------|"
  for i in $(seq 10 10 100);
  do
    OUTPUT=$( { /usr/bin/time -f "%e %M" typst compile $FILE --input iterations=$i; } 2>&1 1>/dev/null )
    # echo $OUTPUT
    ELAPSED=$(echo "$OUTPUT" | awk '{print $1}')
    MEMORY=$(echo "$OUTPUT" | awk '{print $2}')
    echo "| $i | $ELAPSED |  $((MEMORY/1024)) | $(((MEMORY - BASE_MEMORY)/i)) |"
  done
done

Activity

  1. Dherse commented on Jun 26, 2025

    @Dherse
    Contributor

    It is true that there is a potential gain for memory use from disabling memoisation and using for loops does reduce memory usage and improve performance for very small functions. However in real documents, some including CetZ plots, we didn't see this stark of an improvement.

    image

    In this image is shown a score given to each function (it is calculated based on its AST) and several documents and where we place a threshold before enabling memoization. It can have a huge memory impact but almost no performance impact unfortunately. If you have documents where you believe this impact would be higher please do share. We are limited to que quality of the test documents we have access to.

  2. added
    feature request
    scripting
    perf
    on Jun 26, 2025
  3. Danila-Bain commented on Jun 26, 2025

    @Danila-Bain
    Author

    Thank you for your response!

    I should have clarified in the original issue that the performance degradation is primarily due to swap memory usage, not just allocations. Up until the system begins swapping, performance appears to be perfectly fine.

    Regarding the image you shared — am I correct in understanding that it shows document compilation performance as a function of the memoization threshold? That would make sense: as the threshold increases, memory usage decreases (as seen across all graphs), while computation time increases due to more memoization misses (as shown in all graphs except the last one).

    Could you please share a link to the tests used to generate these results? I’d like to learn more and possibly reproduce them in the context of the data visualization use case I mentioned.

    As for a real-life example where I believe disabling memoization would lead to a substantial improvement, I had a project involving visualizations of bitwise operations on small integers. The corresponding images and code are included in the rest of my comment. Both examples are very close to hitting the compilation memory limit in the Typst App on my laptop.

    Image

    #import "@preview/lilaq:0.3.0" as lq
    #set page(width: auto, height: auto, margin: 3mm)
    
    // desired resolution is 2^10=1024 or more
    #let size = calc.pow(2, 9)
    
    #lq.diagram(
      title: $"bitwise" x and y = 0$,
      width: 100mm,
      height: 100mm,
      xaxis: (ticks: (0, size/2, size)),
      yaxis: (ticks: (0, size/2, size)),
      lq.colormesh(
        range(0, size+1),
        range(0, size+1),
        (x, y) => int(x.bit-and(y) == 0),
        map: (white, black),
       )
    );

    And, an example with more diagrams:

    Image

    #import "@preview/lilaq:0.3.0" as lq
    
    #set page(width: auto, height: auto, margin: 5mm)
    
    #set text(9pt);
      
    #let bit_diagram(title, fn) = lq.diagram(
      title: title,
      width: 60pt,
      height: 60pt,
      xaxis: (ticks: (0, 127, 255)),
      yaxis: (ticks: (0, 127, 255)),
      lq.colormesh(
        range(0, 255),
        range(0, 255),
        fn,
        map: (white, black),
        min: 0,
        max: 255,
      )
    );
    
    #bit_diagram($0000: 0$, (x, y) => 0) #h(5mm)
    #bit_diagram($0001: x and y$, (x, y) => x.bit-and(y)) #h(5mm)
    #bit_diagram($0010: x and not y $, (x, y) => x.bit-and(y.bit-not())) #h(5mm)
    #bit_diagram($0011: x$, (x, y) => x)
    
    #bit_diagram($0100: not x and y $, (x, y) => x.bit-not().bit-and(y)) #h(5mm)
    #bit_diagram($0101: y $, (x, y) => y) #h(5mm)
    #bit_diagram($0110: x xor y $, (x, y) => x.bit-xor(y)) #h(5mm)
    #bit_diagram($0111: x or y $, (x, y) => x.bit-or(y)) 
    
    #bit_diagram($1000: not x and not y$, (x, y) => x.bit-not().bit-and(y.bit-not()).bit-and(255)) #h(5mm)
    #bit_diagram($1001: not (x xor y)$, (x, y) => x.bit-xor(y).bit-not().bit-and(255)) #h(5mm)
    #bit_diagram($1010: not y $, (x, y) => y.bit-not().bit-and(255)) #h(5mm)
    #bit_diagram($1011: x or not y$, (x, y) => x.bit-or(y.bit-not()).bit-and(255))
    
    #bit_diagram($1100: not x $, (x, y) => x.bit-not().bit-and(255)) #h(5mm)
    #bit_diagram($1101: not x or y $, (x, y) => x.bit-not().bit-or(y).bit-and(255)) #h(5mm)
    #bit_diagram($1110: not x or not y $, (x, y) => x.bit-not().bit-or(y.bit-not()).bit-and(255)) #h(5mm)
    #bit_diagram($1111: 1 $, (x, y) => 255) 
  4. laurmaedje commented on Jun 26, 2025

    @laurmaedje
    Member

    I am absolutely open to developing some smart heuristic for transparently skipping memoization, but I don't want to expose this to users. It should happen automatically in the background. I think the machine can know better than people anyway (especially with runtime information). It's like inlining in compiled languages: Better to the let the compiler figure it out.

  5. haennes commented on Jan 7, 2026

    @haennes

    As I have just written in #7307 I have a real-world scenario where the compiler is eating more than 60GiB RAM (I gave up at that point).
    For anyone wondering how: approx. 300 question / answer pairs when using https://code.ole.blue/typ2anki/typ2anki

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestperfscripting

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions