Spaces:
Paused
Paused
Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+7
- .gitignore+2-1
- .venv/.gitignoreAdded+2
- .venv/bin/Activate.ps1Added+248
- .venv/bin/activateAdded+76
- .venv/bin/activate.cshAdded+27
- .venv/bin/activate.fishAdded+69
- .venv/bin/pipAdded+8
- .venv/bin/pip3Added+8
- .venv/bin/pip3.13Added+8
- .venv/bin/pythonAdded+3
- .venv/bin/python3Added+3
- .venv/bin/python3.13Added+3
- .venv/lib/python3.13/site-packages/diskcache-5.6.3.dist-info/INSTALLERAdded+1
- .venv/lib/python3.13/site-packages/diskcache-5.6.3.dist-info/LICENSEAdded+12
- .venv/lib/python3.13/site-packages/diskcache-5.6.3.dist-info/METADATAAdded+430
- .venv/lib/python3.13/site-packages/diskcache-5.6.3.dist-info/RECORDAdded+21
- .venv/lib/python3.13/site-packages/diskcache-5.6.3.dist-info/REQUESTEDAdded
- .venv/lib/python3.13/site-packages/diskcache-5.6.3.dist-info/WHEELAdded+5
- .venv/lib/python3.13/site-packages/diskcache-5.6.3.dist-info/top_level.txtAdded+1
- .venv/lib/python3.13/site-packages/diskcache/__init__.pyAdded+68
- .venv/lib/python3.13/site-packages/diskcache/cli.pyAdded+1
- .venv/lib/python3.13/site-packages/diskcache/core.pyAdded+2452
- .venv/lib/python3.13/site-packages/diskcache/djangocache.pyAdded+456
- .venv/lib/python3.13/site-packages/diskcache/fanout.pyAdded+687
- .venv/lib/python3.13/site-packages/diskcache/persistent.pyAdded+1245
- .venv/lib/python3.13/site-packages/diskcache/recipes.pyAdded+488
- .venv/lib/python3.13/site-packages/include/ggml-alloc.hAdded+86
- .venv/lib/python3.13/site-packages/include/ggml-backend.hAdded+437
- .venv/lib/python3.13/site-packages/include/ggml-blas.hAdded+25
- .venv/lib/python3.13/site-packages/include/ggml-cann.hAdded+123
- .venv/lib/python3.13/site-packages/include/ggml-cpp.hAdded+39
- .venv/lib/python3.13/site-packages/include/ggml-cpu.hAdded+152
- .venv/lib/python3.13/site-packages/include/ggml-cuda.hAdded+47
- .venv/lib/python3.13/site-packages/include/ggml-metal.hAdded+61
- .venv/lib/python3.13/site-packages/include/ggml-openvino.hAdded+37
- .venv/lib/python3.13/site-packages/include/ggml-opt.hAdded+256
- .venv/lib/python3.13/site-packages/include/ggml-rpc.hAdded+35
- .venv/lib/python3.13/site-packages/include/ggml-sycl.hAdded+59
- .venv/lib/python3.13/site-packages/include/ggml-virtgpu.hAdded+14
- .venv/lib/python3.13/site-packages/include/ggml-vulkan.hAdded+29
- .venv/lib/python3.13/site-packages/include/ggml-webgpu.hAdded+19
- .venv/lib/python3.13/site-packages/include/ggml-zendnn.hAdded+22
- .venv/lib/python3.13/site-packages/include/ggml.hAdded
- .venv/lib/python3.13/site-packages/include/gguf.hAdded+211
- .venv/lib/python3.13/site-packages/include/llama-cpp.hAdded+35
- .venv/lib/python3.13/site-packages/include/llama.hAdded+1739
- .venv/lib/python3.13/site-packages/include/mtmd-debug.hAdded+17
- .venv/lib/python3.13/site-packages/include/mtmd-helper.hAdded+308
- .venv/lib/python3.13/site-packages/include/mtmd.hAdded+538
1.embed_cache/abd8f399ec0d167307cb-f32.bin filter=lfs diff=lfs merge=lfs -text12345678.embed_cache/abd8f399ec0d167307cb-f32.bin filter=lfs diff=lfs merge=lfs -text.venv/bin/python filter=lfs diff=lfs merge=lfs -text.venv/bin/python3 filter=lfs diff=lfs merge=lfs -text.venv/bin/python3.13 filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.13/site-packages/pip/_vendor/distlib/t64-arm.exe filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.13/site-packages/pip/_vendor/distlib/t64.exe filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.13/site-packages/pip/_vendor/distlib/w64-arm.exe filter=lfs diff=lfs merge=lfs -text.venv/lib/python3.13/site-packages/pip/_vendor/distlib/w64.exe filter=lfs diff=lfs merge=lfs -text
2 unmodified lines34567892 unmodified lines*.gguf# Generated vector cache.embed_cache/# Python.venv/2 unmodified lines3456789102 unmodified lines*.gguf# Generated vector cache# .embed_cache/ holds the resolved noun matrix (2.6 MB), committed so the# Space can start without re-embedding. Local scratch keys would be noise.# Python.venv/
12# Created by venv; see https://docs.python.org/3/library/venv.html*123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248<#
.Synopsis
Activate a Python virtual environment for the current PowerShell session.
.Description
Pushes the python executable for a virtual environment to the front of the
$Env:PATH environment variable and sets the prompt to signify that you are
in a Python virtual environment. Makes use of the command line switches as
well as the `pyvenv.cfg` file values present in the virtual environment.
.Parameter VenvDir
Path to the directory that contains the virtual environment to activate. The
default value for this is the parent of the directory that the Activate.ps1
script is located within.
.Parameter Prompt
The prompt prefix to display when this virtual environment is activated. By
default, this prompt is the name of the virtual environment folder (VenvDir)
surrounded by parentheses and followed by a single space (ie. '(.venv) ').
.Example
Activate.ps1
Activates the Python virtual environment that contains the Activate.ps1 script.
.Example
Activate.ps1 -Verbose
Activates the Python virtual environment that contains the Activate.ps1 script,
and shows extra information about the activation as it executes.
.Example
Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
Activates the Python virtual environment located in the specified location.
.Example
Activate.ps1 -Prompt "MyPython"
Activates the Python virtual environment that contains the Activate.ps1 script,
and prefixes the current prompt with the specified string (surrounded in
parentheses) while the virtual environment is active.
.Notes
On Windows, it may be required to enable this Activate.ps1 script by setting the
execution policy for the user. You can do this by issuing the following PowerShell
command:
PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
For more information on Execution Policies:
https://go.microsoft.com/fwlink/?LinkID=135170
#>
Param(
[Parameter(Mandatory = $false)]
[String]
$VenvDir,
[Parameter(Mandatory = $false)]
[String]
$Prompt
)
<# Function declarations --------------------------------------------------- #>
<#
.Synopsis
Remove all shell session elements added by the Activate script, including the
addition of the virtual environment's Python executable from the beginning of
the PATH variable.
.Parameter NonDestructive
If present, do not remove this function from the global namespace for the
session.
#>
function global:deactivate ([switch]$NonDestructive) {
# Revert to original values
# The prior prompt:
if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
}
# The prior PYTHONHOME:
if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
}
# The prior PATH:
if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
Remove-Item -Path Env:_OLD_VIRTUAL_PATH
}
# Just remove the VIRTUAL_ENV altogether:
if (Test-Path -Path Env:VIRTUAL_ENV) {
Remove-Item -Path env:VIRTUAL_ENV
}
# Just remove VIRTUAL_ENV_PROMPT altogether.
if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) {
Remove-Item -Path env:VIRTUAL_ENV_PROMPT
}
# Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
}
# Leave deactivate function in the global namespace if requested:
if (-not $NonDestructive) {
Remove-Item -Path function:deactivate
}
}
<#
.Description
Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
given folder, and returns them in a map.
For each line in the pyvenv.cfg file, if that line can be parsed into exactly
two strings separated by `=` (with any amount of whitespace surrounding the =)
then it is considered a `key = value` line. The left hand string is the key,
the right hand is the value.
If the value starts with a `'` or a `"` then the first and last character is
stripped from the value before being captured.
.Parameter ConfigDir
Path to the directory that contains the `pyvenv.cfg` file.
#>
function Get-PyVenvConfig(
[String]
$ConfigDir
) {
Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
# Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
$pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
# An empty map will be returned if no config file is found.
$pyvenvConfig = @{ }
if ($pyvenvConfigPath) {
Write-Verbose "File exists, parse `key = value` lines"
$pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
$pyvenvConfigContent | ForEach-Object {
$keyval = $PSItem -split "\s*=\s*", 2
if ($keyval[0] -and $keyval[1]) {
$val = $keyval[1]
# Remove extraneous quotations around a string value.
if ("'""".Contains($val.Substring(0, 1))) {
$val = $val.Substring(1, $val.Length - 2)
}
$pyvenvConfig[$keyval[0]] = $val
Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
}
}
}
return $pyvenvConfig
}
<# Begin Activate script --------------------------------------------------- #>
# Determine the containing directory of this script
$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
$VenvExecDir = Get-Item -Path $VenvExecPath
Write-Verbose "Activation script is located in path: '$VenvExecPath'"
Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
# Set values required in priority: CmdLine, ConfigFile, Default
# First, get the location of the virtual environment, it might not be
# VenvExecDir if specified on the command line.
if ($VenvDir) {
Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
}
else {
Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
$VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
Write-Verbose "VenvDir=$VenvDir"
}
# Next, read the `pyvenv.cfg` file to determine any required value such
# as `prompt`.
$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
# Next, set the prompt from the command line, or the config file, or
# just use the name of the virtual environment folder.
if ($Prompt) {
Write-Verbose "Prompt specified as argument, using '$Prompt'"
}
else {
Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
$Prompt = $pyvenvCfg['prompt'];
}
else {
Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)"
Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
$Prompt = Split-Path -Path $venvDir -Leaf
}
}
Write-Verbose "Prompt = '$Prompt'"
Write-Verbose "VenvDir='$VenvDir'"
# Deactivate any currently active virtual environment, but leave the
# deactivate function in place.
deactivate -nondestructive
# Now set the environment variable VIRTUAL_ENV, used by many tools to determine
# that there is an activated venv.
$env:VIRTUAL_ENV = $VenvDir
$env:VIRTUAL_ENV_PROMPT = $Prompt
if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
Write-Verbose "Setting prompt to '$Prompt'"
# Set the prompt to include the env name
# Make sure _OLD_VIRTUAL_PROMPT is global
function global:_OLD_VIRTUAL_PROMPT { "" }
Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
function global:prompt {
Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
_OLD_VIRTUAL_PROMPT
}
}
# Clear PYTHONHOME
if (Test-Path -Path Env:PYTHONHOME) {
Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
Remove-Item -Path Env:PYTHONHOME
}
# Add the venv to the PATH
Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576# This file must be used with "source bin/activate" *from bash*# You cannot run it directly
deactivate () { # reset old environment variables if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then PATH="${_OLD_VIRTUAL_PATH:-}" export PATH unset _OLD_VIRTUAL_PATH fi if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}" export PYTHONHOME unset _OLD_VIRTUAL_PYTHONHOME fi
# Call hash to forget past locations. Without forgetting # past locations the $PATH changes we made may not be respected. # See "man bash" for more details. hash is usually a builtin of your shell hash -r 2> /dev/null
if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then PS1="${_OLD_VIRTUAL_PS1:-}" export PS1 unset _OLD_VIRTUAL_PS1 fi
unset VIRTUAL_ENV unset VIRTUAL_ENV_PROMPT if [ ! "${1:-}" = "nondestructive" ] ; then # Self destruct! unset -f deactivate fi}
# unset irrelevant variablesdeactivate nondestructive
# on Windows, a path can contain colons and backslashes and has to be converted:case "$(uname)" in CYGWIN*|MSYS*|MINGW*) # transform D:\path\to\venv to /d/path/to/venv on MSYS and MINGW # and to /cygdrive/d/path/to/venv on Cygwin VIRTUAL_ENV=$(cygpath /Users/arin/work/embed-compare-space/.venv) export VIRTUAL_ENV ;; *) # use the path as-is export VIRTUAL_ENV=/Users/arin/work/embed-compare-space/.venv ;;esac
_OLD_VIRTUAL_PATH="$PATH"PATH="$VIRTUAL_ENV/"bin":$PATH"export PATH
VIRTUAL_ENV_PROMPT=.venvexport VIRTUAL_ENV_PROMPT
# unset PYTHONHOME if set# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)# could use `if (set -u; : $PYTHONHOME) ;` in bashif [ -n "${PYTHONHOME:-}" ] ; then _OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}" unset PYTHONHOMEfi
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then _OLD_VIRTUAL_PS1="${PS1:-}" PS1="(".venv") ${PS1:-}" export PS1fi
# Call hash to forget past commands. Without forgetting# past commands the $PATH changes we made may not be respectedhash -r 2> /dev/null123456789101112131415161718192021222324252627# This file must be used with "source bin/activate.csh" *from csh*.# You cannot run it directly.
# Created by Davide Di Blasi <davidedb@gmail.com>.# Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate'
# Unset irrelevant variables.deactivate nondestructive
setenv VIRTUAL_ENV /Users/arin/work/embed-compare-space/.venv
set _OLD_VIRTUAL_PATH="$PATH"setenv PATH "$VIRTUAL_ENV/"bin":$PATH"setenv VIRTUAL_ENV_PROMPT .venv
set _OLD_VIRTUAL_PROMPT="$prompt"
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then set prompt = "(".venv") $prompt:q"endif
alias pydoc python -m pydoc
rehash123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869# This file must be used with "source <venv>/bin/activate.fish" *from fish*# (https://fishshell.com/). You cannot run it directly.
function deactivate -d "Exit virtual environment and return to normal shell environment" # reset old environment variables if test -n "$_OLD_VIRTUAL_PATH" set -gx PATH $_OLD_VIRTUAL_PATH set -e _OLD_VIRTUAL_PATH end if test -n "$_OLD_VIRTUAL_PYTHONHOME" set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME set -e _OLD_VIRTUAL_PYTHONHOME end
if test -n "$_OLD_FISH_PROMPT_OVERRIDE" set -e _OLD_FISH_PROMPT_OVERRIDE # prevents error when using nested fish instances (Issue #93858) if functions -q _old_fish_prompt functions -e fish_prompt functions -c _old_fish_prompt fish_prompt functions -e _old_fish_prompt end end
set -e VIRTUAL_ENV set -e VIRTUAL_ENV_PROMPT if test "$argv[1]" != "nondestructive" # Self-destruct! functions -e deactivate endend
# Unset irrelevant variables.deactivate nondestructive
set -gx VIRTUAL_ENV /Users/arin/work/embed-compare-space/.venv
set -gx _OLD_VIRTUAL_PATH $PATHset -gx PATH "$VIRTUAL_ENV/"bin $PATHset -gx VIRTUAL_ENV_PROMPT .venv
# Unset PYTHONHOME if set.if set -q PYTHONHOME set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME set -e PYTHONHOMEend
if test -z "$VIRTUAL_ENV_DISABLE_PROMPT" # fish uses a function instead of an env var to generate the prompt.
# Save the current fish_prompt function as the function _old_fish_prompt. functions -c fish_prompt _old_fish_prompt
# With the original prompt function renamed, we can override with our own. function fish_prompt # Save the return status of the last command. set -l old_status $status
# Output the venv prompt; color taken from the blue of the Python logo. printf "%s(%s)%s " (set_color 4B8BBE) .venv (set_color normal)
# Restore the return status of the previous command. echo "exit $old_status" | . # Output the original/"old" prompt. _old_fish_prompt end
set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"end12345678#!/Users/arin/work/embed-compare-space/.venv/bin/python3.13# -*- coding: utf-8 -*-import reimport sysfrom pip._internal.cli.main import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())12345678#!/Users/arin/work/embed-compare-space/.venv/bin/python3.13# -*- coding: utf-8 -*-import reimport sysfrom pip._internal.cli.main import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())12345678#!/Users/arin/work/embed-compare-space/.venv/bin/python3.13# -*- coding: utf-8 -*-import reimport sysfrom pip._internal.cli.main import mainif __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) sys.exit(main())123version https://git-lfs.github.com/spec/v1oid sha256:f5d584368bd127649722baa482517054d3c941ea5fbd29a669a8c5323dd21be5size 119328123version https://git-lfs.github.com/spec/v1oid sha256:f5d584368bd127649722baa482517054d3c941ea5fbd29a669a8c5323dd21be5size 119328123version https://git-lfs.github.com/spec/v1oid sha256:f5d584368bd127649722baa482517054d3c941ea5fbd29a669a8c5323dd21be5size 1193281pip123456789101112Copyright 2016-2022 Grant Jenks
Licensed under the Apache License, Version 2.0 (the "License"); you may not usethis file except in compliance with the License. You may obtain a copy of theLicense at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributedunder the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES ORCONDITIONS OF ANY KIND, either express or implied. See the License for thespecific language governing permissions and limitations under the License.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430Metadata-Version: 2.1Name: diskcacheVersion: 5.6.3Summary: Disk Cache -- Disk and file backed persistent cache.Home-page: http://www.grantjenks.com/docs/diskcache/Author: Grant JenksAuthor-email: contact@grantjenks.comLicense: Apache 2.0Project-URL: Documentation, http://www.grantjenks.com/docs/diskcache/Project-URL: Funding, https://gum.co/diskcacheProject-URL: Source, https://github.com/grantjenks/python-diskcacheProject-URL: Tracker, https://github.com/grantjenks/python-diskcache/issuesClassifier: Development Status :: 5 - Production/StableClassifier: Intended Audience :: DevelopersClassifier: License :: OSI Approved :: Apache Software LicenseClassifier: Natural Language :: EnglishClassifier: Programming Language :: PythonClassifier: Programming Language :: Python :: 3Classifier: Programming Language :: Python :: 3.5Classifier: Programming Language :: Python :: 3.6Classifier: Programming Language :: Python :: 3.7Classifier: Programming Language :: Python :: 3.8Classifier: Programming Language :: Python :: 3.9Classifier: Programming Language :: Python :: Implementation :: CPythonRequires-Python: >=3License-File: LICENSE
DiskCache: Disk Backed Cache============================
`DiskCache`_ is an Apache2 licensed disk and file backed cache library, writtenin pure-Python, and compatible with Django.
The cloud-based computing of 2023 puts a premium on memory. Gigabytes of emptyspace is left on disks as processes vie for memory. Among these processes isMemcached (and sometimes Redis) which is used as a cache. Wouldn't it be niceto leverage empty disk space for caching?
Django is Python's most popular web framework and ships with several cachingbackends. Unfortunately the file-based cache in Django is essentiallybroken. The culling method is random and large caches repeatedly scan a cachedirectory which slows linearly with growth. Can you really allow it to takesixty milliseconds to store a key in a cache with a thousand items?
In Python, we can do better. And we can do it in pure-Python!
::
In [1]: import pylibmc In [2]: client = pylibmc.Client(['127.0.0.1'], binary=True) In [3]: client[b'key'] = b'value' In [4]: %timeit client[b'key']
10000 loops, best of 3: 25.4 µs per loop
In [5]: import diskcache as dc In [6]: cache = dc.Cache('tmp') In [7]: cache[b'key'] = b'value' In [8]: %timeit cache[b'key']
100000 loops, best of 3: 11.8 µs per loop
**Note:** Micro-benchmarks have their place but are not a substitute for realmeasurements. DiskCache offers cache benchmarks to defend its performanceclaims. Micro-optimizations are avoided but your mileage may vary.
DiskCache efficiently makes gigabytes of storage space available forcaching. By leveraging rock-solid database libraries and memory-mapped files,cache performance can match and exceed industry-standard solutions. There's noneed for a C compiler or running another process. Performance is a feature andtesting has 100% coverage with unit tests and hours of stress.
Testimonials------------
`Daren Hasenkamp`_, Founder --
"It's a useful, simple API, just like I love about Redis. It has reduced the amount of queries hitting my Elasticsearch cluster by over 25% for a website that gets over a million users/day (100+ hits/second)."
`Mathias Petermann`_, Senior Linux System Engineer --
"I implemented it into a wrapper for our Ansible lookup modules and we were able to speed up some Ansible runs by almost 3 times. DiskCache is saving us a ton of time."
Does your company or website use `DiskCache`_? Send us a `message<contact@grantjenks.com>`_ and let us know.
.. _`Daren Hasenkamp`: https://www.linkedin.com/in/daren-hasenkamp-93006438/.. _`Mathias Petermann`: https://www.linkedin.com/in/mathias-petermann-a8aa273b/
Features--------
- Pure-Python- Fully Documented- Benchmark comparisons (alternatives, Django cache backends)- 100% test coverage- Hours of stress testing- Performance matters- Django compatible API- Thread-safe and process-safe- Supports multiple eviction policies (LRU and LFU included)- Keys support "tag" metadata and eviction- Developed on Python 3.10- Tested on CPython 3.6, 3.7, 3.8, 3.9, 3.10- Tested on Linux, Mac OS X, and Windows- Tested using GitHub Actions
.. image:: https://github.com/grantjenks/python-diskcache/workflows/integration/badge.svg :target: https://github.com/grantjenks/python-diskcache/actions?query=workflow%3Aintegration
.. image:: https://github.com/grantjenks/python-diskcache/workflows/release/badge.svg :target: https://github.com/grantjenks/python-diskcache/actions?query=workflow%3Arelease
Quickstart----------
Installing `DiskCache`_ is simple with `pip <http://www.pip-installer.org/>`_::
$ pip install diskcache
You can access documentation in the interpreter with Python's built-in helpfunction::
>>> import diskcache >>> help(diskcache) # doctest: +SKIP
The core of `DiskCache`_ is three data types intended for caching. `Cache`_objects manage a SQLite database and filesystem directory to store key andvalue pairs. `FanoutCache`_ provides a sharding layer to utilize multiplecaches and `DjangoCache`_ integrates that with `Django`_::
>>> from diskcache import Cache, FanoutCache, DjangoCache >>> help(Cache) # doctest: +SKIP >>> help(FanoutCache) # doctest: +SKIP >>> help(DjangoCache) # doctest: +SKIP
Built atop the caching data types, are `Deque`_ and `Index`_ which work as across-process, persistent replacements for Python's ``collections.deque`` and``dict``. These implement the sequence and mapping container base classes::
>>> from diskcache import Deque, Index >>> help(Deque) # doctest: +SKIP >>> help(Index) # doctest: +SKIP
Finally, a number of `recipes`_ for cross-process synchronization are providedusing an underlying cache. Features like memoization with cache stampedeprevention, cross-process locking, and cross-process throttling are available::
>>> from diskcache import memoize_stampede, Lock, throttle >>> help(memoize_stampede) # doctest: +SKIP >>> help(Lock) # doctest: +SKIP >>> help(throttle) # doctest: +SKIP
Python's docstrings are a quick way to get started but not intended as areplacement for the `DiskCache Tutorial`_ and `DiskCache API Reference`_.
.. _`Cache`: http://www.grantjenks.com/docs/diskcache/tutorial.html#cache.. _`FanoutCache`: http://www.grantjenks.com/docs/diskcache/tutorial.html#fanoutcache.. _`DjangoCache`: http://www.grantjenks.com/docs/diskcache/tutorial.html#djangocache.. _`Django`: https://www.djangoproject.com/.. _`Deque`: http://www.grantjenks.com/docs/diskcache/tutorial.html#deque.. _`Index`: http://www.grantjenks.com/docs/diskcache/tutorial.html#index.. _`recipes`: http://www.grantjenks.com/docs/diskcache/tutorial.html#recipes
User Guide----------
For those wanting more details, this part of the documentation describestutorial, benchmarks, API, and development.
* `DiskCache Tutorial`_* `DiskCache Cache Benchmarks`_* `DiskCache DjangoCache Benchmarks`_* `Case Study: Web Crawler`_* `Case Study: Landing Page Caching`_* `Talk: All Things Cached - SF Python 2017 Meetup`_* `DiskCache API Reference`_* `DiskCache Development`_
.. _`DiskCache Tutorial`: http://www.grantjenks.com/docs/diskcache/tutorial.html.. _`DiskCache Cache Benchmarks`: http://www.grantjenks.com/docs/diskcache/cache-benchmarks.html.. _`DiskCache DjangoCache Benchmarks`: http://www.grantjenks.com/docs/diskcache/djangocache-benchmarks.html.. _`Talk: All Things Cached - SF Python 2017 Meetup`: http://www.grantjenks.com/docs/diskcache/sf-python-2017-meetup-talk.html.. _`Case Study: Web Crawler`: http://www.grantjenks.com/docs/diskcache/case-study-web-crawler.html.. _`Case Study: Landing Page Caching`: http://www.grantjenks.com/docs/diskcache/case-study-landing-page-caching.html.. _`DiskCache API Reference`: http://www.grantjenks.com/docs/diskcache/api.html.. _`DiskCache Development`: http://www.grantjenks.com/docs/diskcache/development.html
Comparisons-----------
Comparisons to popular projects related to `DiskCache`_.
Key-Value Stores................
`DiskCache`_ is mostly a simple key-value store. Feature comparisons with fourother projects are shown in the tables below.
* `dbm`_ is part of Python's standard library and implements a generic interface to variants of the DBM database — dbm.gnu or dbm.ndbm. If none of these modules is installed, the slow-but-simple dbm.dumb is used.* `shelve`_ is part of Python's standard library and implements a “shelf” as a persistent, dictionary-like object. The difference with “dbm” databases is that the values can be anything that the pickle module can handle.* `sqlitedict`_ is a lightweight wrapper around Python's sqlite3 database with a simple, Pythonic dict-like interface and support for multi-thread access. Keys are arbitrary strings, values arbitrary pickle-able objects.* `pickleDB`_ is a lightweight and simple key-value store. It is built upon Python's simplejson module and was inspired by Redis. It is licensed with the BSD three-clause license.
.. _`dbm`: https://docs.python.org/3/library/dbm.html.. _`shelve`: https://docs.python.org/3/library/shelve.html.. _`sqlitedict`: https://github.com/RaRe-Technologies/sqlitedict.. _`pickleDB`: https://pythonhosted.org/pickleDB/
**Features**
================ ============= ========= ========= ============ ============Feature diskcache dbm shelve sqlitedict pickleDB================ ============= ========= ========= ============ ============Atomic? Always Maybe Maybe Maybe NoPersistent? Yes Yes Yes Yes YesThread-safe? Yes No No Yes NoProcess-safe? Yes No No Maybe NoBackend? SQLite DBM DBM SQLite FileSerialization? Customizable None Pickle Customizable JSONData Types? Mapping/Deque Mapping Mapping Mapping MappingOrdering? Insert/Sorted None None None NoneEviction? LRU/LFU/more None None None NoneVacuum? Automatic Maybe Maybe Manual AutomaticTransactions? Yes No No Maybe NoMultiprocessing? Yes No No No NoForkable? Yes No No No NoMetadata? Yes No No No No================ ============= ========= ========= ============ ============
**Quality**
================ ============= ========= ========= ============ ============Project diskcache dbm shelve sqlitedict pickleDB================ ============= ========= ========= ============ ============Tests? Yes Yes Yes Yes YesCoverage? Yes Yes Yes Yes NoStress? Yes No No No NoCI Tests? Linux/Windows Yes Yes Linux NoPython? 2/3/PyPy All All 2/3 2/3License? Apache2 Python Python Apache2 3-Clause BSDDocs? Extensive Summary Summary Readme SummaryBenchmarks? Yes No No No NoSources? GitHub GitHub GitHub GitHub GitHubPure-Python? Yes Yes Yes Yes YesServer? No No No No NoIntegrations? Django None None None None================ ============= ========= ========= ============ ============
**Timings**
These are rough measurements. See `DiskCache Cache Benchmarks`_ for morerigorous data.
================ ============= ========= ========= ============ ============Project diskcache dbm shelve sqlitedict pickleDB================ ============= ========= ========= ============ ============get 25 µs 36 µs 41 µs 513 µs 92 µsset 198 µs 900 µs 928 µs 697 µs 1,020 µsdelete 248 µs 740 µs 702 µs 1,717 µs 1,020 µs================ ============= ========= ========= ============ ============
Caching Libraries.................
* `joblib.Memory`_ provides caching functions and works by explicitly saving the inputs and outputs to files. It is designed to work with non-hashable and potentially large input and output data types such as numpy arrays.* `klepto`_ extends Python’s `lru_cache` to utilize different keymaps and alternate caching algorithms, such as `lfu_cache` and `mru_cache`. Klepto uses a simple dictionary-sytle interface for all caches and archives.
.. _`klepto`: https://pypi.org/project/klepto/.. _`joblib.Memory`: https://joblib.readthedocs.io/en/latest/memory.html
Data Structures...............
* `dict`_ is a mapping object that maps hashable keys to arbitrary values. Mappings are mutable objects. There is currently only one standard Python mapping type, the dictionary.* `pandas`_ is a Python package providing fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive.* `Sorted Containers`_ is an Apache2 licensed sorted collections library, written in pure-Python, and fast as C-extensions. Sorted Containers implements sorted list, sorted dictionary, and sorted set data types.
.. _`dict`: https://docs.python.org/3/library/stdtypes.html#typesmapping.. _`pandas`: https://pandas.pydata.org/.. _`Sorted Containers`: http://www.grantjenks.com/docs/sortedcontainers/
Pure-Python Databases.....................
* `ZODB`_ supports an isomorphic interface for database operations which means there's little impact on your code to make objects persistent and there's no database mapper that partially hides the datbase.* `CodernityDB`_ is an open source, pure-Python, multi-platform, schema-less, NoSQL database and includes an HTTP server version, and a Python client library that aims to be 100% compatible with the embedded version.* `TinyDB`_ is a tiny, document oriented database optimized for your happiness. If you need a simple database with a clean API that just works without lots of configuration, TinyDB might be the right choice for you.
.. _`ZODB`: http://www.zodb.org/.. _`CodernityDB`: https://pypi.org/project/CodernityDB/.. _`TinyDB`: https://tinydb.readthedocs.io/
Object Relational Mappings (ORM)................................
* `Django ORM`_ provides models that are the single, definitive source of information about data and contains the essential fields and behaviors of the stored data. Generally, each model maps to a single SQL database table.* `SQLAlchemy`_ is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. It provides a full suite of well known enterprise-level persistence patterns.* `Peewee`_ is a simple and small ORM. It has few (but expressive) concepts, making it easy to learn and intuitive to use. Peewee supports Sqlite, MySQL, and PostgreSQL with tons of extensions.* `SQLObject`_ is a popular Object Relational Manager for providing an object interface to your database, with tables as classes, rows as instances, and columns as attributes.* `Pony ORM`_ is a Python ORM with beautiful query syntax. Use Python syntax for interacting with the database. Pony translates such queries into SQL and executes them in the database in the most efficient way.
.. _`Django ORM`: https://docs.djangoproject.com/en/dev/topics/db/.. _`SQLAlchemy`: https://www.sqlalchemy.org/.. _`Peewee`: http://docs.peewee-orm.com/.. _`SQLObject`: http://sqlobject.org/.. _`Pony ORM`: https://ponyorm.com/
SQL Databases.............
* `SQLite`_ is part of Python's standard library and provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language.* `MySQL`_ is one of the world’s most popular open source databases and has become a leading database choice for web-based applications. MySQL includes a standardized database driver for Python platforms and development.* `PostgreSQL`_ is a powerful, open source object-relational database system with over 30 years of active development. Psycopg is the most popular PostgreSQL adapter for the Python programming language.* `Oracle DB`_ is a relational database management system (RDBMS) from the Oracle Corporation. Originally developed in 1977, Oracle DB is one of the most trusted and widely used enterprise relational database engines.* `Microsoft SQL Server`_ is a relational database management system developed by Microsoft. As a database server, it stores and retrieves data as requested by other software applications.
.. _`SQLite`: https://docs.python.org/3/library/sqlite3.html.. _`MySQL`: https://dev.mysql.com/downloads/connector/python/.. _`PostgreSQL`: http://initd.org/psycopg/.. _`Oracle DB`: https://pypi.org/project/cx_Oracle/.. _`Microsoft SQL Server`: https://pypi.org/project/pyodbc/
Other Databases...............
* `Memcached`_ is free and open source, high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.* `Redis`_ is an open source, in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, and more.* `MongoDB`_ is a cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schema. PyMongo is the recommended way to work with MongoDB from Python.* `LMDB`_ is a lightning-fast, memory-mapped database. With memory-mapped files, it has the read performance of a pure in-memory database while retaining the persistence of standard disk-based databases.* `BerkeleyDB`_ is a software library intended to provide a high-performance embedded database for key/value data. Berkeley DB is a programmatic toolkit that provides built-in database support for desktop and server applications.* `LevelDB`_ is a fast key-value storage library written at Google that provides an ordered mapping from string keys to string values. Data is stored sorted by key and users can provide a custom comparison function.
.. _`Memcached`: https://pypi.org/project/python-memcached/.. _`MongoDB`: https://api.mongodb.com/python/current/.. _`Redis`: https://redis.io/clients#python.. _`LMDB`: https://lmdb.readthedocs.io/.. _`BerkeleyDB`: https://pypi.org/project/bsddb3/.. _`LevelDB`: https://plyvel.readthedocs.io/
Reference---------
* `DiskCache Documentation`_* `DiskCache at PyPI`_* `DiskCache at GitHub`_* `DiskCache Issue Tracker`_
.. _`DiskCache Documentation`: http://www.grantjenks.com/docs/diskcache/.. _`DiskCache at PyPI`: https://pypi.python.org/pypi/diskcache/.. _`DiskCache at GitHub`: https://github.com/grantjenks/python-diskcache/.. _`DiskCache Issue Tracker`: https://github.com/grantjenks/python-diskcache/issues/
License-------
Copyright 2016-2023 Grant Jenks
Licensed under the Apache License, Version 2.0 (the "License"); you may not usethis file except in compliance with the License. You may obtain a copy of theLicense at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributedunder the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES ORCONDITIONS OF ANY KIND, either express or implied. See the License for thespecific language governing permissions and limitations under the License.
.. _`DiskCache`: http://www.grantjenks.com/docs/diskcache/123456789101112131415161718192021diskcache-5.6.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
diskcache-5.6.3.dist-info/LICENSE,sha256=WDVGuqP9k2B9hFEmVwZ3pAH1COIotQRP77w5Sa8XlnI,559
diskcache-5.6.3.dist-info/METADATA,sha256=b8cM_0OjxmZlMebCaOkAWfuTrliu1wgWPAzuyrJNuu8,20458
diskcache-5.6.3.dist-info/RECORD,,
diskcache-5.6.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
diskcache-5.6.3.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92
diskcache-5.6.3.dist-info/top_level.txt,sha256=A5fqg_AHgOQc_0o1NZ-Uo5Bsb7CV3fR99J-p1-F4yuA,10
diskcache/__init__.py,sha256=JcEtz224G-ysHmgyxWId28A0wQfCIif0mdv4tqC-Zxk,1262
diskcache/__pycache__/__init__.cpython-313.pyc,,
diskcache/__pycache__/cli.cpython-313.pyc,,
diskcache/__pycache__/core.cpython-313.pyc,,
diskcache/__pycache__/djangocache.cpython-313.pyc,,
diskcache/__pycache__/fanout.cpython-313.pyc,,
diskcache/__pycache__/persistent.cpython-313.pyc,,
diskcache/__pycache__/recipes.cpython-313.pyc,,
diskcache/cli.py,sha256=RVv6Fyn7h_0E5BoAVJzbbjOWPDHXO0ZjNgh9g5CBRP8,44
diskcache/core.py,sha256=oinmHnYCXvR2QXVRaBoqPf8iM79M5pAeixajlaJ9TNs,81867
diskcache/djangocache.py,sha256=SX8jl2d-vfOMG7hXZuuh2VCnZEUP-mHGjYLpM2RdMaQ,16110
diskcache/fanout.py,sha256=E4Gk-puAGsaiqyf45YlLdVTf2RM1g7Qy-TPSug1Elpo,22725
diskcache/persistent.py,sha256=Cir3CPetAfACHlCEzY1P5B_YrZPPeWqsoKrkuBBxcCo,34681
diskcache/recipes.py,sha256=dr6CtZ67nRe3XMUBj2J6D_uftquMi_rNpZBg8i6lfRM,1492212345Wheel-Version: 1.0Generator: bdist_wheel (0.41.2)Root-Is-Purelib: trueTag: py3-none-any
1diskcache1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""DiskCache API Reference=======================
The :doc:`tutorial` provides a helpful walkthrough of most methods."""
from .core import ( DEFAULT_SETTINGS, ENOVAL, EVICTION_POLICY, UNKNOWN, Cache, Disk, EmptyDirWarning, JSONDisk, Timeout, UnknownFileWarning,)from .fanout import FanoutCachefrom .persistent import Deque, Indexfrom .recipes import ( Averager, BoundedSemaphore, Lock, RLock, barrier, memoize_stampede, throttle,)
__all__ = [ 'Averager', 'BoundedSemaphore', 'Cache', 'DEFAULT_SETTINGS', 'Deque', 'Disk', 'ENOVAL', 'EVICTION_POLICY', 'EmptyDirWarning', 'FanoutCache', 'Index', 'JSONDisk', 'Lock', 'RLock', 'Timeout', 'UNKNOWN', 'UnknownFileWarning', 'barrier', 'memoize_stampede', 'throttle',]
try: from .djangocache import DjangoCache # noqa
__all__.append('DjangoCache')except Exception: # pylint: disable=broad-except # pragma: no cover # Django not installed or not setup so ignore. pass
__title__ = 'diskcache'__version__ = '5.6.3'__build__ = 0x050603__author__ = 'Grant Jenks'__license__ = 'Apache 2.0'__copyright__ = 'Copyright 2016-2023 Grant Jenks'1"""Command line interface to disk cache."""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452"""Core disk and file backed cache API."""
import codecsimport contextlib as climport errnoimport functools as ftimport ioimport jsonimport osimport os.path as opimport pickleimport pickletoolsimport sqlite3import structimport tempfileimport threadingimport timeimport warningsimport zlib
def full_name(func): """Return full name of `func` by adding the module and function name.""" return func.__module__ + '.' + func.__qualname__
class Constant(tuple): """Pretty display of immutable constant."""
def __new__(cls, name): return tuple.__new__(cls, (name,))
def __repr__(self): return '%s' % self[0]
DBNAME = 'cache.db'ENOVAL = Constant('ENOVAL')UNKNOWN = Constant('UNKNOWN')
MODE_NONE = 0MODE_RAW = 1MODE_BINARY = 2MODE_TEXT = 3MODE_PICKLE = 4
DEFAULT_SETTINGS = { 'statistics': 0, # False 'tag_index': 0, # False 'eviction_policy': 'least-recently-stored', 'size_limit': 2**30, # 1gb 'cull_limit': 10, 'sqlite_auto_vacuum': 1, # FULL 'sqlite_cache_size': 2**13, # 8,192 pages 'sqlite_journal_mode': 'wal', 'sqlite_mmap_size': 2**26, # 64mb 'sqlite_synchronous': 1, # NORMAL 'disk_min_file_size': 2**15, # 32kb 'disk_pickle_protocol': pickle.HIGHEST_PROTOCOL,}
METADATA = { 'count': 0, 'size': 0, 'hits': 0, 'misses': 0,}
EVICTION_POLICY = { 'none': { 'init': None, 'get': None, 'cull': None, }, 'least-recently-stored': { 'init': ( 'CREATE INDEX IF NOT EXISTS Cache_store_time ON' ' Cache (store_time)' ), 'get': None, 'cull': 'SELECT {fields} FROM Cache ORDER BY store_time LIMIT ?', }, 'least-recently-used': { 'init': ( 'CREATE INDEX IF NOT EXISTS Cache_access_time ON' ' Cache (access_time)' ), 'get': 'access_time = {now}', 'cull': 'SELECT {fields} FROM Cache ORDER BY access_time LIMIT ?', }, 'least-frequently-used': { 'init': ( 'CREATE INDEX IF NOT EXISTS Cache_access_count ON' ' Cache (access_count)' ), 'get': 'access_count = access_count + 1', 'cull': 'SELECT {fields} FROM Cache ORDER BY access_count LIMIT ?', },}
class Disk: """Cache key and value serialization for SQLite database and files."""
def __init__(self, directory, min_file_size=0, pickle_protocol=0): """Initialize disk instance.
:param str directory: directory path :param int min_file_size: minimum size for file use :param int pickle_protocol: pickle protocol for serialization
""" self._directory = directory self.min_file_size = min_file_size self.pickle_protocol = pickle_protocol
def hash(self, key): """Compute portable hash for `key`.
:param key: key to hash :return: hash value
""" mask = 0xFFFFFFFF disk_key, _ = self.put(key) type_disk_key = type(disk_key)
if type_disk_key is sqlite3.Binary: return zlib.adler32(disk_key) & mask elif type_disk_key is str: return zlib.adler32(disk_key.encode('utf-8')) & mask # noqa elif type_disk_key is int: return disk_key % mask else: assert type_disk_key is float return zlib.adler32(struct.pack('!d', disk_key)) & mask
def put(self, key): """Convert `key` to fields key and raw for Cache table.
:param key: key to convert :return: (database key, raw boolean) pair
""" # pylint: disable=unidiomatic-typecheck type_key = type(key)
if type_key is bytes: return sqlite3.Binary(key), True elif ( (type_key is str) or ( type_key is int and -9223372036854775808 <= key <= 9223372036854775807 ) or (type_key is float) ): return key, True else: data = pickle.dumps(key, protocol=self.pickle_protocol) result = pickletools.optimize(data) return sqlite3.Binary(result), False
def get(self, key, raw): """Convert fields `key` and `raw` from Cache table to key.
:param key: database key to convert :param bool raw: flag indicating raw database storage :return: corresponding Python key
""" # pylint: disable=unidiomatic-typecheck if raw: return bytes(key) if type(key) is sqlite3.Binary else key else: return pickle.load(io.BytesIO(key))
def store(self, value, read, key=UNKNOWN): """Convert `value` to fields size, mode, filename, and value for Cache table.
:param value: value to convert :param bool read: True when value is file-like object :param key: key for item (default UNKNOWN) :return: (size, mode, filename, value) tuple for Cache table
""" # pylint: disable=unidiomatic-typecheck type_value = type(value) min_file_size = self.min_file_size
if ( (type_value is str and len(value) < min_file_size) or ( type_value is int and -9223372036854775808 <= value <= 9223372036854775807 ) or (type_value is float) ): return 0, MODE_RAW, None, value elif type_value is bytes: if len(value) < min_file_size: return 0, MODE_RAW, None, sqlite3.Binary(value) else: filename, full_path = self.filename(key, value) self._write(full_path, io.BytesIO(value), 'xb') return len(value), MODE_BINARY, filename, None elif type_value is str: filename, full_path = self.filename(key, value) self._write(full_path, io.StringIO(value), 'x', 'UTF-8') size = op.getsize(full_path) return size, MODE_TEXT, filename, None elif read: reader = ft.partial(value.read, 2**22) filename, full_path = self.filename(key, value) iterator = iter(reader, b'') size = self._write(full_path, iterator, 'xb') return size, MODE_BINARY, filename, None else: result = pickle.dumps(value, protocol=self.pickle_protocol)
if len(result) < min_file_size: return 0, MODE_PICKLE, None, sqlite3.Binary(result) else: filename, full_path = self.filename(key, value) self._write(full_path, io.BytesIO(result), 'xb') return len(result), MODE_PICKLE, filename, None
def _write(self, full_path, iterator, mode, encoding=None): full_dir, _ = op.split(full_path)
for count in range(1, 11): with cl.suppress(OSError): os.makedirs(full_dir)
try: # Another cache may have deleted the directory before # the file could be opened. writer = open(full_path, mode, encoding=encoding) except OSError: if count == 10: # Give up after 10 tries to open the file. raise continue
with writer: size = 0 for chunk in iterator: size += len(chunk) writer.write(chunk) return size
def fetch(self, mode, filename, value, read): """Convert fields `mode`, `filename`, and `value` from Cache table to value.
:param int mode: value mode raw, binary, text, or pickle :param str filename: filename of corresponding value :param value: database value :param bool read: when True, return an open file handle :return: corresponding Python value :raises: IOError if the value cannot be read
""" # pylint: disable=unidiomatic-typecheck,consider-using-with if mode == MODE_RAW: return bytes(value) if type(value) is sqlite3.Binary else value elif mode == MODE_BINARY: if read: return open(op.join(self._directory, filename), 'rb') else: with open(op.join(self._directory, filename), 'rb') as reader: return reader.read() elif mode == MODE_TEXT: full_path = op.join(self._directory, filename) with open(full_path, 'r', encoding='UTF-8') as reader: return reader.read() elif mode == MODE_PICKLE: if value is None: with open(op.join(self._directory, filename), 'rb') as reader: return pickle.load(reader) else: return pickle.load(io.BytesIO(value))
def filename(self, key=UNKNOWN, value=UNKNOWN): """Return filename and full-path tuple for file storage.
Filename will be a randomly generated 28 character hexadecimal string with ".val" suffixed. Two levels of sub-directories will be used to reduce the size of directories. On older filesystems, lookups in directories with many files may be slow.
The default implementation ignores the `key` and `value` parameters.
In some scenarios, for example :meth:`Cache.push <diskcache.Cache.push>`, the `key` or `value` may not be known when the item is stored in the cache.
:param key: key for item (default UNKNOWN) :param value: value for item (default UNKNOWN)
""" # pylint: disable=unused-argument hex_name = codecs.encode(os.urandom(16), 'hex').decode('utf-8') sub_dir = op.join(hex_name[:2], hex_name[2:4]) name = hex_name[4:] + '.val' filename = op.join(sub_dir, name) full_path = op.join(self._directory, filename) return filename, full_path
def remove(self, file_path): """Remove a file given by `file_path`.
This method is cross-thread and cross-process safe. If an OSError occurs, it is suppressed.
:param str file_path: relative path to file
""" full_path = op.join(self._directory, file_path) full_dir, _ = op.split(full_path)
# Suppress OSError that may occur if two caches attempt to delete the # same file or directory at the same time.
with cl.suppress(OSError): os.remove(full_path)
with cl.suppress(OSError): os.removedirs(full_dir)
class JSONDisk(Disk): """Cache key and value using JSON serialization with zlib compression."""
def __init__(self, directory, compress_level=1, **kwargs): """Initialize JSON disk instance.
Keys and values are compressed using the zlib library. The `compress_level` is an integer from 0 to 9 controlling the level of compression; 1 is fastest and produces the least compression, 9 is slowest and produces the most compression, and 0 is no compression.
:param str directory: directory path :param int compress_level: zlib compression level (default 1) :param kwargs: super class arguments
""" self.compress_level = compress_level super().__init__(directory, **kwargs)
def put(self, key): json_bytes = json.dumps(key).encode('utf-8') data = zlib.compress(json_bytes, self.compress_level) return super().put(data)
def get(self, key, raw): data = super().get(key, raw) return json.loads(zlib.decompress(data).decode('utf-8'))
def store(self, value, read, key=UNKNOWN): if not read: json_bytes = json.dumps(value).encode('utf-8') value = zlib.compress(json_bytes, self.compress_level) return super().store(value, read, key=key)
def fetch(self, mode, filename, value, read): data = super().fetch(mode, filename, value, read) if not read: data = json.loads(zlib.decompress(data).decode('utf-8')) return data
class Timeout(Exception): """Database timeout expired."""
class UnknownFileWarning(UserWarning): """Warning used by Cache.check for unknown files."""
class EmptyDirWarning(UserWarning): """Warning used by Cache.check for empty directories."""
def args_to_key(base, args, kwargs, typed, ignore): """Create cache key out of function arguments.
:param tuple base: base of key :param tuple args: function arguments :param dict kwargs: function keyword arguments :param bool typed: include types in cache key :param set ignore: positional or keyword args to ignore :return: cache key tuple
""" args = tuple(arg for index, arg in enumerate(args) if index not in ignore) key = base + args + (None,)
if kwargs: kwargs = {key: val for key, val in kwargs.items() if key not in ignore} sorted_items = sorted(kwargs.items())
for item in sorted_items: key += item
if typed: key += tuple(type(arg) for arg in args)
if kwargs: key += tuple(type(value) for _, value in sorted_items)
return key
class Cache: """Disk and file backed cache."""
def __init__(self, directory=None, timeout=60, disk=Disk, **settings): """Initialize cache instance.
:param str directory: cache directory :param float timeout: SQLite connection timeout :param disk: Disk type or subclass for serialization :param settings: any of DEFAULT_SETTINGS
""" try: assert issubclass(disk, Disk) except (TypeError, AssertionError): raise ValueError('disk must subclass diskcache.Disk') from None
if directory is None: directory = tempfile.mkdtemp(prefix='diskcache-') directory = str(directory) directory = op.expanduser(directory) directory = op.expandvars(directory)
self._directory = directory self._timeout = 0 # Manually handle retries during initialization. self._local = threading.local() self._txn_id = None
if not op.isdir(directory): try: os.makedirs(directory, 0o755) except OSError as error: if error.errno != errno.EEXIST: raise EnvironmentError( error.errno, 'Cache directory "%s" does not exist' ' and could not be created' % self._directory, ) from None
sql = self._sql_retry
# Setup Settings table.
try: current_settings = dict( sql('SELECT key, value FROM Settings').fetchall() ) except sqlite3.OperationalError: current_settings = {}
sets = DEFAULT_SETTINGS.copy() sets.update(current_settings) sets.update(settings)
for key in METADATA: sets.pop(key, None)
# Chance to set pragmas before any tables are created.
for key, value in sorted(sets.items()): if key.startswith('sqlite_'): self.reset(key, value, update=False)
sql( 'CREATE TABLE IF NOT EXISTS Settings (' ' key TEXT NOT NULL UNIQUE,' ' value)' )
# Setup Disk object (must happen after settings initialized).
kwargs = { key[5:]: value for key, value in sets.items() if key.startswith('disk_') } self._disk = disk(directory, **kwargs)
# Set cached attributes: updates settings and sets pragmas.
for key, value in sets.items(): query = 'INSERT OR REPLACE INTO Settings VALUES (?, ?)' sql(query, (key, value)) self.reset(key, value)
for key, value in METADATA.items(): query = 'INSERT OR IGNORE INTO Settings VALUES (?, ?)' sql(query, (key, value)) self.reset(key)
((self._page_size,),) = sql('PRAGMA page_size').fetchall()
# Setup Cache table.
sql( 'CREATE TABLE IF NOT EXISTS Cache (' ' rowid INTEGER PRIMARY KEY,' ' key BLOB,' ' raw INTEGER,' ' store_time REAL,' ' expire_time REAL,' ' access_time REAL,' ' access_count INTEGER DEFAULT 0,' ' tag BLOB,' ' size INTEGER DEFAULT 0,' ' mode INTEGER DEFAULT 0,' ' filename TEXT,' ' value BLOB)' )
sql( 'CREATE UNIQUE INDEX IF NOT EXISTS Cache_key_raw ON' ' Cache(key, raw)' )
sql( 'CREATE INDEX IF NOT EXISTS Cache_expire_time ON' ' Cache (expire_time)' )
query = EVICTION_POLICY[self.eviction_policy]['init']
if query is not None: sql(query)
# Use triggers to keep Metadata updated.
sql( 'CREATE TRIGGER IF NOT EXISTS Settings_count_insert' ' AFTER INSERT ON Cache FOR EACH ROW BEGIN' ' UPDATE Settings SET value = value + 1' ' WHERE key = "count"; END' )
sql( 'CREATE TRIGGER IF NOT EXISTS Settings_count_delete' ' AFTER DELETE ON Cache FOR EACH ROW BEGIN' ' UPDATE Settings SET value = value - 1' ' WHERE key = "count"; END' )
sql( 'CREATE TRIGGER IF NOT EXISTS Settings_size_insert' ' AFTER INSERT ON Cache FOR EACH ROW BEGIN' ' UPDATE Settings SET value = value + NEW.size' ' WHERE key = "size"; END' )
sql( 'CREATE TRIGGER IF NOT EXISTS Settings_size_update' ' AFTER UPDATE ON Cache FOR EACH ROW BEGIN' ' UPDATE Settings' ' SET value = value + NEW.size - OLD.size' ' WHERE key = "size"; END' )
sql( 'CREATE TRIGGER IF NOT EXISTS Settings_size_delete' ' AFTER DELETE ON Cache FOR EACH ROW BEGIN' ' UPDATE Settings SET value = value - OLD.size' ' WHERE key = "size"; END' )
# Create tag index if requested.
if self.tag_index: # pylint: disable=no-member self.create_tag_index() else: self.drop_tag_index()
# Close and re-open database connection with given timeout.
self.close() self._timeout = timeout self._sql # pylint: disable=pointless-statement
@property def directory(self): """Cache directory.""" return self._directory
@property def timeout(self): """SQLite connection timeout value in seconds.""" return self._timeout
@property def disk(self): """Disk used for serialization.""" return self._disk
@property def _con(self): # Check process ID to support process forking. If the process # ID changes, close the connection and update the process ID.
local_pid = getattr(self._local, 'pid', None) pid = os.getpid()
if local_pid != pid: self.close() self._local.pid = pid
con = getattr(self._local, 'con', None)
if con is None: con = self._local.con = sqlite3.connect( op.join(self._directory, DBNAME), timeout=self._timeout, isolation_level=None, )
# Some SQLite pragmas work on a per-connection basis so # query the Settings table and reset the pragmas. The # Settings table may not exist so catch and ignore the # OperationalError that may occur.
try: select = 'SELECT key, value FROM Settings' settings = con.execute(select).fetchall() except sqlite3.OperationalError: pass else: for key, value in settings: if key.startswith('sqlite_'): self.reset(key, value, update=False)
return con
@property def _sql(self): return self._con.execute
@property def _sql_retry(self): sql = self._sql
# 2018-11-01 GrantJ - Some SQLite builds/versions handle # the SQLITE_BUSY return value and connection parameter # "timeout" differently. For a more reliable duration, # manually retry the statement for 60 seconds. Only used # by statements which modify the database and do not use # a transaction (like those in ``__init__`` or ``reset``). # See Issue #85 for and tests/issue_85.py for more details.
def _execute_with_retry(statement, *args, **kwargs): start = time.time() while True: try: return sql(statement, *args, **kwargs) except sqlite3.OperationalError as exc: if str(exc) != 'database is locked': raise diff = time.time() - start if diff > 60: raise time.sleep(0.001)
return _execute_with_retry
@cl.contextmanager def transact(self, retry=False): """Context manager to perform a transaction by locking the cache.
While the cache is locked, no other write operation is permitted. Transactions should therefore be as short as possible. Read and write operations performed in a transaction are atomic. Read operations may occur concurrent to a transaction.
Transactions may be nested and may not be shared between threads.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
>>> cache = Cache() >>> with cache.transact(): # Atomically increment two keys. ... _ = cache.incr('total', 123.4) ... _ = cache.incr('count', 1) >>> with cache.transact(): # Atomically calculate average. ... average = cache['total'] / cache['count'] >>> average 123.4
:param bool retry: retry if database timeout occurs (default False) :return: context manager for use in `with` statement :raises Timeout: if database timeout occurs
""" with self._transact(retry=retry): yield
@cl.contextmanager def _transact(self, retry=False, filename=None): sql = self._sql filenames = [] _disk_remove = self._disk.remove tid = threading.get_ident() txn_id = self._txn_id
if tid == txn_id: begin = False else: while True: try: sql('BEGIN IMMEDIATE') begin = True self._txn_id = tid break except sqlite3.OperationalError: if retry: continue if filename is not None: _disk_remove(filename) raise Timeout from None
try: yield sql, filenames.append except BaseException: if begin: assert self._txn_id == tid self._txn_id = None sql('ROLLBACK') raise else: if begin: assert self._txn_id == tid self._txn_id = None sql('COMMIT') for name in filenames: if name is not None: _disk_remove(name)
def set(self, key, value, expire=None, read=False, tag=None, retry=False): """Set `key` and `value` item in cache.
When `read` is `True`, `value` should be a file-like object opened for reading in binary mode.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
:param key: key for item :param value: value for item :param float expire: seconds until item expires (default None, no expiry) :param bool read: read value as bytes from file (default False) :param str tag: text to associate with key (default None) :param bool retry: retry if database timeout occurs (default False) :return: True if item was set :raises Timeout: if database timeout occurs
""" now = time.time() db_key, raw = self._disk.put(key) expire_time = None if expire is None else now + expire size, mode, filename, db_value = self._disk.store(value, read, key=key) columns = (expire_time, tag, size, mode, filename, db_value)
# The order of SELECT, UPDATE, and INSERT is important below. # # Typical cache usage pattern is: # # value = cache.get(key) # if value is None: # value = expensive_calculation() # cache.set(key, value) # # Cache.get does not evict expired keys to avoid writes during lookups. # Commonly used/expired keys will therefore remain in the cache making # an UPDATE the preferred path. # # The alternative is to assume the key is not present by first trying # to INSERT and then handling the IntegrityError that occurs from # violating the UNIQUE constraint. This optimistic approach was # rejected based on the common cache usage pattern. # # INSERT OR REPLACE aka UPSERT is not used because the old filename may # need cleanup.
with self._transact(retry, filename) as (sql, cleanup): rows = sql( 'SELECT rowid, filename FROM Cache' ' WHERE key = ? AND raw = ?', (db_key, raw), ).fetchall()
if rows: ((rowid, old_filename),) = rows cleanup(old_filename) self._row_update(rowid, now, columns) else: self._row_insert(db_key, raw, now, columns)
self._cull(now, sql, cleanup)
return True
def __setitem__(self, key, value): """Set corresponding `value` for `key` in cache.
:param key: key for item :param value: value for item :return: corresponding value :raises KeyError: if key is not found
""" self.set(key, value, retry=True)
def _row_update(self, rowid, now, columns): sql = self._sql expire_time, tag, size, mode, filename, value = columns sql( 'UPDATE Cache SET' ' store_time = ?,' ' expire_time = ?,' ' access_time = ?,' ' access_count = ?,' ' tag = ?,' ' size = ?,' ' mode = ?,' ' filename = ?,' ' value = ?' ' WHERE rowid = ?', ( now, # store_time expire_time, now, # access_time 0, # access_count tag, size, mode, filename, value, rowid, ), )
def _row_insert(self, key, raw, now, columns): sql = self._sql expire_time, tag, size, mode, filename, value = columns sql( 'INSERT INTO Cache(' ' key, raw, store_time, expire_time, access_time,' ' access_count, tag, size, mode, filename, value' ') VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', ( key, raw, now, # store_time expire_time, now, # access_time 0, # access_count tag, size, mode, filename, value, ), )
def _cull(self, now, sql, cleanup, limit=None): cull_limit = self.cull_limit if limit is None else limit
if cull_limit == 0: return
# Evict expired keys.
select_expired_template = ( 'SELECT %s FROM Cache' ' WHERE expire_time IS NOT NULL AND expire_time < ?' ' ORDER BY expire_time LIMIT ?' )
select_expired = select_expired_template % 'filename' rows = sql(select_expired, (now, cull_limit)).fetchall()
if rows: delete_expired = 'DELETE FROM Cache WHERE rowid IN (%s)' % ( select_expired_template % 'rowid' ) sql(delete_expired, (now, cull_limit))
for (filename,) in rows: cleanup(filename)
cull_limit -= len(rows)
if cull_limit == 0: return
# Evict keys by policy.
select_policy = EVICTION_POLICY[self.eviction_policy]['cull']
if select_policy is None or self.volume() < self.size_limit: return
select_filename = select_policy.format(fields='filename', now=now) rows = sql(select_filename, (cull_limit,)).fetchall()
if rows: delete = 'DELETE FROM Cache WHERE rowid IN (%s)' % ( select_policy.format(fields='rowid', now=now) ) sql(delete, (cull_limit,))
for (filename,) in rows: cleanup(filename)
def touch(self, key, expire=None, retry=False): """Touch `key` in cache and update `expire` time.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
:param key: key for item :param float expire: seconds until item expires (default None, no expiry) :param bool retry: retry if database timeout occurs (default False) :return: True if key was touched :raises Timeout: if database timeout occurs
""" now = time.time() db_key, raw = self._disk.put(key) expire_time = None if expire is None else now + expire
with self._transact(retry) as (sql, _): rows = sql( 'SELECT rowid, expire_time FROM Cache' ' WHERE key = ? AND raw = ?', (db_key, raw), ).fetchall()
if rows: ((rowid, old_expire_time),) = rows
if old_expire_time is None or old_expire_time > now: sql( 'UPDATE Cache SET expire_time = ? WHERE rowid = ?', (expire_time, rowid), ) return True
return False
def add(self, key, value, expire=None, read=False, tag=None, retry=False): """Add `key` and `value` item to cache.
Similar to `set`, but only add to cache if key not present.
Operation is atomic. Only one concurrent add operation for a given key will succeed.
When `read` is `True`, `value` should be a file-like object opened for reading in binary mode.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
:param key: key for item :param value: value for item :param float expire: seconds until the key expires (default None, no expiry) :param bool read: read value as bytes from file (default False) :param str tag: text to associate with key (default None) :param bool retry: retry if database timeout occurs (default False) :return: True if item was added :raises Timeout: if database timeout occurs
""" now = time.time() db_key, raw = self._disk.put(key) expire_time = None if expire is None else now + expire size, mode, filename, db_value = self._disk.store(value, read, key=key) columns = (expire_time, tag, size, mode, filename, db_value)
with self._transact(retry, filename) as (sql, cleanup): rows = sql( 'SELECT rowid, filename, expire_time FROM Cache' ' WHERE key = ? AND raw = ?', (db_key, raw), ).fetchall()
if rows: ((rowid, old_filename, old_expire_time),) = rows
if old_expire_time is None or old_expire_time > now: cleanup(filename) return False
cleanup(old_filename) self._row_update(rowid, now, columns) else: self._row_insert(db_key, raw, now, columns)
self._cull(now, sql, cleanup)
return True
def incr(self, key, delta=1, default=0, retry=False): """Increment value by delta for item with key.
If key is missing and default is None then raise KeyError. Else if key is missing and default is not None then use default for value.
Operation is atomic. All concurrent increment operations will be counted individually.
Assumes value may be stored in a SQLite column. Most builds that target machines with 64-bit pointer widths will support 64-bit signed integers.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
:param key: key for item :param int delta: amount to increment (default 1) :param int default: value if key is missing (default 0) :param bool retry: retry if database timeout occurs (default False) :return: new value for item :raises KeyError: if key is not found and default is None :raises Timeout: if database timeout occurs
""" now = time.time() db_key, raw = self._disk.put(key) select = ( 'SELECT rowid, expire_time, filename, value FROM Cache' ' WHERE key = ? AND raw = ?' )
with self._transact(retry) as (sql, cleanup): rows = sql(select, (db_key, raw)).fetchall()
if not rows: if default is None: raise KeyError(key)
value = default + delta columns = (None, None) + self._disk.store( value, False, key=key ) self._row_insert(db_key, raw, now, columns) self._cull(now, sql, cleanup) return value
((rowid, expire_time, filename, value),) = rows
if expire_time is not None and expire_time < now: if default is None: raise KeyError(key)
value = default + delta columns = (None, None) + self._disk.store( value, False, key=key ) self._row_update(rowid, now, columns) self._cull(now, sql, cleanup) cleanup(filename) return value
value += delta
columns = 'store_time = ?, value = ?' update_column = EVICTION_POLICY[self.eviction_policy]['get']
if update_column is not None: columns += ', ' + update_column.format(now=now)
update = 'UPDATE Cache SET %s WHERE rowid = ?' % columns sql(update, (now, value, rowid))
return value
def decr(self, key, delta=1, default=0, retry=False): """Decrement value by delta for item with key.
If key is missing and default is None then raise KeyError. Else if key is missing and default is not None then use default for value.
Operation is atomic. All concurrent decrement operations will be counted individually.
Unlike Memcached, negative values are supported. Value may be decremented below zero.
Assumes value may be stored in a SQLite column. Most builds that target machines with 64-bit pointer widths will support 64-bit signed integers.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
:param key: key for item :param int delta: amount to decrement (default 1) :param int default: value if key is missing (default 0) :param bool retry: retry if database timeout occurs (default False) :return: new value for item :raises KeyError: if key is not found and default is None :raises Timeout: if database timeout occurs
""" return self.incr(key, -delta, default, retry)
def get( self, key, default=None, read=False, expire_time=False, tag=False, retry=False, ): """Retrieve value from cache. If `key` is missing, return `default`.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
:param key: key for item :param default: value to return if key is missing (default None) :param bool read: if True, return file handle to value (default False) :param bool expire_time: if True, return expire_time in tuple (default False) :param bool tag: if True, return tag in tuple (default False) :param bool retry: retry if database timeout occurs (default False) :return: value for item or default if key not found :raises Timeout: if database timeout occurs
""" db_key, raw = self._disk.put(key) update_column = EVICTION_POLICY[self.eviction_policy]['get'] select = ( 'SELECT rowid, expire_time, tag, mode, filename, value' ' FROM Cache WHERE key = ? AND raw = ?' ' AND (expire_time IS NULL OR expire_time > ?)' )
if expire_time and tag: default = (default, None, None) elif expire_time or tag: default = (default, None)
if not self.statistics and update_column is None: # Fast path, no transaction necessary.
rows = self._sql(select, (db_key, raw, time.time())).fetchall()
if not rows: return default
((rowid, db_expire_time, db_tag, mode, filename, db_value),) = rows
try: value = self._disk.fetch(mode, filename, db_value, read) except IOError: # Key was deleted before we could retrieve result. return default
else: # Slow path, transaction required. cache_hit = ( 'UPDATE Settings SET value = value + 1 WHERE key = "hits"' ) cache_miss = ( 'UPDATE Settings SET value = value + 1 WHERE key = "misses"' )
with self._transact(retry) as (sql, _): rows = sql(select, (db_key, raw, time.time())).fetchall()
if not rows: if self.statistics: sql(cache_miss) return default
( (rowid, db_expire_time, db_tag, mode, filename, db_value), ) = rows # noqa: E127
try: value = self._disk.fetch(mode, filename, db_value, read) except IOError: # Key was deleted before we could retrieve result. if self.statistics: sql(cache_miss) return default
if self.statistics: sql(cache_hit)
now = time.time() update = 'UPDATE Cache SET %s WHERE rowid = ?'
if update_column is not None: sql(update % update_column.format(now=now), (rowid,))
if expire_time and tag: return (value, db_expire_time, db_tag) elif expire_time: return (value, db_expire_time) elif tag: return (value, db_tag) else: return value
def __getitem__(self, key): """Return corresponding value for `key` from cache.
:param key: key matching item :return: corresponding value :raises KeyError: if key is not found
""" value = self.get(key, default=ENOVAL, retry=True) if value is ENOVAL: raise KeyError(key) return value
def read(self, key, retry=False): """Return file handle value corresponding to `key` from cache.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
:param key: key matching item :param bool retry: retry if database timeout occurs (default False) :return: file open for reading in binary mode :raises KeyError: if key is not found :raises Timeout: if database timeout occurs
""" handle = self.get(key, default=ENOVAL, read=True, retry=retry) if handle is ENOVAL: raise KeyError(key) return handle
def __contains__(self, key): """Return `True` if `key` matching item is found in cache.
:param key: key matching item :return: True if key matching item
""" sql = self._sql db_key, raw = self._disk.put(key) select = ( 'SELECT rowid FROM Cache' ' WHERE key = ? AND raw = ?' ' AND (expire_time IS NULL OR expire_time > ?)' )
rows = sql(select, (db_key, raw, time.time())).fetchall()
return bool(rows)
def pop( self, key, default=None, expire_time=False, tag=False, retry=False ): # noqa: E501 """Remove corresponding item for `key` from cache and return value.
If `key` is missing, return `default`.
Operation is atomic. Concurrent operations will be serialized.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
:param key: key for item :param default: value to return if key is missing (default None) :param bool expire_time: if True, return expire_time in tuple (default False) :param bool tag: if True, return tag in tuple (default False) :param bool retry: retry if database timeout occurs (default False) :return: value for item or default if key not found :raises Timeout: if database timeout occurs
""" db_key, raw = self._disk.put(key) select = ( 'SELECT rowid, expire_time, tag, mode, filename, value' ' FROM Cache WHERE key = ? AND raw = ?' ' AND (expire_time IS NULL OR expire_time > ?)' )
if expire_time and tag: default = default, None, None elif expire_time or tag: default = default, None
with self._transact(retry) as (sql, _): rows = sql(select, (db_key, raw, time.time())).fetchall()
if not rows: return default
((rowid, db_expire_time, db_tag, mode, filename, db_value),) = rows
sql('DELETE FROM Cache WHERE rowid = ?', (rowid,))
try: value = self._disk.fetch(mode, filename, db_value, False) except IOError: # Key was deleted before we could retrieve result. return default finally: if filename is not None: self._disk.remove(filename)
if expire_time and tag: return value, db_expire_time, db_tag elif expire_time: return value, db_expire_time elif tag: return value, db_tag else: return value
def __delitem__(self, key, retry=True): """Delete corresponding item for `key` from cache.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default `True`).
:param key: key matching item :param bool retry: retry if database timeout occurs (default True) :raises KeyError: if key is not found :raises Timeout: if database timeout occurs
""" db_key, raw = self._disk.put(key)
with self._transact(retry) as (sql, cleanup): rows = sql( 'SELECT rowid, filename FROM Cache' ' WHERE key = ? AND raw = ?' ' AND (expire_time IS NULL OR expire_time > ?)', (db_key, raw, time.time()), ).fetchall()
if not rows: raise KeyError(key)
((rowid, filename),) = rows sql('DELETE FROM Cache WHERE rowid = ?', (rowid,)) cleanup(filename)
return True
def delete(self, key, retry=False): """Delete corresponding item for `key` from cache.
Missing keys are ignored.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
:param key: key matching item :param bool retry: retry if database timeout occurs (default False) :return: True if item was deleted :raises Timeout: if database timeout occurs
""" # pylint: disable=unnecessary-dunder-call try: return self.__delitem__(key, retry=retry) except KeyError: return False
def push( self, value, prefix=None, side='back', expire=None, read=False, tag=None, retry=False, ): """Push `value` onto `side` of queue identified by `prefix` in cache.
When prefix is None, integer keys are used. Otherwise, string keys are used in the format "prefix-integer". Integer starts at 500 trillion.
Defaults to pushing value on back of queue. Set side to 'front' to push value on front of queue. Side must be one of 'back' or 'front'.
Operation is atomic. Concurrent operations will be serialized.
When `read` is `True`, `value` should be a file-like object opened for reading in binary mode.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
See also `Cache.pull`.
>>> cache = Cache() >>> print(cache.push('first value')) 500000000000000 >>> cache.get(500000000000000) 'first value' >>> print(cache.push('second value')) 500000000000001 >>> print(cache.push('third value', side='front')) 499999999999999 >>> cache.push(1234, prefix='userids') 'userids-500000000000000'
:param value: value for item :param str prefix: key prefix (default None, key is integer) :param str side: either 'back' or 'front' (default 'back') :param float expire: seconds until the key expires (default None, no expiry) :param bool read: read value as bytes from file (default False) :param str tag: text to associate with key (default None) :param bool retry: retry if database timeout occurs (default False) :return: key for item in cache :raises Timeout: if database timeout occurs
""" if prefix is None: min_key = 0 max_key = 999999999999999 else: min_key = prefix + '-000000000000000' max_key = prefix + '-999999999999999'
now = time.time() raw = True expire_time = None if expire is None else now + expire size, mode, filename, db_value = self._disk.store(value, read) columns = (expire_time, tag, size, mode, filename, db_value) order = {'back': 'DESC', 'front': 'ASC'} select = ( 'SELECT key FROM Cache' ' WHERE ? < key AND key < ? AND raw = ?' ' ORDER BY key %s LIMIT 1' ) % order[side]
with self._transact(retry, filename) as (sql, cleanup): rows = sql(select, (min_key, max_key, raw)).fetchall()
if rows: ((key,),) = rows
if prefix is not None: num = int(key[(key.rfind('-') + 1) :]) else: num = key
if side == 'back': num += 1 else: assert side == 'front' num -= 1 else: num = 500000000000000
if prefix is not None: db_key = '{0}-{1:015d}'.format(prefix, num) else: db_key = num
self._row_insert(db_key, raw, now, columns) self._cull(now, sql, cleanup)
return db_key
def pull( self, prefix=None, default=(None, None), side='front', expire_time=False, tag=False, retry=False, ): """Pull key and value item pair from `side` of queue in cache.
When prefix is None, integer keys are used. Otherwise, string keys are used in the format "prefix-integer". Integer starts at 500 trillion.
If queue is empty, return default.
Defaults to pulling key and value item pairs from front of queue. Set side to 'back' to pull from back of queue. Side must be one of 'front' or 'back'.
Operation is atomic. Concurrent operations will be serialized.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
See also `Cache.push` and `Cache.get`.
>>> cache = Cache() >>> cache.pull() (None, None) >>> for letter in 'abc': ... print(cache.push(letter)) 500000000000000 500000000000001 500000000000002 >>> key, value = cache.pull() >>> print(key) 500000000000000 >>> value 'a' >>> _, value = cache.pull(side='back') >>> value 'c' >>> cache.push(1234, 'userids') 'userids-500000000000000' >>> _, value = cache.pull('userids') >>> value 1234
:param str prefix: key prefix (default None, key is integer) :param default: value to return if key is missing (default (None, None)) :param str side: either 'front' or 'back' (default 'front') :param bool expire_time: if True, return expire_time in tuple (default False) :param bool tag: if True, return tag in tuple (default False) :param bool retry: retry if database timeout occurs (default False) :return: key and value item pair or default if queue is empty :raises Timeout: if database timeout occurs
""" # Caution: Nearly identical code exists in Cache.peek if prefix is None: min_key = 0 max_key = 999999999999999 else: min_key = prefix + '-000000000000000' max_key = prefix + '-999999999999999'
order = {'front': 'ASC', 'back': 'DESC'} select = ( 'SELECT rowid, key, expire_time, tag, mode, filename, value' ' FROM Cache WHERE ? < key AND key < ? AND raw = 1' ' ORDER BY key %s LIMIT 1' ) % order[side]
if expire_time and tag: default = default, None, None elif expire_time or tag: default = default, None
while True: while True: with self._transact(retry) as (sql, cleanup): rows = sql(select, (min_key, max_key)).fetchall()
if not rows: return default
( (rowid, key, db_expire, db_tag, mode, name, db_value), ) = rows
sql('DELETE FROM Cache WHERE rowid = ?', (rowid,))
if db_expire is not None and db_expire < time.time(): cleanup(name) else: break
try: value = self._disk.fetch(mode, name, db_value, False) except IOError: # Key was deleted before we could retrieve result. continue finally: if name is not None: self._disk.remove(name) break
if expire_time and tag: return (key, value), db_expire, db_tag elif expire_time: return (key, value), db_expire elif tag: return (key, value), db_tag else: return key, value
def peek( self, prefix=None, default=(None, None), side='front', expire_time=False, tag=False, retry=False, ): """Peek at key and value item pair from `side` of queue in cache.
When prefix is None, integer keys are used. Otherwise, string keys are used in the format "prefix-integer". Integer starts at 500 trillion.
If queue is empty, return default.
Defaults to peeking at key and value item pairs from front of queue. Set side to 'back' to pull from back of queue. Side must be one of 'front' or 'back'.
Expired items are deleted from cache. Operation is atomic. Concurrent operations will be serialized.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
See also `Cache.pull` and `Cache.push`.
>>> cache = Cache() >>> for letter in 'abc': ... print(cache.push(letter)) 500000000000000 500000000000001 500000000000002 >>> key, value = cache.peek() >>> print(key) 500000000000000 >>> value 'a' >>> key, value = cache.peek(side='back') >>> print(key) 500000000000002 >>> value 'c'
:param str prefix: key prefix (default None, key is integer) :param default: value to return if key is missing (default (None, None)) :param str side: either 'front' or 'back' (default 'front') :param bool expire_time: if True, return expire_time in tuple (default False) :param bool tag: if True, return tag in tuple (default False) :param bool retry: retry if database timeout occurs (default False) :return: key and value item pair or default if queue is empty :raises Timeout: if database timeout occurs
""" # Caution: Nearly identical code exists in Cache.pull if prefix is None: min_key = 0 max_key = 999999999999999 else: min_key = prefix + '-000000000000000' max_key = prefix + '-999999999999999'
order = {'front': 'ASC', 'back': 'DESC'} select = ( 'SELECT rowid, key, expire_time, tag, mode, filename, value' ' FROM Cache WHERE ? < key AND key < ? AND raw = 1' ' ORDER BY key %s LIMIT 1' ) % order[side]
if expire_time and tag: default = default, None, None elif expire_time or tag: default = default, None
while True: while True: with self._transact(retry) as (sql, cleanup): rows = sql(select, (min_key, max_key)).fetchall()
if not rows: return default
( (rowid, key, db_expire, db_tag, mode, name, db_value), ) = rows
if db_expire is not None and db_expire < time.time(): sql('DELETE FROM Cache WHERE rowid = ?', (rowid,)) cleanup(name) else: break
try: value = self._disk.fetch(mode, name, db_value, False) except IOError: # Key was deleted before we could retrieve result. continue break
if expire_time and tag: return (key, value), db_expire, db_tag elif expire_time: return (key, value), db_expire elif tag: return (key, value), db_tag else: return key, value
def peekitem(self, last=True, expire_time=False, tag=False, retry=False): """Peek at key and value item pair in cache based on iteration order.
Expired items are deleted from cache. Operation is atomic. Concurrent operations will be serialized.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
>>> cache = Cache() >>> for num, letter in enumerate('abc'): ... cache[letter] = num >>> cache.peekitem() ('c', 2) >>> cache.peekitem(last=False) ('a', 0)
:param bool last: last item in iteration order (default True) :param bool expire_time: if True, return expire_time in tuple (default False) :param bool tag: if True, return tag in tuple (default False) :param bool retry: retry if database timeout occurs (default False) :return: key and value item pair :raises KeyError: if cache is empty :raises Timeout: if database timeout occurs
""" order = ('ASC', 'DESC') select = ( 'SELECT rowid, key, raw, expire_time, tag, mode, filename, value' ' FROM Cache ORDER BY rowid %s LIMIT 1' ) % order[last]
while True: while True: with self._transact(retry) as (sql, cleanup): rows = sql(select).fetchall()
if not rows: raise KeyError('dictionary is empty')
( ( rowid, db_key, raw, db_expire, db_tag, mode, name, db_value, ), ) = rows
if db_expire is not None and db_expire < time.time(): sql('DELETE FROM Cache WHERE rowid = ?', (rowid,)) cleanup(name) else: break
key = self._disk.get(db_key, raw)
try: value = self._disk.fetch(mode, name, db_value, False) except IOError: # Key was deleted before we could retrieve result. continue break
if expire_time and tag: return (key, value), db_expire, db_tag elif expire_time: return (key, value), db_expire elif tag: return (key, value), db_tag else: return key, value
def memoize( self, name=None, typed=False, expire=None, tag=None, ignore=() ): """Memoizing cache decorator.
Decorator to wrap callable with memoizing function using cache. Repeated calls with the same arguments will lookup result in cache and avoid function evaluation.
If name is set to None (default), the callable name will be determined automatically.
When expire is set to zero, function results will not be set in the cache. Cache lookups still occur, however. Read :doc:`case-study-landing-page-caching` for example usage.
If typed is set to True, function arguments of different types will be cached separately. For example, f(3) and f(3.0) will be treated as distinct calls with distinct results.
The original underlying function is accessible through the __wrapped__ attribute. This is useful for introspection, for bypassing the cache, or for rewrapping the function with a different cache.
>>> from diskcache import Cache >>> cache = Cache() >>> @cache.memoize(expire=1, tag='fib') ... def fibonacci(number): ... if number == 0: ... return 0 ... elif number == 1: ... return 1 ... else: ... return fibonacci(number - 1) + fibonacci(number - 2) >>> print(fibonacci(100)) 354224848179261915075
An additional `__cache_key__` attribute can be used to generate the cache key used for the given arguments.
>>> key = fibonacci.__cache_key__(100) >>> print(cache[key]) 354224848179261915075
Remember to call memoize when decorating a callable. If you forget, then a TypeError will occur. Note the lack of parenthenses after memoize below:
>>> @cache.memoize ... def test(): ... pass Traceback (most recent call last): ... TypeError: name cannot be callable
:param cache: cache to store callable arguments and return values :param str name: name given for callable (default None, automatic) :param bool typed: cache different types separately (default False) :param float expire: seconds until arguments expire (default None, no expiry) :param str tag: text to associate with arguments (default None) :param set ignore: positional or keyword args to ignore (default ()) :return: callable decorator
""" # Caution: Nearly identical code exists in DjangoCache.memoize if callable(name): raise TypeError('name cannot be callable')
def decorator(func): """Decorator created by memoize() for callable `func`.""" base = (full_name(func),) if name is None else (name,)
@ft.wraps(func) def wrapper(*args, **kwargs): """Wrapper for callable to cache arguments and return values.""" key = wrapper.__cache_key__(*args, **kwargs) result = self.get(key, default=ENOVAL, retry=True)
if result is ENOVAL: result = func(*args, **kwargs) if expire is None or expire > 0: self.set(key, result, expire, tag=tag, retry=True)
return result
def __cache_key__(*args, **kwargs): """Make key for cache given function arguments.""" return args_to_key(base, args, kwargs, typed, ignore)
wrapper.__cache_key__ = __cache_key__ return wrapper
return decorator
def check(self, fix=False, retry=False): """Check database and file system consistency.
Intended for use in testing and post-mortem error analysis.
While checking the Cache table for consistency, a writer lock is held on the database. The lock blocks other cache clients from writing to the database. For caches with many file references, the lock may be held for a long time. For example, local benchmarking shows that a cache with 1,000 file references takes ~60ms to check.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
:param bool fix: correct inconsistencies :param bool retry: retry if database timeout occurs (default False) :return: list of warnings :raises Timeout: if database timeout occurs
""" # pylint: disable=access-member-before-definition,W0201 with warnings.catch_warnings(record=True) as warns: sql = self._sql
# Check integrity of database.
rows = sql('PRAGMA integrity_check').fetchall()
if len(rows) != 1 or rows[0][0] != 'ok': for (message,) in rows: warnings.warn(message)
if fix: sql('VACUUM')
with self._transact(retry) as (sql, _):
# Check Cache.filename against file system.
filenames = set() select = ( 'SELECT rowid, size, filename FROM Cache' ' WHERE filename IS NOT NULL' )
rows = sql(select).fetchall()
for rowid, size, filename in rows: full_path = op.join(self._directory, filename) filenames.add(full_path)
if op.exists(full_path): real_size = op.getsize(full_path)
if size != real_size: message = 'wrong file size: %s, %d != %d' args = full_path, real_size, size warnings.warn(message % args)
if fix: sql( 'UPDATE Cache SET size = ?' ' WHERE rowid = ?', (real_size, rowid), )
continue
warnings.warn('file not found: %s' % full_path)
if fix: sql('DELETE FROM Cache WHERE rowid = ?', (rowid,))
# Check file system against Cache.filename.
for dirpath, _, files in os.walk(self._directory): paths = [op.join(dirpath, filename) for filename in files] error = set(paths) - filenames
for full_path in error: if DBNAME in full_path: continue
message = 'unknown file: %s' % full_path warnings.warn(message, UnknownFileWarning)
if fix: os.remove(full_path)
# Check for empty directories.
for dirpath, dirs, files in os.walk(self._directory): if not (dirs or files): message = 'empty directory: %s' % dirpath warnings.warn(message, EmptyDirWarning)
if fix: os.rmdir(dirpath)
# Check Settings.count against count of Cache rows.
self.reset('count') ((count,),) = sql('SELECT COUNT(key) FROM Cache').fetchall()
if self.count != count: message = 'Settings.count != COUNT(Cache.key); %d != %d' warnings.warn(message % (self.count, count))
if fix: sql( 'UPDATE Settings SET value = ? WHERE key = ?', (count, 'count'), )
# Check Settings.size against sum of Cache.size column.
self.reset('size') select_size = 'SELECT COALESCE(SUM(size), 0) FROM Cache' ((size,),) = sql(select_size).fetchall()
if self.size != size: message = 'Settings.size != SUM(Cache.size); %d != %d' warnings.warn(message % (self.size, size))
if fix: sql( 'UPDATE Settings SET value = ? WHERE key =?', (size, 'size'), )
return warns
def create_tag_index(self): """Create tag index on cache database.
It is better to initialize cache with `tag_index=True` than use this.
:raises Timeout: if database timeout occurs
""" sql = self._sql sql('CREATE INDEX IF NOT EXISTS Cache_tag_rowid ON Cache(tag, rowid)') self.reset('tag_index', 1)
def drop_tag_index(self): """Drop tag index on cache database.
:raises Timeout: if database timeout occurs
""" sql = self._sql sql('DROP INDEX IF EXISTS Cache_tag_rowid') self.reset('tag_index', 0)
def evict(self, tag, retry=False): """Remove items with matching `tag` from cache.
Removing items is an iterative process. In each iteration, a subset of items is removed. Concurrent writes may occur between iterations.
If a :exc:`Timeout` occurs, the first element of the exception's `args` attribute will be the number of items removed before the exception occurred.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
:param str tag: tag identifying items :param bool retry: retry if database timeout occurs (default False) :return: count of rows removed :raises Timeout: if database timeout occurs
""" select = ( 'SELECT rowid, filename FROM Cache' ' WHERE tag = ? AND rowid > ?' ' ORDER BY rowid LIMIT ?' ) args = [tag, 0, 100] return self._select_delete(select, args, arg_index=1, retry=retry)
def expire(self, now=None, retry=False): """Remove expired items from cache.
Removing items is an iterative process. In each iteration, a subset of items is removed. Concurrent writes may occur between iterations.
If a :exc:`Timeout` occurs, the first element of the exception's `args` attribute will be the number of items removed before the exception occurred.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
:param float now: current time (default None, ``time.time()`` used) :param bool retry: retry if database timeout occurs (default False) :return: count of items removed :raises Timeout: if database timeout occurs
""" select = ( 'SELECT rowid, expire_time, filename FROM Cache' ' WHERE ? < expire_time AND expire_time < ?' ' ORDER BY expire_time LIMIT ?' ) args = [0, now or time.time(), 100] return self._select_delete(select, args, row_index=1, retry=retry)
def cull(self, retry=False): """Cull items from cache until volume is less than size limit.
Removing items is an iterative process. In each iteration, a subset of items is removed. Concurrent writes may occur between iterations.
If a :exc:`Timeout` occurs, the first element of the exception's `args` attribute will be the number of items removed before the exception occurred.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
:param bool retry: retry if database timeout occurs (default False) :return: count of items removed :raises Timeout: if database timeout occurs
""" now = time.time()
# Remove expired items.
count = self.expire(now)
# Remove items by policy.
select_policy = EVICTION_POLICY[self.eviction_policy]['cull']
if select_policy is None: return 0
select_filename = select_policy.format(fields='filename', now=now)
try: while self.volume() > self.size_limit: with self._transact(retry) as (sql, cleanup): rows = sql(select_filename, (10,)).fetchall()
if not rows: break
count += len(rows) delete = ( 'DELETE FROM Cache WHERE rowid IN (%s)' % select_policy.format(fields='rowid', now=now) ) sql(delete, (10,))
for (filename,) in rows: cleanup(filename) except Timeout: raise Timeout(count) from None
return count
def clear(self, retry=False): """Remove all items from cache.
Removing items is an iterative process. In each iteration, a subset of items is removed. Concurrent writes may occur between iterations.
If a :exc:`Timeout` occurs, the first element of the exception's `args` attribute will be the number of items removed before the exception occurred.
Raises :exc:`Timeout` error when database timeout occurs and `retry` is `False` (default).
:param bool retry: retry if database timeout occurs (default False) :return: count of rows removed :raises Timeout: if database timeout occurs
""" select = ( 'SELECT rowid, filename FROM Cache' ' WHERE rowid > ?' ' ORDER BY rowid LIMIT ?' ) args = [0, 100] return self._select_delete(select, args, retry=retry)
def _select_delete( self, select, args, row_index=0, arg_index=0, retry=False ): count = 0 delete = 'DELETE FROM Cache WHERE rowid IN (%s)'
try: while True: with self._transact(retry) as (sql, cleanup): rows = sql(select, args).fetchall()
if not rows: break
count += len(rows) sql(delete % ','.join(str(row[0]) for row in rows))
for row in rows: args[arg_index] = row[row_index] cleanup(row[-1])
except Timeout: raise Timeout(count) from None
return count
def iterkeys(self, reverse=False): """Iterate Cache keys in database sort order.
>>> cache = Cache() >>> for key in [4, 1, 3, 0, 2]: ... cache[key] = key >>> list(cache.iterkeys()) [0, 1, 2, 3, 4] >>> list(cache.iterkeys(reverse=True)) [4, 3, 2, 1, 0]
:param bool reverse: reverse sort order (default False) :return: iterator of Cache keys
""" sql = self._sql limit = 100 _disk_get = self._disk.get
if reverse: select = ( 'SELECT key, raw FROM Cache' ' ORDER BY key DESC, raw DESC LIMIT 1' ) iterate = ( 'SELECT key, raw FROM Cache' ' WHERE key = ? AND raw < ? OR key < ?' ' ORDER BY key DESC, raw DESC LIMIT ?' ) else: select = ( 'SELECT key, raw FROM Cache' ' ORDER BY key ASC, raw ASC LIMIT 1' ) iterate = ( 'SELECT key, raw FROM Cache' ' WHERE key = ? AND raw > ? OR key > ?' ' ORDER BY key ASC, raw ASC LIMIT ?' )
row = sql(select).fetchall()
if row: ((key, raw),) = row else: return
yield _disk_get(key, raw)
while True: rows = sql(iterate, (key, raw, key, limit)).fetchall()
if not rows: break
for key, raw in rows: yield _disk_get(key, raw)
def _iter(self, ascending=True): sql = self._sql rows = sql('SELECT MAX(rowid) FROM Cache').fetchall() ((max_rowid,),) = rows yield # Signal ready.
if max_rowid is None: return
bound = max_rowid + 1 limit = 100 _disk_get = self._disk.get rowid = 0 if ascending else bound select = ( 'SELECT rowid, key, raw FROM Cache' ' WHERE ? < rowid AND rowid < ?' ' ORDER BY rowid %s LIMIT ?' ) % ('ASC' if ascending else 'DESC')
while True: if ascending: args = (rowid, bound, limit) else: args = (0, rowid, limit)
rows = sql(select, args).fetchall()
if not rows: break
for rowid, key, raw in rows: yield _disk_get(key, raw)
def __iter__(self): """Iterate keys in cache including expired items.""" iterator = self._iter() next(iterator) return iterator
def __reversed__(self): """Reverse iterate keys in cache including expired items.""" iterator = self._iter(ascending=False) next(iterator) return iterator
def stats(self, enable=True, reset=False): """Return cache statistics hits and misses.
:param bool enable: enable collecting statistics (default True) :param bool reset: reset hits and misses to 0 (default False) :return: (hits, misses)
""" # pylint: disable=E0203,W0201 result = (self.reset('hits'), self.reset('misses'))
if reset: self.reset('hits', 0) self.reset('misses', 0)
self.reset('statistics', enable)
return result
def volume(self): """Return estimated total size of cache on disk.
:return: size in bytes
""" ((page_count,),) = self._sql('PRAGMA page_count').fetchall() total_size = self._page_size * page_count + self.reset('size') return total_size
def close(self): """Close database connection.""" con = getattr(self._local, 'con', None)
if con is None: return
con.close()
try: delattr(self._local, 'con') except AttributeError: pass
def __enter__(self): # Create connection in thread. # pylint: disable=unused-variable connection = self._con # noqa return self
def __exit__(self, *exception): self.close()
def __len__(self): """Count of items in cache including expired items.""" return self.reset('count')
def __getstate__(self): return (self.directory, self.timeout, type(self.disk))
def __setstate__(self, state): self.__init__(*state)
def reset(self, key, value=ENOVAL, update=True): """Reset `key` and `value` item from Settings table.
Use `reset` to update the value of Cache settings correctly. Cache settings are stored in the Settings table of the SQLite database. If `update` is ``False`` then no attempt is made to update the database.
If `value` is not given, it is reloaded from the Settings table. Otherwise, the Settings table is updated.
Settings with the ``disk_`` prefix correspond to Disk attributes. Updating the value will change the unprefixed attribute on the associated Disk instance.
Settings with the ``sqlite_`` prefix correspond to SQLite pragmas. Updating the value will execute the corresponding PRAGMA statement.
SQLite PRAGMA statements may be executed before the Settings table exists in the database by setting `update` to ``False``.
:param str key: Settings key for item :param value: value for item (optional) :param bool update: update database Settings table (default True) :return: updated value for item :raises Timeout: if database timeout occurs
""" sql = self._sql sql_retry = self._sql_retry
if value is ENOVAL: select = 'SELECT value FROM Settings WHERE key = ?' ((value,),) = sql_retry(select, (key,)).fetchall() setattr(self, key, value) return value
if update: statement = 'UPDATE Settings SET value = ? WHERE key = ?' sql_retry(statement, (value, key))
if key.startswith('sqlite_'): pragma = key[7:]
# 2016-02-17 GrantJ - PRAGMA and isolation_level=None # don't always play nicely together. Retry setting the # PRAGMA. I think some PRAGMA statements expect to # immediately take an EXCLUSIVE lock on the database. I # can't find any documentation for this but without the # retry, stress will intermittently fail with multiple # processes.
# 2018-11-05 GrantJ - Avoid setting pragma values that # are already set. Pragma settings like auto_vacuum and # journal_mode can take a long time or may not work after # tables have been created.
start = time.time() while True: try: try: ((old_value,),) = sql( 'PRAGMA %s' % (pragma) ).fetchall() update = old_value != value except ValueError: update = True if update: sql('PRAGMA %s = %s' % (pragma, value)).fetchall() break except sqlite3.OperationalError as exc: if str(exc) != 'database is locked': raise diff = time.time() - start if diff > 60: raise time.sleep(0.001) elif key.startswith('disk_'): attr = key[5:] setattr(self._disk, attr, value)
setattr(self, key, value) return value123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456"""Django-compatible disk and file backed cache."""
from functools import wraps
from django.core.cache.backends.base import BaseCache
try: from django.core.cache.backends.base import DEFAULT_TIMEOUTexcept ImportError: # pragma: no cover # For older versions of Django simply use 300 seconds. DEFAULT_TIMEOUT = 300
from .core import ENOVAL, args_to_key, full_namefrom .fanout import FanoutCache
class DjangoCache(BaseCache): """Django-compatible disk and file backed cache."""
def __init__(self, directory, params): """Initialize DjangoCache instance.
:param str directory: cache directory :param dict params: cache parameters
""" super().__init__(params) shards = params.get('SHARDS', 8) timeout = params.get('DATABASE_TIMEOUT', 0.010) options = params.get('OPTIONS', {}) self._cache = FanoutCache(directory, shards, timeout, **options)
@property def directory(self): """Cache directory.""" return self._cache.directory
def cache(self, name): """Return Cache with given `name` in subdirectory.
:param str name: subdirectory name for Cache :return: Cache with given name
""" return self._cache.cache(name)
def deque(self, name, maxlen=None): """Return Deque with given `name` in subdirectory.
:param str name: subdirectory name for Deque :param maxlen: max length (default None, no max) :return: Deque with given name
""" return self._cache.deque(name, maxlen=maxlen)
def index(self, name): """Return Index with given `name` in subdirectory.
:param str name: subdirectory name for Index :return: Index with given name
""" return self._cache.index(name)
def add( self, key, value, timeout=DEFAULT_TIMEOUT, version=None, read=False, tag=None, retry=True, ): """Set a value in the cache if the key does not already exist. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used.
Return True if the value was stored, False otherwise.
:param key: key for item :param value: value for item :param float timeout: seconds until the item expires (default 300 seconds) :param int version: key version number (default None, cache parameter) :param bool read: read value as bytes from file (default False) :param str tag: text to associate with key (default None) :param bool retry: retry if database timeout occurs (default True) :return: True if item was added
""" # pylint: disable=arguments-differ key = self.make_key(key, version=version) timeout = self.get_backend_timeout(timeout=timeout) return self._cache.add(key, value, timeout, read, tag, retry)
def get( self, key, default=None, version=None, read=False, expire_time=False, tag=False, retry=False, ): """Fetch a given key from the cache. If the key does not exist, return default, which itself defaults to None.
:param key: key for item :param default: return value if key is missing (default None) :param int version: key version number (default None, cache parameter) :param bool read: if True, return file handle to value (default False) :param float expire_time: if True, return expire_time in tuple (default False) :param tag: if True, return tag in tuple (default False) :param bool retry: retry if database timeout occurs (default False) :return: value for item if key is found else default
""" # pylint: disable=arguments-differ key = self.make_key(key, version=version) return self._cache.get(key, default, read, expire_time, tag, retry)
def read(self, key, version=None): """Return file handle corresponding to `key` from Cache.
:param key: Python key to retrieve :param int version: key version number (default None, cache parameter) :return: file open for reading in binary mode :raises KeyError: if key is not found
""" key = self.make_key(key, version=version) return self._cache.read(key)
def set( self, key, value, timeout=DEFAULT_TIMEOUT, version=None, read=False, tag=None, retry=True, ): """Set a value in the cache. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used.
:param key: key for item :param value: value for item :param float timeout: seconds until the item expires (default 300 seconds) :param int version: key version number (default None, cache parameter) :param bool read: read value as bytes from file (default False) :param str tag: text to associate with key (default None) :param bool retry: retry if database timeout occurs (default True) :return: True if item was set
""" # pylint: disable=arguments-differ key = self.make_key(key, version=version) timeout = self.get_backend_timeout(timeout=timeout) return self._cache.set(key, value, timeout, read, tag, retry)
def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None, retry=True): """Touch a key in the cache. If timeout is given, that timeout will be used for the key; otherwise the default cache timeout will be used.
:param key: key for item :param float timeout: seconds until the item expires (default 300 seconds) :param int version: key version number (default None, cache parameter) :param bool retry: retry if database timeout occurs (default True) :return: True if key was touched
""" # pylint: disable=arguments-differ key = self.make_key(key, version=version) timeout = self.get_backend_timeout(timeout=timeout) return self._cache.touch(key, timeout, retry)
def pop( self, key, default=None, version=None, expire_time=False, tag=False, retry=True, ): """Remove corresponding item for `key` from cache and return value.
If `key` is missing, return `default`.
Operation is atomic. Concurrent operations will be serialized.
:param key: key for item :param default: return value if key is missing (default None) :param int version: key version number (default None, cache parameter) :param float expire_time: if True, return expire_time in tuple (default False) :param tag: if True, return tag in tuple (default False) :param bool retry: retry if database timeout occurs (default True) :return: value for item if key is found else default
""" key = self.make_key(key, version=version) return self._cache.pop(key, default, expire_time, tag, retry)
def delete(self, key, version=None, retry=True): """Delete a key from the cache, failing silently.
:param key: key for item :param int version: key version number (default None, cache parameter) :param bool retry: retry if database timeout occurs (default True) :return: True if item was deleted
""" # pylint: disable=arguments-differ key = self.make_key(key, version=version) return self._cache.delete(key, retry)
def incr(self, key, delta=1, version=None, default=None, retry=True): """Increment value by delta for item with key.
If key is missing and default is None then raise KeyError. Else if key is missing and default is not None then use default for value.
Operation is atomic. All concurrent increment operations will be counted individually.
Assumes value may be stored in a SQLite column. Most builds that target machines with 64-bit pointer widths will support 64-bit signed integers.
:param key: key for item :param int delta: amount to increment (default 1) :param int version: key version number (default None, cache parameter) :param int default: value if key is missing (default None) :param bool retry: retry if database timeout occurs (default True) :return: new value for item on success else None :raises ValueError: if key is not found and default is None
""" # pylint: disable=arguments-differ key = self.make_key(key, version=version) try: return self._cache.incr(key, delta, default, retry) except KeyError: raise ValueError("Key '%s' not found" % key) from None
def decr(self, key, delta=1, version=None, default=None, retry=True): """Decrement value by delta for item with key.
If key is missing and default is None then raise KeyError. Else if key is missing and default is not None then use default for value.
Operation is atomic. All concurrent decrement operations will be counted individually.
Unlike Memcached, negative values are supported. Value may be decremented below zero.
Assumes value may be stored in a SQLite column. Most builds that target machines with 64-bit pointer widths will support 64-bit signed integers.
:param key: key for item :param int delta: amount to decrement (default 1) :param int version: key version number (default None, cache parameter) :param int default: value if key is missing (default None) :param bool retry: retry if database timeout occurs (default True) :return: new value for item on success else None :raises ValueError: if key is not found and default is None
""" # pylint: disable=arguments-differ return self.incr(key, -delta, version, default, retry)
def has_key(self, key, version=None): """Returns True if the key is in the cache and has not expired.
:param key: key for item :param int version: key version number (default None, cache parameter) :return: True if key is found
""" key = self.make_key(key, version=version) return key in self._cache
def expire(self): """Remove expired items from cache.
:return: count of items removed
""" return self._cache.expire()
def stats(self, enable=True, reset=False): """Return cache statistics hits and misses.
:param bool enable: enable collecting statistics (default True) :param bool reset: reset hits and misses to 0 (default False) :return: (hits, misses)
""" return self._cache.stats(enable=enable, reset=reset)
def create_tag_index(self): """Create tag index on cache database.
Better to initialize cache with `tag_index=True` than use this.
:raises Timeout: if database timeout occurs
""" self._cache.create_tag_index()
def drop_tag_index(self): """Drop tag index on cache database.
:raises Timeout: if database timeout occurs
""" self._cache.drop_tag_index()
def evict(self, tag): """Remove items with matching `tag` from cache.
:param str tag: tag identifying items :return: count of items removed
""" return self._cache.evict(tag)
def cull(self): """Cull items from cache until volume is less than size limit.
:return: count of items removed
""" return self._cache.cull()
def clear(self): """Remove *all* values from the cache at once.""" return self._cache.clear()
def close(self, **kwargs): """Close the cache connection.""" # pylint: disable=unused-argument self._cache.close()
def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT): """Return seconds to expiration.
:param float timeout: seconds until the item expires (default 300 seconds)
""" if timeout == DEFAULT_TIMEOUT: timeout = self.default_timeout elif timeout == 0: # ticket 21147 - avoid time.time() related precision issues timeout = -1 return None if timeout is None else timeout
def memoize( self, name=None, timeout=DEFAULT_TIMEOUT, version=None, typed=False, tag=None, ignore=(), ): """Memoizing cache decorator.
Decorator to wrap callable with memoizing function using cache. Repeated calls with the same arguments will lookup result in cache and avoid function evaluation.
If name is set to None (default), the callable name will be determined automatically.
When timeout is set to zero, function results will not be set in the cache. Cache lookups still occur, however. Read :doc:`case-study-landing-page-caching` for example usage.
If typed is set to True, function arguments of different types will be cached separately. For example, f(3) and f(3.0) will be treated as distinct calls with distinct results.
The original underlying function is accessible through the __wrapped__ attribute. This is useful for introspection, for bypassing the cache, or for rewrapping the function with a different cache.
An additional `__cache_key__` attribute can be used to generate the cache key used for the given arguments.
Remember to call memoize when decorating a callable. If you forget, then a TypeError will occur.
:param str name: name given for callable (default None, automatic) :param float timeout: seconds until the item expires (default 300 seconds) :param int version: key version number (default None, cache parameter) :param bool typed: cache different types separately (default False) :param str tag: text to associate with arguments (default None) :param set ignore: positional or keyword args to ignore (default ()) :return: callable decorator
""" # Caution: Nearly identical code exists in Cache.memoize if callable(name): raise TypeError('name cannot be callable')
def decorator(func): """Decorator created by memoize() for callable `func`.""" base = (full_name(func),) if name is None else (name,)
@wraps(func) def wrapper(*args, **kwargs): """Wrapper for callable to cache arguments and return values.""" key = wrapper.__cache_key__(*args, **kwargs) result = self.get(key, ENOVAL, version, retry=True)
if result is ENOVAL: result = func(*args, **kwargs) valid_timeout = ( timeout is None or timeout == DEFAULT_TIMEOUT or timeout > 0 ) if valid_timeout: self.set( key, result, timeout, version, tag=tag, retry=True, )
return result
def __cache_key__(*args, **kwargs): """Make key for cache given function arguments.""" return args_to_key(base, args, kwargs, typed, ignore)
wrapper.__cache_key__ = __cache_key__ return wrapper
return decorator123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687"""Fanout cache automatically shards keys and values."""
import contextlib as climport functoolsimport itertools as itimport operatorimport os.path as opimport sqlite3import tempfileimport time
from .core import DEFAULT_SETTINGS, ENOVAL, Cache, Disk, Timeoutfrom .persistent import Deque, Index
class FanoutCache: """Cache that shards keys and values."""
def __init__( self, directory=None, shards=8, timeout=0.010, disk=Disk, **settings ): """Initialize cache instance.
:param str directory: cache directory :param int shards: number of shards to distribute writes :param float timeout: SQLite connection timeout :param disk: `Disk` instance for serialization :param settings: any of `DEFAULT_SETTINGS`
""" if directory is None: directory = tempfile.mkdtemp(prefix='diskcache-') directory = str(directory) directory = op.expanduser(directory) directory = op.expandvars(directory)
default_size_limit = DEFAULT_SETTINGS['size_limit'] size_limit = settings.pop('size_limit', default_size_limit) / shards
self._count = shards self._directory = directory self._disk = disk self._shards = tuple( Cache( directory=op.join(directory, '%03d' % num), timeout=timeout, disk=disk, size_limit=size_limit, **settings, ) for num in range(shards) ) self._hash = self._shards[0].disk.hash self._caches = {} self._deques = {} self._indexes = {}
@property def directory(self): """Cache directory.""" return self._directory
def __getattr__(self, name): safe_names = {'timeout', 'disk'} valid_name = name in DEFAULT_SETTINGS or name in safe_names assert valid_name, 'cannot access {} in cache shard'.format(name) return getattr(self._shards[0], name)
@cl.contextmanager def transact(self, retry=True): """Context manager to perform a transaction by locking the cache.
While the cache is locked, no other write operation is permitted. Transactions should therefore be as short as possible. Read and write operations performed in a transaction are atomic. Read operations may occur concurrent to a transaction.
Transactions may be nested and may not be shared between threads.
Blocks until transactions are held on all cache shards by retrying as necessary.
>>> cache = FanoutCache() >>> with cache.transact(): # Atomically increment two keys. ... _ = cache.incr('total', 123.4) ... _ = cache.incr('count', 1) >>> with cache.transact(): # Atomically calculate average. ... average = cache['total'] / cache['count'] >>> average 123.4
:return: context manager for use in `with` statement
""" assert retry, 'retry must be True in FanoutCache' with cl.ExitStack() as stack: for shard in self._shards: shard_transaction = shard.transact(retry=True) stack.enter_context(shard_transaction) yield
def set(self, key, value, expire=None, read=False, tag=None, retry=False): """Set `key` and `value` item in cache.
When `read` is `True`, `value` should be a file-like object opened for reading in binary mode.
If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`).
:param key: key for item :param value: value for item :param float expire: seconds until the key expires (default None, no expiry) :param bool read: read value as raw bytes from file (default False) :param str tag: text to associate with key (default None) :param bool retry: retry if database timeout occurs (default False) :return: True if item was set
""" index = self._hash(key) % self._count shard = self._shards[index] try: return shard.set(key, value, expire, read, tag, retry) except Timeout: return False
def __setitem__(self, key, value): """Set `key` and `value` item in cache.
Calls :func:`FanoutCache.set` internally with `retry` set to `True`.
:param key: key for item :param value: value for item
""" index = self._hash(key) % self._count shard = self._shards[index] shard[key] = value
def touch(self, key, expire=None, retry=False): """Touch `key` in cache and update `expire` time.
If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`).
:param key: key for item :param float expire: seconds until the key expires (default None, no expiry) :param bool retry: retry if database timeout occurs (default False) :return: True if key was touched
""" index = self._hash(key) % self._count shard = self._shards[index] try: return shard.touch(key, expire, retry) except Timeout: return False
def add(self, key, value, expire=None, read=False, tag=None, retry=False): """Add `key` and `value` item to cache.
Similar to `set`, but only add to cache if key not present.
This operation is atomic. Only one concurrent add operation for given key from separate threads or processes will succeed.
When `read` is `True`, `value` should be a file-like object opened for reading in binary mode.
If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`).
:param key: key for item :param value: value for item :param float expire: seconds until the key expires (default None, no expiry) :param bool read: read value as bytes from file (default False) :param str tag: text to associate with key (default None) :param bool retry: retry if database timeout occurs (default False) :return: True if item was added
""" index = self._hash(key) % self._count shard = self._shards[index] try: return shard.add(key, value, expire, read, tag, retry) except Timeout: return False
def incr(self, key, delta=1, default=0, retry=False): """Increment value by delta for item with key.
If key is missing and default is None then raise KeyError. Else if key is missing and default is not None then use default for value.
Operation is atomic. All concurrent increment operations will be counted individually.
Assumes value may be stored in a SQLite column. Most builds that target machines with 64-bit pointer widths will support 64-bit signed integers.
If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`).
:param key: key for item :param int delta: amount to increment (default 1) :param int default: value if key is missing (default 0) :param bool retry: retry if database timeout occurs (default False) :return: new value for item on success else None :raises KeyError: if key is not found and default is None
""" index = self._hash(key) % self._count shard = self._shards[index] try: return shard.incr(key, delta, default, retry) except Timeout: return None
def decr(self, key, delta=1, default=0, retry=False): """Decrement value by delta for item with key.
If key is missing and default is None then raise KeyError. Else if key is missing and default is not None then use default for value.
Operation is atomic. All concurrent decrement operations will be counted individually.
Unlike Memcached, negative values are supported. Value may be decremented below zero.
Assumes value may be stored in a SQLite column. Most builds that target machines with 64-bit pointer widths will support 64-bit signed integers.
If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`).
:param key: key for item :param int delta: amount to decrement (default 1) :param int default: value if key is missing (default 0) :param bool retry: retry if database timeout occurs (default False) :return: new value for item on success else None :raises KeyError: if key is not found and default is None
""" index = self._hash(key) % self._count shard = self._shards[index] try: return shard.decr(key, delta, default, retry) except Timeout: return None
def get( self, key, default=None, read=False, expire_time=False, tag=False, retry=False, ): """Retrieve value from cache. If `key` is missing, return `default`.
If database timeout occurs then returns `default` unless `retry` is set to `True` (default `False`).
:param key: key for item :param default: return value if key is missing (default None) :param bool read: if True, return file handle to value (default False) :param float expire_time: if True, return expire_time in tuple (default False) :param tag: if True, return tag in tuple (default False) :param bool retry: retry if database timeout occurs (default False) :return: value for item if key is found else default
""" index = self._hash(key) % self._count shard = self._shards[index] try: return shard.get(key, default, read, expire_time, tag, retry) except (Timeout, sqlite3.OperationalError): return default
def __getitem__(self, key): """Return corresponding value for `key` from cache.
Calls :func:`FanoutCache.get` internally with `retry` set to `True`.
:param key: key for item :return: value for item :raises KeyError: if key is not found
""" index = self._hash(key) % self._count shard = self._shards[index] return shard[key]
def read(self, key): """Return file handle corresponding to `key` from cache.
:param key: key for item :return: file open for reading in binary mode :raises KeyError: if key is not found
""" handle = self.get(key, default=ENOVAL, read=True, retry=True) if handle is ENOVAL: raise KeyError(key) return handle
def __contains__(self, key): """Return `True` if `key` matching item is found in cache.
:param key: key for item :return: True if key is found
""" index = self._hash(key) % self._count shard = self._shards[index] return key in shard
def pop( self, key, default=None, expire_time=False, tag=False, retry=False ): # noqa: E501 """Remove corresponding item for `key` from cache and return value.
If `key` is missing, return `default`.
Operation is atomic. Concurrent operations will be serialized.
If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`).
:param key: key for item :param default: return value if key is missing (default None) :param float expire_time: if True, return expire_time in tuple (default False) :param tag: if True, return tag in tuple (default False) :param bool retry: retry if database timeout occurs (default False) :return: value for item if key is found else default
""" index = self._hash(key) % self._count shard = self._shards[index] try: return shard.pop(key, default, expire_time, tag, retry) except Timeout: return default
def delete(self, key, retry=False): """Delete corresponding item for `key` from cache.
Missing keys are ignored.
If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`).
:param key: key for item :param bool retry: retry if database timeout occurs (default False) :return: True if item was deleted
""" index = self._hash(key) % self._count shard = self._shards[index] try: return shard.delete(key, retry) except Timeout: return False
def __delitem__(self, key): """Delete corresponding item for `key` from cache.
Calls :func:`FanoutCache.delete` internally with `retry` set to `True`.
:param key: key for item :raises KeyError: if key is not found
""" index = self._hash(key) % self._count shard = self._shards[index] del shard[key]
def check(self, fix=False, retry=False): """Check database and file system consistency.
Intended for use in testing and post-mortem error analysis.
While checking the cache table for consistency, a writer lock is held on the database. The lock blocks other cache clients from writing to the database. For caches with many file references, the lock may be held for a long time. For example, local benchmarking shows that a cache with 1,000 file references takes ~60ms to check.
If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`).
:param bool fix: correct inconsistencies :param bool retry: retry if database timeout occurs (default False) :return: list of warnings :raises Timeout: if database timeout occurs
""" warnings = (shard.check(fix, retry) for shard in self._shards) return functools.reduce(operator.iadd, warnings, [])
def expire(self, retry=False): """Remove expired items from cache.
If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`).
:param bool retry: retry if database timeout occurs (default False) :return: count of items removed
""" return self._remove('expire', args=(time.time(),), retry=retry)
def create_tag_index(self): """Create tag index on cache database.
Better to initialize cache with `tag_index=True` than use this.
:raises Timeout: if database timeout occurs
""" for shard in self._shards: shard.create_tag_index()
def drop_tag_index(self): """Drop tag index on cache database.
:raises Timeout: if database timeout occurs
""" for shard in self._shards: shard.drop_tag_index()
def evict(self, tag, retry=False): """Remove items with matching `tag` from cache.
If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`).
:param str tag: tag identifying items :param bool retry: retry if database timeout occurs (default False) :return: count of items removed
""" return self._remove('evict', args=(tag,), retry=retry)
def cull(self, retry=False): """Cull items from cache until volume is less than size limit.
If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`).
:param bool retry: retry if database timeout occurs (default False) :return: count of items removed
""" return self._remove('cull', retry=retry)
def clear(self, retry=False): """Remove all items from cache.
If database timeout occurs then fails silently unless `retry` is set to `True` (default `False`).
:param bool retry: retry if database timeout occurs (default False) :return: count of items removed
""" return self._remove('clear', retry=retry)
def _remove(self, name, args=(), retry=False): total = 0 for shard in self._shards: method = getattr(shard, name) while True: try: count = method(*args, retry=retry) total += count except Timeout as timeout: total += timeout.args[0] else: break return total
def stats(self, enable=True, reset=False): """Return cache statistics hits and misses.
:param bool enable: enable collecting statistics (default True) :param bool reset: reset hits and misses to 0 (default False) :return: (hits, misses)
""" results = [shard.stats(enable, reset) for shard in self._shards] total_hits = sum(hits for hits, _ in results) total_misses = sum(misses for _, misses in results) return total_hits, total_misses
def volume(self): """Return estimated total size of cache on disk.
:return: size in bytes
""" return sum(shard.volume() for shard in self._shards)
def close(self): """Close database connection.""" for shard in self._shards: shard.close() self._caches.clear() self._deques.clear() self._indexes.clear()
def __enter__(self): return self
def __exit__(self, *exception): self.close()
def __getstate__(self): return (self._directory, self._count, self.timeout, type(self.disk))
def __setstate__(self, state): self.__init__(*state)
def __iter__(self): """Iterate keys in cache including expired items.""" iterators = (iter(shard) for shard in self._shards) return it.chain.from_iterable(iterators)
def __reversed__(self): """Reverse iterate keys in cache including expired items.""" iterators = (reversed(shard) for shard in reversed(self._shards)) return it.chain.from_iterable(iterators)
def __len__(self): """Count of items in cache including expired items.""" return sum(len(shard) for shard in self._shards)
def reset(self, key, value=ENOVAL): """Reset `key` and `value` item from Settings table.
If `value` is not given, it is reloaded from the Settings table. Otherwise, the Settings table is updated.
Settings attributes on cache objects are lazy-loaded and read-only. Use `reset` to update the value.
Settings with the ``sqlite_`` prefix correspond to SQLite pragmas. Updating the value will execute the corresponding PRAGMA statement.
:param str key: Settings key for item :param value: value for item (optional) :return: updated value for item
""" for shard in self._shards: while True: try: result = shard.reset(key, value) except Timeout: pass else: break return result
def cache(self, name, timeout=60, disk=None, **settings): """Return Cache with given `name` in subdirectory.
If disk is none (default), uses the fanout cache disk.
>>> fanout_cache = FanoutCache() >>> cache = fanout_cache.cache('test') >>> cache.set('abc', 123) True >>> cache.get('abc') 123 >>> len(cache) 1 >>> cache.delete('abc') True
:param str name: subdirectory name for Cache :param float timeout: SQLite connection timeout :param disk: Disk type or subclass for serialization :param settings: any of DEFAULT_SETTINGS :return: Cache with given name
""" _caches = self._caches
try: return _caches[name] except KeyError: parts = name.split('/') directory = op.join(self._directory, 'cache', *parts) temp = Cache( directory=directory, timeout=timeout, disk=self._disk if disk is None else Disk, **settings, ) _caches[name] = temp return temp
def deque(self, name, maxlen=None): """Return Deque with given `name` in subdirectory.
>>> cache = FanoutCache() >>> deque = cache.deque('test') >>> deque.extend('abc') >>> deque.popleft() 'a' >>> deque.pop() 'c' >>> len(deque) 1
:param str name: subdirectory name for Deque :param maxlen: max length (default None, no max) :return: Deque with given name
""" _deques = self._deques
try: return _deques[name] except KeyError: parts = name.split('/') directory = op.join(self._directory, 'deque', *parts) cache = Cache( directory=directory, disk=self._disk, eviction_policy='none', ) deque = Deque.fromcache(cache, maxlen=maxlen) _deques[name] = deque return deque
def index(self, name): """Return Index with given `name` in subdirectory.
>>> cache = FanoutCache() >>> index = cache.index('test') >>> index['abc'] = 123 >>> index['def'] = 456 >>> index['ghi'] = 789 >>> index.popitem() ('ghi', 789) >>> del index['abc'] >>> len(index) 1 >>> index['def'] 456
:param str name: subdirectory name for Index :return: Index with given name
""" _indexes = self._indexes
try: return _indexes[name] except KeyError: parts = name.split('/') directory = op.join(self._directory, 'index', *parts) cache = Cache( directory=directory, disk=self._disk, eviction_policy='none', ) index = Index.fromcache(cache) _indexes[name] = index return index
FanoutCache.memoize = Cache.memoize # type: ignore123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245"""Persistent Data Types"""
import operator as opfrom collections import OrderedDictfrom collections.abc import ( ItemsView, KeysView, MutableMapping, Sequence, ValuesView,)from contextlib import contextmanagerfrom shutil import rmtree
from .core import ENOVAL, Cache
def _make_compare(seq_op, doc): """Make compare method with Sequence semantics."""
def compare(self, that): """Compare method for deque and sequence.""" if not isinstance(that, Sequence): return NotImplemented
len_self = len(self) len_that = len(that)
if len_self != len_that: if seq_op is op.eq: return False if seq_op is op.ne: return True
for alpha, beta in zip(self, that): if alpha != beta: return seq_op(alpha, beta)
return seq_op(len_self, len_that)
compare.__name__ = '__{0}__'.format(seq_op.__name__) doc_str = 'Return True if and only if deque is {0} `that`.' compare.__doc__ = doc_str.format(doc)
return compare
class Deque(Sequence): """Persistent sequence with double-ended queue semantics.
Double-ended queue is an ordered collection with optimized access at its endpoints.
Items are serialized to disk. Deque may be initialized from directory path where items are stored.
>>> deque = Deque() >>> deque += range(5) >>> list(deque) [0, 1, 2, 3, 4] >>> for value in range(5): ... deque.appendleft(-value) >>> len(deque) 10 >>> list(deque) [-4, -3, -2, -1, 0, 0, 1, 2, 3, 4] >>> deque.pop() 4 >>> deque.popleft() -4 >>> deque.reverse() >>> list(deque) [3, 2, 1, 0, 0, -1, -2, -3]
"""
def __init__(self, iterable=(), directory=None, maxlen=None): """Initialize deque instance.
If directory is None then temporary directory created. The directory will *not* be automatically removed.
:param iterable: iterable of items to append to deque :param directory: deque directory (default None)
""" self._cache = Cache(directory, eviction_policy='none') self._maxlen = float('inf') if maxlen is None else maxlen self._extend(iterable)
@classmethod def fromcache(cls, cache, iterable=(), maxlen=None): """Initialize deque using `cache`.
>>> cache = Cache() >>> deque = Deque.fromcache(cache, [5, 6, 7, 8]) >>> deque.cache is cache True >>> len(deque) 4 >>> 7 in deque True >>> deque.popleft() 5
:param Cache cache: cache to use :param iterable: iterable of items :return: initialized Deque
""" # pylint: disable=no-member,protected-access self = cls.__new__(cls) self._cache = cache self._maxlen = float('inf') if maxlen is None else maxlen self._extend(iterable) return self
@property def cache(self): """Cache used by deque.""" return self._cache
@property def directory(self): """Directory path where deque is stored.""" return self._cache.directory
@property def maxlen(self): """Max length of the deque.""" return self._maxlen
@maxlen.setter def maxlen(self, value): """Set max length of the deque.
Pops items from left while length greater than max.
>>> deque = Deque() >>> deque.extendleft('abcde') >>> deque.maxlen = 3 >>> list(deque) ['c', 'd', 'e']
:param value: max length
""" self._maxlen = value with self._cache.transact(retry=True): while len(self._cache) > self._maxlen: self._popleft()
def _index(self, index, func): len_self = len(self)
if index >= 0: if index >= len_self: raise IndexError('deque index out of range')
for key in self._cache.iterkeys(): if index == 0: try: return func(key) except KeyError: continue index -= 1 else: if index < -len_self: raise IndexError('deque index out of range')
index += 1
for key in self._cache.iterkeys(reverse=True): if index == 0: try: return func(key) except KeyError: continue index += 1
raise IndexError('deque index out of range')
def __getitem__(self, index): """deque.__getitem__(index) <==> deque[index]
Return corresponding item for `index` in deque.
See also `Deque.peekleft` and `Deque.peek` for indexing deque at index ``0`` or ``-1``.
>>> deque = Deque() >>> deque.extend('abcde') >>> deque[1] 'b' >>> deque[-2] 'd'
:param int index: index of item :return: corresponding item :raises IndexError: if index out of range
""" return self._index(index, self._cache.__getitem__)
def __setitem__(self, index, value): """deque.__setitem__(index, value) <==> deque[index] = value
Store `value` in deque at `index`.
>>> deque = Deque() >>> deque.extend([None] * 3) >>> deque[0] = 'a' >>> deque[1] = 'b' >>> deque[-1] = 'c' >>> ''.join(deque) 'abc'
:param int index: index of value :param value: value to store :raises IndexError: if index out of range
"""
def _set_value(key): return self._cache.__setitem__(key, value)
self._index(index, _set_value)
def __delitem__(self, index): """deque.__delitem__(index) <==> del deque[index]
Delete item in deque at `index`.
>>> deque = Deque() >>> deque.extend([None] * 3) >>> del deque[0] >>> del deque[1] >>> del deque[-1] >>> len(deque) 0
:param int index: index of item :raises IndexError: if index out of range
""" self._index(index, self._cache.__delitem__)
def __repr__(self): """deque.__repr__() <==> repr(deque)
Return string with printable representation of deque.
""" name = type(self).__name__ return '{0}(directory={1!r})'.format(name, self.directory)
__eq__ = _make_compare(op.eq, 'equal to') __ne__ = _make_compare(op.ne, 'not equal to') __lt__ = _make_compare(op.lt, 'less than') __gt__ = _make_compare(op.gt, 'greater than') __le__ = _make_compare(op.le, 'less than or equal to') __ge__ = _make_compare(op.ge, 'greater than or equal to')
def __iadd__(self, iterable): """deque.__iadd__(iterable) <==> deque += iterable
Extend back side of deque with items from iterable.
:param iterable: iterable of items to append to deque :return: deque with added items
""" self._extend(iterable) return self
def __iter__(self): """deque.__iter__() <==> iter(deque)
Return iterator of deque from front to back.
""" _cache = self._cache
for key in _cache.iterkeys(): try: yield _cache[key] except KeyError: pass
def __len__(self): """deque.__len__() <==> len(deque)
Return length of deque.
""" return len(self._cache)
def __reversed__(self): """deque.__reversed__() <==> reversed(deque)
Return iterator of deque from back to front.
>>> deque = Deque() >>> deque.extend('abcd') >>> iterator = reversed(deque) >>> next(iterator) 'd' >>> list(iterator) ['c', 'b', 'a']
""" _cache = self._cache
for key in _cache.iterkeys(reverse=True): try: yield _cache[key] except KeyError: pass
def __getstate__(self): return self.directory, self.maxlen
def __setstate__(self, state): directory, maxlen = state self.__init__(directory=directory, maxlen=maxlen)
def append(self, value): """Add `value` to back of deque.
>>> deque = Deque() >>> deque.append('a') >>> deque.append('b') >>> deque.append('c') >>> list(deque) ['a', 'b', 'c']
:param value: value to add to back of deque
""" with self._cache.transact(retry=True): self._cache.push(value, retry=True) if len(self._cache) > self._maxlen: self._popleft()
_append = append
def appendleft(self, value): """Add `value` to front of deque.
>>> deque = Deque() >>> deque.appendleft('a') >>> deque.appendleft('b') >>> deque.appendleft('c') >>> list(deque) ['c', 'b', 'a']
:param value: value to add to front of deque
""" with self._cache.transact(retry=True): self._cache.push(value, side='front', retry=True) if len(self._cache) > self._maxlen: self._pop()
_appendleft = appendleft
def clear(self): """Remove all elements from deque.
>>> deque = Deque('abc') >>> len(deque) 3 >>> deque.clear() >>> list(deque) []
""" self._cache.clear(retry=True)
_clear = clear
def copy(self): """Copy deque with same directory and max length.""" TypeSelf = type(self) return TypeSelf(directory=self.directory, maxlen=self.maxlen)
def count(self, value): """Return number of occurrences of `value` in deque.
>>> deque = Deque() >>> deque += [num for num in range(1, 5) for _ in range(num)] >>> deque.count(0) 0 >>> deque.count(1) 1 >>> deque.count(4) 4
:param value: value to count in deque :return: count of items equal to value in deque
""" return sum(1 for item in self if value == item)
def extend(self, iterable): """Extend back side of deque with values from `iterable`.
:param iterable: iterable of values
""" for value in iterable: self._append(value)
_extend = extend
def extendleft(self, iterable): """Extend front side of deque with value from `iterable`.
>>> deque = Deque() >>> deque.extendleft('abc') >>> list(deque) ['c', 'b', 'a']
:param iterable: iterable of values
""" for value in iterable: self._appendleft(value)
def peek(self): """Peek at value at back of deque.
Faster than indexing deque at -1.
If deque is empty then raise IndexError.
>>> deque = Deque() >>> deque.peek() Traceback (most recent call last): ... IndexError: peek from an empty deque >>> deque += 'abc' >>> deque.peek() 'c'
:return: value at back of deque :raises IndexError: if deque is empty
""" default = None, ENOVAL _, value = self._cache.peek(default=default, side='back', retry=True) if value is ENOVAL: raise IndexError('peek from an empty deque') return value
def peekleft(self): """Peek at value at front of deque.
Faster than indexing deque at 0.
If deque is empty then raise IndexError.
>>> deque = Deque() >>> deque.peekleft() Traceback (most recent call last): ... IndexError: peek from an empty deque >>> deque += 'abc' >>> deque.peekleft() 'a'
:return: value at front of deque :raises IndexError: if deque is empty
""" default = None, ENOVAL _, value = self._cache.peek(default=default, side='front', retry=True) if value is ENOVAL: raise IndexError('peek from an empty deque') return value
def pop(self): """Remove and return value at back of deque.
If deque is empty then raise IndexError.
>>> deque = Deque() >>> deque += 'ab' >>> deque.pop() 'b' >>> deque.pop() 'a' >>> deque.pop() Traceback (most recent call last): ... IndexError: pop from an empty deque
:return: value at back of deque :raises IndexError: if deque is empty
""" default = None, ENOVAL _, value = self._cache.pull(default=default, side='back', retry=True) if value is ENOVAL: raise IndexError('pop from an empty deque') return value
_pop = pop
def popleft(self): """Remove and return value at front of deque.
>>> deque = Deque() >>> deque += 'ab' >>> deque.popleft() 'a' >>> deque.popleft() 'b' >>> deque.popleft() Traceback (most recent call last): ... IndexError: pop from an empty deque
:return: value at front of deque :raises IndexError: if deque is empty
""" default = None, ENOVAL _, value = self._cache.pull(default=default, retry=True) if value is ENOVAL: raise IndexError('pop from an empty deque') return value
_popleft = popleft
def remove(self, value): """Remove first occurrence of `value` in deque.
>>> deque = Deque() >>> deque += 'aab' >>> deque.remove('a') >>> list(deque) ['a', 'b'] >>> deque.remove('b') >>> list(deque) ['a'] >>> deque.remove('c') Traceback (most recent call last): ... ValueError: deque.remove(value): value not in deque
:param value: value to remove :raises ValueError: if value not in deque
""" _cache = self._cache
for key in _cache.iterkeys(): try: item = _cache[key] except KeyError: continue else: if value == item: try: del _cache[key] except KeyError: continue return
raise ValueError('deque.remove(value): value not in deque')
def reverse(self): """Reverse deque in place.
>>> deque = Deque() >>> deque += 'abc' >>> deque.reverse() >>> list(deque) ['c', 'b', 'a']
""" # pylint: disable=protected-access # GrantJ 2019-03-22 Consider using an algorithm that swaps the values # at two keys. Like self._cache.swap(key1, key2, retry=True) The swap # method would exchange the values at two given keys. Then, using a # forward iterator and a reverse iterator, the reverse method could # avoid making copies of the values. temp = Deque(iterable=reversed(self)) self._clear() self._extend(temp) directory = temp.directory temp._cache.close() del temp rmtree(directory)
def rotate(self, steps=1): """Rotate deque right by `steps`.
If steps is negative then rotate left.
>>> deque = Deque() >>> deque += range(5) >>> deque.rotate(2) >>> list(deque) [3, 4, 0, 1, 2] >>> deque.rotate(-1) >>> list(deque) [4, 0, 1, 2, 3]
:param int steps: number of steps to rotate (default 1)
""" if not isinstance(steps, int): type_name = type(steps).__name__ raise TypeError('integer argument expected, got %s' % type_name)
len_self = len(self)
if not len_self: return
if steps >= 0: steps %= len_self
for _ in range(steps): try: value = self._pop() except IndexError: return else: self._appendleft(value) else: steps *= -1 steps %= len_self
for _ in range(steps): try: value = self._popleft() except IndexError: return else: self._append(value)
__hash__ = None # type: ignore
@contextmanager def transact(self): """Context manager to perform a transaction by locking the deque.
While the deque is locked, no other write operation is permitted. Transactions should therefore be as short as possible. Read and write operations performed in a transaction are atomic. Read operations may occur concurrent to a transaction.
Transactions may be nested and may not be shared between threads.
>>> from diskcache import Deque >>> deque = Deque() >>> deque += range(5) >>> with deque.transact(): # Atomically rotate elements. ... value = deque.pop() ... deque.appendleft(value) >>> list(deque) [4, 0, 1, 2, 3]
:return: context manager for use in `with` statement
""" with self._cache.transact(retry=True): yield
class Index(MutableMapping): """Persistent mutable mapping with insertion order iteration.
Items are serialized to disk. Index may be initialized from directory path where items are stored.
Hashing protocol is not used. Keys are looked up by their serialized format. See ``diskcache.Disk`` for details.
>>> index = Index() >>> index.update([('a', 1), ('b', 2), ('c', 3)]) >>> index['a'] 1 >>> list(index) ['a', 'b', 'c'] >>> len(index) 3 >>> del index['b'] >>> index.popitem() ('c', 3)
"""
def __init__(self, *args, **kwargs): """Initialize index in directory and update items.
Optional first argument may be string specifying directory where items are stored. When None or not given, temporary directory is created.
>>> index = Index({'a': 1, 'b': 2, 'c': 3}) >>> len(index) 3 >>> directory = index.directory >>> inventory = Index(directory, d=4) >>> inventory['b'] 2 >>> len(inventory) 4
""" if args and isinstance(args[0], (bytes, str)): directory = args[0] args = args[1:] else: if args and args[0] is None: args = args[1:] directory = None self._cache = Cache(directory, eviction_policy='none') self._update(*args, **kwargs)
_update = MutableMapping.update
@classmethod def fromcache(cls, cache, *args, **kwargs): """Initialize index using `cache` and update items.
>>> cache = Cache() >>> index = Index.fromcache(cache, {'a': 1, 'b': 2, 'c': 3}) >>> index.cache is cache True >>> len(index) 3 >>> 'b' in index True >>> index['c'] 3
:param Cache cache: cache to use :param args: mapping or sequence of items :param kwargs: mapping of items :return: initialized Index
""" # pylint: disable=no-member,protected-access self = cls.__new__(cls) self._cache = cache self._update(*args, **kwargs) return self
@property def cache(self): """Cache used by index.""" return self._cache
@property def directory(self): """Directory path where items are stored.""" return self._cache.directory
def __getitem__(self, key): """index.__getitem__(key) <==> index[key]
Return corresponding value for `key` in index.
>>> index = Index() >>> index.update({'a': 1, 'b': 2}) >>> index['a'] 1 >>> index['b'] 2 >>> index['c'] Traceback (most recent call last): ... KeyError: 'c'
:param key: key for item :return: value for item in index with given key :raises KeyError: if key is not found
""" return self._cache[key]
def __setitem__(self, key, value): """index.__setitem__(key, value) <==> index[key] = value
Set `key` and `value` item in index.
>>> index = Index() >>> index['a'] = 1 >>> index[0] = None >>> len(index) 2
:param key: key for item :param value: value for item
""" self._cache[key] = value
def __delitem__(self, key): """index.__delitem__(key) <==> del index[key]
Delete corresponding item for `key` from index.
>>> index = Index() >>> index.update({'a': 1, 'b': 2}) >>> del index['a'] >>> del index['b'] >>> len(index) 0 >>> del index['c'] Traceback (most recent call last): ... KeyError: 'c'
:param key: key for item :raises KeyError: if key is not found
""" del self._cache[key]
def setdefault(self, key, default=None): """Set and get value for `key` in index using `default`.
If `key` is not in index then set corresponding value to `default`. If `key` is in index then ignore `default` and return existing value.
>>> index = Index() >>> index.setdefault('a', 0) 0 >>> index.setdefault('a', 1) 0
:param key: key for item :param default: value if key is missing (default None) :return: value for item in index with given key
""" _cache = self._cache while True: try: return _cache[key] except KeyError: _cache.add(key, default, retry=True)
def peekitem(self, last=True): """Peek at key and value item pair in index based on iteration order.
>>> index = Index() >>> for num, letter in enumerate('xyz'): ... index[letter] = num >>> index.peekitem() ('z', 2) >>> index.peekitem(last=False) ('x', 0)
:param bool last: last item in iteration order (default True) :return: key and value item pair :raises KeyError: if cache is empty
""" return self._cache.peekitem(last, retry=True)
def pop(self, key, default=ENOVAL): """Remove corresponding item for `key` from index and return value.
If `key` is missing then return `default`. If `default` is `ENOVAL` then raise KeyError.
>>> index = Index({'a': 1, 'b': 2}) >>> index.pop('a') 1 >>> index.pop('b') 2 >>> index.pop('c', default=3) 3 >>> index.pop('d') Traceback (most recent call last): ... KeyError: 'd'
:param key: key for item :param default: return value if key is missing (default ENOVAL) :return: value for item if key is found else default :raises KeyError: if key is not found and default is ENOVAL
""" _cache = self._cache value = _cache.pop(key, default=default, retry=True) if value is ENOVAL: raise KeyError(key) return value
def popitem(self, last=True): """Remove and return item pair.
Item pairs are returned in last-in-first-out (LIFO) order if last is True else first-in-first-out (FIFO) order. LIFO order imitates a stack and FIFO order imitates a queue.
>>> index = Index() >>> index.update([('a', 1), ('b', 2), ('c', 3)]) >>> index.popitem() ('c', 3) >>> index.popitem(last=False) ('a', 1) >>> index.popitem() ('b', 2) >>> index.popitem() Traceback (most recent call last): ... KeyError: 'dictionary is empty'
:param bool last: pop last item pair (default True) :return: key and value item pair :raises KeyError: if index is empty
""" # pylint: disable=arguments-differ,unbalanced-tuple-unpacking _cache = self._cache
with _cache.transact(retry=True): key, value = _cache.peekitem(last=last) del _cache[key]
return key, value
def push(self, value, prefix=None, side='back'): """Push `value` onto `side` of queue in index identified by `prefix`.
When prefix is None, integer keys are used. Otherwise, string keys are used in the format "prefix-integer". Integer starts at 500 trillion.
Defaults to pushing value on back of queue. Set side to 'front' to push value on front of queue. Side must be one of 'back' or 'front'.
See also `Index.pull`.
>>> index = Index() >>> print(index.push('apples')) 500000000000000 >>> print(index.push('beans')) 500000000000001 >>> print(index.push('cherries', side='front')) 499999999999999 >>> index[500000000000001] 'beans' >>> index.push('dates', prefix='fruit') 'fruit-500000000000000'
:param value: value for item :param str prefix: key prefix (default None, key is integer) :param str side: either 'back' or 'front' (default 'back') :return: key for item in cache
""" return self._cache.push(value, prefix, side, retry=True)
def pull(self, prefix=None, default=(None, None), side='front'): """Pull key and value item pair from `side` of queue in index.
When prefix is None, integer keys are used. Otherwise, string keys are used in the format "prefix-integer". Integer starts at 500 trillion.
If queue is empty, return default.
Defaults to pulling key and value item pairs from front of queue. Set side to 'back' to pull from back of queue. Side must be one of 'front' or 'back'.
See also `Index.push`.
>>> index = Index() >>> for letter in 'abc': ... print(index.push(letter)) 500000000000000 500000000000001 500000000000002 >>> key, value = index.pull() >>> print(key) 500000000000000 >>> value 'a' >>> _, value = index.pull(side='back') >>> value 'c' >>> index.pull(prefix='fruit') (None, None)
:param str prefix: key prefix (default None, key is integer) :param default: value to return if key is missing (default (None, None)) :param str side: either 'front' or 'back' (default 'front') :return: key and value item pair or default if queue is empty
""" return self._cache.pull(prefix, default, side, retry=True)
def clear(self): """Remove all items from index.
>>> index = Index({'a': 0, 'b': 1, 'c': 2}) >>> len(index) 3 >>> index.clear() >>> dict(index) {}
""" self._cache.clear(retry=True)
def __iter__(self): """index.__iter__() <==> iter(index)
Return iterator of index keys in insertion order.
""" return iter(self._cache)
def __reversed__(self): """index.__reversed__() <==> reversed(index)
Return iterator of index keys in reversed insertion order.
>>> index = Index() >>> index.update([('a', 1), ('b', 2), ('c', 3)]) >>> iterator = reversed(index) >>> next(iterator) 'c' >>> list(iterator) ['b', 'a']
""" return reversed(self._cache)
def __len__(self): """index.__len__() <==> len(index)
Return length of index.
""" return len(self._cache)
def keys(self): """Set-like object providing a view of index keys.
>>> index = Index() >>> index.update({'a': 1, 'b': 2, 'c': 3}) >>> keys_view = index.keys() >>> 'b' in keys_view True
:return: keys view
""" return KeysView(self)
def values(self): """Set-like object providing a view of index values.
>>> index = Index() >>> index.update({'a': 1, 'b': 2, 'c': 3}) >>> values_view = index.values() >>> 2 in values_view True
:return: values view
""" return ValuesView(self)
def items(self): """Set-like object providing a view of index items.
>>> index = Index() >>> index.update({'a': 1, 'b': 2, 'c': 3}) >>> items_view = index.items() >>> ('b', 2) in items_view True
:return: items view
""" return ItemsView(self)
__hash__ = None # type: ignore
def __getstate__(self): return self.directory
def __setstate__(self, state): self.__init__(state)
def __eq__(self, other): """index.__eq__(other) <==> index == other
Compare equality for index and `other`.
Comparison to another index or ordered dictionary is order-sensitive. Comparison to all other mappings is order-insensitive.
>>> index = Index() >>> pairs = [('a', 1), ('b', 2), ('c', 3)] >>> index.update(pairs) >>> from collections import OrderedDict >>> od = OrderedDict(pairs) >>> index == od True >>> index == {'c': 3, 'b': 2, 'a': 1} True
:param other: other mapping in equality comparison :return: True if index equals other
""" if len(self) != len(other): return False
if isinstance(other, (Index, OrderedDict)): alpha = ((key, self[key]) for key in self) beta = ((key, other[key]) for key in other) pairs = zip(alpha, beta) return not any(a != x or b != y for (a, b), (x, y) in pairs) else: return all(self[key] == other.get(key, ENOVAL) for key in self)
def __ne__(self, other): """index.__ne__(other) <==> index != other
Compare inequality for index and `other`.
Comparison to another index or ordered dictionary is order-sensitive. Comparison to all other mappings is order-insensitive.
>>> index = Index() >>> index.update([('a', 1), ('b', 2), ('c', 3)]) >>> from collections import OrderedDict >>> od = OrderedDict([('c', 3), ('b', 2), ('a', 1)]) >>> index != od True >>> index != {'a': 1, 'b': 2} True
:param other: other mapping in inequality comparison :return: True if index does not equal other
""" return not self == other
def memoize(self, name=None, typed=False, ignore=()): """Memoizing cache decorator.
Decorator to wrap callable with memoizing function using cache. Repeated calls with the same arguments will lookup result in cache and avoid function evaluation.
If name is set to None (default), the callable name will be determined automatically.
If typed is set to True, function arguments of different types will be cached separately. For example, f(3) and f(3.0) will be treated as distinct calls with distinct results.
The original underlying function is accessible through the __wrapped__ attribute. This is useful for introspection, for bypassing the cache, or for rewrapping the function with a different cache.
>>> from diskcache import Index >>> mapping = Index() >>> @mapping.memoize() ... def fibonacci(number): ... if number == 0: ... return 0 ... elif number == 1: ... return 1 ... else: ... return fibonacci(number - 1) + fibonacci(number - 2) >>> print(fibonacci(100)) 354224848179261915075
An additional `__cache_key__` attribute can be used to generate the cache key used for the given arguments.
>>> key = fibonacci.__cache_key__(100) >>> print(mapping[key]) 354224848179261915075
Remember to call memoize when decorating a callable. If you forget, then a TypeError will occur. Note the lack of parenthenses after memoize below:
>>> @mapping.memoize ... def test(): ... pass Traceback (most recent call last): ... TypeError: name cannot be callable
:param str name: name given for callable (default None, automatic) :param bool typed: cache different types separately (default False) :param set ignore: positional or keyword args to ignore (default ()) :return: callable decorator
""" return self._cache.memoize(name, typed, ignore=ignore)
@contextmanager def transact(self): """Context manager to perform a transaction by locking the index.
While the index is locked, no other write operation is permitted. Transactions should therefore be as short as possible. Read and write operations performed in a transaction are atomic. Read operations may occur concurrent to a transaction.
Transactions may be nested and may not be shared between threads.
>>> from diskcache import Index >>> mapping = Index() >>> with mapping.transact(): # Atomically increment two keys. ... mapping['total'] = mapping.get('total', 0) + 123.4 ... mapping['count'] = mapping.get('count', 0) + 1 >>> with mapping.transact(): # Atomically calculate average. ... average = mapping['total'] / mapping['count'] >>> average 123.4
:return: context manager for use in `with` statement
""" with self._cache.transact(retry=True): yield
def __repr__(self): """index.__repr__() <==> repr(index)
Return string with printable representation of index.
""" name = type(self).__name__ return '{0}({1!r})'.format(name, self.directory)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488"""Disk Cache Recipes"""
import functoolsimport mathimport osimport randomimport threadingimport time
from .core import ENOVAL, args_to_key, full_name
class Averager: """Recipe for calculating a running average.
Sometimes known as "online statistics," the running average maintains the total and count. The average can then be calculated at any time.
Assumes the key will not be evicted. Set the eviction policy to 'none' on the cache to guarantee the key is not evicted.
>>> import diskcache >>> cache = diskcache.FanoutCache() >>> ave = Averager(cache, 'latency') >>> ave.add(0.080) >>> ave.add(0.120) >>> ave.get() 0.1 >>> ave.add(0.160) >>> ave.pop() 0.12 >>> print(ave.get()) None
"""
def __init__(self, cache, key, expire=None, tag=None): self._cache = cache self._key = key self._expire = expire self._tag = tag
def add(self, value): """Add `value` to average.""" with self._cache.transact(retry=True): total, count = self._cache.get(self._key, default=(0.0, 0)) total += value count += 1 self._cache.set( self._key, (total, count), expire=self._expire, tag=self._tag, )
def get(self): """Get current average or return `None` if count equals zero.""" total, count = self._cache.get(self._key, default=(0.0, 0), retry=True) return None if count == 0 else total / count
def pop(self): """Return current average and delete key.""" total, count = self._cache.pop(self._key, default=(0.0, 0), retry=True) return None if count == 0 else total / count
class Lock: """Recipe for cross-process and cross-thread lock.
Assumes the key will not be evicted. Set the eviction policy to 'none' on the cache to guarantee the key is not evicted.
>>> import diskcache >>> cache = diskcache.Cache() >>> lock = Lock(cache, 'report-123') >>> lock.acquire() >>> lock.release() >>> with lock: ... pass
"""
def __init__(self, cache, key, expire=None, tag=None): self._cache = cache self._key = key self._expire = expire self._tag = tag
def acquire(self): """Acquire lock using spin-lock algorithm.""" while True: added = self._cache.add( self._key, None, expire=self._expire, tag=self._tag, retry=True, ) if added: break time.sleep(0.001)
def release(self): """Release lock by deleting key.""" self._cache.delete(self._key, retry=True)
def locked(self): """Return true if the lock is acquired.""" return self._key in self._cache
def __enter__(self): self.acquire()
def __exit__(self, *exc_info): self.release()
class RLock: """Recipe for cross-process and cross-thread re-entrant lock.
Assumes the key will not be evicted. Set the eviction policy to 'none' on the cache to guarantee the key is not evicted.
>>> import diskcache >>> cache = diskcache.Cache() >>> rlock = RLock(cache, 'user-123') >>> rlock.acquire() >>> rlock.acquire() >>> rlock.release() >>> with rlock: ... pass >>> rlock.release() >>> rlock.release() Traceback (most recent call last): ... AssertionError: cannot release un-acquired lock
"""
def __init__(self, cache, key, expire=None, tag=None): self._cache = cache self._key = key self._expire = expire self._tag = tag
def acquire(self): """Acquire lock by incrementing count using spin-lock algorithm.""" pid = os.getpid() tid = threading.get_ident() pid_tid = '{}-{}'.format(pid, tid)
while True: with self._cache.transact(retry=True): value, count = self._cache.get(self._key, default=(None, 0)) if pid_tid == value or count == 0: self._cache.set( self._key, (pid_tid, count + 1), expire=self._expire, tag=self._tag, ) return time.sleep(0.001)
def release(self): """Release lock by decrementing count.""" pid = os.getpid() tid = threading.get_ident() pid_tid = '{}-{}'.format(pid, tid)
with self._cache.transact(retry=True): value, count = self._cache.get(self._key, default=(None, 0)) is_owned = pid_tid == value and count > 0 assert is_owned, 'cannot release un-acquired lock' self._cache.set( self._key, (value, count - 1), expire=self._expire, tag=self._tag, )
def __enter__(self): self.acquire()
def __exit__(self, *exc_info): self.release()
class BoundedSemaphore: """Recipe for cross-process and cross-thread bounded semaphore.
Assumes the key will not be evicted. Set the eviction policy to 'none' on the cache to guarantee the key is not evicted.
>>> import diskcache >>> cache = diskcache.Cache() >>> semaphore = BoundedSemaphore(cache, 'max-cons', value=2) >>> semaphore.acquire() >>> semaphore.acquire() >>> semaphore.release() >>> with semaphore: ... pass >>> semaphore.release() >>> semaphore.release() Traceback (most recent call last): ... AssertionError: cannot release un-acquired semaphore
"""
def __init__(self, cache, key, value=1, expire=None, tag=None): self._cache = cache self._key = key self._value = value self._expire = expire self._tag = tag
def acquire(self): """Acquire semaphore by decrementing value using spin-lock algorithm.""" while True: with self._cache.transact(retry=True): value = self._cache.get(self._key, default=self._value) if value > 0: self._cache.set( self._key, value - 1, expire=self._expire, tag=self._tag, ) return time.sleep(0.001)
def release(self): """Release semaphore by incrementing value.""" with self._cache.transact(retry=True): value = self._cache.get(self._key, default=self._value) assert self._value > value, 'cannot release un-acquired semaphore' value += 1 self._cache.set( self._key, value, expire=self._expire, tag=self._tag, )
def __enter__(self): self.acquire()
def __exit__(self, *exc_info): self.release()
def throttle( cache, count, seconds, name=None, expire=None, tag=None, time_func=time.time, sleep_func=time.sleep,): """Decorator to throttle calls to function.
Assumes keys will not be evicted. Set the eviction policy to 'none' on the cache to guarantee the keys are not evicted.
>>> import diskcache, time >>> cache = diskcache.Cache() >>> count = 0 >>> @throttle(cache, 2, 1) # 2 calls per 1 second ... def increment(): ... global count ... count += 1 >>> start = time.time() >>> while (time.time() - start) <= 2: ... increment() >>> count in (6, 7) # 6 or 7 calls depending on CPU load True
"""
def decorator(func): rate = count / float(seconds) key = full_name(func) if name is None else name now = time_func() cache.set(key, (now, count), expire=expire, tag=tag, retry=True)
@functools.wraps(func) def wrapper(*args, **kwargs): while True: with cache.transact(retry=True): last, tally = cache.get(key) now = time_func() tally += (now - last) * rate delay = 0
if tally > count: cache.set(key, (now, count - 1), expire) elif tally >= 1: cache.set(key, (now, tally - 1), expire) else: delay = (1 - tally) / rate
if delay: sleep_func(delay) else: break
return func(*args, **kwargs)
return wrapper
return decorator
def barrier(cache, lock_factory, name=None, expire=None, tag=None): """Barrier to calling decorated function.
Supports different kinds of locks: Lock, RLock, BoundedSemaphore.
Assumes keys will not be evicted. Set the eviction policy to 'none' on the cache to guarantee the keys are not evicted.
>>> import diskcache, time >>> cache = diskcache.Cache() >>> @barrier(cache, Lock) ... def work(num): ... print('worker started') ... time.sleep(1) ... print('worker finished') >>> import multiprocessing.pool >>> pool = multiprocessing.pool.ThreadPool(2) >>> _ = pool.map(work, range(2)) worker started worker finished worker started worker finished >>> pool.terminate()
"""
def decorator(func): key = full_name(func) if name is None else name lock = lock_factory(cache, key, expire=expire, tag=tag)
@functools.wraps(func) def wrapper(*args, **kwargs): with lock: return func(*args, **kwargs)
return wrapper
return decorator
def memoize_stampede( cache, expire, name=None, typed=False, tag=None, beta=1, ignore=()): """Memoizing cache decorator with cache stampede protection.
Cache stampedes are a type of system overload that can occur when parallel computing systems using memoization come under heavy load. This behaviour is sometimes also called dog-piling, cache miss storm, cache choking, or the thundering herd problem.
The memoization decorator implements cache stampede protection through early recomputation. Early recomputation of function results will occur probabilistically before expiration in a background thread of execution. Early probabilistic recomputation is based on research by Vattani, A.; Chierichetti, F.; Lowenstein, K. (2015), Optimal Probabilistic Cache Stampede Prevention, VLDB, pp. 886-897, ISSN 2150-8097
If name is set to None (default), the callable name will be determined automatically.
If typed is set to True, function arguments of different types will be cached separately. For example, f(3) and f(3.0) will be treated as distinct calls with distinct results.
The original underlying function is accessible through the `__wrapped__` attribute. This is useful for introspection, for bypassing the cache, or for rewrapping the function with a different cache.
>>> from diskcache import Cache >>> cache = Cache() >>> @memoize_stampede(cache, expire=1) ... def fib(number): ... if number == 0: ... return 0 ... elif number == 1: ... return 1 ... else: ... return fib(number - 1) + fib(number - 2) >>> print(fib(100)) 354224848179261915075
An additional `__cache_key__` attribute can be used to generate the cache key used for the given arguments.
>>> key = fib.__cache_key__(100) >>> del cache[key]
Remember to call memoize when decorating a callable. If you forget, then a TypeError will occur.
:param cache: cache to store callable arguments and return values :param float expire: seconds until arguments expire :param str name: name given for callable (default None, automatic) :param bool typed: cache different types separately (default False) :param str tag: text to associate with arguments (default None) :param set ignore: positional or keyword args to ignore (default ()) :return: callable decorator
""" # Caution: Nearly identical code exists in Cache.memoize def decorator(func): """Decorator created by memoize call for callable.""" base = (full_name(func),) if name is None else (name,)
def timer(*args, **kwargs): """Time execution of `func` and return result and time delta.""" start = time.time() result = func(*args, **kwargs) delta = time.time() - start return result, delta
@functools.wraps(func) def wrapper(*args, **kwargs): """Wrapper for callable to cache arguments and return values.""" key = wrapper.__cache_key__(*args, **kwargs) pair, expire_time = cache.get( key, default=ENOVAL, expire_time=True, retry=True, )
if pair is not ENOVAL: result, delta = pair now = time.time() ttl = expire_time - now
if (-delta * beta * math.log(random.random())) < ttl: return result # Cache hit.
# Check whether a thread has started for early recomputation.
thread_key = key + (ENOVAL,) thread_added = cache.add( thread_key, None, expire=delta, retry=True, )
if thread_added: # Start thread for early recomputation. def recompute(): with cache: pair = timer(*args, **kwargs) cache.set( key, pair, expire=expire, tag=tag, retry=True, )
thread = threading.Thread(target=recompute) thread.daemon = True thread.start()
return result
pair = timer(*args, **kwargs) cache.set(key, pair, expire=expire, tag=tag, retry=True) return pair[0]
def __cache_key__(*args, **kwargs): """Make key for cache given function arguments.""" return args_to_key(base, args, kwargs, typed, ignore)
wrapper.__cache_key__ = __cache_key__ return wrapper
return decorator1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586#pragma once
#include "ggml.h"
#ifdef __cplusplusextern "C" {#endif
typedef struct ggml_backend_buffer_type * ggml_backend_buffer_type_t;typedef struct ggml_backend_buffer * ggml_backend_buffer_t;typedef struct ggml_backend * ggml_backend_t;
// Tensor allocatorstruct ggml_tallocr { ggml_backend_buffer_t buffer; void * base; size_t alignment; size_t offset;};
GGML_API struct ggml_tallocr ggml_tallocr_new(ggml_backend_buffer_t buffer);GGML_API enum ggml_status ggml_tallocr_alloc(struct ggml_tallocr * talloc, struct ggml_tensor * tensor);
// Graph allocator/* Example usage: ggml_gallocr_t galloc = ggml_gallocr_new(ggml_backend_cpu_buffer_type());
// optional: create a worst-case graph and reserve the buffers to avoid reallocations ggml_gallocr_reserve(galloc, build_graph(max_batch));
// allocate the graph struct ggml_cgraph * graph = build_graph(batch); ggml_gallocr_alloc_graph(galloc, graph);
printf("compute buffer size: %zu bytes\n", ggml_gallocr_get_buffer_size(galloc, 0));
// evaluate the graph ggml_backend_graph_compute(backend, graph);*/
// special tensor flags for use with the graph allocator:// ggml_set_input(): all input tensors are allocated at the beginning of the graph in non-overlapping addresses// ggml_set_output(): output tensors are never freed and never overwritten
typedef struct ggml_gallocr * ggml_gallocr_t;
GGML_API ggml_gallocr_t ggml_gallocr_new(ggml_backend_buffer_type_t buft);GGML_API ggml_gallocr_t ggml_gallocr_new_n(ggml_backend_buffer_type_t * bufts, int n_bufs);GGML_API void ggml_gallocr_free(ggml_gallocr_t galloc);
// pre-allocate buffers from a measure graph - does not allocate or modify the graph// call with a worst-case graph to avoid buffer reallocations// not strictly required for single buffer usage: ggml_gallocr_alloc_graph will reallocate the buffers automatically if needed// returns false if the buffer allocation failed// ggml_gallocr_resrve_n_size writes the buffer sizes per galloc buffer that would be allocated by ggml_gallocr_reserve_n to sizesGGML_API bool ggml_gallocr_reserve(ggml_gallocr_t galloc, struct ggml_cgraph * graph);GGML_API void ggml_gallocr_reserve_n_size( ggml_gallocr_t galloc, struct ggml_cgraph * graph, const int * node_buffer_ids, const int * leaf_buffer_ids, size_t * sizes);GGML_API bool ggml_gallocr_reserve_n( ggml_gallocr_t galloc, struct ggml_cgraph * graph, const int * node_buffer_ids, const int * leaf_buffer_ids);
// automatic reallocation if the topology changes when using a single buffer// returns false if using multiple buffers and a re-allocation is needed (call ggml_gallocr_reserve_n first to set the node buffers)GGML_API bool ggml_gallocr_alloc_graph(ggml_gallocr_t galloc, struct ggml_cgraph * graph);
GGML_API size_t ggml_gallocr_get_buffer_size(ggml_gallocr_t galloc, int buffer_id);
// Utils// Create a buffer and allocate all the tensors in a ggml_context// ggml_backend_alloc_ctx_tensors_from_buft_size returns the size of the buffer that would be allocated by ggml_backend_alloc_ctx_tensors_from_buft// ggml_backend_alloc_ctx_tensors_from_buft returns NULL on failure or if all tensors in ctx are already allocated or zero-sizedGGML_API size_t ggml_backend_alloc_ctx_tensors_from_buft_size(struct ggml_context * ctx, ggml_backend_buffer_type_t buft);GGML_API struct ggml_backend_buffer * ggml_backend_alloc_ctx_tensors_from_buft(struct ggml_context * ctx, ggml_backend_buffer_type_t buft);GGML_API struct ggml_backend_buffer * ggml_backend_alloc_ctx_tensors(struct ggml_context * ctx, ggml_backend_t backend);
#ifdef __cplusplus}#endif123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437#pragma once
#include "ggml.h"#include "ggml-alloc.h"
#ifdef GGML_BACKEND_SHARED# if defined(_WIN32) && !defined(__MINGW32__)# ifdef GGML_BACKEND_BUILD# define GGML_BACKEND_API __declspec(dllexport) extern# else# define GGML_BACKEND_API __declspec(dllimport) extern# endif# else# define GGML_BACKEND_API __attribute__ ((visibility ("default"))) extern# endif#else# define GGML_BACKEND_API extern#endif
#ifdef __cplusplusextern "C" {#endif
typedef struct ggml_backend_buffer_type * ggml_backend_buffer_type_t; typedef struct ggml_backend_buffer * ggml_backend_buffer_t; typedef struct ggml_backend_event * ggml_backend_event_t; typedef struct ggml_backend * ggml_backend_t; typedef void * ggml_backend_graph_plan_t; typedef struct ggml_backend_reg * ggml_backend_reg_t; typedef struct ggml_backend_device * ggml_backend_dev_t;
// // Backend buffer type //
GGML_API const char * ggml_backend_buft_name (ggml_backend_buffer_type_t buft); GGML_API ggml_backend_buffer_t ggml_backend_buft_alloc_buffer (ggml_backend_buffer_type_t buft, size_t size); GGML_API size_t ggml_backend_buft_get_alignment (ggml_backend_buffer_type_t buft); GGML_API size_t ggml_backend_buft_get_max_size (ggml_backend_buffer_type_t buft); GGML_API size_t ggml_backend_buft_get_alloc_size(ggml_backend_buffer_type_t buft, const struct ggml_tensor * tensor); GGML_API bool ggml_backend_buft_is_host (ggml_backend_buffer_type_t buft); GGML_API ggml_backend_dev_t ggml_backend_buft_get_device (ggml_backend_buffer_type_t buft);
// // Backend buffer //
enum ggml_backend_buffer_usage { GGML_BACKEND_BUFFER_USAGE_ANY = 0, GGML_BACKEND_BUFFER_USAGE_WEIGHTS = 1, GGML_BACKEND_BUFFER_USAGE_COMPUTE = 2, };
GGML_API const char * ggml_backend_buffer_name (ggml_backend_buffer_t buffer); GGML_API void ggml_backend_buffer_free (ggml_backend_buffer_t buffer); GGML_API void * ggml_backend_buffer_get_base (ggml_backend_buffer_t buffer); GGML_API size_t ggml_backend_buffer_get_size (ggml_backend_buffer_t buffer); GGML_API enum ggml_status ggml_backend_buffer_init_tensor (ggml_backend_buffer_t buffer, struct ggml_tensor * tensor); GGML_API size_t ggml_backend_buffer_get_alignment (ggml_backend_buffer_t buffer); GGML_API size_t ggml_backend_buffer_get_max_size (ggml_backend_buffer_t buffer); GGML_API size_t ggml_backend_buffer_get_alloc_size(ggml_backend_buffer_t buffer, const struct ggml_tensor * tensor); GGML_API void ggml_backend_buffer_clear (ggml_backend_buffer_t buffer, uint8_t value); GGML_API bool ggml_backend_buffer_is_host (ggml_backend_buffer_t buffer); GGML_API void ggml_backend_buffer_set_usage (ggml_backend_buffer_t buffer, enum ggml_backend_buffer_usage usage); GGML_API enum ggml_backend_buffer_usage ggml_backend_buffer_get_usage (ggml_backend_buffer_t buffer); GGML_API ggml_backend_buffer_type_t ggml_backend_buffer_get_type (ggml_backend_buffer_t buffer); GGML_API void ggml_backend_buffer_reset (ggml_backend_buffer_t buffer);
// tensor copy between different backends GGML_API void ggml_backend_tensor_copy(const struct ggml_tensor * src, struct ggml_tensor * dst);
// // Backend (stream) //
GGML_API ggml_guid_t ggml_backend_guid(ggml_backend_t backend); GGML_API const char * ggml_backend_name(ggml_backend_t backend); GGML_API void ggml_backend_free(ggml_backend_t backend);
GGML_API ggml_backend_buffer_type_t ggml_backend_get_default_buffer_type(ggml_backend_t backend); GGML_API ggml_backend_buffer_t ggml_backend_alloc_buffer(ggml_backend_t backend, size_t size); GGML_API size_t ggml_backend_get_alignment(ggml_backend_t backend); GGML_API size_t ggml_backend_get_max_size(ggml_backend_t backend);
GGML_API void ggml_backend_tensor_set_async (ggml_backend_t backend, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size); GGML_API void ggml_backend_tensor_get_async (ggml_backend_t backend, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size); GGML_API void ggml_backend_tensor_set_2d_async(ggml_backend_t backend, struct ggml_tensor * tensor, const void * data, size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data); GGML_API void ggml_backend_tensor_get_2d_async(ggml_backend_t backend, const struct ggml_tensor * tensor, void * data, size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data);
// "offset" refers to the offset in tensor->data for setting/getting data GGML_API void ggml_backend_tensor_set ( struct ggml_tensor * tensor, const void * data, size_t offset, size_t size); GGML_API void ggml_backend_tensor_get (const struct ggml_tensor * tensor, void * data, size_t offset, size_t size); GGML_API void ggml_backend_tensor_set_2d( struct ggml_tensor * tensor, const void * data, size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data); GGML_API void ggml_backend_tensor_get_2d(const struct ggml_tensor * tensor, void * data, size_t offset, size_t size, size_t n_copies, size_t stride_tensor, size_t stride_data); GGML_API void ggml_backend_tensor_memset( struct ggml_tensor * tensor, uint8_t value, size_t offset, size_t size);
GGML_API void ggml_backend_synchronize(ggml_backend_t backend);
GGML_API ggml_backend_graph_plan_t ggml_backend_graph_plan_create(ggml_backend_t backend, struct ggml_cgraph * cgraph); GGML_API void ggml_backend_graph_plan_free (ggml_backend_t backend, ggml_backend_graph_plan_t plan);
GGML_API enum ggml_status ggml_backend_graph_plan_compute (ggml_backend_t backend, ggml_backend_graph_plan_t plan); GGML_API enum ggml_status ggml_backend_graph_compute (ggml_backend_t backend, struct ggml_cgraph * cgraph); GGML_API enum ggml_status ggml_backend_graph_compute_async(ggml_backend_t backend, struct ggml_cgraph * cgraph);
// NOTE: will be removed, use device version instead GGML_API bool ggml_backend_supports_op(ggml_backend_t backend, const struct ggml_tensor * op); GGML_API bool ggml_backend_supports_buft(ggml_backend_t backend, ggml_backend_buffer_type_t buft); GGML_API bool ggml_backend_offload_op(ggml_backend_t backend, const struct ggml_tensor * op);
// asynchronous copy // the copy is performed after all the currently queued operations in backend_src // backend_dst will wait for the copy to complete before performing other operations // automatic fallback to sync copy if async is not supported GGML_API void ggml_backend_tensor_copy_async(ggml_backend_t backend_src, ggml_backend_t backend_dst, const struct ggml_tensor * src, struct ggml_tensor * dst);
GGML_API ggml_backend_dev_t ggml_backend_get_device(ggml_backend_t backend);
// // Events //
GGML_API ggml_backend_event_t ggml_backend_event_new(ggml_backend_dev_t device); GGML_API void ggml_backend_event_free(ggml_backend_event_t event); GGML_API void ggml_backend_event_record(ggml_backend_event_t event, ggml_backend_t backend); GGML_API void ggml_backend_event_synchronize(ggml_backend_event_t event); GGML_API void ggml_backend_event_wait(ggml_backend_t backend, ggml_backend_event_t event);
// // Backend device //
enum ggml_backend_dev_type { // CPU device using system memory GGML_BACKEND_DEVICE_TYPE_CPU, // GPU device using dedicated memory GGML_BACKEND_DEVICE_TYPE_GPU, // integrated GPU device using host memory GGML_BACKEND_DEVICE_TYPE_IGPU, // accelerator devices intended to be used together with the CPU backend (e.g. BLAS or AMX) GGML_BACKEND_DEVICE_TYPE_ACCEL, // "meta" device wrapping multiple other devices for tensor parallelism GGML_BACKEND_DEVICE_TYPE_META, };
// functionality supported by the device struct ggml_backend_dev_caps { // asynchronous operations bool async; // pinned host buffer bool host_buffer; // creating buffers from host ptr bool buffer_from_host_ptr; // event synchronization bool events; // mmap is supported for loading bool mmap_support; };
// all the device properties struct ggml_backend_dev_props { // device name const char * name; // device description const char * description; // device free memory in bytes size_t memory_free; // device total memory in bytes size_t memory_total; // device type enum ggml_backend_dev_type type; // device id // for PCI devices, this should be the lower-case PCI bus id formatted as "domain:bus:device.function" (e.g. "0000:c1:00.0") // if the id is unknown, this should be NULL const char * device_id; // device capabilities struct ggml_backend_dev_caps caps; };
GGML_API const char * ggml_backend_dev_name(ggml_backend_dev_t device); GGML_API const char * ggml_backend_dev_description(ggml_backend_dev_t device); GGML_API void ggml_backend_dev_memory(ggml_backend_dev_t device, size_t * free, size_t * total); GGML_API enum ggml_backend_dev_type ggml_backend_dev_type(ggml_backend_dev_t device); GGML_API void ggml_backend_dev_get_props(ggml_backend_dev_t device, struct ggml_backend_dev_props * props); GGML_API ggml_backend_reg_t ggml_backend_dev_backend_reg(ggml_backend_dev_t device); GGML_API ggml_backend_t ggml_backend_dev_init(ggml_backend_dev_t device, const char * params); GGML_API ggml_backend_buffer_type_t ggml_backend_dev_buffer_type(ggml_backend_dev_t device); GGML_API ggml_backend_buffer_type_t ggml_backend_dev_host_buffer_type(ggml_backend_dev_t device); GGML_API ggml_backend_buffer_t ggml_backend_dev_buffer_from_host_ptr(ggml_backend_dev_t device, void * ptr, size_t size, size_t max_tensor_size);
GGML_API bool ggml_backend_dev_supports_op(ggml_backend_dev_t device, const struct ggml_tensor * op); GGML_API bool ggml_backend_dev_supports_buft(ggml_backend_dev_t device, ggml_backend_buffer_type_t buft); GGML_API bool ggml_backend_dev_offload_op(ggml_backend_dev_t device, const struct ggml_tensor * op);
// // Backend (reg) //
GGML_API const char * ggml_backend_reg_name(ggml_backend_reg_t reg); GGML_API size_t ggml_backend_reg_dev_count(ggml_backend_reg_t reg); GGML_API ggml_backend_dev_t ggml_backend_reg_dev_get(ggml_backend_reg_t reg, size_t index); GGML_API void * ggml_backend_reg_get_proc_address(ggml_backend_reg_t reg, const char * name);
// Common functions that may be obtained using ggml_backend_reg_get_proc_address
// Context management and operations for faster communication between backends, used for tensor parallelism (meta backend) typedef void * (*ggml_backend_comm_init_t)(ggml_backend_t * backends, size_t n_backends); typedef void (*ggml_backend_comm_free_t)(void * comm_ctx); typedef bool (*ggml_backend_comm_allreduce_tensor_t)(void * comm_ctx, struct ggml_tensor ** tensors);
// Split buffer type for tensor parallelism (old) typedef ggml_backend_buffer_type_t (*ggml_backend_split_buffer_type_t)(int main_device, const float * tensor_split); // Set the number of threads for the backend typedef void (*ggml_backend_set_n_threads_t)(ggml_backend_t backend, int n_threads); // Get additional buffer types provided by the device (returns a NULL-terminated array) typedef ggml_backend_buffer_type_t * (*ggml_backend_dev_get_extra_bufts_t)(ggml_backend_dev_t device); // Set the abort callback for the backend typedef void (*ggml_backend_set_abort_callback_t)(ggml_backend_t backend, ggml_abort_callback abort_callback, void * abort_callback_data); // Get a list of feature flags supported by the backend (returns a NULL-terminated array) struct ggml_backend_feature { const char * name; const char * value; }; typedef struct ggml_backend_feature * (*ggml_backend_get_features_t)(ggml_backend_reg_t reg);
// // Backend registry //
GGML_API void ggml_backend_register(ggml_backend_reg_t reg);
GGML_API void ggml_backend_device_register(ggml_backend_dev_t device);
// Backend (reg) enumeration GGML_API size_t ggml_backend_reg_count(void); GGML_API ggml_backend_reg_t ggml_backend_reg_get(size_t index); GGML_API ggml_backend_reg_t ggml_backend_reg_by_name(const char * name);
// Device enumeration GGML_API size_t ggml_backend_dev_count(void); GGML_API ggml_backend_dev_t ggml_backend_dev_get(size_t index); GGML_API ggml_backend_dev_t ggml_backend_dev_by_name(const char * name); GGML_API ggml_backend_dev_t ggml_backend_dev_by_type(enum ggml_backend_dev_type type);
// Direct backend (stream) initialization // = ggml_backend_dev_init(ggml_backend_dev_by_name(name), params) GGML_API ggml_backend_t ggml_backend_init_by_name(const char * name, const char * params); // = ggml_backend_dev_init(ggml_backend_dev_by_type(type), params) GGML_API ggml_backend_t ggml_backend_init_by_type(enum ggml_backend_dev_type type, const char * params); // = ggml_backend_dev_init(ggml_backend_dev_by_type(GPU) OR ggml_backend_dev_by_type(CPU), NULL) GGML_API ggml_backend_t ggml_backend_init_best(void);
// Load a backend from a dynamic library and register it GGML_API ggml_backend_reg_t ggml_backend_load(const char * path); // Unload a backend if loaded dynamically and unregister it GGML_API void ggml_backend_unload(ggml_backend_reg_t reg); // Load all known backends from dynamic libraries GGML_API void ggml_backend_load_all(void); GGML_API void ggml_backend_load_all_from_path(const char * dir_path);
// // Backend scheduler //
// The backend scheduler allows for multiple backend devices to be used together // Handles compute buffer allocation, assignment of tensors to backends, and copying of tensors between backends // The backends are selected based on: // - the backend that supports the operation // - the location of the pre-allocated tensors (e.g. the weights) /* Example usage:
// operations that use tensors allocated in a buffer with USAGE_WEIGHTS will be assigned // preferably to run on the same backend as the buffer ggml_backend_buffer_set_usage(buf_weights, GGML_BACKEND_BUFFER_USAGE_WEIGHTS);
sched = ggml_backend_sched_new({backend_gpu, backend_gpu2, backend_cpu}, NULL, num_backends, GGML_DEFAULT_GRAPH_SIZE, false, true);
// initialize buffers from a max size graph (optional) reserve_graph = build_graph(sched, max_batch_size);
// manually assign nodes to a backend (optional, should not be needed in most cases) struct ggml_tensor * node = ggml_mul_mat(ctx, ...); ggml_backend_sched_set_tensor_backend(sched, node, backend_gpu);
ggml_backend_sched_reserve(sched, reserve_graph);
// compute graph = build_graph(sched); // the graph and its tensors are single-use in terms of allocation, multi-use in terms of computation for (int i = 0; i < 10; ++i) { ggml_backend_sched_graph_compute(sched, graph); // on the first iteration the graph is allocated automatically }
// if there are graph inputs: graph = build_graph(sched); // get a new graph that is not allocated (the metadata for the old graph is freed once ggml_free is called) ggml_backend_sched_reset(sched); // clear the allocation of the previous graph ggml_backend_sched_alloc_graph(sched, graph); // explicitly allocate the new graph but do not execute it ggml_backend_tensor_set(input_tensor, ...); // copy data to the newly allocated graph tensors ggml_backend_sched_graph_compute(sched, graph); // execute the graph
// as an alternative to the above it is also possible to assign the inputs to a dedicated context and // allocate them statically via ggml_backend_alloc_ctx_tensors } */
typedef struct ggml_backend_sched * ggml_backend_sched_t;
// Evaluation callback for each node in the graph (set with ggml_backend_sched_set_eval_callback) // when ask == true, the scheduler wants to know if the user wants to observe this node // this allows the scheduler to batch nodes together in order to evaluate them in a single call // // when ask == false, the scheduler is passing the node tensor to the user for observation // if the user returns false, the scheduler will cancel the graph compute // typedef bool (*ggml_backend_sched_eval_callback)(struct ggml_tensor * t, bool ask, void * user_data);
// Initialize a backend scheduler, backends with low index are given priority over backends with high index GGML_API ggml_backend_sched_t ggml_backend_sched_new(ggml_backend_t * backends, ggml_backend_buffer_type_t * bufts, int n_backends, size_t graph_size, bool parallel, bool op_offload); GGML_API void ggml_backend_sched_free(ggml_backend_sched_t sched);
// Initialize backend buffers from a measure graph GGML_API void ggml_backend_sched_reserve_size(ggml_backend_sched_t sched, struct ggml_cgraph * measure_graph, size_t * sizes); GGML_API bool ggml_backend_sched_reserve(ggml_backend_sched_t sched, struct ggml_cgraph * measure_graph); // returns success
GGML_API int ggml_backend_sched_get_n_backends(ggml_backend_sched_t sched); GGML_API ggml_backend_t ggml_backend_sched_get_backend(ggml_backend_sched_t sched, int i);
// Get the number of splits of the last graph GGML_API int ggml_backend_sched_get_n_splits(ggml_backend_sched_t sched); GGML_API int ggml_backend_sched_get_n_copies(ggml_backend_sched_t sched);
GGML_API ggml_backend_buffer_type_t ggml_backend_sched_get_buffer_type(ggml_backend_sched_t sched, ggml_backend_t backend); GGML_API size_t ggml_backend_sched_get_buffer_size(ggml_backend_sched_t sched, ggml_backend_t backend);
GGML_API void ggml_backend_sched_set_tensor_backend(ggml_backend_sched_t sched, struct ggml_tensor * node, ggml_backend_t backend); GGML_API ggml_backend_t ggml_backend_sched_get_tensor_backend(ggml_backend_sched_t sched, struct ggml_tensor * node);
// Split graph without allocating it GGML_API void ggml_backend_sched_split_graph(ggml_backend_sched_t sched, struct ggml_cgraph * graph);
// Allocate and compute graph on the backend scheduler GGML_API bool ggml_backend_sched_alloc_graph(ggml_backend_sched_t sched, struct ggml_cgraph * graph); // returns success GGML_API enum ggml_status ggml_backend_sched_graph_compute(ggml_backend_sched_t sched, struct ggml_cgraph * graph); GGML_API enum ggml_status ggml_backend_sched_graph_compute_async(ggml_backend_sched_t sched, struct ggml_cgraph * graph); GGML_API void ggml_backend_sched_synchronize(ggml_backend_sched_t sched);
// Reset all assignments and allocators - must be called before changing the node backends or allocating a new graph. // This in effect deallocates all tensors that were previously allocated and leaves them with dangling pointers. // The correct way to use this API is to discard the deallocated tensors and create new ones. GGML_API void ggml_backend_sched_reset(ggml_backend_sched_t sched);
// Set a callback to be called for each resulting node during graph compute GGML_API void ggml_backend_sched_set_eval_callback(ggml_backend_sched_t sched, ggml_backend_sched_eval_callback callback, void * user_data);
// // Meta backend //
#define GGML_BACKEND_META_MAX_DEVICES 16
enum ggml_backend_meta_split_axis { // tensor split by tensor dimensions: GGML_BACKEND_SPLIT_AXIS_0 = 0, GGML_BACKEND_SPLIT_AXIS_1 = 1, GGML_BACKEND_SPLIT_AXIS_2 = 2, GGML_BACKEND_SPLIT_AXIS_3 = 3,
GGML_BACKEND_SPLIT_AXIS_MIRRORED = 10, // all values on all backends GGML_BACKEND_SPLIT_AXIS_PARTIAL = 11, // each backend has a partial sum
// for internal bookkeeping only: GGML_BACKEND_SPLIT_AXIS_NONE = 98, GGML_BACKEND_SPLIT_AXIS_UNKNOWN = 99, }; GGML_API const char * ggml_backend_meta_split_axis_name(enum ggml_backend_meta_split_axis split_axis);
struct ggml_backend_meta_split_state { enum ggml_backend_meta_split_axis axis;
// for tensors with axis >= 0 && axis < GGML_MAX_DIMS: // - each device has a slice of the tensor along the split axis // - most tensors have n_segments == 1 and a contiguous slice of the tensor data // - some tensors have an inhomogenenous data layout along the split axis, // those tensors are divided into segments which are each individually split across devices // - ne has one entry per segment and device and that segment repeats nr times, // in total when accounting for repetitions the segments add up to ggml_tensor::ne for that axis, // the outer/inner loops are over segments/devices like [seg0_dev0_r0, seg0_dev1_r0, seg0_dev0_r1, seg0_dev1_r1, seg1_dev0_r0, seg1_dev1_r0], // - for example, a transformer may have a fused QKV matrix rather than 3 matrices, those would be 3 separate segments // that each need to be split individually across devices so that each device gets a slice of Q, K, and V, // the Q matrix can be larger than the K and V matrices so this can either be expressed as 3 segments or as 2 segments // where the segment for K/V repeats twice int64_t ne[16*GGML_BACKEND_META_MAX_DEVICES]; uint32_t nr[16]; uint32_t n_segments; };
// function to assign split states for statically allocated tensors, compute tensor split states will be assigned to be compatible: typedef struct ggml_backend_meta_split_state(*ggml_backend_meta_get_split_state_t)(const struct ggml_tensor * tensor, void * userdata);
// create a new meta device from "simple" devices, meta buffer type/buffer/backend is then derived from this: // TODO: this looks a bit strange - a backend API creates a device. I think we should try // express this as a backend registry functionality instead GGML_API ggml_backend_dev_t ggml_backend_meta_device( ggml_backend_dev_t * devs, size_t n_devs, ggml_backend_meta_get_split_state_t get_split_state, void * get_split_state_ud);
// // Utils //
struct ggml_backend_graph_copy { ggml_backend_buffer_t buffer; struct ggml_context * ctx_allocated; struct ggml_context * ctx_unallocated; struct ggml_cgraph * graph; };
// Copy a graph to a different backend GGML_API struct ggml_backend_graph_copy ggml_backend_graph_copy(ggml_backend_t backend, struct ggml_cgraph * graph); GGML_API void ggml_backend_graph_copy_free(struct ggml_backend_graph_copy copy);
typedef bool (*ggml_backend_eval_callback)(int node_index, struct ggml_tensor * t1, struct ggml_tensor * t2, void * user_data);
// Compare the output of two backends GGML_API bool ggml_backend_compare_graph_backend(ggml_backend_t backend1, ggml_backend_t backend2, struct ggml_cgraph * graph, ggml_backend_eval_callback callback, void * user_data, struct ggml_tensor const * const * test_nodes, size_t num_test_nodes);
// Tensor initialization GGML_API enum ggml_status ggml_backend_tensor_alloc(ggml_backend_buffer_t buffer, struct ggml_tensor * tensor, void * addr); GGML_API enum ggml_status ggml_backend_view_init(struct ggml_tensor * tensor);
// CPU buffer types are always available GGML_API ggml_backend_buffer_t ggml_backend_cpu_buffer_from_ptr(void * ptr, size_t size); GGML_API ggml_backend_buffer_type_t ggml_backend_cpu_buffer_type(void);
#ifdef __cplusplus}#endif12345678910111213141516171819202122232425#pragma once
#include "ggml.h"#include "ggml-backend.h"
#ifdef __cplusplusextern "C" {#endif
// backend APIGGML_BACKEND_API ggml_backend_t ggml_backend_blas_init(void);
GGML_BACKEND_API bool ggml_backend_is_blas(ggml_backend_t backend);
// number of threads used for conversion to float// for openblas and blis, this will also set the number of threads used for blas operationsGGML_BACKEND_API void ggml_backend_blas_set_n_threads(ggml_backend_t backend_blas, int n_threads);
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_blas_reg(void);
#ifdef __cplusplus}#endif123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123/* * Copyright (c) 2023-2026 The ggml authors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */
#pragma once
#include "ggml-backend.h"#include "ggml.h"
#ifdef __cplusplusextern "C" {#endif
/** * @brief Maximum number of CANN devices supported. */#define GGML_CANN_MAX_DEVICES 16
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_cann_reg(void);
/** * @brief Initializes the CANN backend for a specified device. * * This function initializes the CANN backend for the given device. * It verifies the device index, allocates a context, and creates a backend * instance. * * @param device The index of the device to initialize. * @return A pointer to the initialized backend instance, or nullptr on failure. */GGML_BACKEND_API ggml_backend_t ggml_backend_cann_init(int32_t device);
/** * @brief Checks if a given backend is a CANN backend. * * This function verifies if the provided backend is a CANN backend by comparing * its GUID with the CANN backend's GUID. * * @param backend The backend instance to check. * @return True if the backend is a CANN backend, false otherwise. */GGML_BACKEND_API bool ggml_backend_is_cann(ggml_backend_t backend);
/** * @brief Retrieves the CANN buffer type for a specified device. * * This function initializes and returns the buffer type interface associated * with the given device. It ensures thread-safe access using a mutex. * * @param device The device index for which to retrieve the buffer type. * @return A pointer to the buffer type interface for the specified device, or * nullptr if the device index is out of range. */GGML_BACKEND_API ggml_backend_buffer_type_tggml_backend_cann_buffer_type(int32_t device);
/** * @brief Retrieves the number of CANN devices available. * * This function returns the number of CANN devices available based on * information obtained from `ggml_cann_info()`. * * @return The number of CANN devices available. */GGML_BACKEND_API int32_t ggml_backend_cann_get_device_count(void);
/** * @brief pinned host buffer for use with the CPU backend for faster copies between CPU and NPU. * * @return A pointer to the host buffer type interface. */GGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_cann_host_buffer_type(void);
/** * @brief Retrieves the description of a specific CANN device. * * This function sets the specified device, retrieves the SoC name, * and writes it into the provided description buffer. * * @param device The device index to retrieve the description for. * @param description Pointer to a buffer where the description will be written. * @param description_size Size of the description buffer. */GGML_BACKEND_API void ggml_backend_cann_get_device_description( int32_t device, char* description, size_t description_size);
/** * @brief Retrieves the memory information of a specific CANN device. * * This function sets the specified device, retrieves the free and total * memory information of the specified type (ACL_HBM_MEM), and stores them * in the provided pointers. * * @param device The device index to retrieve memory information for. * @param free Pointer to a variable where the free memory size will be stored. * @param total Pointer to a variable where the total memory size will be * stored. */GGML_BACKEND_API void ggml_backend_cann_get_device_memory(int32_t device, size_t* free, size_t* total);
#ifdef __cplusplus}#endif123456789101112131415161718192021222324252627282930313233343536373839#pragma once
#ifndef __cplusplus#error "This header is for C++ only"#endif
#include "ggml.h"#include "ggml-alloc.h"#include "ggml-backend.h"#include "gguf.h"#include <memory>
// Smart pointers for ggml types
// ggml
struct ggml_context_deleter { void operator()(ggml_context * ctx) { ggml_free(ctx); } };struct gguf_context_deleter { void operator()(gguf_context * ctx) { gguf_free(ctx); } };
typedef std::unique_ptr<ggml_context, ggml_context_deleter> ggml_context_ptr;typedef std::unique_ptr<gguf_context, gguf_context_deleter> gguf_context_ptr;
// ggml-alloc
struct ggml_gallocr_deleter { void operator()(ggml_gallocr_t galloc) { ggml_gallocr_free(galloc); } };
typedef std::unique_ptr<ggml_gallocr, ggml_gallocr_deleter> ggml_gallocr_ptr;
// ggml-backend
struct ggml_backend_deleter { void operator()(ggml_backend_t backend) { ggml_backend_free(backend); } };struct ggml_backend_buffer_deleter { void operator()(ggml_backend_buffer_t buffer) { ggml_backend_buffer_free(buffer); } };struct ggml_backend_event_deleter { void operator()(ggml_backend_event_t event) { ggml_backend_event_free(event); } };struct ggml_backend_sched_deleter { void operator()(ggml_backend_sched_t sched) { ggml_backend_sched_free(sched); } };
typedef std::unique_ptr<ggml_backend, ggml_backend_deleter> ggml_backend_ptr;typedef std::unique_ptr<ggml_backend_buffer, ggml_backend_buffer_deleter> ggml_backend_buffer_ptr;typedef std::unique_ptr<ggml_backend_event, ggml_backend_event_deleter> ggml_backend_event_ptr;typedef std::unique_ptr<ggml_backend_sched, ggml_backend_sched_deleter> ggml_backend_sched_ptr;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152#pragma once
#include "ggml.h"#include "ggml-backend.h"
#ifdef __cplusplusextern "C" {#endif
// the compute plan that needs to be prepared for ggml_graph_compute() // since https://github.com/ggml-org/ggml/issues/287 struct ggml_cplan { size_t work_size; // size of work buffer, calculated by `ggml_graph_plan()` uint8_t * work_data; // work buffer, to be allocated by caller before calling to `ggml_graph_compute()`
int n_threads; struct ggml_threadpool * threadpool;
// abort ggml_graph_compute when true ggml_abort_callback abort_callback; void * abort_callback_data;
// use only reference implementations bool use_ref; };
// numa strategies enum ggml_numa_strategy { GGML_NUMA_STRATEGY_DISABLED = 0, GGML_NUMA_STRATEGY_DISTRIBUTE = 1, GGML_NUMA_STRATEGY_ISOLATE = 2, GGML_NUMA_STRATEGY_NUMACTL = 3, GGML_NUMA_STRATEGY_MIRROR = 4, GGML_NUMA_STRATEGY_COUNT };
GGML_BACKEND_API void ggml_numa_init(enum ggml_numa_strategy numa); // call once for better performance on NUMA systems GGML_BACKEND_API bool ggml_is_numa(void); // true if init detected that system has >1 NUMA node
GGML_BACKEND_API struct ggml_tensor * ggml_new_i32(struct ggml_context * ctx, int32_t value); GGML_BACKEND_API struct ggml_tensor * ggml_new_f32(struct ggml_context * ctx, float value);
GGML_BACKEND_API struct ggml_tensor * ggml_set_i32 (struct ggml_tensor * tensor, int32_t value); GGML_BACKEND_API struct ggml_tensor * ggml_set_f32 (struct ggml_tensor * tensor, float value);
GGML_BACKEND_API int32_t ggml_get_i32_1d(const struct ggml_tensor * tensor, int i); GGML_BACKEND_API void ggml_set_i32_1d(const struct ggml_tensor * tensor, int i, int32_t value);
GGML_BACKEND_API int32_t ggml_get_i32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3); GGML_BACKEND_API void ggml_set_i32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3, int32_t value);
GGML_BACKEND_API float ggml_get_f32_1d(const struct ggml_tensor * tensor, int i); GGML_BACKEND_API void ggml_set_f32_1d(const struct ggml_tensor * tensor, int i, float value);
GGML_BACKEND_API float ggml_get_f32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3); GGML_BACKEND_API void ggml_set_f32_nd(const struct ggml_tensor * tensor, int i0, int i1, int i2, int i3, float value);
GGML_BACKEND_API struct ggml_threadpool * ggml_threadpool_new (struct ggml_threadpool_params * params); GGML_BACKEND_API void ggml_threadpool_free (struct ggml_threadpool * threadpool); GGML_BACKEND_API int ggml_threadpool_get_n_threads (struct ggml_threadpool * threadpool); GGML_BACKEND_API void ggml_threadpool_pause (struct ggml_threadpool * threadpool); GGML_BACKEND_API void ggml_threadpool_resume (struct ggml_threadpool * threadpool);
// ggml_graph_plan() has to be called before ggml_graph_compute() // when plan.work_size > 0, caller must allocate memory for plan.work_data GGML_BACKEND_API struct ggml_cplan ggml_graph_plan( const struct ggml_cgraph * cgraph, int n_threads, /* = GGML_DEFAULT_N_THREADS */ struct ggml_threadpool * threadpool /* = NULL */ ); GGML_BACKEND_API enum ggml_status ggml_graph_compute(struct ggml_cgraph * cgraph, struct ggml_cplan * cplan);
// same as ggml_graph_compute() but the work data is allocated as a part of the context // note: the drawback of this API is that you must have ensured that the context has enough memory for the work data GGML_BACKEND_API enum ggml_status ggml_graph_compute_with_ctx(struct ggml_context * ctx, struct ggml_cgraph * cgraph, int n_threads);
// // system info //
// x86 GGML_BACKEND_API int ggml_cpu_has_sse3 (void); GGML_BACKEND_API int ggml_cpu_has_ssse3 (void); GGML_BACKEND_API int ggml_cpu_has_avx (void); GGML_BACKEND_API int ggml_cpu_has_avx_vnni (void); GGML_BACKEND_API int ggml_cpu_has_avx2 (void); GGML_BACKEND_API int ggml_cpu_has_bmi2 (void); GGML_BACKEND_API int ggml_cpu_has_f16c (void); GGML_BACKEND_API int ggml_cpu_has_fma (void); GGML_BACKEND_API int ggml_cpu_has_avx512 (void); GGML_BACKEND_API int ggml_cpu_has_avx512_vbmi(void); GGML_BACKEND_API int ggml_cpu_has_avx512_vnni(void); GGML_BACKEND_API int ggml_cpu_has_avx512_bf16(void); GGML_BACKEND_API int ggml_cpu_has_amx_int8 (void); // ARM GGML_BACKEND_API int ggml_cpu_has_neon (void); GGML_BACKEND_API int ggml_cpu_has_arm_fma (void); GGML_BACKEND_API int ggml_cpu_has_fp16_va (void); GGML_BACKEND_API int ggml_cpu_has_dotprod (void); GGML_BACKEND_API int ggml_cpu_has_matmul_int8(void); GGML_BACKEND_API int ggml_cpu_has_sve (void); GGML_BACKEND_API int ggml_cpu_get_sve_cnt (void); // sve vector length in bytes GGML_BACKEND_API int ggml_cpu_has_sme (void); GGML_BACKEND_API int ggml_cpu_has_sme2 (void); // other GGML_BACKEND_API int ggml_cpu_has_riscv_v (void); GGML_BACKEND_API int ggml_cpu_get_rvv_vlen (void); // risc-v vector length in bytes GGML_BACKEND_API int ggml_cpu_has_vsx (void); GGML_BACKEND_API int ggml_cpu_has_vxe (void); GGML_BACKEND_API int ggml_cpu_has_wasm_simd (void); GGML_BACKEND_API int ggml_cpu_has_llamafile (void);
// Internal types and functions exposed for tests and benchmarks
typedef void (*ggml_vec_dot_t) (int n, float * GGML_RESTRICT s, size_t bs, const void * GGML_RESTRICT x, size_t bx, const void * GGML_RESTRICT y, size_t by, int nrc);
struct ggml_type_traits_cpu { ggml_from_float_t from_float; ggml_vec_dot_t vec_dot; enum ggml_type vec_dot_type; int64_t nrows; // number of rows to process simultaneously };
GGML_BACKEND_API const struct ggml_type_traits_cpu * ggml_get_type_traits_cpu(enum ggml_type type);
GGML_BACKEND_API void ggml_cpu_init(void);
// // CPU backend //
GGML_BACKEND_API ggml_backend_t ggml_backend_cpu_init(void);
GGML_BACKEND_API bool ggml_backend_is_cpu (ggml_backend_t backend); GGML_BACKEND_API void ggml_backend_cpu_set_n_threads (ggml_backend_t backend_cpu, int n_threads); GGML_BACKEND_API void ggml_backend_cpu_set_threadpool (ggml_backend_t backend_cpu, ggml_threadpool_t threadpool); GGML_BACKEND_API void ggml_backend_cpu_set_abort_callback(ggml_backend_t backend_cpu, ggml_abort_callback abort_callback, void * abort_callback_data);
GGML_BACKEND_API void ggml_backend_cpu_set_use_ref(ggml_backend_t backend_cpu, bool use_ref);
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_cpu_reg(void);
GGML_BACKEND_API void ggml_cpu_fp32_to_fp32(const float *, float *, int64_t); GGML_BACKEND_API void ggml_cpu_fp32_to_i32 (const float *, int32_t *, int64_t); GGML_BACKEND_API void ggml_cpu_fp32_to_fp16(const float *, ggml_fp16_t *, int64_t); GGML_BACKEND_API void ggml_cpu_fp16_to_fp32(const ggml_fp16_t *, float *, int64_t); GGML_BACKEND_API void ggml_cpu_fp32_to_bf16(const float *, ggml_bf16_t *, int64_t); GGML_BACKEND_API void ggml_cpu_bf16_to_fp32(const ggml_bf16_t *, float *, int64_t);
#ifdef __cplusplus}#endif1234567891011121314151617181920212223242526272829303132333435363738394041424344454647#pragma once
#include "ggml.h"#include "ggml-backend.h"
#ifdef __cplusplusextern "C" {#endif
#ifdef GGML_USE_HIP#define GGML_CUDA_NAME "ROCm"#define GGML_CUBLAS_NAME "hipBLAS"#elif defined(GGML_USE_MUSA)#define GGML_CUDA_NAME "MUSA"#define GGML_CUBLAS_NAME "muBLAS"#else#define GGML_CUDA_NAME "CUDA"#define GGML_CUBLAS_NAME "cuBLAS"#endif#define GGML_CUDA_MAX_DEVICES 16
// backend APIGGML_BACKEND_API ggml_backend_t ggml_backend_cuda_init(int device);
GGML_BACKEND_API bool ggml_backend_is_cuda(ggml_backend_t backend);
// device bufferGGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_cuda_buffer_type(int device);
// conduct allreduce operation between devicesGGML_BACKEND_API bool ggml_backend_cuda_allreduce_tensor(ggml_backend_t * backends, struct ggml_tensor ** tensors, size_t n_backends);
// pinned host buffer for use with the CPU backend for faster copies between CPU and GPUGGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_cuda_host_buffer_type(void);
GGML_BACKEND_API int ggml_backend_cuda_get_device_count(void);GGML_BACKEND_API void ggml_backend_cuda_get_device_description(int device, char * description, size_t description_size);GGML_BACKEND_API void ggml_backend_cuda_get_device_memory(int device, size_t * free, size_t * total);
GGML_BACKEND_API bool ggml_backend_cuda_register_host_buffer(void * buffer, size_t size);GGML_BACKEND_API void ggml_backend_cuda_unregister_host_buffer(void * buffer);
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_cuda_reg(void);
#ifdef __cplusplus}#endif12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061// Note: this description is outdated//// An interface allowing to compute ggml_cgraph with Metal//// This is a fully functional interface that extends ggml with GPU support for Apple devices.// A similar interface can be created for other GPU backends (e.g. Vulkan, CUDA, etc.)//// How it works?//// As long as your program can create and evaluate a ggml_cgraph on the CPU, you can use this// interface to evaluate the same graph on the GPU. Instead of using ggml_graph_compute(), you// use ggml_metal_graph_compute() (or ggml_vulkan_graph_compute(), etc.)//// You only need to make sure that all memory buffers that you used during the graph creation// are mapped to the device memory with the ggml_metal_add_buffer() function. This mapping is// used during the graph evaluation to determine the arguments of the compute kernels.//// Synchronization between device and host memory (for example for input and output tensors)// is done with the ggml_metal_set_tensor() and ggml_metal_get_tensor() functions.//
#pragma once
#include "ggml.h"#include "ggml-backend.h"
#include <stddef.h>#include <stdbool.h>
struct ggml_tensor;struct ggml_cgraph;
#ifdef __cplusplusextern "C" {#endif
//// backend API// user-code should use only these functions//
// TODO: remove in the futureGGML_BACKEND_API ggml_backend_t ggml_backend_metal_init(void);
GGML_BACKEND_API bool ggml_backend_is_metal(ggml_backend_t backend);
GGML_BACKEND_API void ggml_backend_metal_set_abort_callback(ggml_backend_t backend, ggml_abort_callback abort_callback, void * user_data);
// helper to check if the device supports a specific family// ideally, the user code should be doing these checks// ref: https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdfGGML_BACKEND_API bool ggml_backend_metal_supports_family(ggml_backend_t backend, int family);
// capture all command buffers committed the next time `ggml_backend_graph_compute` is calledGGML_BACKEND_API void ggml_backend_metal_capture_next_compute(ggml_backend_t backend);
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_metal_reg(void);
#ifdef __cplusplus}#endif12345678910111213141516171819202122232425262728293031323334353637#pragma once
#include "ggml-backend.h"
#include <cstring>
#ifdef __cplusplusextern "C" {#endif
#define GGML_OPENVINO_NAME "OPENVINO"
// backend APIGGML_BACKEND_API ggml_backend_t ggml_backend_openvino_init(int device);
GGML_BACKEND_API bool ggml_backend_is_openvino(ggml_backend_t backend);
GGML_BACKEND_API bool ggml_backend_buffer_is_openvino(ggml_backend_buffer_t buffer);
GGML_BACKEND_API bool ggml_backend_buft_is_openvino(ggml_backend_buffer_type_t buft);
GGML_BACKEND_API bool ggml_backend_buft_is_openvino_host(ggml_backend_buffer_type_t buft);
GGML_BACKEND_API size_t ggml_backend_openvino_buffer_get_ctx_id(ggml_backend_buffer_t buffer);
// device bufferGGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_openvino_buffer_type(int device);
GGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_openvino_host_buffer_type(int device);
GGML_BACKEND_API int ggml_backend_openvino_get_device_count(void);
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_openvino_reg(void);
#ifdef __cplusplus}#endif123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256// This file contains functionality for training models using GGML.// It is not strictly needed vs. just vanilla GGML but it provides a more high-level interface for common needs such as datasets.// At the bottom of this file especially there are relatively high-level functions that are suitable use or adaptation in user code.//// Module maintainer: Johannes Gäßler (@JohannesGaessler, johannesg@5d6.de)
#pragma once
#include "ggml.h"#include "ggml-backend.h"
#include <stdint.h>
#ifdef __cplusplusextern "C" {#endif
struct ggml_opt_dataset; struct ggml_opt_context; struct ggml_opt_result;
typedef struct ggml_opt_dataset * ggml_opt_dataset_t; typedef struct ggml_opt_context * ggml_opt_context_t; typedef struct ggml_opt_result * ggml_opt_result_t;
// ====== Loss ======
// built-in loss types, i.e. the built-in quantities minimized by the optimizer // custom loss types can be defined via mean or sum which simply reduce the outputs for all datapoints to a single value enum ggml_opt_loss_type { GGML_OPT_LOSS_TYPE_MEAN, GGML_OPT_LOSS_TYPE_SUM, GGML_OPT_LOSS_TYPE_CROSS_ENTROPY, GGML_OPT_LOSS_TYPE_MEAN_SQUARED_ERROR, };
// ====== Dataset ======
GGML_API ggml_opt_dataset_t ggml_opt_dataset_init( enum ggml_type type_data, // the type for the internal data tensor enum ggml_type type_label, // the type for the internal labels tensor int64_t ne_datapoint, // number of elements per datapoint int64_t ne_label, // number of elements per label int64_t ndata, // total number of datapoints/labels int64_t ndata_shard); // number of datapoints/labels per shard (unit at which the dataset is shuffled/copied) GGML_API void ggml_opt_dataset_free(ggml_opt_dataset_t dataset);
// get underlying tensors that store the data GGML_API int64_t ggml_opt_dataset_ndata (ggml_opt_dataset_t dataset); GGML_API struct ggml_tensor * ggml_opt_dataset_data (ggml_opt_dataset_t dataset); // shape = [ne_datapoint, ndata] GGML_API struct ggml_tensor * ggml_opt_dataset_labels(ggml_opt_dataset_t dataset); // shape = [nd_label, ndata]
// shuffle idata first datapoints from dataset with RNG from opt_ctx, shuffle all datapoints if idata is negative GGML_API void ggml_opt_dataset_shuffle(ggml_opt_context_t opt_ctx, ggml_opt_dataset_t dataset, int64_t idata);
// get batch at position ibatch from dataset and copy the data to data_batch and labels_batch GGML_API void ggml_opt_dataset_get_batch( ggml_opt_dataset_t dataset, struct ggml_tensor * data_batch, // shape = [ne_datapoint, ndata_batch] struct ggml_tensor * labels_batch, // shape = [ne_label, ndata_batch] int64_t ibatch); GGML_API void ggml_opt_dataset_get_batch_host( ggml_opt_dataset_t dataset, void * data_batch, size_t nb_data_batch, void * labels_batch, int64_t ibatch);
// ====== Model / Context ======
enum ggml_opt_build_type { GGML_OPT_BUILD_TYPE_FORWARD = 10, GGML_OPT_BUILD_TYPE_GRAD = 20, GGML_OPT_BUILD_TYPE_OPT = 30, };
enum ggml_opt_optimizer_type { GGML_OPT_OPTIMIZER_TYPE_ADAMW, GGML_OPT_OPTIMIZER_TYPE_SGD,
GGML_OPT_OPTIMIZER_TYPE_COUNT };
// parameters that control which optimizer is used and how said optimizer tries to find the minimal loss struct ggml_opt_optimizer_params { struct { float alpha; // learning rate float beta1; // first AdamW momentum float beta2; // second AdamW momentum float eps; // epsilon for numerical stability float wd; // weight decay - 0.0f to disable } adamw; struct { float alpha; // learning rate float wd; // weight decay } sgd; };
// callback to calculate optimizer parameters prior to a backward pass // userdata can be used to pass arbitrary data typedef struct ggml_opt_optimizer_params (*ggml_opt_get_optimizer_params)(void * userdata);
// returns the default optimizer params (constant, hard-coded values) // userdata is not used GGML_API struct ggml_opt_optimizer_params ggml_opt_get_default_optimizer_params(void * userdata);
// casts userdata to ggml_opt_optimizer_params and returns it GGML_API struct ggml_opt_optimizer_params ggml_opt_get_constant_optimizer_params(void * userdata);
// parameters for initializing a new optimization context struct ggml_opt_params { ggml_backend_sched_t backend_sched; // defines which backends are used to construct the compute graphs
// by default the forward graph needs to be reconstructed for each eval // if ctx_compute, inputs, and outputs are set the graphs are instead allocated statically struct ggml_context * ctx_compute; struct ggml_tensor * inputs; struct ggml_tensor * outputs;
enum ggml_opt_loss_type loss_type; enum ggml_opt_build_type build_type;
int32_t opt_period; // after how many gradient accumulation steps an optimizer step should be done
ggml_opt_get_optimizer_params get_opt_pars; // callback for calculating optimizer parameters void * get_opt_pars_ud; // userdata for calculating optimizer parameters
// only GGML_OPT_OPTIMIZER_TYPE_ADAMW needs m, v momenta per parameter tensor enum ggml_opt_optimizer_type optimizer; };
// get parameters for an optimization context with defaults set where possible // parameters for which no sensible defaults exist are supplied as arguments to this function GGML_API struct ggml_opt_params ggml_opt_default_params( ggml_backend_sched_t backend_sched, enum ggml_opt_loss_type loss_type);
GGML_API ggml_opt_context_t ggml_opt_init(struct ggml_opt_params params); GGML_API void ggml_opt_free(ggml_opt_context_t opt_ctx);
// set gradients to zero, initialize loss, and optionally reset the optimizer GGML_API void ggml_opt_reset(ggml_opt_context_t opt_ctx, bool optimizer);
GGML_API bool ggml_opt_static_graphs(ggml_opt_context_t opt_ctx); // whether the graphs are allocated_statically
// get underlying tensors that store data // if not using static graphs these pointers become invalid with the next call to ggml_opt_alloc GGML_API struct ggml_tensor * ggml_opt_inputs( ggml_opt_context_t opt_ctx); // forward graph input tensor GGML_API struct ggml_tensor * ggml_opt_outputs( ggml_opt_context_t opt_ctx); // forward graph output tensor GGML_API struct ggml_tensor * ggml_opt_labels( ggml_opt_context_t opt_ctx); // labels to compare outputs against GGML_API struct ggml_tensor * ggml_opt_loss( ggml_opt_context_t opt_ctx); // scalar tensor that contains the loss GGML_API struct ggml_tensor * ggml_opt_pred( ggml_opt_context_t opt_ctx); // predictions made by outputs GGML_API struct ggml_tensor * ggml_opt_ncorrect(ggml_opt_context_t opt_ctx); // number of matching predictions between outputs and labels
// get the gradient accumulator for a node from the forward graph GGML_API struct ggml_tensor * ggml_opt_grad_acc(ggml_opt_context_t opt_ctx, struct ggml_tensor * node);
GGML_API enum ggml_opt_optimizer_type ggml_opt_context_optimizer_type(ggml_opt_context_t); //TODO consistent naming scheme
GGML_API const char * ggml_opt_optimizer_name(enum ggml_opt_optimizer_type);
// ====== Optimization Result ======
GGML_API ggml_opt_result_t ggml_opt_result_init(void); GGML_API void ggml_opt_result_free(ggml_opt_result_t result); GGML_API void ggml_opt_result_reset(ggml_opt_result_t result);
// get data from result, uncertainties are optional and can be ignored by passing NULL GGML_API void ggml_opt_result_ndata( ggml_opt_result_t result, int64_t * ndata); // writes 1 value, number of datapoints GGML_API void ggml_opt_result_loss( ggml_opt_result_t result, double * loss, double * unc); // writes 1 value GGML_API void ggml_opt_result_pred( ggml_opt_result_t result, int32_t * pred); // writes ndata values GGML_API void ggml_opt_result_accuracy(ggml_opt_result_t result, double * accuracy, double * unc); // writes 1 value
// ====== Computation ======
// if not using static graphs, this function must be called prior to ggml_opt_alloc GGML_API void ggml_opt_prepare_alloc( ggml_opt_context_t opt_ctx, struct ggml_context * ctx_compute, struct ggml_cgraph * gf, struct ggml_tensor * inputs, struct ggml_tensor * outputs);
// allocate the next graph for evaluation, either forward or forward + backward // must be called exactly once prior to calling ggml_opt_eval GGML_API void ggml_opt_alloc(ggml_opt_context_t opt_ctx, bool backward);
// do forward pass, increment result if not NULL, do backward pass if allocated GGML_API void ggml_opt_eval(ggml_opt_context_t opt_ctx, ggml_opt_result_t result);
// ############################################################################ // ## The high-level functions start here. They do not depend on any private ## // ## functions or structs and can be copied to and adapted for user code. ## // ############################################################################
// ====== Intended Usage ====== // // 1. Select the appropriate loss for your problem. // 2. Create a dataset and set the data for the "data" tensor. Also set the "labels" tensor if your loss needs them. // Setting the shard size to 1 will be fine, it's the granularity with which data is shuffled/loaded (bigger values are faster). // 3. Create a GGML graph for your model with no_alloc == true. Use two separate contexts for the tensors. // The first context should contain the model parameters and inputs and be allocated statically in user code. // The second context should contain all other tensors and will be (re)allocated automatically. // Due to this automated allocation the data of the second context is not defined when accessed in user code. // Note that the second dimension of the inputs/outputs are interpreted as the number of datapoints in those tensors. // 4. Call ggml_opt_fit. If you need more control you can use ggml_opt_epoch instead.
// signature for a callback while evaluating opt_ctx on dataset, called after an evaluation typedef void (*ggml_opt_epoch_callback)( bool train, // true after training evaluation, false after validation evaluation ggml_opt_context_t opt_ctx, ggml_opt_dataset_t dataset, ggml_opt_result_t result, // result associated with the dataset subsection int64_t ibatch, // number of batches that have been evaluated so far int64_t ibatch_max, // total number of batches in this dataset subsection int64_t t_start_us); // time at which the evaluation on the dataset subsection was started
// do training on front of dataset, do evaluation only on back of dataset GGML_API void ggml_opt_epoch( ggml_opt_context_t opt_ctx, ggml_opt_dataset_t dataset, ggml_opt_result_t result_train, // result to increment during training, ignored if NULL ggml_opt_result_t result_eval, // result to increment during evaluation, ignored if NULL int64_t idata_split, // data index at which to split training and evaluation ggml_opt_epoch_callback callback_train, ggml_opt_epoch_callback callback_eval);
// callback that prints a progress bar on stderr GGML_API void ggml_opt_epoch_callback_progress_bar( bool train, ggml_opt_context_t opt_ctx, ggml_opt_dataset_t dataset, ggml_opt_result_t result, int64_t ibatch, int64_t ibatch_max, int64_t t_start_us);
// fit model defined by inputs and outputs to dataset GGML_API void ggml_opt_fit( ggml_backend_sched_t backend_sched, // backend scheduler for constructing the compute graphs struct ggml_context * ctx_compute, // context with temporarily allocated tensors to calculate the outputs struct ggml_tensor * inputs, // input tensor with shape [ne_datapoint, ndata_batch] struct ggml_tensor * outputs, // output tensor, must have shape [ne_label, ndata_batch] if labels are used ggml_opt_dataset_t dataset, // dataset with data and optionally also labels enum ggml_opt_loss_type loss_type, // loss to minimize enum ggml_opt_optimizer_type optimizer, // sgd or adamw ggml_opt_get_optimizer_params get_opt_pars, // callback to get optimizer params, userdata is pointer to epoch (of type int64_t) int64_t nepoch, // how many times the dataset should be iterated over int64_t nbatch_logical, // datapoints optimizer step, must be a multiple of ndata_batch in inputs/outputs float val_split, // fraction of the dataset to use for validation, must be in [0.0f, 1.0f) bool silent); // whether or not info prints to stderr should be suppressed
#ifdef __cplusplus}#endif1234567891011121314151617181920212223242526272829303132333435#pragma once
#include "ggml-backend.h"
#ifdef __cplusplusextern "C" {#endif
#define RPC_PROTO_MAJOR_VERSION 7#define RPC_PROTO_MINOR_VERSION 0#define RPC_PROTO_PATCH_VERSION 0
#ifdef __cplusplusstatic_assert(GGML_OP_COUNT == 101, "GGML_OP_COUNT has changed - update RPC_PROTO_PATCH_VERSION");#endif
#define GGML_RPC_MAX_SERVERS 16
// backend APIGGML_BACKEND_API ggml_backend_t ggml_backend_rpc_init(const char * endpoint, uint32_t device);GGML_BACKEND_API bool ggml_backend_is_rpc(ggml_backend_t backend);
GGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_rpc_buffer_type(const char * endpoint, uint32_t device);
GGML_BACKEND_API void ggml_backend_rpc_get_device_memory(const char * endpoint, uint32_t device, size_t * free, size_t * total);
GGML_BACKEND_API void ggml_backend_rpc_start_server(const char * endpoint, const char * cache_dir, size_t n_threads, size_t n_devices, ggml_backend_dev_t * devices);
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_rpc_reg(void);GGML_BACKEND_API ggml_backend_reg_t ggml_backend_rpc_add_server(const char * endpoint);
#ifdef __cplusplus}#endif1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859//// MIT license// Copyright (C) 2024 Intel Corporation// SPDX-License-Identifier: MIT//
#pragma once
#include "ggml.h"#include "ggml-backend.h"
#define GGML_SYCL_NAME "SYCL"#define GGML_SYCL_MAX_DEVICES 48
#ifdef __cplusplusextern "C" {#endif
// backend APIGGML_BACKEND_API ggml_backend_t ggml_backend_sycl_init(int device);
GGML_BACKEND_API bool ggml_backend_is_sycl(ggml_backend_t backend);
// devide bufferGGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_sycl_buffer_type(int device);
// split tensor buffer that splits matrices by rows across multiple devicesGGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_sycl_split_buffer_type(int main_device, const float * tensor_split);
// Tensor parallelism (--split-mode tensor): comm_init/free/allreduce_tensor// trio queried by the meta-backend via ggml_backend_reg_get_proc_address.// See typedefs in ggml/include/ggml-backend.h. Mirrors the CUDA backend's// pattern (ggml_backend_cuda_comm_*).GGML_BACKEND_API void * ggml_backend_sycl_comm_init(ggml_backend_t * backends, size_t n_backends);GGML_BACKEND_API void ggml_backend_sycl_comm_free(void * comm_ctx);GGML_BACKEND_API bool ggml_backend_sycl_comm_allreduce_tensor(void * comm_ctx, struct ggml_tensor ** tensors);
// pinned host buffer for use with the CPU backend for faster copies between CPU and GPU// pins on device 0 - a copy between another device and this memory can fail,// use ggml_backend_dev_host_buffer_type to pin on the device that does the copyGGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_sycl_host_buffer_type(void);
GGML_BACKEND_API void ggml_backend_sycl_print_sycl_devices(void);GGML_BACKEND_API void ggml_backend_sycl_get_gpu_list(int *id_list, int max_len);GGML_BACKEND_API void ggml_backend_sycl_get_device_description(int device, char *description, size_t description_size);GGML_BACKEND_API int ggml_backend_sycl_get_device_count(void);GGML_BACKEND_API void ggml_backend_sycl_get_device_memory(int device, size_t *free, size_t *total);
// SYCL doesn't support registering host memory, keep here for reference// GGML_BACKEND_API bool ggml_backend_sycl_register_host_buffer(void * buffer, size_t size);// GGML_BACKEND_API void ggml_backend_sycl_unregister_host_buffer(void * buffer);
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_sycl_reg(void);
#ifdef __cplusplus}#endif1234567891011121314#pragma once
#include "ggml.h"#include "ggml-backend.h"
#ifdef __cplusplusextern "C" {#endif
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_virtgpu_reg();
#ifdef __cplusplus}#endif1234567891011121314151617181920212223242526272829#pragma once
#include "ggml.h"#include "ggml-backend.h"
#ifdef __cplusplusextern "C" {#endif
#define GGML_VK_NAME "Vulkan"#define GGML_VK_MAX_DEVICES 16
// backend APIGGML_BACKEND_API ggml_backend_t ggml_backend_vk_init(size_t dev_num);
GGML_BACKEND_API bool ggml_backend_is_vk(ggml_backend_t backend);GGML_BACKEND_API int ggml_backend_vk_get_device_count(void);GGML_BACKEND_API void ggml_backend_vk_get_device_description(int device, char * description, size_t description_size);GGML_BACKEND_API void ggml_backend_vk_get_device_memory(int device, size_t * free, size_t * total);
GGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_vk_buffer_type(size_t dev_num);// pinned host buffer for use with the CPU backend for faster copies between CPU and GPUGGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_vk_host_buffer_type(void);
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_vk_reg(void);
#ifdef __cplusplus}#endif12345678910111213141516171819#pragma once
#include "ggml.h"#include "ggml-backend.h"
#ifdef __cplusplusextern "C" {#endif
#define GGML_WEBGPU_NAME "WebGPU"
// Needed for examples in ggmlGGML_BACKEND_API ggml_backend_t ggml_backend_webgpu_init(void);
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_webgpu_reg(void);
#ifdef __cplusplus}#endif12345678910111213141516171819202122#pragma once
#include "ggml-backend.h"#include "ggml.h"
#ifdef __cplusplusextern "C" {#endif
// backend APIGGML_BACKEND_API ggml_backend_t ggml_backend_zendnn_init(void);
GGML_BACKEND_API bool ggml_backend_is_zendnn(ggml_backend_t backend);
// number of threads used for zendnn operationsGGML_BACKEND_API void ggml_backend_zendnn_set_n_threads(ggml_backend_t backend_zendnn, int n_threads);
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_zendnn_reg(void);
#ifdef __cplusplus}#endif123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211// This file contains functionality related to "GGUF" files, the binary file format used by ggml.// GGUF files have the following structure://// 1. File magic "GGUF" (4 bytes).// 2. File version (uint32_t).// 3. Number of ggml tensors in file (int64_t).// 4. Number of key-value-pairs in file (int64_t).// 5. For each KV pair:// 1. The key (string).// 2. The value type (gguf_type).// 3a. If the value type is GGUF_TYPE_ARRAY:// 1. The type of the array (gguf_type).// 2. The number of elements in the array (uint64_t).// 3. The binary representation of each element in the array.// 3b. Otherwise:// 1. The binary representation of the value.// 6. For each ggml tensor:// 1. The tensor name (string).// 2. The number of dimensions of the tensor (uint32_t).// 3. For each dimension:// 1. The size of the tensor in the dimension (int64_t).// 4. The tensor data type (ggml_type).// 5. The tensor data offset in the tensor data binary blob (uint64_t).// 7. The tensor data binary blob (optional, aligned).//// Strings are serialized as the string length (uint64_t) followed by the C string without the null terminator.// All enums are stored as int32_t.// All bool values are stored as int8_t.// If the special key "general.alignment" (uint32_t) is defined it is used for alignment,// otherwise GGUF_DEFAULT_ALIGNMENT is used.//// Module maintainer: Johannes Gäßler (@JohannesGaessler, johannesg@5d6.de)
#pragma once
#include "ggml.h"
#include <stdbool.h>#include <stdint.h>
#define GGUF_MAGIC "GGUF"#define GGUF_VERSION 3
#define GGUF_KEY_GENERAL_ALIGNMENT "general.alignment"
#define GGUF_DEFAULT_ALIGNMENT 32
#ifdef __cplusplusextern "C" {#endif
// types that can be stored as GGUF KV data enum gguf_type { GGUF_TYPE_UINT8 = 0, GGUF_TYPE_INT8 = 1, GGUF_TYPE_UINT16 = 2, GGUF_TYPE_INT16 = 3, GGUF_TYPE_UINT32 = 4, GGUF_TYPE_INT32 = 5, GGUF_TYPE_FLOAT32 = 6, GGUF_TYPE_BOOL = 7, GGUF_TYPE_STRING = 8, GGUF_TYPE_ARRAY = 9, GGUF_TYPE_UINT64 = 10, GGUF_TYPE_INT64 = 11, GGUF_TYPE_FLOAT64 = 12, GGUF_TYPE_COUNT, // marks the end of the enum };
struct gguf_context;
struct gguf_init_params { bool no_alloc;
// if not NULL, create a ggml_context and allocate the tensor data in it struct ggml_context ** ctx; };
// callback to simulate or wrap a FILE pointer - read up to `len` bytes at `offset` into `output` and return the number of bytes read typedef size_t (*gguf_reader_callback_t)(void * userdata, void * output, uint64_t offset, size_t len);
GGML_API struct gguf_context * gguf_init_empty(void); GGML_API struct gguf_context * gguf_init_from_file_ptr(FILE * file, struct gguf_init_params params); GGML_API struct gguf_context * gguf_init_from_file(const char * fname, struct gguf_init_params params); GGML_API struct gguf_context * gguf_init_from_buffer(const void * data, size_t size, struct gguf_init_params params);
// max_chunk_read is the maximum number of bytes that the GGUF code will read at once from the callback, a value of 0 means no limit GGML_API struct gguf_context * gguf_init_from_callback(gguf_reader_callback_t callback, void * userdata, size_t max_chunk_read, uint64_t max_expected_size, struct gguf_init_params params);
GGML_API void gguf_free(struct gguf_context * ctx);
GGML_API const char * gguf_type_name(enum gguf_type type);
GGML_API uint32_t gguf_get_version (const struct gguf_context * ctx); GGML_API size_t gguf_get_alignment (const struct gguf_context * ctx); GGML_API size_t gguf_get_data_offset(const struct gguf_context * ctx); // padded to gguf_get_alignment if and only if the gguf_context contains at least one tensor
GGML_API int64_t gguf_get_n_kv(const struct gguf_context * ctx); GGML_API int64_t gguf_find_key(const struct gguf_context * ctx, const char * key); // returns -1 if key is not found GGML_API const char * gguf_get_key (const struct gguf_context * ctx, int64_t key_id);
GGML_API enum gguf_type gguf_get_kv_type (const struct gguf_context * ctx, int64_t key_id); GGML_API enum gguf_type gguf_get_arr_type(const struct gguf_context * ctx, int64_t key_id);
// will abort if the wrong type is used for the key GGML_API uint8_t gguf_get_val_u8 (const struct gguf_context * ctx, int64_t key_id); GGML_API int8_t gguf_get_val_i8 (const struct gguf_context * ctx, int64_t key_id); GGML_API uint16_t gguf_get_val_u16 (const struct gguf_context * ctx, int64_t key_id); GGML_API int16_t gguf_get_val_i16 (const struct gguf_context * ctx, int64_t key_id); GGML_API uint32_t gguf_get_val_u32 (const struct gguf_context * ctx, int64_t key_id); GGML_API int32_t gguf_get_val_i32 (const struct gguf_context * ctx, int64_t key_id); GGML_API float gguf_get_val_f32 (const struct gguf_context * ctx, int64_t key_id); GGML_API uint64_t gguf_get_val_u64 (const struct gguf_context * ctx, int64_t key_id); GGML_API int64_t gguf_get_val_i64 (const struct gguf_context * ctx, int64_t key_id); GGML_API double gguf_get_val_f64 (const struct gguf_context * ctx, int64_t key_id); GGML_API bool gguf_get_val_bool(const struct gguf_context * ctx, int64_t key_id); GGML_API const char * gguf_get_val_str (const struct gguf_context * ctx, int64_t key_id); GGML_API const void * gguf_get_val_data(const struct gguf_context * ctx, int64_t key_id); GGML_API size_t gguf_get_arr_n (const struct gguf_context * ctx, int64_t key_id);
// get raw pointer to the first element of the array with the given key_id // for bool arrays, note that they are always stored as int8 on all platforms (usually this makes no difference) GGML_API const void * gguf_get_arr_data(const struct gguf_context * ctx, int64_t key_id);
// get ith C string from array with given key_id GGML_API const char * gguf_get_arr_str (const struct gguf_context * ctx, int64_t key_id, size_t i);
GGML_API int64_t gguf_get_n_tensors (const struct gguf_context * ctx); GGML_API int64_t gguf_find_tensor (const struct gguf_context * ctx, const char * name); // returns -1 if the tensor is not found GGML_API size_t gguf_get_tensor_offset(const struct gguf_context * ctx, int64_t tensor_id); GGML_API const char * gguf_get_tensor_name (const struct gguf_context * ctx, int64_t tensor_id); GGML_API const int64_t * gguf_get_tensor_ne (const struct gguf_context * ctx, int64_t tensor_id); // returns ne, an array of GGML_MAX_DIMS elements; ne[dim] is 1 for dim >= n_dims GGML_API enum ggml_type gguf_get_tensor_type (const struct gguf_context * ctx, int64_t tensor_id); GGML_API size_t gguf_get_tensor_size (const struct gguf_context * ctx, int64_t tensor_id);
// removes key if it exists, returns id that the key had prior to removal (-1 if it didn't exist) GGML_API int64_t gguf_remove_key(struct gguf_context * ctx, const char * key);
// overrides an existing KV pair or adds a new one, the new KV pair is always at the back GGML_API void gguf_set_val_u8 (struct gguf_context * ctx, const char * key, uint8_t val); GGML_API void gguf_set_val_i8 (struct gguf_context * ctx, const char * key, int8_t val); GGML_API void gguf_set_val_u16 (struct gguf_context * ctx, const char * key, uint16_t val); GGML_API void gguf_set_val_i16 (struct gguf_context * ctx, const char * key, int16_t val); GGML_API void gguf_set_val_u32 (struct gguf_context * ctx, const char * key, uint32_t val); GGML_API void gguf_set_val_i32 (struct gguf_context * ctx, const char * key, int32_t val); GGML_API void gguf_set_val_f32 (struct gguf_context * ctx, const char * key, float val); GGML_API void gguf_set_val_u64 (struct gguf_context * ctx, const char * key, uint64_t val); GGML_API void gguf_set_val_i64 (struct gguf_context * ctx, const char * key, int64_t val); GGML_API void gguf_set_val_f64 (struct gguf_context * ctx, const char * key, double val); GGML_API void gguf_set_val_bool(struct gguf_context * ctx, const char * key, bool val); GGML_API void gguf_set_val_str (struct gguf_context * ctx, const char * key, const char * val);
// creates a new array with n elements of the given type and copies the corresponding number of bytes from data GGML_API void gguf_set_arr_data(struct gguf_context * ctx, const char * key, enum gguf_type type, const void * data, size_t n);
// creates a new array with n strings and copies the corresponding strings from data GGML_API void gguf_set_arr_str (struct gguf_context * ctx, const char * key, const char ** data, size_t n);
// set or add KV pairs from another context GGML_API void gguf_set_kv(struct gguf_context * ctx, const struct gguf_context * src);
// add tensor to GGUF context, tensor name must be unique GGML_API void gguf_add_tensor(struct gguf_context * ctx, const struct ggml_tensor * tensor);
// after changing a tensor's type, the offsets of all tensors with higher indices are immediately recalculated // in such a way that the tensor data remains as one contiguous block (except for padding) GGML_API void gguf_set_tensor_type(struct gguf_context * ctx, const char * name, enum ggml_type type);
// assumes that at least gguf_get_tensor_size bytes can be read from data GGML_API void gguf_set_tensor_data(struct gguf_context * ctx, const char * name, const void * data);
// writing gguf files can be done in 3 ways: // // - write the entire gguf_context to a binary file in a single pass: // // gguf_write_to_file(ctx, fname, /*only_meta =*/ false); // // - write only the meta data to a file, then re-open the file and append the tensor data: // // gguf_write_to_file(ctx, fname, /*only_meta =*/ true); // FILE * f = fopen(fname, "ab"); // fwrite(f, ...); // write tensor data // fclose(f); // // - first prepare a file with a placeholder for the meta data, write the tensor data, then write the meta data: // // FILE * f = fopen(fname, "wb"); // const size_t size_meta = gguf_get_meta_size(ctx); // fseek(f, size_meta, SEEK_SET); // fwrite(f, ...); // write tensor data // void * data = malloc(size_meta); // gguf_get_meta_data(ctx, data); // rewind(f); // fwrite(data, 1, data, f); // free(data); // fclose(f); //
// write the entire context to a binary file GGML_API bool gguf_write_to_file_ptr(const struct gguf_context * ctx, FILE * file, bool only_meta); GGML_API bool gguf_write_to_file(const struct gguf_context * ctx, const char * fname, bool only_meta);
// get the size in bytes of the meta data (header, kv pairs, tensor info) including padding GGML_API size_t gguf_get_meta_size(const struct gguf_context * ctx);
// writes the meta data to pointer "data" GGML_API void gguf_get_meta_data(const struct gguf_context * ctx, void * data);
#ifdef __cplusplus}#endif1234567891011121314151617181920212223242526272829303132333435#pragma once
#ifndef __cplusplus#error "This header is for C++ only"#endif
#include <memory>
#include "llama.h"
struct llama_model_deleter { void operator()(llama_model * model) { llama_model_free(model); }};
struct llama_context_deleter { void operator()(llama_context * context) { llama_free(context); }};
struct llama_sampler_deleter { void operator()(llama_sampler * sampler) { llama_sampler_free(sampler); }};
struct llama_adapter_lora_deleter { void operator()(llama_adapter_lora * adapter) { llama_adapter_lora_free(adapter); }};
struct llama_batch_ext_deleter { void operator()(llama_batch_ext * batch) { llama_batch_ext_free(batch); }};
typedef std::unique_ptr<llama_model, llama_model_deleter> llama_model_ptr;typedef std::unique_ptr<llama_context, llama_context_deleter> llama_context_ptr;typedef std::unique_ptr<llama_sampler, llama_sampler_deleter> llama_sampler_ptr;typedef std::unique_ptr<llama_adapter_lora, llama_adapter_lora_deleter> llama_adapter_lora_ptr;typedef std::unique_ptr<llama_batch_ext, llama_batch_ext_deleter> llama_batch_ext_ptr;12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739#ifndef LLAMA_H#define LLAMA_H
#include "ggml.h"#include "ggml-cpu.h"#include "ggml-backend.h"#include "ggml-opt.h"#include "gguf.h"
#include <stddef.h>#include <stdint.h>#include <stdio.h>#include <stdbool.h>
#ifdef LLAMA_SHARED# if defined(_WIN32) && !defined(__MINGW32__)# ifdef LLAMA_BUILD# define LLAMA_API __declspec(dllexport)# else# define LLAMA_API __declspec(dllimport)# endif# else# define LLAMA_API __attribute__ ((visibility ("default")))# endif#else# define LLAMA_API#endif
#ifdef __GNUC__# define DEPRECATED(func, hint) func __attribute__((deprecated(hint)))#elif defined(_MSC_VER)# define DEPRECATED(func, hint) __declspec(deprecated(hint)) func#else# define DEPRECATED(func, hint) func#endif
#define LLAMA_DEFAULT_SEED 0xFFFFFFFF
#define LLAMA_TOKEN_NULL -1
#define LLAMA_FILE_MAGIC_GGLA 0x67676c61u // 'ggla'#define LLAMA_FILE_MAGIC_GGSN 0x6767736eu // 'ggsn'#define LLAMA_FILE_MAGIC_GGSQ 0x67677371u // 'ggsq'
#define LLAMA_SESSION_MAGIC LLAMA_FILE_MAGIC_GGSN#define LLAMA_SESSION_VERSION 10
#define LLAMA_STATE_SEQ_MAGIC LLAMA_FILE_MAGIC_GGSQ#define LLAMA_STATE_SEQ_VERSION 3
#ifdef __cplusplusextern "C" {#endif
// // C interface // // TODO: show sample usage //
struct llama_vocab; struct llama_model; struct llama_context; struct llama_sampler;
typedef struct llama_memory_i * llama_memory_t;
typedef int32_t llama_pos; typedef int32_t llama_token; typedef int32_t llama_seq_id;
enum llama_vocab_type { LLAMA_VOCAB_TYPE_NONE = 0, // For models without vocab LLAMA_VOCAB_TYPE_SPM = 1, // LLaMA tokenizer based on byte-level BPE with byte fallback LLAMA_VOCAB_TYPE_BPE = 2, // GPT-2 tokenizer based on byte-level BPE LLAMA_VOCAB_TYPE_WPM = 3, // BERT tokenizer based on WordPiece LLAMA_VOCAB_TYPE_UGM = 4, // T5 tokenizer based on Unigram LLAMA_VOCAB_TYPE_RWKV = 5, // RWKV tokenizer based on greedy tokenization LLAMA_VOCAB_TYPE_PLAMO2 = 6, // PLaMo-2 tokenizer based on Aho-Corasick with dynamic programming LLAMA_VOCAB_TYPE_TEST = 7, // Dummy tokenizer for testing: rolling hash of fixed-size chunks -> tokens, tokens -> hex };
enum llama_rope_type { LLAMA_ROPE_TYPE_NONE = -1, LLAMA_ROPE_TYPE_NORM = 0, LLAMA_ROPE_TYPE_NEOX = GGML_ROPE_TYPE_NEOX, LLAMA_ROPE_TYPE_MROPE = GGML_ROPE_TYPE_MROPE, LLAMA_ROPE_TYPE_IMROPE = GGML_ROPE_TYPE_IMROPE, LLAMA_ROPE_TYPE_VISION = GGML_ROPE_TYPE_VISION, };
enum llama_token_type { //TODO: remove, required until per token attributes are available from GGUF file LLAMA_TOKEN_TYPE_UNDEFINED = 0, LLAMA_TOKEN_TYPE_NORMAL = 1, LLAMA_TOKEN_TYPE_UNKNOWN = 2, LLAMA_TOKEN_TYPE_CONTROL = 3, LLAMA_TOKEN_TYPE_USER_DEFINED = 4, LLAMA_TOKEN_TYPE_UNUSED = 5, LLAMA_TOKEN_TYPE_BYTE = 6, };
enum llama_token_attr { LLAMA_TOKEN_ATTR_UNDEFINED = 0, LLAMA_TOKEN_ATTR_UNKNOWN = 1 << 0, LLAMA_TOKEN_ATTR_UNUSED = 1 << 1, LLAMA_TOKEN_ATTR_NORMAL = 1 << 2, LLAMA_TOKEN_ATTR_CONTROL = 1 << 3, // SPECIAL? LLAMA_TOKEN_ATTR_USER_DEFINED = 1 << 4, LLAMA_TOKEN_ATTR_BYTE = 1 << 5, LLAMA_TOKEN_ATTR_NORMALIZED = 1 << 6, LLAMA_TOKEN_ATTR_LSTRIP = 1 << 7, LLAMA_TOKEN_ATTR_RSTRIP = 1 << 8, LLAMA_TOKEN_ATTR_SINGLE_WORD = 1 << 9, };
// model file types enum llama_ftype { LLAMA_FTYPE_ALL_F32 = 0, LLAMA_FTYPE_MOSTLY_F16 = 1, // except 1d tensors LLAMA_FTYPE_MOSTLY_Q4_0 = 2, // except 1d tensors LLAMA_FTYPE_MOSTLY_Q4_1 = 3, // except 1d tensors // LLAMA_FTYPE_MOSTLY_Q4_1_SOME_F16 = 4, // tok_embeddings.weight and output.weight are F16 // LLAMA_FTYPE_MOSTLY_Q4_2 = 5, // support has been removed // LLAMA_FTYPE_MOSTLY_Q4_3 = 6, // support has been removed LLAMA_FTYPE_MOSTLY_Q8_0 = 7, // except 1d tensors LLAMA_FTYPE_MOSTLY_Q5_0 = 8, // except 1d tensors LLAMA_FTYPE_MOSTLY_Q5_1 = 9, // except 1d tensors LLAMA_FTYPE_MOSTLY_Q2_K = 10, // except 1d tensors LLAMA_FTYPE_MOSTLY_Q3_K_S = 11, // except 1d tensors LLAMA_FTYPE_MOSTLY_Q3_K_M = 12, // except 1d tensors LLAMA_FTYPE_MOSTLY_Q3_K_L = 13, // except 1d tensors LLAMA_FTYPE_MOSTLY_Q4_K_S = 14, // except 1d tensors LLAMA_FTYPE_MOSTLY_Q4_K_M = 15, // except 1d tensors LLAMA_FTYPE_MOSTLY_Q5_K_S = 16, // except 1d tensors LLAMA_FTYPE_MOSTLY_Q5_K_M = 17, // except 1d tensors LLAMA_FTYPE_MOSTLY_Q6_K = 18, // except 1d tensors LLAMA_FTYPE_MOSTLY_IQ2_XXS = 19, // except 1d tensors LLAMA_FTYPE_MOSTLY_IQ2_XS = 20, // except 1d tensors LLAMA_FTYPE_MOSTLY_Q2_K_S = 21, // except 1d tensors LLAMA_FTYPE_MOSTLY_IQ3_XS = 22, // except 1d tensors LLAMA_FTYPE_MOSTLY_IQ3_XXS = 23, // except 1d tensors LLAMA_FTYPE_MOSTLY_IQ1_S = 24, // except 1d tensors LLAMA_FTYPE_MOSTLY_IQ4_NL = 25, // except 1d tensors LLAMA_FTYPE_MOSTLY_IQ3_S = 26, // except 1d tensors LLAMA_FTYPE_MOSTLY_IQ3_M = 27, // except 1d tensors LLAMA_FTYPE_MOSTLY_IQ2_S = 28, // except 1d tensors LLAMA_FTYPE_MOSTLY_IQ2_M = 29, // except 1d tensors LLAMA_FTYPE_MOSTLY_IQ4_XS = 30, // except 1d tensors LLAMA_FTYPE_MOSTLY_IQ1_M = 31, // except 1d tensors LLAMA_FTYPE_MOSTLY_BF16 = 32, // except 1d tensors //LLAMA_FTYPE_MOSTLY_Q4_0_4_4 = 33, // removed from gguf files, use Q4_0 and runtime repack //LLAMA_FTYPE_MOSTLY_Q4_0_4_8 = 34, // removed from gguf files, use Q4_0 and runtime repack //LLAMA_FTYPE_MOSTLY_Q4_0_8_8 = 35, // removed from gguf files, use Q4_0 and runtime repack LLAMA_FTYPE_MOSTLY_TQ1_0 = 36, // except 1d tensors LLAMA_FTYPE_MOSTLY_TQ2_0 = 37, // except 1d tensors LLAMA_FTYPE_MOSTLY_MXFP4_MOE = 38, // except 1d tensors LLAMA_FTYPE_MOSTLY_NVFP4 = 39, // except 1d tensors LLAMA_FTYPE_MOSTLY_Q1_0 = 40, // except 1d tensors LLAMA_FTYPE_MOSTLY_Q2_0 = 41, // except 1d tensors
LLAMA_FTYPE_GUESSED = 1024, // not specified in the model file };
// Get the model file type (quantization) as a string, e.g. "Q8_0" or "Q4_K - Medium" LLAMA_API const char * llama_ftype_name(enum llama_ftype ftype);
enum llama_rope_scaling_type { LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED = -1, LLAMA_ROPE_SCALING_TYPE_NONE = 0, LLAMA_ROPE_SCALING_TYPE_LINEAR = 1, LLAMA_ROPE_SCALING_TYPE_YARN = 2, LLAMA_ROPE_SCALING_TYPE_LONGROPE = 3, LLAMA_ROPE_SCALING_TYPE_MAX_VALUE = LLAMA_ROPE_SCALING_TYPE_LONGROPE, };
enum llama_pooling_type { LLAMA_POOLING_TYPE_UNSPECIFIED = -1, LLAMA_POOLING_TYPE_NONE = 0, LLAMA_POOLING_TYPE_MEAN = 1, LLAMA_POOLING_TYPE_CLS = 2, LLAMA_POOLING_TYPE_LAST = 3, LLAMA_POOLING_TYPE_RANK = 4, // used by reranking models to attach the classification head to the graph };
enum llama_attention_type { LLAMA_ATTENTION_TYPE_UNSPECIFIED = -1, LLAMA_ATTENTION_TYPE_CAUSAL = 0, LLAMA_ATTENTION_TYPE_NON_CAUSAL = 1, };
enum llama_flash_attn_type { LLAMA_FLASH_ATTN_TYPE_AUTO = -1, LLAMA_FLASH_ATTN_TYPE_DISABLED = 0, LLAMA_FLASH_ATTN_TYPE_ENABLED = 1, };
LLAMA_API const char * llama_flash_attn_type_name(enum llama_flash_attn_type flash_attn_type);
enum llama_split_mode { LLAMA_SPLIT_MODE_NONE = 0, // single GPU LLAMA_SPLIT_MODE_LAYER = 1, // split layers and KV across GPUs LLAMA_SPLIT_MODE_ROW = 2, // split layers and KV across GPUs, use tensor parallelism if supported LLAMA_SPLIT_MODE_TENSOR = 3, };
enum llama_load_mode { LLAMA_LOAD_MODE_AUTO = -1, // auto-detect based on device capabilities LLAMA_LOAD_MODE_NONE = 0, // no special loading mode LLAMA_LOAD_MODE_MMAP = 1, // memory map the model LLAMA_LOAD_MODE_MLOCK = 2, // force system to keep model in RAM rather than swapping or compressing LLAMA_LOAD_MODE_MMAP_MLOCK = 3, // mmap + force system to keep model in RAM rather than swapping or compressing LLAMA_LOAD_MODE_DIRECT_IO = 4, // use direct I/O if available };
LLAMA_API const char * llama_load_mode_name(enum llama_load_mode load_mode); LLAMA_API enum llama_load_mode llama_load_mode_from_str(const char * str);
enum llama_lazy_mode { LLAMA_LAZY_MODE_OFF = 0, // always read the whole tensor up front LLAMA_LAZY_MODE_AUTO = 1, // lazy only for marked tensors larger than 4 GiB (requires mmap) LLAMA_LAZY_MODE_ON = 2, // read the rows of tensors marked by the arch on demand (requires mmap) };
enum llama_context_type { LLAMA_CONTEXT_TYPE_DEFAULT = 0, LLAMA_CONTEXT_TYPE_MTP = 1, };
// TODO: simplify (https://github.com/ggml-org/llama.cpp/pull/9294#pullrequestreview-2286561979) typedef struct llama_token_data { llama_token id; // token id float logit; // log-odds of the token float p; // probability of the token } llama_token_data;
typedef struct llama_token_data_array { // TODO: consider SoA // NOTE: this pointer can be modified by the samplers llama_token_data * data; size_t size; int64_t selected; // this is the index in the data array (i.e. not the token id) bool sorted; // note: do not assume the data is sorted - always check this flag } llama_token_data_array;
typedef bool (*llama_progress_callback)(float progress, void * user_data);
// Input data for llama_encode/llama_decode // A llama_batch object can contain input about one or many sequences // The provided arrays (i.e. token, embd, pos, etc.) must have size of n_tokens // // - token : the token ids of the input (used when embd is NULL) // - embd : token embeddings (i.e. float vector of size n_embd) (used when token is NULL) // - pos : the positions of the respective token in the sequence // (if set to NULL, the token position will be tracked automatically by llama_encode/llama_decode) // - seq_id : the sequence to which the respective token belongs // (if set to NULL, the sequence ID will be assumed to be 0) // - logits : if zero, the logits (and/or the embeddings) for the respective token will not be output // (if set to NULL: // - if embeddings: all tokens are output // - if not: only the last token is output // ) // typedef struct llama_batch { int32_t n_tokens;
llama_token * token; float * embd; llama_pos * pos; int32_t * n_seq_id; llama_seq_id ** seq_id; int8_t * logits; // TODO: rename this to "output" } llama_batch;
enum llama_model_kv_override_type { LLAMA_KV_OVERRIDE_TYPE_INT, LLAMA_KV_OVERRIDE_TYPE_FLOAT, LLAMA_KV_OVERRIDE_TYPE_BOOL, LLAMA_KV_OVERRIDE_TYPE_STR, };
enum llama_model_meta_key { LLAMA_MODEL_META_KEY_SAMPLING_SEQUENCE, LLAMA_MODEL_META_KEY_SAMPLING_TOP_K, LLAMA_MODEL_META_KEY_SAMPLING_TOP_P, LLAMA_MODEL_META_KEY_SAMPLING_MIN_P, LLAMA_MODEL_META_KEY_SAMPLING_XTC_PROBABILITY, LLAMA_MODEL_META_KEY_SAMPLING_XTC_THRESHOLD, LLAMA_MODEL_META_KEY_SAMPLING_TEMP, LLAMA_MODEL_META_KEY_SAMPLING_PENALTY_LAST_N, LLAMA_MODEL_META_KEY_SAMPLING_PENALTY_REPEAT, LLAMA_MODEL_META_KEY_SAMPLING_MIROSTAT, LLAMA_MODEL_META_KEY_SAMPLING_MIROSTAT_TAU, LLAMA_MODEL_META_KEY_SAMPLING_MIROSTAT_ETA, };
enum llama_process_type { LLAMA_PROCESS_TYPE_ENCODE, LLAMA_PROCESS_TYPE_DECODE, };
struct llama_model_kv_override { enum llama_model_kv_override_type tag;
char key[128];
union { int64_t val_i64; double val_f64; bool val_bool; char val_str[128]; }; };
struct llama_model_tensor_buft_override { const char * pattern; ggml_backend_buffer_type_t buft; };
struct llama_model_params { // NULL-terminated list of devices to use for offloading (if NULL, all available devices are used) ggml_backend_dev_t * devices;
// NULL-terminated list of buffer types to use for tensors that match a pattern const struct llama_model_tensor_buft_override * tensor_buft_overrides;
int32_t n_gpu_layers; // number of layers to store in VRAM, a negative value means all layers enum llama_split_mode split_mode; // how to split the model across multiple GPUs enum llama_load_mode load_mode; // how to load the model
enum llama_lazy_mode lazy_mode; // on-demand reading of tensors marked by the arch
// the GPU that is used for the entire model when split_mode is LLAMA_SPLIT_MODE_NONE int32_t main_gpu;
// proportion of the model (layers or rows) to offload to each GPU, size: llama_max_devices() const float * tensor_split;
// Called with a progress value between 0.0 and 1.0. Pass NULL to disable. // If the provided progress_callback returns true, model loading continues. // If it returns false, model loading is immediately aborted. llama_progress_callback progress_callback;
// context pointer passed to the progress callback void * progress_callback_user_data;
// override key-value pairs of the model meta data const struct llama_model_kv_override * kv_overrides;
// Keep the booleans together to avoid misalignment during copy-by-value. bool vocab_only; // only load the vocabulary, no weights bool check_tensors; // validate model tensor data bool use_extra_bufts; // use extra buffer types (used for weight repacking) bool no_host; // bypass host buffer allowing extra buffers to be used bool no_alloc; // only load metadata and simulate memory allocations bool load_mtp; // whether to load MTP layers };
struct llama_sampler_seq_config { llama_seq_id seq_id; struct llama_sampler * sampler; };
// NOTE: changing the default values of parameters marked as [EXPERIMENTAL] may cause crashes or incorrect results in certain configurations // https://github.com/ggml-org/llama.cpp/pull/7544 struct llama_context_params { uint32_t n_ctx; // text context, 0 = from model uint32_t n_batch; // logical maximum batch size that can be submitted to llama_decode uint32_t n_ubatch; // physical maximum batch size uint32_t n_seq_max; // max number of sequences (i.e. distinct states for recurrent models) uint32_t n_rs_seq; // number of recurrent-state snapshots per seq for rollback (0 = no rollback) [EXPERIMENTAL] uint32_t n_outputs_max; // max outputs in a ubatch (0 = n_batch) uint32_t n_outputs_max_per_seq; // max outputs per sequence (0 = n_outputs_max) int32_t n_threads; // number of threads to use for generation int32_t n_threads_batch; // number of threads to use for batch processing
enum llama_context_type ctx_type; // set the context type (e.g. MTP) enum llama_rope_scaling_type rope_scaling_type; // RoPE scaling type, from `enum llama_rope_scaling_type` enum llama_pooling_type pooling_type; // whether to pool (sum) embedding results by sequence id enum llama_attention_type attention_type; // attention type to use for embeddings enum llama_flash_attn_type flash_attn_type; // when to enable Flash Attention
// ref: https://github.com/ggml-org/llama.cpp/pull/2054 float rope_freq_base; // RoPE base frequency, 0 = from model float rope_freq_scale; // RoPE frequency scaling factor, 0 = from model float yarn_ext_factor; // YaRN extrapolation mix factor, negative = from model float yarn_attn_factor; // YaRN magnitude scaling factor float yarn_beta_fast; // YaRN low correction dim float yarn_beta_slow; // YaRN high correction dim uint32_t yarn_orig_ctx; // YaRN original context size float defrag_thold; // [DEPRECATED] defragment the KV cache if holes/size > thold, <= 0 disabled (default)
ggml_backend_sched_eval_callback cb_eval; void * cb_eval_user_data;
enum ggml_type type_k; // data type for K cache [EXPERIMENTAL] enum ggml_type type_v; // data type for V cache [EXPERIMENTAL]
// Abort callback // if it returns true, execution of llama_decode() will be aborted // currently works only with CPU execution ggml_abort_callback abort_callback; void * abort_callback_data;
// Keep the booleans together and at the end of the struct to avoid misalignment during copy-by-value. bool embeddings; // if true, extract embeddings (together with logits) bool offload_kqv; // offload the KQV ops (including the KV cache) to GPU bool no_perf; // measure performance timings bool op_offload; // offload host tensor operations to device bool swa_full; // use full-size SWA cache (https://github.com/ggml-org/llama.cpp/pull/13194#issuecomment-2868343055) // NOTE: setting to false when n_seq_max > 1 can cause bad performance in some cases // ref: https://github.com/ggml-org/llama.cpp/pull/13845#issuecomment-2924800573 bool kv_unified; // use a unified buffer across the input sequences when computing the attention // try to disable when n_seq_max > 1 for improved performance when the sequences do not share a large prefix // ref: https://github.com/ggml-org/llama.cpp/pull/14363
// [EXPERIMENTAL] // backend sampler chain configuration (make sure the caller keeps the sampler chains alive) // note: the samplers must be sampler chains (i.e. use llama_sampler_chain_init) struct llama_sampler_seq_config * samplers; size_t n_samplers;
// a source/target/parent context // can be utilized in various ways, for example by sharing results or llama_memory between 2 contexts struct llama_context * ctx_other; };
struct llama_model_tensor_override { const char * pattern; enum ggml_type type; };
struct llama_model_imatrix_data { const char * name; const float * data; size_t size; };
// model quantization parameters typedef struct llama_model_quantize_params { int32_t nthread; // number of threads to use for quantizing, if <=0 will use std::thread::hardware_concurrency() enum llama_ftype ftype; // quantize to this llama_ftype enum ggml_type output_tensor_type; // output tensor type enum ggml_type token_embedding_type; // token embeddings tensor type bool allow_requantize; // allow quantizing non-f32/f16 tensors bool quantize_output_tensor; // quantize output.weight bool only_copy; // only copy tensors - ftype, allow_requantize and quantize_output_tensor are ignored bool pure; // quantize all tensors to the default type bool keep_split; // quantize to the same number of shards bool dry_run; // calculate and show the final quantization size without performing quantization const struct llama_model_imatrix_data * imatrix; // pointer to importance matrix data const struct llama_model_kv_override * kv_overrides; // pointer to kv overrides const struct llama_model_tensor_override * tt_overrides; // pointer to tensor overrides const int32_t * prune_layers; // pointer to layer indices to prune size_t max_buf_size; // max bytes of tensor rows kept in memory at once, 0 = default (8 GiB) } llama_model_quantize_params;
typedef struct llama_logit_bias { llama_token token; float bias; } llama_logit_bias;
typedef struct llama_sampler_chain_params { bool no_perf; // whether to measure performance timings } llama_sampler_chain_params;
// used in chat template typedef struct llama_chat_message { const char * role; const char * content; } llama_chat_message;
// lora adapter struct llama_adapter_lora;
LLAMA_API const char * llama_version(void);
// Helpers for getting default parameters // TODO: update API to start accepting pointers to params structs (https://github.com/ggml-org/llama.cpp/discussions/9172) LLAMA_API struct llama_model_params llama_model_default_params(void); LLAMA_API struct llama_context_params llama_context_default_params(void); LLAMA_API struct llama_sampler_chain_params llama_sampler_chain_default_params(void); LLAMA_API struct llama_model_quantize_params llama_model_quantize_default_params(void);
// Initialize the llama + ggml backend // Call once at the start of the program LLAMA_API void llama_backend_init(void);
// Call once at the end of the program - currently only used for MPI LLAMA_API void llama_backend_free(void);
// Optional: enable numa optimizations // TODO: deprecate and make part of llama_backend_init() LLAMA_API void llama_numa_init(enum ggml_numa_strategy numa);
// Optional: an auto threadpool gets created in ggml if not passed explicitly LLAMA_API void llama_attach_threadpool( struct llama_context * ctx, ggml_threadpool_t threadpool, ggml_threadpool_t threadpool_batch);
LLAMA_API void llama_detach_threadpool(struct llama_context * ctx);
typedef void (*llama_model_set_tensor_data_t)(struct ggml_tensor * tensor, void * userdata);
// Create a new model from GGUF metadata as well as a function to set the tensor data // - tensors are created as GGML_TYPE_F32 by default, // override by adding a tensor with the same name but a different name to the context LLAMA_API struct llama_model * llama_model_init_from_user( struct gguf_context * metadata, llama_model_set_tensor_data_t set_tensor_data, // function to initialize tensor data with void * set_tensor_data_ud, // userdata for function struct llama_model_params params);
DEPRECATED(LLAMA_API struct llama_model * llama_load_model_from_file( const char * path_model, struct llama_model_params params), "use llama_model_load_from_file instead");
// Load a model from a file // If the file is split into multiple parts, the file name must follow this pattern: <name>-%05d-of-%05d.gguf // If the split file name does not follow this pattern, use llama_model_load_from_splits LLAMA_API struct llama_model * llama_model_load_from_file( const char * path_model, struct llama_model_params params);
// Load a model from an open FILE pointer // The GGUF is read from the current position, so it can be embedded in a larger file // mmap needs the GGUF data section at a file offset to be aligned to the CPU tensor alignment (32 bytes) LLAMA_API struct llama_model * llama_model_load_from_file_ptr( FILE * file, struct llama_model_params params);
// Load a model from multiple splits (support custom naming scheme) // The paths must be in the correct order LLAMA_API struct llama_model * llama_model_load_from_splits( const char ** paths, size_t n_paths, struct llama_model_params params);
LLAMA_API void llama_model_save_to_file( const struct llama_model * model, const char * path_model);
DEPRECATED(LLAMA_API void llama_free_model(struct llama_model * model), "use llama_model_free instead");
LLAMA_API void llama_model_free(struct llama_model * model);
LLAMA_API struct llama_context * llama_init_from_model( struct llama_model * model, struct llama_context_params params);
DEPRECATED(LLAMA_API struct llama_context * llama_new_context_with_model( struct llama_model * model, struct llama_context_params params), "use llama_init_from_model instead");
// Frees all allocated memory LLAMA_API void llama_free(struct llama_context * ctx);
LLAMA_API int64_t llama_time_us(void);
LLAMA_API size_t llama_max_devices(void); LLAMA_API size_t llama_max_parallel_sequences(void); LLAMA_API size_t llama_max_tensor_buft_overrides(void);
LLAMA_API bool llama_supports_mmap (void); LLAMA_API bool llama_supports_mlock (void); LLAMA_API bool llama_supports_gpu_offload(void); LLAMA_API bool llama_supports_rpc (void);
// NOTE: After creating a llama_context, it is recommended to query the actual values using these functions // In some cases the requested values via llama_context_params may differ from the actual values used by the context // ref: https://github.com/ggml-org/llama.cpp/pull/17046#discussion_r2503085732 LLAMA_API uint32_t llama_n_ctx (const struct llama_context * ctx); LLAMA_API uint32_t llama_n_ctx_seq (const struct llama_context * ctx); LLAMA_API uint32_t llama_n_batch (const struct llama_context * ctx); LLAMA_API uint32_t llama_n_ubatch (const struct llama_context * ctx); LLAMA_API uint32_t llama_n_seq_max (const struct llama_context * ctx); LLAMA_API uint32_t llama_n_rs_seq (const struct llama_context * ctx);
DEPRECATED(LLAMA_API int32_t llama_n_ctx_train(const struct llama_model * model), "use llama_model_n_ctx_train instead"); DEPRECATED(LLAMA_API int32_t llama_n_embd (const struct llama_model * model), "use llama_model_n_embd instead"); DEPRECATED(LLAMA_API int32_t llama_n_layer (const struct llama_model * model), "use llama_model_n_layer instead"); DEPRECATED(LLAMA_API int32_t llama_n_head (const struct llama_model * model), "use llama_model_n_head instead");
DEPRECATED(LLAMA_API int32_t llama_n_vocab (const struct llama_vocab * vocab), "use llama_vocab_n_tokens instead");
LLAMA_API const struct llama_model * llama_get_model (const struct llama_context * ctx); LLAMA_API llama_memory_t llama_get_memory (const struct llama_context * ctx); LLAMA_API enum llama_pooling_type llama_pooling_type(const struct llama_context * ctx); // TODO: rename to llama_get_pooling_type
LLAMA_API const struct llama_vocab * llama_model_get_vocab(const struct llama_model * model); LLAMA_API enum llama_rope_type llama_model_rope_type(const struct llama_model * model);
LLAMA_API int32_t llama_model_n_ctx_train (const struct llama_model * model); LLAMA_API int32_t llama_model_n_embd (const struct llama_model * model); LLAMA_API int32_t llama_model_n_embd_inp (const struct llama_model * model); LLAMA_API int32_t llama_model_n_embd_out (const struct llama_model * model); LLAMA_API int32_t llama_model_n_layer (const struct llama_model * model); LLAMA_API int32_t llama_model_n_layer_nextn(const struct llama_model * model); LLAMA_API int32_t llama_model_n_head (const struct llama_model * model); LLAMA_API int32_t llama_model_n_head_kv (const struct llama_model * model); LLAMA_API int32_t llama_model_n_swa (const struct llama_model * model);
// Get the model's RoPE frequency scaling factor LLAMA_API float llama_model_rope_freq_scale_train(const struct llama_model * model);
// Returns the number of classifier outputs (only valid for classifier models) // Undefined behavior for non-classifier models LLAMA_API uint32_t llama_model_n_cls_out(const struct llama_model * model);
// Returns label of classifier output by index (<n_cls_out). Returns nullptr if no label provided LLAMA_API const char * llama_model_cls_label(const struct llama_model * model, uint32_t i);
LLAMA_API enum llama_vocab_type llama_vocab_type(const struct llama_vocab * vocab);
LLAMA_API int32_t llama_vocab_n_tokens(const struct llama_vocab * vocab);
// Functions to access the model's GGUF metadata scalar values // - The functions return the length of the string on success, or -1 on failure // - The output string is always null-terminated and cleared on failure // - When retrieving a string, an extra byte must be allocated to account for the null terminator // - GGUF array values are not supported by these functions
// Get metadata value as a string by key name LLAMA_API int32_t llama_model_meta_val_str(const struct llama_model * model, const char * key, char * buf, size_t buf_size);
// Get the number of metadata key/value pairs LLAMA_API int32_t llama_model_meta_count(const struct llama_model * model);
// Get sampling metadata key name. Returns nullptr if the key is invalid LLAMA_API const char * llama_model_meta_key_str(enum llama_model_meta_key key);
// Get metadata key name by index LLAMA_API int32_t llama_model_meta_key_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size);
// Get metadata value as a string by index LLAMA_API int32_t llama_model_meta_val_str_by_index(const struct llama_model * model, int32_t i, char * buf, size_t buf_size);
// Get a string describing the model type LLAMA_API int32_t llama_model_desc(const struct llama_model * model, char * buf, size_t buf_size);
// Get the model file type (quantization), e.g. LLAMA_FTYPE_MOSTLY_Q8_0 LLAMA_API enum llama_ftype llama_model_ftype(const struct llama_model * model);
// Returns the total size of all the tensors in the model in bytes LLAMA_API uint64_t llama_model_size(const struct llama_model * model);
// Get the default chat template. Returns nullptr if not available // If name is NULL, returns the default chat template LLAMA_API const char * llama_model_chat_template(const struct llama_model * model, const char * name);
// Returns the total number of parameters in the model LLAMA_API uint64_t llama_model_n_params(const struct llama_model * model);
// Returns true if the model contains an encoder that requires llama_encode() call LLAMA_API bool llama_model_has_encoder(const struct llama_model * model);
// Returns true if the model contains a decoder that requires llama_decode() call LLAMA_API bool llama_model_has_decoder(const struct llama_model * model);
// For encoder-decoder models, this function returns id of the token that must be provided // to the decoder to start generating output sequence. For other models, it returns -1. LLAMA_API llama_token llama_model_decoder_start_token(const struct llama_model * model);
// Returns true if the model is recurrent (like Mamba, RWKV, etc.) LLAMA_API bool llama_model_is_recurrent(const struct llama_model * model);
// Returns true if the model is hybrid (like Jamba, Granite, etc.) LLAMA_API bool llama_model_is_hybrid(const struct llama_model * model);
// Returns true if the model is diffusion-based (like LLaDA, Dream, etc.) LLAMA_API bool llama_model_is_diffusion(const struct llama_model * model);
// Returns 0 on success LLAMA_API uint32_t llama_model_quantize( const char * fname_inp, const char * fname_out, const llama_model_quantize_params * params);
// // Adapters //
// Load a LoRA adapter from file // The adapter is valid as long as the associated model is not freed LLAMA_API struct llama_adapter_lora * llama_adapter_lora_init( struct llama_model * model, const char * path_lora);
// Load a LoRA adapter from an open FILE pointer, reading from its current position LLAMA_API struct llama_adapter_lora * llama_adapter_lora_init_from_file_ptr( struct llama_model * model, FILE * file);
// Functions to access the adapter's GGUF metadata scalar values // - The functions return the length of the string on success, or -1 on failure // - The output string is always null-terminated and cleared on failure // - When retrieving a string, an extra byte must be allocated to account for the null terminator // - GGUF array values are not supported by these functions
// Get metadata value as a string by key name LLAMA_API int32_t llama_adapter_meta_val_str(const struct llama_adapter_lora * adapter, const char * key, char * buf, size_t buf_size);
// Get the number of metadata key/value pairs LLAMA_API int32_t llama_adapter_meta_count(const struct llama_adapter_lora * adapter);
// Get metadata key name by index LLAMA_API int32_t llama_adapter_meta_key_by_index(const struct llama_adapter_lora * adapter, int32_t i, char * buf, size_t buf_size);
// Get metadata value as a string by index LLAMA_API int32_t llama_adapter_meta_val_str_by_index(const struct llama_adapter_lora * adapter, int32_t i, char * buf, size_t buf_size);
// Manually free a LoRA adapter // NOTE: loaded adapters that are not manually freed will be freed when the associated model is deleted LLAMA_API void llama_adapter_lora_free(struct llama_adapter_lora * adapter);
// Get the invocation tokens if the current lora is an alora LLAMA_API uint64_t llama_adapter_get_alora_n_invocation_tokens(const struct llama_adapter_lora * adapter); LLAMA_API const llama_token * llama_adapter_get_alora_invocation_tokens (const struct llama_adapter_lora * adapter);
// The following functions operate on a llama_context, hence the naming: llama_verb_...
// Set LoRa adapters on the context. Will only modify if the adapters currently in context are different. LLAMA_API int32_t llama_set_adapters_lora( struct llama_context * ctx, struct llama_adapter_lora ** adapters, size_t n_adapters, float * scales);
// Apply a loaded control vector to a llama_context, or if data is NULL, clear // the currently loaded vector. // n_embd should be the size of a single layer's control, and data should point // to an n_embd x n_layers buffer starting from layer 1. // il_start and il_end are the layer range the vector should apply to (both inclusive) // See llama_control_vector_load in common to load a control vector. LLAMA_API int32_t llama_set_adapter_cvec( struct llama_context * ctx, const float * data, size_t len, int32_t n_embd, int32_t il_start, int32_t il_end);
// // Memory //
// Clear the memory contents // If data == true, the data buffers will also be cleared together with the metadata LLAMA_API void llama_memory_clear( llama_memory_t mem, bool data);
// Removes all tokens that belong to the specified sequence and have positions in [p0, p1) // Returns false if a partial sequence cannot be removed. Removing a whole sequence never fails // seq_id < 0 : match any sequence [TAG_LLAMA_SEQ_ID_NEG] // p0 < 0 : [0, p1] // p1 < 0 : [p0, inf) LLAMA_API bool llama_memory_seq_rm( llama_memory_t mem, llama_seq_id seq_id, llama_pos p0, llama_pos p1);
// Copy all tokens that belong to the specified sequence to another sequence // p0 < 0 : [0, p1] // p1 < 0 : [p0, inf) LLAMA_API void llama_memory_seq_cp( llama_memory_t mem, llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1);
// Removes all tokens that do not belong to the specified sequence LLAMA_API void llama_memory_seq_keep( llama_memory_t mem, llama_seq_id seq_id);
// Adds relative position "delta" to all tokens that belong to the specified sequence and have positions in [p0, p1) // p0 < 0 : [0, p1] // p1 < 0 : [p0, inf) LLAMA_API void llama_memory_seq_add( llama_memory_t mem, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta);
// Integer division of the positions by factor of `d > 1` // p0 < 0 : [0, p1] // p1 < 0 : [p0, inf) LLAMA_API void llama_memory_seq_div( llama_memory_t mem, llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d);
// Returns the smallest position present in the memory for the specified sequence // This is typically non-zero only for SWA caches // Note that all positions in the range [pos_min, pos_max] are guaranteed to be present in the memory // Return -1 if the sequence is empty LLAMA_API llama_pos llama_memory_seq_pos_min( llama_memory_t mem, llama_seq_id seq_id);
// Returns the largest position present in the memory for the specified sequence // Note that all positions in the range [pos_min, pos_max] are guaranteed to be present in the memory // Return -1 if the sequence is empty LLAMA_API llama_pos llama_memory_seq_pos_max( llama_memory_t mem, llama_seq_id seq_id);
// Check if the memory supports shifting LLAMA_API bool llama_memory_can_shift(llama_memory_t mem);
// // State / sessions //
// Returns the *actual* size in bytes of the state // (logits, embedding and memory) // Only use when saving the state, not when restoring it, otherwise the size may be too small. LLAMA_API size_t llama_state_get_size(struct llama_context * ctx); LLAMA_API DEPRECATED(size_t llama_get_state_size(struct llama_context * ctx), "use llama_state_get_size instead");
// Copies the state to the specified destination address. // Destination needs to have allocated enough memory. // Returns the number of bytes copied LLAMA_API size_t llama_state_get_data( struct llama_context * ctx, uint8_t * dst, size_t size); LLAMA_API DEPRECATED(size_t llama_copy_state_data( struct llama_context * ctx, uint8_t * dst), "use llama_state_get_data instead");
// Set the state reading from the specified address // Returns the number of bytes read LLAMA_API size_t llama_state_set_data( struct llama_context * ctx, const uint8_t * src, size_t size); LLAMA_API DEPRECATED(size_t llama_set_state_data( struct llama_context * ctx, const uint8_t * src), "use llama_state_set_data instead");
// Save/load session file LLAMA_API bool llama_state_load_file( struct llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out); LLAMA_API DEPRECATED(bool llama_load_session_file( struct llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out), "use llama_state_load_file instead");
LLAMA_API bool llama_state_save_file( struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count); LLAMA_API DEPRECATED(bool llama_save_session_file( struct llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count), "use llama_state_save_file instead");
// Get the exact size needed to copy the state of a single sequence LLAMA_API size_t llama_state_seq_get_size( struct llama_context * ctx, llama_seq_id seq_id);
// Copy the state of a single sequence into the specified buffer LLAMA_API size_t llama_state_seq_get_data( struct llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id);
// Copy the sequence data (originally copied with `llama_state_seq_get_data`) into the specified sequence // Returns: // - Positive: Ok // - Zero: Failed to load LLAMA_API size_t llama_state_seq_set_data( struct llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id dest_seq_id);
LLAMA_API size_t llama_state_seq_save_file( struct llama_context * ctx, const char * filepath, llama_seq_id seq_id, const llama_token * tokens, size_t n_token_count);
// If tokens_out is NULL, only the token count is reported through n_token_count_out and no state is loaded LLAMA_API size_t llama_state_seq_load_file( struct llama_context * ctx, const char * filepath, llama_seq_id dest_seq_id, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out);
#define LLAMA_STATE_SEQ_FLAGS_NONE 0
// for backwards-compat#define LLAMA_STATE_SEQ_FLAGS_SWA_ONLY 1
// work only with partial states, such as SWA KV cache or recurrent cache (e.g. Mamba)#define LLAMA_STATE_SEQ_FLAGS_PARTIAL_ONLY 1
// Keeps the tensor data on device buffers (i.e. not accessible in host memory, but faster save/load).// Getting the state for a seq_id with this flag invalidates all prior states gotten for that seq_id with this flag.#define LLAMA_STATE_SEQ_FLAGS_ON_DEVICE 2
typedef uint32_t llama_state_seq_flags;
LLAMA_API size_t llama_state_seq_get_size_ext( struct llama_context * ctx, llama_seq_id seq_id, llama_state_seq_flags flags);
LLAMA_API size_t llama_state_seq_get_data_ext( struct llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id, llama_state_seq_flags flags);
LLAMA_API size_t llama_state_seq_set_data_ext( struct llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id dest_seq_id, llama_state_seq_flags flags);
// // Decoding //
// Return batch for single sequence of tokens // The sequence ID will be fixed to 0 // The position of the tokens will be tracked automatically by llama_decode // // NOTE: this is a helper function to facilitate transition to the new batch API - avoid using it // LLAMA_API struct llama_batch llama_batch_get_one( llama_token * tokens, int32_t n_tokens);
// Allocates a batch of tokens on the heap that can hold a maximum of n_tokens // Each token can be assigned up to n_seq_max sequence ids // The batch has to be freed with llama_batch_free() // If embd != 0, llama_batch.embd will be allocated with size of n_tokens * embd * sizeof(float) // Otherwise, llama_batch.token will be allocated to store n_tokens llama_token // The rest of the llama_batch members are allocated with size n_tokens // All members are left uninitialized LLAMA_API struct llama_batch llama_batch_init( int32_t n_tokens, int32_t embd, int32_t n_seq_max);
// Frees a batch of tokens allocated with llama_batch_init() LLAMA_API void llama_batch_free(struct llama_batch batch);
// Process a batch of tokens. // In contrast to llama_decode() - this call does not use KV cache. // For encode-decoder contexts, processes the batch using the encoder. // Can store the encoder output internally for later use by the decoder's cross-attention layers. // 0 - success // < 0 - error. the memory state is restored to the state before this call LLAMA_API int32_t llama_encode( struct llama_context * ctx, struct llama_batch batch);
// Process a batch of tokens. // Requires the context to have a memory. // For encode-decoder contexts, processes the batch using the decoder. // Positive return values does not mean a fatal error, but rather a warning. // Upon fatal-error or abort, the ubatches that managed to be been processed will remain in the memory state of the context // To handle this correctly, query the memory state using llama_memory_seq_pos_min() and llama_memory_seq_pos_max() // Upon other return values, the memory state is restored to the state before this call // 0 - success // 1 - could not find a KV slot for the batch (try reducing the size of the batch or increase the context) // 2 - aborted (processed ubatches will remain in the context's memory) // -1 - invalid input batch // < -1 - fatal error (processed ubatches will remain in the context's memory) LLAMA_API int32_t llama_decode( struct llama_context * ctx, struct llama_batch batch);
// // Extended batch API //
struct llama_batch_ext;
struct llama_embd { const float * data; size_t n_rows; // number of embedding rows in data size_t n_embd; // size of one row };
LLAMA_API struct llama_batch_ext * llama_batch_ext_init (struct llama_context * ctx); LLAMA_API void llama_batch_ext_free (struct llama_batch_ext * batch); LLAMA_API void llama_batch_ext_clear(struct llama_batch_ext * batch);
// Add an input token to the batch, with default values: // id = LLAMA_TOKEN_NULL // embd = nullptr // pos = not set, the caller must set it with llama_batch_ext_set_pos() // Returns the batch index (>= 0) // On error: // -1: batch is full // -2: token is invalid (id == LLAMA_TOKEN_NULL or invalid embd) // -3: invalid sequence id LLAMA_API int32_t llama_batch_ext_add (struct llama_batch_ext * batch, llama_seq_id seq_id);
// Add an input token to the batch, with a specified token ID or token embedding LLAMA_API int32_t llama_batch_ext_add_token(struct llama_batch_ext * batch, llama_seq_id seq_id, llama_token id); LLAMA_API int32_t llama_batch_ext_add_embd (struct llama_batch_ext * batch, llama_seq_id seq_id, struct llama_embd embd);
// Add the token at index idx in the batch to another sequence id. The position will stays the same. // Note: this should be called before other _set() functions LLAMA_API bool llama_batch_ext_add_seq( struct llama_batch_ext * batch, int32_t idx, llama_seq_id seq_id);
// Set the token embedding for the token at index idx in the batch // use it after llama_batch_ext_add_token() to have an entry with both a token id and an embedding LLAMA_API bool llama_batch_ext_set_embd_token( struct llama_batch_ext * batch, int32_t idx, struct llama_embd embd);
// Set the "state" embedding for the token at index idx in the batch // "state" here means extra hidden state carried over from a previous stage, e.g.: // - MTP: state from N layers of the target model // - Qwen3 VL (deepstack): state from N layers of the vision encoder LLAMA_API bool llama_batch_ext_set_embd_state( struct llama_batch_ext * batch, int32_t idx, struct llama_embd embd);
// Set if output embeddings should be available for the token at index idx in the batch // Note: for now, this is equivalent to setting the output logits LLAMA_API bool llama_batch_ext_set_output_embd( struct llama_batch_ext * batch, int32_t idx, bool value);
// Set output logits for the token at index idx in the batch // Note: for now, this is equivalent to setting the output embd LLAMA_API bool llama_batch_ext_set_output_logits( struct llama_batch_ext * batch, int32_t idx, bool value);
// Set custom position for the token at index idx in the batch // For M-RoPE models: // - Embedding tokens must have multiple positions per token // - Text token only requires one single position per token LLAMA_API bool llama_batch_ext_set_pos( struct llama_batch_ext * batch, int32_t idx, const llama_pos * pos);
// TODO: implement get_embeddings() and get_logits() for llama_batch_ext
// Return values are the same as llama_decode() LLAMA_API int32_t llama_process( struct llama_context * ctx, enum llama_process_type type, struct llama_batch_ext * batch);
// Set the number of threads used for decoding // n_threads is the number of threads used for generation (single token) // n_threads_batch is the number of threads used for prompt and batch processing (multiple tokens) LLAMA_API void llama_set_n_threads(struct llama_context * ctx, int32_t n_threads, int32_t n_threads_batch);
// Get the number of threads used for generation of a single token. LLAMA_API int32_t llama_n_threads(struct llama_context * ctx);
// Get the number of threads used for prompt and batch processing (multiple token). LLAMA_API int32_t llama_n_threads_batch(struct llama_context * ctx);
// Set whether the context outputs embeddings or not // TODO: rename to avoid confusion with llama_get_embeddings() LLAMA_API void llama_set_embeddings(struct llama_context * ctx, bool embeddings);
// Set whether to use causal attention or not // If set to true, the model will only attend to the past tokens LLAMA_API void llama_set_causal_attn(struct llama_context * ctx, bool causal_attn);
// Returns whether the context is currently using causal attention LLAMA_API bool llama_get_causal_attn(const struct llama_context * ctx);
// Set whether the model is in warmup mode or not // If true, all model tensors are activated during llama_decode() to load and cache their weights. // // note: using this can cause extra graph reallocations because it changes the graph topology with MoE models, // so it is generally not recommended to use in practice. will be removed in the future DEPRECATED(LLAMA_API void llama_set_warmup(struct llama_context * ctx, bool warmup), "user code should do warmup runs manually [TAG_LLAMA_GRAPH_NO_WARMUP]");
// Set abort callback LLAMA_API void llama_set_abort_callback(struct llama_context * ctx, ggml_abort_callback abort_callback, void * abort_callback_data);
// Wait until all computations are finished // This is automatically done when using one of the functions below to obtain the computation results // and is not necessary to call it explicitly in most cases LLAMA_API void llama_synchronize(struct llama_context * ctx);
// Token logits obtained from the last call to llama_decode() // The logits for which llama_batch.logits[i] != 0 are stored contiguously // in the order they have appeared in the batch. // Rows: number of tokens for which llama_batch.logits[i] != 0 // Cols: n_vocab // TODO: deprecate in favor of llama_get_logits_ith() (ref: https://github.com/ggml-org/llama.cpp/pull/14853#issuecomment-3113143522) LLAMA_API float * llama_get_logits(struct llama_context * ctx);
// Logits for the ith token. For positive indices, Equivalent to: // llama_get_logits(ctx) + ctx->output_ids[i]*n_vocab // Negative indices can be used to access logits in reverse order, -1 is the last logit. // returns NULL for invalid ids. LLAMA_API float * llama_get_logits_ith(struct llama_context * ctx, int32_t i);
// Get all output token embeddings. // when pooling_type == LLAMA_POOLING_TYPE_NONE or when using a generative model, // the embeddings for which llama_batch.logits[i] != 0 are stored contiguously // in the order they have appeared in the batch. // shape: [n_outputs*n_embd] // Otherwise, returns NULL. // TODO: deprecate in favor of llama_get_embeddings_ith() (ref: https://github.com/ggml-org/llama.cpp/pull/14853#issuecomment-3113143522) LLAMA_API float * llama_get_embeddings(struct llama_context * ctx);
// Get the embeddings for the ith token. For positive indices, Equivalent to: // llama_get_embeddings(ctx) + ctx->output_ids[i]*n_embd // Negative indices can be used to access embeddings in reverse order, -1 is the last embedding. // shape: [n_embd] (1-dimensional) // returns NULL for invalid ids. LLAMA_API float * llama_get_embeddings_ith(struct llama_context * ctx, int32_t i);
// Get the embeddings for a sequence id // Returns NULL if pooling_type is LLAMA_POOLING_TYPE_NONE // when pooling_type == LLAMA_POOLING_TYPE_RANK, returns float[n_cls_out] with the rank(s) of the sequence // otherwise: float[n_embd] (1-dimensional) LLAMA_API float * llama_get_embeddings_seq(struct llama_context * ctx, llama_seq_id seq_id);
// // backend sampling API [EXPERIMENTAL] // note: use only if the llama_context was created with at least one llama_sampler_seq_config //
// Get the backend sampled token for the ith token. // With multiple outputs, sampler state advances when the token is accepted, // not when it is read through this function. // When accepting multiple outputs, accept a contiguous prefix in output order. // Returns LLAMA_TOKEN_NULL if no token was sampled. LLAMA_API llama_token llama_get_sampled_token_ith(struct llama_context * ctx, int32_t i);
// Get the backend sampled probabilities for the ith token // The index matches llama_get_sampled_token_ith(). // Returns NULL if no probabilities were generated. LLAMA_API float * llama_get_sampled_probs_ith (struct llama_context * ctx, int32_t i); LLAMA_API uint32_t llama_get_sampled_probs_count_ith(struct llama_context * ctx, int32_t i);
// Get the backend sampled logits for the ith token // Returns NULL if no logits were sampled. LLAMA_API float * llama_get_sampled_logits_ith (struct llama_context * ctx, int32_t i); LLAMA_API uint32_t llama_get_sampled_logits_count_ith(struct llama_context * ctx, int32_t i);
// Get the backend sampled candidates (token ids) for the ith token // These are needed to map probability/logit indices to vocab token ids. // Returns NULL if no candidates were sampled. LLAMA_API llama_token * llama_get_sampled_candidates_ith (struct llama_context * ctx, int32_t i); LLAMA_API uint32_t llama_get_sampled_candidates_count_ith(struct llama_context * ctx, int32_t i);
// // Vocab //
LLAMA_API const char * llama_vocab_get_text(const struct llama_vocab * vocab, llama_token token);
LLAMA_API float llama_vocab_get_score(const struct llama_vocab * vocab, llama_token token);
LLAMA_API enum llama_token_attr llama_vocab_get_attr(const struct llama_vocab * vocab, llama_token token);
// Check if the token is supposed to end generation (end-of-generation, eg. EOS, EOT, etc.) LLAMA_API bool llama_vocab_is_eog(const struct llama_vocab * vocab, llama_token token);
// Identify if Token Id is a control token or a render-able token LLAMA_API bool llama_vocab_is_control(const struct llama_vocab * vocab, llama_token token);
// Special tokens LLAMA_API llama_token llama_vocab_bos(const struct llama_vocab * vocab); // beginning-of-sentence LLAMA_API llama_token llama_vocab_eos(const struct llama_vocab * vocab); // end-of-sentence LLAMA_API llama_token llama_vocab_eot(const struct llama_vocab * vocab); // end-of-turn LLAMA_API llama_token llama_vocab_sep(const struct llama_vocab * vocab); // sentence separator LLAMA_API llama_token llama_vocab_nl (const struct llama_vocab * vocab); // next-line LLAMA_API llama_token llama_vocab_pad(const struct llama_vocab * vocab); // padding LLAMA_API llama_token llama_vocab_mask(const struct llama_vocab * vocab); // mask
LLAMA_API bool llama_vocab_get_add_bos(const struct llama_vocab * vocab); LLAMA_API bool llama_vocab_get_add_eos(const struct llama_vocab * vocab); LLAMA_API bool llama_vocab_get_add_sep(const struct llama_vocab * vocab);
// model-specific suppress tokens (gguf key: tokenizer.ggml.suppress_tokens) LLAMA_API const llama_token * llama_vocab_get_suppress_tokens(const struct llama_vocab * vocab, int32_t * n_suppress_tokens);
LLAMA_API llama_token llama_vocab_fim_pre(const struct llama_vocab * vocab); LLAMA_API llama_token llama_vocab_fim_suf(const struct llama_vocab * vocab); LLAMA_API llama_token llama_vocab_fim_mid(const struct llama_vocab * vocab); LLAMA_API llama_token llama_vocab_fim_pad(const struct llama_vocab * vocab); LLAMA_API llama_token llama_vocab_fim_rep(const struct llama_vocab * vocab); LLAMA_API llama_token llama_vocab_fim_sep(const struct llama_vocab * vocab);
DEPRECATED(LLAMA_API const char * llama_token_get_text(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_get_text instead"); DEPRECATED(LLAMA_API float llama_token_get_score(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_get_score instead"); DEPRECATED(LLAMA_API enum llama_token_attr llama_token_get_attr(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_get_attr instead"); DEPRECATED(LLAMA_API bool llama_token_is_eog(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_is_eog instead"); DEPRECATED(LLAMA_API bool llama_token_is_control(const struct llama_vocab * vocab, llama_token token), "use llama_vocab_is_control instead"); DEPRECATED(LLAMA_API llama_token llama_token_bos(const struct llama_vocab * vocab), "use llama_vocab_bos instead"); DEPRECATED(LLAMA_API llama_token llama_token_eos(const struct llama_vocab * vocab), "use llama_vocab_eos instead"); DEPRECATED(LLAMA_API llama_token llama_token_eot(const struct llama_vocab * vocab), "use llama_vocab_eot instead"); DEPRECATED(LLAMA_API llama_token llama_token_cls(const struct llama_vocab * vocab), "use llama_vocab_cls instead"); DEPRECATED(LLAMA_API llama_token llama_token_sep(const struct llama_vocab * vocab), "use llama_vocab_sep instead"); DEPRECATED(LLAMA_API llama_token llama_token_nl (const struct llama_vocab * vocab), "use llama_vocab_nl instead"); DEPRECATED(LLAMA_API llama_token llama_token_pad(const struct llama_vocab * vocab), "use llama_vocab_pad instead"); DEPRECATED(LLAMA_API bool llama_add_bos_token(const struct llama_vocab * vocab), "use llama_vocab_get_add_bos instead"); DEPRECATED(LLAMA_API bool llama_add_eos_token(const struct llama_vocab * vocab), "use llama_vocab_get_add_eos instead"); DEPRECATED(LLAMA_API llama_token llama_token_fim_pre(const struct llama_vocab * vocab), "use llama_vocab_fim_pre instead"); DEPRECATED(LLAMA_API llama_token llama_token_fim_suf(const struct llama_vocab * vocab), "use llama_vocab_fim_suf instead"); DEPRECATED(LLAMA_API llama_token llama_token_fim_mid(const struct llama_vocab * vocab), "use llama_vocab_fim_mid instead"); DEPRECATED(LLAMA_API llama_token llama_token_fim_pad(const struct llama_vocab * vocab), "use llama_vocab_fim_pad instead"); DEPRECATED(LLAMA_API llama_token llama_token_fim_rep(const struct llama_vocab * vocab), "use llama_vocab_fim_rep instead"); DEPRECATED(LLAMA_API llama_token llama_token_fim_sep(const struct llama_vocab * vocab), "use llama_vocab_fim_sep instead");
// CLS is equivalent to BOS DEPRECATED(LLAMA_API llama_token llama_vocab_cls(const struct llama_vocab * vocab), // classification "use llama_vocab_bos instead");
// // Tokenization // // The API is thread-safe. //
/// @details Convert the provided text into tokens. /// @param tokens The tokens pointer must be large enough to hold the resulting tokens. /// @return Returns the number of tokens on success, no more than n_tokens_max /// @return Returns a negative number on failure - the number of tokens that would have been returned /// @return Returns INT32_MIN on overflow (e.g., tokenization result size exceeds int32_t limit) /// @param add_special Allow to add BOS and EOS tokens if model is configured to do so. /// @param parse_special Allow tokenizing special and/or control tokens which otherwise are not exposed and treated /// as plaintext. Does not insert a leading space. LLAMA_API int32_t llama_tokenize( const struct llama_vocab * vocab, const char * text, int32_t text_len, llama_token * tokens, int32_t n_tokens_max, bool add_special, bool parse_special);
// Token Id -> Piece. // Uses the vocabulary in the provided context. // Does not write null terminator to the buffer. // User can skip up to 'lstrip' leading spaces before copying (useful when encoding/decoding multiple tokens with 'add_space_prefix') // @param special If true, special tokens are rendered in the output. LLAMA_API int32_t llama_token_to_piece( const struct llama_vocab * vocab, llama_token token, char * buf, int32_t length, int32_t lstrip, bool special);
/// @details Convert the provided tokens into text (inverse of llama_tokenize()). /// @param text The char pointer must be large enough to hold the resulting text. /// @return Returns the number of chars/bytes on success, no more than text_len_max. /// @return Returns a negative number on failure - the number of chars/bytes that would have been returned. /// @param remove_special Allow to remove BOS and EOS tokens if model is configured to do so. /// @param unparse_special If true, special tokens are rendered in the output. LLAMA_API int32_t llama_detokenize( const struct llama_vocab * vocab, const llama_token * tokens, int32_t n_tokens, char * text, int32_t text_len_max, bool remove_special, bool unparse_special);
// // Chat templates //
/// Apply chat template. Inspired by hf apply_chat_template() on python. /// /// NOTE: This function does not use a jinja parser. It only support a pre-defined list of template. See more: https://github.com/ggml-org/llama.cpp/wiki/Templates-supported-by-llama_chat_apply_template /// @param tmpl A Jinja template to use for this chat. /// @param chat Pointer to a list of multiple llama_chat_message /// @param n_msg Number of llama_chat_message in this chat /// @param add_ass Whether to end the prompt with the token(s) that indicate the start of an assistant message. /// @param buf A buffer to hold the output formatted prompt. The recommended alloc size is 2 * (total number of characters of all messages) /// @param length The size of the allocated buffer /// @return The total number of bytes of the formatted prompt. If is it larger than the size of buffer, you may need to re-alloc it and then re-apply the template. LLAMA_API int32_t llama_chat_apply_template( const char * tmpl, const struct llama_chat_message * chat, size_t n_msg, bool add_ass, char * buf, int32_t length);
// Get list of built-in chat templates LLAMA_API int32_t llama_chat_builtin_templates(const char ** output, size_t len);
// // Sampling API // // Sample usage: // // // prepare the sampling chain at the start // auto sparams = llama_sampler_chain_default_params(); // // llama_sampler * smpl = llama_sampler_chain_init(sparams); // // llama_sampler_chain_add(smpl, llama_sampler_init_top_k(50)); // llama_sampler_chain_add(smpl, llama_sampler_init_top_p(0.9, 1)); // llama_sampler_chain_add(smpl, llama_sampler_init_temp (0.8)); // // // typically, the chain should end with a sampler such as "greedy", "dist" or "mirostat" // // this sampler will be responsible to select the actual token // llama_sampler_chain_add(smpl, llama_sampler_init_dist(seed)); // // ... // // // decoding loop: // while (...) { // ... // // llama_decode(ctx, batch); // // // sample from the logits of the last token in the batch // const llama_token id = llama_sampler_sample(smpl, ctx, -1); // // ... // } // // llama_sampler_free(smpl); //
typedef void * llama_sampler_context_t;
struct llama_sampler_data { struct ggml_tensor * logits; struct ggml_tensor * probs; struct ggml_tensor * sampled; struct ggml_tensor * candidates; };
// user code can implement the interface below in order to create custom llama_sampler struct llama_sampler_i { const char * (*name) (const struct llama_sampler * smpl); // can be NULL void (*accept)( struct llama_sampler * smpl, llama_token token); // can be NULL void (*apply) ( struct llama_sampler * smpl, llama_token_data_array * cur_p); // required void (*reset) ( struct llama_sampler * smpl); // can be NULL struct llama_sampler * (*clone) (const struct llama_sampler * smpl); // can be NULL if ctx is NULL void (*free) ( struct llama_sampler * smpl); // can be NULL if ctx is NULL
// [EXPERIMENTAL] // backend sampling interface:
// return true if the backend supports all ops needed by the sampler and can handle up to n_outputs_max_per_seq outputs per sequence // note: call once per sampler bool (*backend_init)( struct llama_sampler * smpl, ggml_backend_buffer_type_t buft, uint32_t n_outputs_max_per_seq);
// call after .backend_apply() void (*backend_accept)( struct llama_sampler * smpl, struct ggml_context * ctx, struct ggml_cgraph * gf, struct ggml_tensor * selected_token);
// call after .backend_init() void (*backend_apply)( struct llama_sampler * smpl, struct ggml_context * ctx, struct ggml_cgraph * gf, struct llama_sampler_data * data);
// called before graph execution to set inputs for the current ubatch void (*backend_set_input)(struct llama_sampler * smpl);
// called before rebuilding a sampling graph to clear any internal sampler state void (*backend_reset)(struct llama_sampler * smpl);
// copy mutable state from src into dst while keeping dst's references to the current sampling graph // src and dst must have the same type and configuration void (*copy_state)(const struct llama_sampler * src, struct llama_sampler * dst); };
struct llama_sampler { struct llama_sampler_i * iface;
llama_sampler_context_t ctx; };
// [EXPERIMENTAL] // attach a sampler to the context // note: prefer initializing the context with llama_context_params.samplers when possible LLAMA_API bool llama_set_sampler(struct llama_context * ctx, llama_seq_id seq_id, struct llama_sampler * smpl);
// mirror of llama_sampler_i: LLAMA_API struct llama_sampler * llama_sampler_init ( struct llama_sampler_i * iface, llama_sampler_context_t ctx); LLAMA_API const char * llama_sampler_name (const struct llama_sampler * smpl); LLAMA_API void llama_sampler_accept( struct llama_sampler * smpl, llama_token token); LLAMA_API void llama_sampler_apply ( struct llama_sampler * smpl, llama_token_data_array * cur_p); LLAMA_API void llama_sampler_reset ( struct llama_sampler * smpl); LLAMA_API struct llama_sampler * llama_sampler_clone (const struct llama_sampler * smpl); LLAMA_API void llama_sampler_copy (const struct llama_sampler * src, struct llama_sampler * dst); // important: do not free if the sampler has been added to a llama_sampler_chain (via llama_sampler_chain_add) LLAMA_API void llama_sampler_free ( struct llama_sampler * smpl);
// llama_sampler_chain // a type of llama_sampler that can chain multiple samplers one after another
LLAMA_API struct llama_sampler * llama_sampler_chain_init(struct llama_sampler_chain_params params);
// important: takes ownership of the sampler object and will free it when llama_sampler_free is called LLAMA_API void llama_sampler_chain_add( struct llama_sampler * chain, struct llama_sampler * smpl);
// return NULL if: // - the sampler is NULL // - the sampler is not a llama_sampler_chain // - the index is out of bounds, unless i == -1 // - if i == -1, returns the chain itself (can be used to check if the sampler is a chain) LLAMA_API struct llama_sampler * llama_sampler_chain_get( struct llama_sampler * chain, int32_t i);
// the total number of samplers in the chain LLAMA_API int32_t llama_sampler_chain_n (const struct llama_sampler * chain);
// after removing a sampler, the chain will no longer own it, and it will not be freed when the chain is freed LLAMA_API struct llama_sampler * llama_sampler_chain_remove( struct llama_sampler * chain, int32_t i);
// available samplers:
LLAMA_API struct llama_sampler * llama_sampler_init_greedy(void);
/// seed == LLAMA_DEFAULT_SEED to use a random seed. LLAMA_API struct llama_sampler * llama_sampler_init_dist(uint32_t seed);
/// @details Top-K sampling described in academic paper "The Curious Case of Neural Text Degeneration" https://arxiv.org/abs/1904.09751 /// Setting k <= 0 makes this a noop LLAMA_API struct llama_sampler * llama_sampler_init_top_k (int32_t k);
/// @details Nucleus sampling described in academic paper "The Curious Case of Neural Text Degeneration" https://arxiv.org/abs/1904.09751 LLAMA_API struct llama_sampler * llama_sampler_init_top_p (float p, size_t min_keep);
/// @details Minimum P sampling as described in https://github.com/ggml-org/llama.cpp/pull/3841 LLAMA_API struct llama_sampler * llama_sampler_init_min_p (float p, size_t min_keep);
/// @details Locally Typical Sampling implementation described in the paper https://arxiv.org/abs/2202.00666. LLAMA_API struct llama_sampler * llama_sampler_init_typical (float p, size_t min_keep);
/// #details Updates the logits l_i` = l_i/t. When t <= 0.0f, the maximum logit is kept at it's original value, the rest are set to -inf LLAMA_API struct llama_sampler * llama_sampler_init_temp (float t);
/// @details Dynamic temperature implementation (a.k.a. entropy) described in the paper https://arxiv.org/abs/2309.02772. LLAMA_API struct llama_sampler * llama_sampler_init_temp_ext (float t, float delta, float exponent);
/// @details XTC sampler as described in https://github.com/oobabooga/text-generation-webui/pull/6335 LLAMA_API struct llama_sampler * llama_sampler_init_xtc (float p, float t, size_t min_keep, uint32_t seed);
/// @details Top n sigma sampling as described in academic paper "Top-nσ: Not All Logits Are You Need" https://arxiv.org/pdf/2411.07641 LLAMA_API struct llama_sampler * llama_sampler_init_top_n_sigma(float n);
/// @details Mirostat 1.0 algorithm described in the paper https://arxiv.org/abs/2007.14966. Uses tokens instead of words. /// @param candidates A vector of `llama_token_data` containing the candidate tokens, their probabilities (p), and log-odds (logit) for the current position in the generated text. /// @param tau The target cross-entropy (or surprise) value you want to achieve for the generated text. A higher value corresponds to more surprising or less predictable text, while a lower value corresponds to less surprising or more predictable text. /// @param eta The learning rate used to update `mu` based on the error between the target and observed surprisal of the sampled word. A larger learning rate will cause `mu` to be updated more quickly, while a smaller learning rate will result in slower updates. /// @param m The number of tokens considered in the estimation of `s_hat`. This is an arbitrary value that is used to calculate `s_hat`, which in turn helps to calculate the value of `k`. In the paper, they use `m = 100`, but you can experiment with different values to see how it affects the performance of the algorithm. /// @param mu Maximum cross-entropy. This value is initialized to be twice the target cross-entropy (`2 * tau`) and is updated in the algorithm based on the error between the target and observed surprisal. LLAMA_API struct llama_sampler * llama_sampler_init_mirostat( int32_t n_vocab, uint32_t seed, float tau, float eta, int32_t m);
/// @details Mirostat 2.0 algorithm described in the paper https://arxiv.org/abs/2007.14966. Uses tokens instead of words. /// @param candidates A vector of `llama_token_data` containing the candidate tokens, their probabilities (p), and log-odds (logit) for the current position in the generated text. /// @param tau The target cross-entropy (or surprise) value you want to achieve for the generated text. A higher value corresponds to more surprising or less predictable text, while a lower value corresponds to less surprising or more predictable text. /// @param eta The learning rate used to update `mu` based on the error between the target and observed surprisal of the sampled word. A larger learning rate will cause `mu` to be updated more quickly, while a smaller learning rate will result in slower updates. /// @param mu Maximum cross-entropy. This value is initialized to be twice the target cross-entropy (`2 * tau`) and is updated in the algorithm based on the error between the target and observed surprisal. LLAMA_API struct llama_sampler * llama_sampler_init_mirostat_v2( uint32_t seed, float tau, float eta);
/// @details Initializes a GBNF grammar, see grammars/README.md for details. /// @param vocab The vocabulary that this grammar will be used with. /// @param grammar_str The production rules for the grammar, encoded as a string. Returns an empty grammar if empty. Returns NULL if parsing of grammar_str fails. /// @param grammar_root The name of the start symbol for the grammar. LLAMA_API struct llama_sampler * llama_sampler_init_grammar( const struct llama_vocab * vocab, const char * grammar_str, const char * grammar_root);
DEPRECATED(LLAMA_API struct llama_sampler * llama_sampler_init_grammar_lazy( const struct llama_vocab * vocab, const char * grammar_str, const char * grammar_root, const char ** trigger_words, size_t num_trigger_words, const llama_token * trigger_tokens, size_t num_trigger_tokens), "use llama_sampler_init_grammar_lazy_patterns instead");
/// @details Lazy grammar sampler, introduced in https://github.com/ggml-org/llama.cpp/pull/9639 /// @param trigger_patterns A list of patterns that will trigger the grammar sampler. Pattern will be matched from the start of the generation output, and grammar sampler will be fed content starting from its first match group. /// @param trigger_tokens A list of tokens that will trigger the grammar sampler. Grammar sampler will be fed content starting from the trigger token included. LLAMA_API struct llama_sampler * llama_sampler_init_grammar_lazy_patterns( const struct llama_vocab * vocab, const char * grammar_str, const char * grammar_root, const char ** trigger_patterns, size_t num_trigger_patterns, const llama_token * trigger_tokens, size_t num_trigger_tokens);
/// NOTE: Avoid using on the full vocabulary as searching for repeated tokens can become slow. For example, apply top-k or top-p sampling first. LLAMA_API struct llama_sampler * llama_sampler_init_penalties( int32_t n_vocab, int32_t penalty_last_n, // last n tokens to penalize (0 = disable penalty) float penalty_repeat, // must be > 0.0, 1.0 = disabled float penalty_freq, // must be finite, 0.0 = disabled float penalty_present); // must be finite, 0.0 = disabled
/// @details DRY sampler, designed by p-e-w, as described in: https://github.com/oobabooga/text-generation-webui/pull/5677, porting Koboldcpp implementation authored by pi6am: https://github.com/LostRuins/koboldcpp/pull/982 LLAMA_API struct llama_sampler * llama_sampler_init_dry( const struct llama_vocab * vocab, float dry_multiplier, float dry_base, int32_t dry_allowed_length, int32_t dry_penalty_last_n, // last n tokens to penalize (0 = disable penalty) const char ** seq_breakers, size_t num_breakers);
/// adaptive-p: select tokens near a configurable target probability over time. /// /// the adaptive-p sampler transforms the token probability distribution to favor tokens /// that fall near a user-configurable probability target. /// /// internally, the sampler maintains an exponential moving average of the *ORIGINAL* /// probabilities of selected tokens at each sampling step. it uses this EMA to compute an /// adapted target probability at each sampling step, thus maintaining the desired target /// probability over time. /// /// adaptive-p selects a token ID rather than just mutating candidates, so it must be last /// in the sampler chain (like mirostat, dist, greedy). /// /// only mild truncation before this sampler is recommended. we suggest applying min-p /// before adaptive-p as the only other active sampler in the chain. /// /// @param target select tokens near this probability (valid range 0.0 to 1.0; negative = disabled) /// @param decay EMA decay for adaptation; history ≈ 1/(1-decay) tokens (valid range 0.0 - 0.99) /// @param seed RNG seed /// /// ref: https://github.com/ggml-org/llama.cpp/pull/17927 /// LLAMA_API struct llama_sampler * llama_sampler_init_adaptive_p( float target, float decay, uint32_t seed);
LLAMA_API struct llama_sampler * llama_sampler_init_logit_bias( int32_t n_vocab, int32_t n_logit_bias, const llama_logit_bias * logit_bias);
// this sampler is meant to be used for fill-in-the-middle infilling // it's supposed to be used after top_k + top_p sampling // // 1. if the sum of the EOG probs times the number of candidates is higher than the sum of the other probs -> pick EOG // 2. combine probs of tokens that have the same prefix // // example: // // - before: // "hel": 0.5 // "hell": 0.2 // "hello": 0.1 // "dummy": 0.1 // // - after: // "hel": 0.8 // "dummy": 0.1 // // 3. discard non-EOG tokens with low prob // 4. if no tokens are left -> pick EOT // LLAMA_API struct llama_sampler * llama_sampler_init_infill(const struct llama_vocab * vocab);
// Returns the seed used by the sampler if applicable, LLAMA_DEFAULT_SEED otherwise LLAMA_API uint32_t llama_sampler_get_seed(const struct llama_sampler * smpl);
/// @details Sample and accept a token from the idx-th output of the last evaluation // For multiple outputs from one sampler, call this function in output order without gaps. // // Shorthand for: // const auto * logits = llama_get_logits_ith(ctx, idx); // llama_token_data_array cur_p = { ... init from logits ... }; // llama_sampler_apply(smpl, &cur_p); // auto token = cur_p.data[cur_p.selected].id; // llama_sampler_accept(smpl, token); // return token; // Returns the sampled token LLAMA_API llama_token llama_sampler_sample(struct llama_sampler * smpl, struct llama_context * ctx, int32_t idx);
// TODO: extend in the future //LLAMA_API void llama_decode_with_sampler(struct llama_context * ctx, struct llama_sampler * smpl, struct llama_batch batch, ...);
// // Model split //
/// @details Build a split GGUF final path for this chunk. /// llama_split_path(split_path, sizeof(split_path), "/models/ggml-model-q4_0", 2, 4) => split_path = "/models/ggml-model-q4_0-00002-of-00004.gguf" // Returns the split_path length. LLAMA_API int32_t llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int32_t split_no, int32_t split_count);
/// @details Extract the path prefix from the split_path if and only if the split_no and split_count match. /// llama_split_prefix(split_prefix, 64, "/models/ggml-model-q4_0-00002-of-00004.gguf", 2, 4) => split_prefix = "/models/ggml-model-q4_0" // Returns the split_prefix length. LLAMA_API int32_t llama_split_prefix(char * split_prefix, size_t maxlen, const char * split_path, int32_t split_no, int32_t split_count);
// Print system information LLAMA_API const char * llama_print_system_info(void);
// Set callback for all future logging events. // If this is not called, or NULL is supplied, everything is output on stderr. // The logger state is global so these functions are NOT thread safe. LLAMA_API void llama_log_get(ggml_log_callback * log_callback, void ** user_data); LLAMA_API void llama_log_set(ggml_log_callback log_callback, void * user_data);
// // Performance utils // // NOTE: Used by llama.cpp examples/tools, avoid using in third-party apps. Instead, do your own performance measurements. //
struct llama_perf_context_data { // ms == milliseconds double t_start_ms; // absolute start time double t_load_ms; // time needed for loading the model double t_p_eval_ms; // time needed for processing the prompt double t_eval_ms; // time needed for generating tokens
int32_t n_p_eval; // number of prompt tokens int32_t n_eval; // number of generated tokens int32_t n_reused; // number of times a ggml compute graph had been reused };
struct llama_perf_sampler_data { double t_sample_ms; // time needed for sampling in ms
int32_t n_sample; // number of sampled tokens };
LLAMA_API struct llama_perf_context_data llama_perf_context (const struct llama_context * ctx); LLAMA_API void llama_perf_context_print(const struct llama_context * ctx); LLAMA_API void llama_perf_context_reset( struct llama_context * ctx);
// NOTE: the following work only with samplers constructed via llama_sampler_chain_init LLAMA_API struct llama_perf_sampler_data llama_perf_sampler (const struct llama_sampler * chain); LLAMA_API void llama_perf_sampler_print(const struct llama_sampler * chain); LLAMA_API void llama_perf_sampler_reset( struct llama_sampler * chain);
// // training //
// function that returns whether or not a given tensor contains trainable parameters typedef bool (*llama_opt_param_filter)(const struct ggml_tensor * tensor, void * userdata);
// always returns true LLAMA_API bool llama_opt_param_filter_all(const struct ggml_tensor * tensor, void * userdata);
struct llama_opt_params { uint32_t n_ctx_train; // assumed context size post training, use context size specified in llama_context if 0
llama_opt_param_filter param_filter; // callback for determining which tensors contain trainable parameters void * param_filter_ud; // userdata for determining which tensors contain trainable parameters
ggml_opt_get_optimizer_params get_opt_pars; // callback for calculating optimizer parameters void * get_opt_pars_ud; // userdata for calculating optimizer parameters
enum ggml_opt_optimizer_type optimizer_type; };
LLAMA_API void llama_opt_init(struct llama_context * lctx, struct llama_model * model, struct llama_opt_params lopt_params);
LLAMA_API void llama_opt_epoch( struct llama_context * lctx, ggml_opt_dataset_t dataset, ggml_opt_result_t result_train, ggml_opt_result_t result_eval, int64_t idata_split, ggml_opt_epoch_callback callback_train, ggml_opt_epoch_callback callback_eval);
#ifdef __cplusplus}#endif
#endif // LLAMA_H1234567891011121314151617#pragma once
#include "mtmd.h"
#include <vector>
// INTERNAL HEADER FOR DEBUGGING PURPOSES ONLY// NOT INTENDED FOR PUBLIC USE// Do not raise issues related to this debugging API
// encode take the pre-processed f32 values, print the intermidiate values via cb_eval callbackMTMD_API void mtmd_debug_encode_image(mtmd_context * ctx, const std::vector<std::vector<float>> & image);MTMD_API void mtmd_debug_encode_audio(mtmd_context * ctx, const std::vector<float> & input); // will be broadcasted to fit n_mel
// preprocess take the raw input valuesMTMD_API void mtmd_debug_preprocess_image(mtmd_context * ctx, const std::vector<uint8_t> & rgb_values, int nx, int ny);MTMD_API void mtmd_debug_preprocess_audio(mtmd_context * ctx, const std::vector<float> & pcm_samples);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308#ifndef MTMD_HELPER_H#define MTMD_HELPER_H
#include "ggml.h"#include "llama.h"#include "mtmd.h"
#include <stddef.h>#include <stdint.h>#include <stdbool.h>
#ifdef __cplusplusextern "C" {#endif
//// libmtmd helper functions//// Please note that these helpers are not guaranteed to be stable.// BREAKING CHANGES are expected.//
struct mtmd_helper_video;typedef struct mtmd_helper_video mtmd_helper_video;
struct mtmd_helper_video_init_params { float fps_target; // desired output fps; <= 0 means use the video's native fps, defaulted to 4.0f const char * ffmpeg_bin_dir; // directory containing ffmpeg/ffprobe binaries; NULL means search PATH int64_t timestamp_interval_ms; // interval for adding timestamp as text chunk (example: "[10m50.5s]"); <= 0 means no timestamp, defaulted to 5000ms // TODO @ngxson : allow "placeholder" bitmap output for counting tokens};
MTMD_API struct mtmd_helper_video_init_params mtmd_helper_video_init_params_default(void);
// opt for mtmd_helper_bitmap_init_from_*()struct mtmd_helper_init_opt { struct mtmd_helper_video_init_params video_params;};typedef struct mtmd_helper_init_opt mtmd_helper_init_opt;
MTMD_API struct mtmd_helper_init_opt mtmd_helper_init_opt_default(void);
// Set callback for all future logging events.// If this is not called, or NULL is supplied, everything is output on stderr.// Note: this also call mtmd_log_set() internallyMTMD_API void mtmd_helper_log_set(ggml_log_callback log_callback, void * user_data);
// Returns true if this build includes video support (MTMD_VIDEO was ON at compile time).MTMD_API bool mtmd_helper_support_video(const mtmd_context * ctx);
struct mtmd_helper_bitmap_wrapper { mtmd_bitmap * bitmap; mtmd_helper_video * video_ctx;};
// helper function to construct a mtmd_bitmap from a file// it calls mtmd_helper_bitmap_init_from_buf() internally// returns nullptr on failure// this function is thread-safeMTMD_API struct mtmd_helper_bitmap_wrapper mtmd_helper_bitmap_init_from_file( const mtmd_context * ctx, const char * fname, bool placeholder, struct mtmd_helper_init_opt opt);
// helper function to construct a mtmd_bitmap from a buffer containing a file// supported formats:// image: formats supported by stb_image: jpg, png, bmp, gif, etc.// webp is decoded via ffmpeg, requires MTMD_VIDEO build with ffmpeg in PATH// audio: formats supported by miniaudio: wav, mp3, flac// note:// - for now, video input is only supported via C++ helper functions// - audio files will be auto-detected based on magic bytes// - output bitmap will have SHA-256 hash (hex string) as the ID// returns nullptr on failure// this function is thread-safeMTMD_API struct mtmd_helper_bitmap_wrapper mtmd_helper_bitmap_init_from_buf( const mtmd_context * ctx, const unsigned char * buf, size_t len, bool placeholder, struct mtmd_helper_init_opt opt);
// helper to count the total number of tokens from a list of chunks, useful to keep track of KV cacheMTMD_API size_t mtmd_helper_get_n_tokens(const mtmd_input_chunks * chunks);
// helper to count the total position of tokens from a list of chunks, useful to keep track of n_past// normally, n_pos is equal to n_tokens, but for M-RoPE it is differentMTMD_API llama_pos mtmd_helper_get_n_pos(const mtmd_input_chunks * chunks);
// helper to get the list of relative positions corresponding to the embedding tokens, to be used by M-RoPE// out_pos must have length == mtmd_helper_get_n_tokens(image)MTMD_API void mtmd_helper_image_get_decoder_pos(const mtmd_image_tokens * image, llama_pos pos_0, struct mtmd_decoder_pos * out_pos);
// helper function that automatically:// 1. decode text chunks// 2. run mtmd_encode_chunk() on image chunks, then mtmd_get_output_embd() and then decode the embeddings// if any of the mtmd_encode_chunk() or decode calls return non-zero, stop and forward the error// otherwise, returns 0 on success// this function is NOT thread-safeMTMD_API int32_t mtmd_helper_eval_chunks(mtmd_context * ctx, struct llama_context * lctx, const mtmd_input_chunks * chunks, llama_pos n_past, llama_seq_id seq_id, int32_t n_batch, bool logits_last, llama_pos * new_n_past);
// works like mtmd_helper_eval_chunks(), but only for a single chunk// this function is NOT thread-safeMTMD_API int32_t mtmd_helper_eval_chunk_single(mtmd_context * ctx, struct llama_context * lctx, const mtmd_input_chunk * chunk, llama_pos n_past, llama_seq_id seq_id, int32_t n_batch, bool logits_last, llama_pos * new_n_past);
// one decoded sub-batch of embeddings, passed to mtmd_helper_post_decode_callbackstruct mtmd_helper_embd_batch { int32_t n_tokens; const float * embd; // [n_tokens, n_embd] int32_t n_embd; const llama_pos * pos; // [n_pos, n_tokens], section-major int32_t n_pos; // 4 for M-RoPE models, 1 otherwise llama_seq_id seq_id;};
typedef int32_t (*mtmd_helper_post_decode_callback)(const struct mtmd_helper_embd_batch * batch, void * user_data);
// helper function to decode an image whose embeddings have already been calculated// this helper will handle batching and pre/post decoding setup (for ex. gemma 3 requires non-causal attention)// ret 0 on success, -1 on chunk not being a valid image chunk, 1 on decode failureMTMD_API int32_t mtmd_helper_decode_image_chunk(mtmd_context * ctx, struct llama_context * lctx, const mtmd_input_chunk * chunk, float * encoded_embd, llama_pos n_past, llama_seq_id seq_id, int32_t n_batch, llama_pos * new_n_past, mtmd_helper_post_decode_callback callback, void * user_data);
//// video input helpers (requires ffmpeg/ffprobe installed on the system)// the notion of video only exists at the helper level, it is not visible to the core mtmd library//// NOTE: this implementation is model-agnostic, it can be used with any vision-capable model// however, it may not be accurate for some specific models// (this is expected for now, to keep the implementation simple)//
struct mtmd_helper_video_info { uint32_t width; uint32_t height; float fps; // effective fps (fps_target if set, else original video fps) int32_t n_frames; // estimated total frames at effective fps (-1 if unknown)};
// note: mtmd_helper_video_init_params is defined at the top, as it is part of mtmd_helper_init_opt
// returns NULL on failure (ffprobe not found, file unreadable, etc.)MTMD_API mtmd_helper_video * mtmd_helper_video_init( const struct mtmd_context * mctx, const char * path, struct mtmd_helper_video_init_params params);
// Same as mtmd_helper_video_init(), but reads from an in-memory buffer.// The buffer is copied internally; the caller does not need to keep it alive.// Note: pipe input is not seekable, so seeking will use output-side seeking// (ffmpeg decodes and discards frames up to the target position).MTMD_API mtmd_helper_video * mtmd_helper_video_init_from_buf( const struct mtmd_context * mctx, const unsigned char * buf, size_t len, struct mtmd_helper_video_init_params params);MTMD_API void mtmd_helper_video_free(mtmd_helper_video * ctx);MTMD_API struct mtmd_helper_video_info mtmd_helper_video_get_info(const mtmd_helper_video * ctx);
// Read the next item from the video stream; exactly one of out_bitmap or out_text is set per call.// *out_bitmap - heap-allocated; caller must free with mtmd_bitmap_free()// *out_text - heap-allocated (always via strdup/malloc); caller must free with free()// returns 0 on success, -1 on EOF, -2 on errorMTMD_API int32_t mtmd_helper_video_read_next(mtmd_helper_video * ctx, mtmd_bitmap ** out_bitmap, char ** out_text);
// return true if model can be used for chatMTMD_API bool mtmd_helper_model_can_chat(const struct llama_context * lctx, const struct mtmd_context * mctx);
//// Audio generation helpers// (early-stage experimental, subjected to breaking changes)//
// audio generation helper context// contains accumulator for generated audio features and PCM audiostruct mtmd_helper_gen_audio;typedef struct mtmd_helper_gen_audio mtmd_helper_gen_audio;
enum mtmd_helper_gen_audio_outtype { MTMD_HELPER_GEN_AUDIO_OUTTYPE_PCM, // raw PCM MTMD_HELPER_GEN_AUDIO_OUTTYPE_WAV, // WAV PCM 16-bit LE, mono};struct mtmd_helper_gen_audio_inp { llama_seq_id seq_id;
const char * prompt; size_t prompt_len;
mtmd_bitmap * speaker_ref; // optional, can be NULL const char * lang; // optional, can be NULL
int32_t top_k; float top_p; uint32_t seed; // UINT32_MAX for random (default: random)
enum mtmd_helper_gen_audio_outtype out_type;};
MTMD_API mtmd_helper_gen_audio * mtmd_helper_gen_audio_init( struct llama_context * lctx, struct mtmd_context * mctx);
MTMD_API void mtmd_helper_gen_audio_free(mtmd_helper_gen_audio * ctx);
MTMD_API void mtmd_helper_gen_audio_reset(mtmd_helper_gen_audio * ctx);
MTMD_API int32_t mtmd_helper_gen_audio_set_input( mtmd_helper_gen_audio * ctx, const struct mtmd_helper_gen_audio_inp * inp);
// processes at most n_batch prompt tokens per call// returns: >0 = number of prompt tokens remaining, 0 = done, <0 = errorMTMD_API int32_t mtmd_helper_gen_audio_step_prompt( mtmd_helper_gen_audio * ctx, int32_t n_batch);
// generates one frame; must only be called after step_prompt() has returned 0// sampled can be LLAMA_TOKEN_NULL for pipelines with no discrete backbone token// out_stop (optional) is set on end-of-speech, the caller must then stop the loop// h_state_out is valid until next step_gen() or reset() call, null if no frame is generatedMTMD_API int32_t mtmd_helper_gen_audio_step_gen( mtmd_helper_gen_audio * ctx, llama_token sampled, const float * h_state_in, const float ** h_state_out, bool * out_stop);
// out_data valid until next get_output() or reset() call// out_n_samples (optional, can be NULL) receives the number of generated PCM samplesMTMD_API int32_t mtmd_helper_gen_audio_get_output( mtmd_helper_gen_audio * ctx, int32_t * out_sample_rate, const char ** out_data, size_t * out_data_len, int64_t * out_n_samples);
#ifdef __cplusplus} // extern "C"#endif
#ifdef __cplusplus#include <set>#include <memory>
namespace mtmd_helper {
//// C++ wrappers//
// video-related C++ wrappersstruct mtmd_helper_video_deleter { void operator()(mtmd_helper_video * val) { mtmd_helper_video_free(val); }};using video_ptr = std::unique_ptr<mtmd_helper_video, mtmd_helper_video_deleter>;
// audio generation-related C++ wrappersstruct mtmd_helper_gen_audio_deleter { void operator()(mtmd_helper_gen_audio * val) { mtmd_helper_gen_audio_free(val); }};using gen_audio_ptr = std::unique_ptr<mtmd_helper_gen_audio, mtmd_helper_gen_audio_deleter>;struct gen_audio { gen_audio_ptr ctx; gen_audio(struct llama_context * lctx, struct mtmd_context * mctx) : ctx(mtmd_helper_gen_audio_init(lctx, mctx)) {} void reset() { mtmd_helper_gen_audio_reset(ctx.get()); } int32_t set_input(const struct mtmd_helper_gen_audio_inp * inp) { return mtmd_helper_gen_audio_set_input(ctx.get(), inp); } int32_t step_prompt(int32_t n_batch) { return mtmd_helper_gen_audio_step_prompt(ctx.get(), n_batch); } int32_t step_gen(llama_token sampled, const float * h_state, const float ** h_state_out, bool * out_stop = nullptr) { return mtmd_helper_gen_audio_step_gen(ctx.get(), sampled, h_state, h_state_out, out_stop); } int32_t get_output(int32_t * out_sample_rate, const char ** out_data, size_t * out_data_len, int64_t * out_n_samples = nullptr) { return mtmd_helper_gen_audio_get_output(ctx.get(), out_sample_rate, out_data, out_data_len, out_n_samples); }};
} // namespace mtmd_helper#endif
#endif123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538#ifndef MTMD_H#define MTMD_H
#include "ggml.h"#include "llama.h"
#include <stddef.h>#include <stdint.h>#include <stdbool.h>
#ifdef __cplusplus#include <map>#include <string>#include <vector>#include <cinttypes>#include <memory>#endif
/** * libmtmd: A library for multimodal support in llama.cpp. * * WARNING: This API is experimental and subject to many BREAKING CHANGES. * Issues related to API usage may receive lower priority support. * * For the usage, see an example in mtmd-cli.cpp * * For contributors: * - Make sure the C API is aligned with the libllama C API (as in llama.h) * - Do not include model name (e.g., qwen, gemma) in the API, use generic terms instead * - Keep the API minimal, do not expose internal details unless necessary * * IMPORTANT: The mtmd module does NOT accept pull requests that are fully or predominantly AI-generated. * We encourage human contributors to ensure the quality and reliability of the codebase. */
#ifdef LLAMA_SHARED# if defined(_WIN32) && !defined(__MINGW32__)# ifdef LLAMA_BUILD# define MTMD_API __declspec(dllexport)# else# define MTMD_API __declspec(dllimport)# endif# else# define MTMD_API __attribute__ ((visibility ("default")))# endif#else# define MTMD_API#endif
#ifdef __cplusplusextern "C" {#endif
enum mtmd_input_chunk_type { MTMD_INPUT_CHUNK_TYPE_TEXT, MTMD_INPUT_CHUNK_TYPE_IMAGE, MTMD_INPUT_CHUNK_TYPE_AUDIO, MTMD_INPUT_CHUNK_TYPE_COUNT, // for validation};
// opaque typesstruct mtmd_context;struct mtmd_bitmap;struct mtmd_image_tokens;struct mtmd_input_chunk;struct mtmd_input_chunks;struct mtmd_batch;
struct mtmd_input_text { const char * text; size_t text_len; bool add_special; bool parse_special;};
struct mtmd_input_part { // only text or bitmap can be set, not both const struct mtmd_input_text * text; const struct mtmd_bitmap * bitmap;};
//// C API//
typedef struct mtmd_context mtmd_context;typedef struct mtmd_bitmap mtmd_bitmap;typedef struct mtmd_image_tokens mtmd_image_tokens;typedef struct mtmd_input_chunk mtmd_input_chunk;typedef struct mtmd_input_chunks mtmd_input_chunks;typedef struct mtmd_input_text mtmd_input_text;typedef struct mtmd_input_part mtmd_input_part;typedef struct mtmd_batch mtmd_batch;
typedef bool (*mtmd_progress_callback)(float progress, void * user_data);
struct mtmd_context_params { bool use_gpu; ggml_backend_dev_t device; bool print_timings; int n_threads; const char * image_marker; // deprecated, use media_marker instead const char * media_marker; enum llama_flash_attn_type flash_attn_type; bool warmup; // whether to run a warmup encode pass after initialization
// limit number of image tokens, only for vision models with dynamic resolution int image_min_tokens; // minimum number of tokens for image input (default: read from metadata) int image_max_tokens; // maximum number of tokens for image input (default: read from metadata)
// callback function passed over to mtmd proper ggml_backend_sched_eval_callback cb_eval; void * cb_eval_user_data;
// batching params int32_t batch_max_tokens; // maximum number of output tokens in a batch // (note: this is not a hard-limit, the first image will always be added even if it exceeds this limit) // (default: 1024)
// Called with a progress value between 0.0 and 1.0. Pass NULL to disable. // If the provided progress_callback returns true, model loading continues. // If it returns false, model loading is immediately aborted. mtmd_progress_callback progress_callback; void * progress_callback_user_data;};
MTMD_API const char * mtmd_default_marker(void);
MTMD_API struct mtmd_context_params mtmd_context_params_default(void);
// initialize the mtmd context// return nullptr on failureMTMD_API mtmd_context * mtmd_init_from_file(const char * mmproj_fname, const struct llama_model * text_model, const struct mtmd_context_params ctx_params);
MTMD_API void mtmd_free(mtmd_context * ctx);
// whether we need to set non-causal mask before llama_decode// if chunk is nullptr, we assume the default case where chunk is an image chunkMTMD_API bool mtmd_decode_use_non_causal(const mtmd_context * ctx, const mtmd_input_chunk * chunk);
// whether the current model use M-RoPE for llama_decodeMTMD_API bool mtmd_decode_use_mrope(const mtmd_context * ctx);
// whether the current model supports vision inputMTMD_API bool mtmd_support_vision(const mtmd_context * ctx);
// whether the current model supports audio inputMTMD_API bool mtmd_support_audio(const mtmd_context * ctx);
// get audio sample rate in Hz, for example 16000 for Whisper// return -1 if audio is not supportedMTMD_API int mtmd_get_audio_sample_rate(const mtmd_context * ctx);
// get the current marker stringMTMD_API const char * mtmd_get_marker(const mtmd_context * ctx);
// mtmd_bitmap//// if bitmap is image:// length of data must be nx * ny * 3// the data is in RGBRGBRGB... format// note: some video-capable models (i.e. qwen-vl) can merge consecutive bitmaps// into one chunk; mtmd_tokenize() handles this, but remember to set// mtmd_bitmap_set_mergeable(true) for every frame// if bitmap is audio:// length of data must be n_samples * sizeof(float)// the data is in float format (PCM F32)//// if data == nullptr:// the bitmap is considered "empty", and will be treated as a placeholder for counting tokens// you can pass the bitmap via mtmd_tokenize(), then call mtmd_*_get_n_tokens() to count the tokens// note: passing a placeholder bitmap to mtmd_encode() will return an errorMTMD_API mtmd_bitmap * mtmd_bitmap_init (uint32_t nx, uint32_t ny, const unsigned char * data);MTMD_API mtmd_bitmap * mtmd_bitmap_init_from_audio(size_t n_samples, const float * data);MTMD_API uint32_t mtmd_bitmap_get_nx (const mtmd_bitmap * bitmap);MTMD_API uint32_t mtmd_bitmap_get_ny (const mtmd_bitmap * bitmap);MTMD_API const unsigned char * mtmd_bitmap_get_data (const mtmd_bitmap * bitmap);MTMD_API size_t mtmd_bitmap_get_n_bytes(const mtmd_bitmap * bitmap);MTMD_API bool mtmd_bitmap_is_audio (const mtmd_bitmap * bitmap);MTMD_API void mtmd_bitmap_free (mtmd_bitmap * bitmap);// bitmap ID is optional, but useful for KV cache tracking// these getters/setters are dedicated functions, so you can for example calculate the hash of the image based on mtmd_bitmap_get_data()MTMD_API const char * mtmd_bitmap_get_id(const mtmd_bitmap * bitmap);MTMD_API void mtmd_bitmap_set_id(mtmd_bitmap * bitmap, const char * id);// if true, this bitmap can be merged (temporal merge) with an adjacent mergeable bitmap by certain video input modelsMTMD_API void mtmd_bitmap_set_mergeable(mtmd_bitmap * bitmap, bool mergeable);
// mtmd_bitmap lazy//// this is a special bitmap that:// - does not hold the actual data// - can be expanded into one or more chunks (either media to text chunks)// user must provide a callback to fill in the data when mtmd_tokenize() is called// this is useful for large video inputs:// - allow reading video frame by frame, without loading the entire video into memory// - allow tracking the whole video with a single ID (for example, the file hash)
// set (*out_bitmap) to non-nullptr to emit a bitmap chunk; it will be freed automatically// set (*out_text) to non-nullptr to emit a text chunk; it must be heap-allocated, null-terminated and will be freed automatically// either out_bitmap or out_text can be set, but not both// out_bitmap cannot be another lazy bitmap (no nested lazy allowed)// return value:// 0 on success// -1 on EOF (signal to mtmd_tokenize to move on)// -2 on error (signal to mtmd_tokenize to abort)typedef int(* mtmd_bitmap_lazy_callback)( size_t chunk_idx, void * user_data, mtmd_bitmap ** out_bitmap, char ** out_text);
MTMD_API mtmd_bitmap * mtmd_bitmap_init_lazy(const mtmd_context * ctx, const char * id, // usually set to file hash void * user_data, mtmd_bitmap_lazy_callback callback);
// mtmd_input_chunks//// this is simply a list of mtmd_input_chunk// the elements can only be populated via mtmd_tokenize()MTMD_API mtmd_input_chunks * mtmd_input_chunks_init(void);MTMD_API size_t mtmd_input_chunks_size(const mtmd_input_chunks * chunks);MTMD_API const mtmd_input_chunk * mtmd_input_chunks_get (const mtmd_input_chunks * chunks, size_t idx);MTMD_API void mtmd_input_chunks_free(mtmd_input_chunks * chunks);
// mtmd_input_chunk//// the instance will be constructed via mtmd_tokenize()// it will be freed along with mtmd_input_chunksMTMD_API enum mtmd_input_chunk_type mtmd_input_chunk_get_type (const mtmd_input_chunk * chunk);MTMD_API const llama_token * mtmd_input_chunk_get_tokens_text (const mtmd_input_chunk * chunk, size_t * n_tokens_output);MTMD_API const mtmd_image_tokens * mtmd_input_chunk_get_tokens_image(const mtmd_input_chunk * chunk);MTMD_API size_t mtmd_input_chunk_get_n_tokens (const mtmd_input_chunk * chunk);// returns nullptr for ID on text chunkMTMD_API const char * mtmd_input_chunk_get_id (const mtmd_input_chunk * chunk);// number of temporal positions (equals to max(t,h,w) for M-RoPE; equals to n_tokens otherwise)MTMD_API llama_pos mtmd_input_chunk_get_n_pos (const mtmd_input_chunk * chunk);
// in case you want to use custom logic to handle the chunk (i.e. KV cache management)// you can move the chunk ownership to your own code by copying it// remember to free the chunk when you are done with itMTMD_API mtmd_input_chunk * mtmd_input_chunk_copy(const mtmd_input_chunk * chunk);MTMD_API void mtmd_input_chunk_free(mtmd_input_chunk * chunk);
// similar to mtmd_input_chunk_copy, but returns a placeholder chunkMTMD_API mtmd_input_chunk * mtmd_input_chunk_get_placeholder(const mtmd_input_chunk * chunk);
// save/load an input chunk to/from a buffer (useful for KV save/load)// important: only chunk's metadata will be saved, the actual image/audio data will not be saved// the loaded chunk will always be a placeholder, cannot be used for mtmd_encode() or mtmd_batch_encode()// out_buf can be nullptr (to query expected_out_len)// returns 0 on success, non-zero on failureMTMD_API int32_t mtmd_input_chunk_save(const mtmd_input_chunk * chunk, char * out_buf, size_t out_len, size_t * expected_out_len);// returns nullptr on failureMTMD_API mtmd_input_chunk * mtmd_input_chunk_load(const char * buf, size_t len);
// mtmd_image_tokens//// the instance will be constructed via mtmd_tokenize()// it will be freed along with mtmd_input_chunkMTMD_API size_t mtmd_image_tokens_get_n_tokens(const mtmd_image_tokens * image_tokens); // TODO: deprecateMTMD_API const char * mtmd_image_tokens_get_id (const mtmd_image_tokens * image_tokens); // TODO: deprecate// number of temporal positions (equals to max(t,h,w) for M-RoPE; equals to n_tokens otherwise)MTMD_API llama_pos mtmd_image_tokens_get_n_pos (const mtmd_image_tokens * image_tokens); // TODO: deprecate
DEPRECATED(MTMD_API size_t mtmd_image_tokens_get_nx(const mtmd_image_tokens * image_tokens), "use mtmd_image_tokens_get_decoder_pos() instead");DEPRECATED(MTMD_API size_t mtmd_image_tokens_get_ny(const mtmd_image_tokens * image_tokens), "use mtmd_image_tokens_get_decoder_pos() instead");
struct mtmd_decoder_pos { uint32_t t; uint32_t x; uint32_t y; uint32_t z; // unused for now, reserved for future use};// get position for decoder attention, to be used by M-RoPE models// i is the index of the embedding token, ranging from 0 to mtmd_image_tokens_get_n_tokens() - 1// pos_0 is the absolute position of the first token// return relative position (for example, embedding 0 will have position (0, 0, 0); remember to adjust it to the current absolute position)MTMD_API struct mtmd_decoder_pos mtmd_image_tokens_get_decoder_pos(const mtmd_image_tokens * image_tokens, llama_pos pos_0, size_t i);
// tokenize an input text prompt and a list of bitmaps (image/audio)// the prompt must have the input media marker (default: "<__media__>") in it// the default marker is defined by mtmd_default_marker()// the marker will be replaced with the media chunk// for example:// "here is an image: <__media__>\ndescribe it in detail."// this will gives 3 chunks:// 1. "here is an image: <start_of_image>"// 2. (image/audio tokens)// 3. "<end_of_image>\ndescribe it in detail."// number of bitmaps must be equal to the number of markers in the prompt// this function is thread-safe (shared ctx)// return values:// 0 on success// 1 on number of bitmaps not matching the number of markers// 2 on media preprocessing errorMTMD_API int32_t mtmd_tokenize(const mtmd_context * ctx, mtmd_input_chunks * output, const mtmd_input_text * text, const mtmd_bitmap * const * bitmaps, size_t n_bitmaps);
// same as mtmd_tokenize(), but takes an array of mtmd_input_part// use cases:// - when you don't want to use media markers (they will be tokenized as normal text)// - when you want to control parse_special for each text part// note: per-part add_special will be ignored// return 1 if a part has both text and bitmap set (or neither)MTMD_API int32_t mtmd_tokenize_from_parts(const mtmd_context * ctx, mtmd_input_chunks * output, const mtmd_input_part * const * parts, size_t n_parts, bool add_special);
DEPRECATED(MTMD_API int32_t mtmd_encode(mtmd_context * ctx, const mtmd_image_tokens * image_tokens), "use mtmd_encode_chunk() instead");
// text chunk will be ignored silently, only media chunk will be encoded// returns 0 on success// returns 1 on generic errorMTMD_API int32_t mtmd_encode_chunk(mtmd_context * ctx, const mtmd_input_chunk * chunk);
// get output embeddings from the last encode pass// the reading size (in bytes) is equal to:// llama_model_n_embd_inp(model) * mtmd_input_chunk_get_n_tokens(chunk) * sizeof(float)MTMD_API float * mtmd_get_output_embd(mtmd_context * ctx);
// batch encoding API// chunks are not owned by the batch, they will not be freed by mtmd_batch_free()// batch is valid for a given context, cannot be shared across contextsMTMD_API mtmd_batch * mtmd_batch_init(mtmd_context * ctx);MTMD_API void mtmd_batch_free(mtmd_batch * batch);
// only media chunks are allowed, text chunks will be rejected// returns 0 on success// returns 1 on generic error// returns 2 if the batch is too large (chunk won't be added)// returns 3 if it cannot be batched with the existing chunks in the batchMTMD_API int32_t mtmd_batch_add_chunk(mtmd_batch * batch, const mtmd_input_chunk * chunk);
// returns 0 on success// returns 1 on generic errorMTMD_API int32_t mtmd_batch_encode(mtmd_batch * batch);MTMD_API float * mtmd_batch_get_output_embd(mtmd_batch * batch, const mtmd_input_chunk * chunk);
// Set callback for all future logging events.// If this is not called, or NULL is supplied, everything is output on stderr.MTMD_API void mtmd_log_set(ggml_log_callback log_callback, void * user_data);
// EXPERIMENTAL API to get mmproj's capabilities without initializing the full context// This is only intended to be used by llama-server, breaking changes is expectedstruct mtmd_caps { bool inp_vision; bool inp_audio;};MTMD_API struct mtmd_caps mtmd_get_cap_from_file(const char * mmproj_fname);
/////////////////////////////////////////// EXPERIMENTAL API for audio generation, subjected to breaking changes
// represent the pipeline typeenum mtmd_gen_audio_type { MTMD_GEN_AUDIO_TYPE_NONE, // not supported MTMD_GEN_AUDIO_TYPE_QWEN3TTS, MTMD_GEN_AUDIO_TYPE_POCKETTTS,};
struct mtmd_gen_audio_info { enum mtmd_gen_audio_type type; int32_t sample_rate; // in Hz, for example 24000 for qwen3tts const char * model_variant; // name of the weight variant, can be nullptr if not applicable};
MTMD_API struct mtmd_gen_audio_info mtmd_gen_audio_get_info(const mtmd_context * ctx);
enum mtmd_gen_process_type { MTMD_GEN_PROCESS_TYPE_GEN_CODE, // h_state to semantic (codes, mel-spectrogram, etc.) MTMD_GEN_PROCESS_TYPE_GEN_WAV, // convert semantic to PCM audio // for qwen3tts, this is code2wav // for pocket-tts, this is mimi decoder};
struct mtmd_gen_inp { enum mtmd_gen_process_type type;
// for MTMD_GEN_PROCESS_TYPE_GEN_CODE int32_t code0; // the sampled codebook 0 entry from backbone float * embd; // the hidden state from backbone, must have n_text_embd elements int32_t top_k; float top_p; uint32_t seed; // UINT32_MAX for random float temp; // sampling temperature, or noise scale for flow-matching decoders
// for MTMD_GEN_PROCESS_TYPE_GEN_WAV // pass either codes (discrete) or feats (continuous), depending on the pipeline int32_t * codes; size_t n_codes; const float * feats; size_t n_feats; const char * state_data; size_t state_size;};
struct mtmd_gen_out { // note: output memory is allocated by the context, valid until next process() call
// for MTMD_GEN_PROCESS_TYPE_GEN_CODE const int32_t * codes; size_t n_codes; const float * feats; // continuous counterpart of codes size_t n_feats; const float * embd; // the generated hidden state, to be fed back to backbone // it must have n_text_embd elements bool is_eos; // only set by pipelines having the EOS head inside mmproj
// for MTMD_GEN_PROCESS_TYPE_GEN_WAV const float * audio; size_t n_samples; const char * state_data; size_t state_size;};
// defaults tuned for the loaded pipeline, callers override only what they care aboutMTMD_API struct mtmd_gen_inp mtmd_gen_inp_default(const mtmd_context * ctx);
// note: this API is stateless, caller must handle state management and audio frame accumulationMTMD_API int32_t mtmd_gen_audio_process(mtmd_context * ctx, const struct mtmd_gen_inp * inp, struct mtmd_gen_out * out);
/////////////////////////////////////////
// test function, to be used in test-mtmd-c-api.cMTMD_API mtmd_input_chunks * mtmd_test_create_input_chunks(void);
#ifdef __cplusplus} // extern "C"#endif
// Get memory usage of the current model in bytes, per backend device// Note: this is an unstable API, used internally by fit_params; it WILL be removed or changed without deprecation#ifdef __cplusplusMTMD_API std::map<ggml_backend_dev_t, size_t> mtmd_get_memory_usage( const char * mmproj_fname, struct mtmd_context_params ctx_params);#endif
//// C++ wrappers//
#ifdef __cplusplus
namespace mtmd {
struct mtmd_context_deleter { void operator()(mtmd_context * val) { mtmd_free(val); }};using context_ptr = std::unique_ptr<mtmd_context, mtmd_context_deleter>;
struct mtmd_bitmap_deleter { void operator()(mtmd_bitmap * val) { mtmd_bitmap_free(val); }};using bitmap_ptr = std::unique_ptr<mtmd_bitmap, mtmd_bitmap_deleter>;
struct mtmd_input_chunks_deleter { void operator()(mtmd_input_chunks * val) { mtmd_input_chunks_free(val); }};using input_chunks_ptr = std::unique_ptr<mtmd_input_chunks, mtmd_input_chunks_deleter>;
struct mtmd_input_chunk_deleter { void operator()(mtmd_input_chunk * val) { mtmd_input_chunk_free(val); }};using input_chunk_ptr = std::unique_ptr<mtmd_input_chunk, mtmd_input_chunk_deleter>;
struct mtmd_batch_deleter { void operator()(mtmd_batch * val) { mtmd_batch_free(val); }};using batch_ptr = std::unique_ptr<mtmd_batch, mtmd_batch_deleter>;
struct bitmap { bitmap_ptr ptr; bitmap() : ptr(nullptr) {} bitmap(mtmd_bitmap * bitmap) : ptr(bitmap) {} bitmap(bitmap && other) noexcept : ptr(std::move(other.ptr)) {} bitmap(uint32_t nx, uint32_t ny, const unsigned char * data) { ptr.reset(mtmd_bitmap_init(nx, ny, data)); } ~bitmap() = default; uint32_t nx() const { return mtmd_bitmap_get_nx(ptr.get()); } uint32_t ny() const { return mtmd_bitmap_get_ny(ptr.get()); } const unsigned char * data() const { return mtmd_bitmap_get_data(ptr.get()); } size_t n_bytes() const { return mtmd_bitmap_get_n_bytes(ptr.get()); } std::string id() const { return mtmd_bitmap_get_id(ptr.get()); } void set_id(const char * id) const { mtmd_bitmap_set_id(ptr.get(), id); }};
struct bitmaps { std::vector<bitmap> entries; ~bitmaps() = default; // return list of pointers to mtmd_bitmap // example: // auto bitmaps_c_ptr = bitmaps.c_ptr(); // int32_t res = mtmd_tokenize(... bitmaps_c_ptr.data(), bitmaps_c_ptr.size()); std::vector<const mtmd_bitmap *> c_ptr() { std::vector<const mtmd_bitmap *> res(entries.size()); for (size_t i = 0; i < entries.size(); i++) { res[i] = entries[i].ptr.get(); } return res; }};
struct input_chunks { input_chunks_ptr ptr; input_chunks() = default; input_chunks(mtmd_input_chunks * chunks) : ptr(chunks) {} ~input_chunks() = default; size_t size() const { return mtmd_input_chunks_size(ptr.get()); } const mtmd_input_chunk * operator[](size_t idx) const { return mtmd_input_chunks_get(ptr.get(), idx); }};
} // namespace mtmd
#endif
#endif.gitattributes+7
.gitignore+2-1
.venv/.gitignoreAdded+2
.venv/bin/Activate.ps1Added+248
.venv/bin/activateAdded+76
.venv/bin/activate.cshAdded+27
.venv/bin/activate.fishAdded+69
.venv/bin/pipAdded+8
.venv/bin/pip3Added+8
.venv/bin/pip3.13Added+8
.venv/bin/pythonAdded+3
.venv/bin/python3Added+3
.venv/bin/python3.13Added+3
.venv/lib/python3.13/site-packages/diskcache-5.6.3.dist-info/INSTALLERAdded+1
.venv/lib/python3.13/site-packages/diskcache-5.6.3.dist-info/LICENSEAdded+12
.venv/lib/python3.13/site-packages/diskcache-5.6.3.dist-info/METADATAAdded+430
.venv/lib/python3.13/site-packages/diskcache-5.6.3.dist-info/RECORDAdded+21
.venv/lib/python3.13/site-packages/diskcache-5.6.3.dist-info/REQUESTEDAdded
.venv/lib/python3.13/site-packages/diskcache-5.6.3.dist-info/WHEELAdded+5
.venv/lib/python3.13/site-packages/diskcache-5.6.3.dist-info/top_level.txtAdded+1
.venv/lib/python3.13/site-packages/diskcache/__init__.pyAdded+68
.venv/lib/python3.13/site-packages/diskcache/cli.pyAdded+1
.venv/lib/python3.13/site-packages/diskcache/core.pyAdded+2452
.venv/lib/python3.13/site-packages/diskcache/djangocache.pyAdded+456
.venv/lib/python3.13/site-packages/diskcache/fanout.pyAdded+687
.venv/lib/python3.13/site-packages/diskcache/persistent.pyAdded+1245
.venv/lib/python3.13/site-packages/diskcache/recipes.pyAdded+488
.venv/lib/python3.13/site-packages/include/ggml-alloc.hAdded+86
.venv/lib/python3.13/site-packages/include/ggml-backend.hAdded+437
.venv/lib/python3.13/site-packages/include/ggml-blas.hAdded+25
.venv/lib/python3.13/site-packages/include/ggml-cann.hAdded+123
.venv/lib/python3.13/site-packages/include/ggml-cpp.hAdded+39
.venv/lib/python3.13/site-packages/include/ggml-cpu.hAdded+152
.venv/lib/python3.13/site-packages/include/ggml-cuda.hAdded+47
.venv/lib/python3.13/site-packages/include/ggml-metal.hAdded+61
.venv/lib/python3.13/site-packages/include/ggml-openvino.hAdded+37
.venv/lib/python3.13/site-packages/include/ggml-opt.hAdded+256
.venv/lib/python3.13/site-packages/include/ggml-rpc.hAdded+35
.venv/lib/python3.13/site-packages/include/ggml-sycl.hAdded+59
.venv/lib/python3.13/site-packages/include/ggml-virtgpu.hAdded+14
.venv/lib/python3.13/site-packages/include/ggml-vulkan.hAdded+29
.venv/lib/python3.13/site-packages/include/ggml-webgpu.hAdded+19
.venv/lib/python3.13/site-packages/include/ggml-zendnn.hAdded+22
.venv/lib/python3.13/site-packages/include/ggml.hAdded
.venv/lib/python3.13/site-packages/include/gguf.hAdded+211
.venv/lib/python3.13/site-packages/include/llama-cpp.hAdded+35
.venv/lib/python3.13/site-packages/include/llama.hAdded+1739
.venv/lib/python3.13/site-packages/include/mtmd-debug.hAdded+17
.venv/lib/python3.13/site-packages/include/mtmd-helper.hAdded+308
.venv/lib/python3.13/site-packages/include/mtmd.hAdded+538