diff --git a/.gitattributes b/.gitattributes index 4fadc88897f15f7ce3c7295c41afea6913545e23..bfeef204d47e4fef221284a3fd88854a29c9f300 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4506,3 +4506,6 @@ tool_server/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/cpp_exten tool_server/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/cuda_to_hip_mappings.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text tool_server/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text tool_server/.venv/lib/python3.12/site-packages/torchgen/__pycache__/model.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_validators.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/xformers/flash_attn_3/_C.so filter=lfs diff=lfs merge=lfs -text +tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bwd_prefill_fused.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema-4.25.1.dist-info/licenses/COPYING b/tool_server/.venv/lib/python3.12/site-packages/jsonschema-4.25.1.dist-info/licenses/COPYING new file mode 100644 index 0000000000000000000000000000000000000000..af9cfbdb134f42e5205ecbad597421d778826481 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema-4.25.1.dist-info/licenses/COPYING @@ -0,0 +1,19 @@ +Copyright (c) 2013 Julian Berman + +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. diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6f760153d4d33df493671890c51db8ab430b404 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/__main__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/__main__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c464039188ff944d8760d6beb18d8f8e0577ce79 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/__main__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_format.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_format.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fefa6b0ad1c8803530ef4403cc74e54fd98b76c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_format.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_keywords.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_keywords.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b33265abd3c8e00f4665fdd6c43911974aa00607 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_keywords.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_legacy_keywords.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_legacy_keywords.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2dab2ecd8964a94a1b318155e5b4a10434ef46aa Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_legacy_keywords.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9684c6ea1d21b527fb3296bb5f155339eb4f65b7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_types.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_typing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_typing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e739425d1bd13a9c3c3994cf3bb1985d795b0d88 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_typing.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cce5cb1a1abf40e824320ca44070ad2649cc9fa4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/cli.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/cli.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c910ec54b3f57b89d15092d34e96752cc96060d7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/cli.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/exceptions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ef4d417492b0683807979c54bae7e03a9532750 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/exceptions.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/protocols.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/protocols.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f368bb4bbb4b0fd3c7dcd839894600ba7455a49a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/protocols.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/validators.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/validators.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..079a1810a4ed937e1bd2b13de407825f66bf5098 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/__pycache__/validators.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e3dcc689930da95198c251ce806637d6413c8b1e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__init__.py @@ -0,0 +1,5 @@ +""" +Benchmarks for validation. + +This package is *not* public API. +""" diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89b51b2802786973d4fff0da938ec74386f7b0cd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/const_vs_enum.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/const_vs_enum.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4fba126b45ad1b7c9570a8583d41195c567f7439 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/const_vs_enum.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/contains.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/contains.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d53066bd001e69ebdbd49995ad1fac5e3c929ea9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/contains.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/issue232.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/issue232.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05f43376e96f80efcb29f2672be973b71209c1eb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/issue232.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/json_schema_test_suite.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/json_schema_test_suite.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da249bf71952ddb9f386e80c6807c6e43a8d1ea0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/json_schema_test_suite.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/nested_schemas.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/nested_schemas.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d52c0caeeb6f743061866bc88836812cbf026b1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/nested_schemas.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/subcomponents.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/subcomponents.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa4d02748fe2b16c6dc74aa024b566999105d136 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/subcomponents.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/unused_registry.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/unused_registry.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5287e1a854807a396e3c8dae4dd496b962bf1d15 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/unused_registry.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/useless_applicator_schemas.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/useless_applicator_schemas.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c523b8f89e39db4f61a412b4d49ab675215731d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/useless_applicator_schemas.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/useless_keywords.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/useless_keywords.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..305950343fca1ed8d8209687091b0fb505da3bdb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/useless_keywords.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/validator_creation.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/validator_creation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5811d1c397e7fb079f656c6d33785fa7e874cfa Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/__pycache__/validator_creation.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/const_vs_enum.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/const_vs_enum.py new file mode 100644 index 0000000000000000000000000000000000000000..c6fecd10f6d8b845c675be9c19e9b504b08d30b9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/const_vs_enum.py @@ -0,0 +1,30 @@ +""" +A benchmark for comparing equivalent validation of `const` and `enum`. +""" + +from pyperf import Runner + +from jsonschema import Draft202012Validator + +value = [37] * 100 +const_schema = {"const": list(value)} +enum_schema = {"enum": [list(value)]} + +valid = list(value) +invalid = [*valid, 73] + +const = Draft202012Validator(const_schema) +enum = Draft202012Validator(enum_schema) + +assert const.is_valid(valid) +assert enum.is_valid(valid) +assert not const.is_valid(invalid) +assert not enum.is_valid(invalid) + + +if __name__ == "__main__": + runner = Runner() + runner.bench_func("const valid", lambda: const.is_valid(valid)) + runner.bench_func("const invalid", lambda: const.is_valid(invalid)) + runner.bench_func("enum valid", lambda: enum.is_valid(valid)) + runner.bench_func("enum invalid", lambda: enum.is_valid(invalid)) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/contains.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/contains.py new file mode 100644 index 0000000000000000000000000000000000000000..739cd044cceb807b4029dca9447e954214a24809 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/contains.py @@ -0,0 +1,28 @@ +""" +A benchmark for validation of the `contains` keyword. +""" + +from pyperf import Runner + +from jsonschema import Draft202012Validator + +schema = { + "type": "array", + "contains": {"const": 37}, +} +validator = Draft202012Validator(schema) + +size = 1000 +beginning = [37] + [0] * (size - 1) +middle = [0] * (size // 2) + [37] + [0] * (size // 2) +end = [0] * (size - 1) + [37] +invalid = [0] * size + + +if __name__ == "__main__": + runner = Runner() + runner.bench_func("baseline", lambda: validator.is_valid([])) + runner.bench_func("beginning", lambda: validator.is_valid(beginning)) + runner.bench_func("middle", lambda: validator.is_valid(middle)) + runner.bench_func("end", lambda: validator.is_valid(end)) + runner.bench_func("invalid", lambda: validator.is_valid(invalid)) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/issue232.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/issue232.py new file mode 100644 index 0000000000000000000000000000000000000000..efd07154822e4b0609900482eb26636fc3c100eb --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/issue232.py @@ -0,0 +1,25 @@ +""" +A performance benchmark using the example from issue #232. + +See https://github.com/python-jsonschema/jsonschema/pull/232. +""" +from pathlib import Path + +from pyperf import Runner +from referencing import Registry + +from jsonschema.tests._suite import Version +import jsonschema + +issue232 = Version( + path=Path(__file__).parent / "issue232", + remotes=Registry(), + name="issue232", +) + + +if __name__ == "__main__": + issue232.benchmark( + runner=Runner(), + Validator=jsonschema.Draft4Validator, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/issue232/issue.json b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/issue232/issue.json new file mode 100644 index 0000000000000000000000000000000000000000..804c340845fa0694e8db1083cfe7c290c04f36b1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/issue232/issue.json @@ -0,0 +1,2653 @@ +[ + { + "description": "Petstore", + "schema": { + "title": "A JSON Schema for Swagger 2.0 API.", + "id": "http://swagger.io/v2/schema.json#", + "$schema": "http://json-schema.org/draft-04/schema#", + "type": "object", + "required": [ + "swagger", + "info", + "paths" + ], + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "swagger": { + "type": "string", + "enum": [ + "2.0" + ], + "description": "The Swagger version of this document." + }, + "info": { + "$ref": "#/definitions/info" + }, + "host": { + "type": "string", + "pattern": "^[^{}/ :\\\\]+(?::\\d+)?$", + "description": "The host (name or ip) of the API. Example: 'swagger.io'" + }, + "basePath": { + "type": "string", + "pattern": "^/", + "description": "The base path to the API. Example: '/api'." + }, + "schemes": { + "$ref": "#/definitions/schemesList" + }, + "consumes": { + "description": "A list of MIME types accepted by the API.", + "allOf": [ + { + "$ref": "#/definitions/mediaTypeList" + } + ] + }, + "produces": { + "description": "A list of MIME types the API can produce.", + "allOf": [ + { + "$ref": "#/definitions/mediaTypeList" + } + ] + }, + "paths": { + "$ref": "#/definitions/paths" + }, + "definitions": { + "$ref": "#/definitions/definitions" + }, + "parameters": { + "$ref": "#/definitions/parameterDefinitions" + }, + "responses": { + "$ref": "#/definitions/responseDefinitions" + }, + "security": { + "$ref": "#/definitions/security" + }, + "securityDefinitions": { + "$ref": "#/definitions/securityDefinitions" + }, + "tags": { + "type": "array", + "items": { + "$ref": "#/definitions/tag" + }, + "uniqueItems": true + }, + "externalDocs": { + "$ref": "#/definitions/externalDocs" + } + }, + "definitions": { + "info": { + "type": "object", + "description": "General information about the API.", + "required": [ + "version", + "title" + ], + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "title": { + "type": "string", + "description": "A unique and precise title of the API." + }, + "version": { + "type": "string", + "description": "A semantic version number of the API." + }, + "description": { + "type": "string", + "description": "A longer description of the API. Should be different from the title. GitHub Flavored Markdown is allowed." + }, + "termsOfService": { + "type": "string", + "description": "The terms of service for the API." + }, + "contact": { + "$ref": "#/definitions/contact" + }, + "license": { + "$ref": "#/definitions/license" + } + } + }, + "contact": { + "type": "object", + "description": "Contact information for the owners of the API.", + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + "description": "The identifying name of the contact person/organization." + }, + "url": { + "type": "string", + "description": "The URL pointing to the contact information.", + "format": "uri" + }, + "email": { + "type": "string", + "description": "The email address of the contact person/organization.", + "format": "email" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "license": { + "type": "object", + "required": [ + "name" + ], + "additionalProperties": false, + "properties": { + "name": { + "type": "string", + "description": "The name of the license type. It's encouraged to use an OSI compatible license." + }, + "url": { + "type": "string", + "description": "The URL pointing to the license.", + "format": "uri" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "paths": { + "type": "object", + "description": "Relative paths to the individual endpoints. They must be relative to the 'basePath'.", + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + }, + "^/": { + "$ref": "#/definitions/pathItem" + } + }, + "additionalProperties": false + }, + "definitions": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/schema" + }, + "description": "One or more JSON objects describing the schemas being consumed and produced by the API." + }, + "parameterDefinitions": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/parameter" + }, + "description": "One or more JSON representations for parameters" + }, + "responseDefinitions": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/response" + }, + "description": "One or more JSON representations for parameters" + }, + "externalDocs": { + "type": "object", + "additionalProperties": false, + "description": "information about external documentation", + "required": [ + "url" + ], + "properties": { + "description": { + "type": "string" + }, + "url": { + "type": "string", + "format": "uri" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "examples": { + "type": "object", + "additionalProperties": true + }, + "mimeType": { + "type": "string", + "description": "The MIME type of the HTTP message." + }, + "operation": { + "type": "object", + "required": [ + "responses" + ], + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "tags": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true + }, + "summary": { + "type": "string", + "description": "A brief summary of the operation." + }, + "description": { + "type": "string", + "description": "A longer description of the operation, GitHub Flavored Markdown is allowed." + }, + "externalDocs": { + "$ref": "#/definitions/externalDocs" + }, + "operationId": { + "type": "string", + "description": "A unique identifier of the operation." + }, + "produces": { + "description": "A list of MIME types the API can produce.", + "allOf": [ + { + "$ref": "#/definitions/mediaTypeList" + } + ] + }, + "consumes": { + "description": "A list of MIME types the API can consume.", + "allOf": [ + { + "$ref": "#/definitions/mediaTypeList" + } + ] + }, + "parameters": { + "$ref": "#/definitions/parametersList" + }, + "responses": { + "$ref": "#/definitions/responses" + }, + "schemes": { + "$ref": "#/definitions/schemesList" + }, + "deprecated": { + "type": "boolean", + "default": false + }, + "security": { + "$ref": "#/definitions/security" + } + } + }, + "pathItem": { + "type": "object", + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "$ref": { + "type": "string" + }, + "get": { + "$ref": "#/definitions/operation" + }, + "put": { + "$ref": "#/definitions/operation" + }, + "post": { + "$ref": "#/definitions/operation" + }, + "delete": { + "$ref": "#/definitions/operation" + }, + "options": { + "$ref": "#/definitions/operation" + }, + "head": { + "$ref": "#/definitions/operation" + }, + "patch": { + "$ref": "#/definitions/operation" + }, + "parameters": { + "$ref": "#/definitions/parametersList" + } + } + }, + "responses": { + "type": "object", + "description": "Response objects names can either be any valid HTTP status code or 'default'.", + "minProperties": 1, + "additionalProperties": false, + "patternProperties": { + "^([0-9]{3})$|^(default)$": { + "$ref": "#/definitions/responseValue" + }, + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "not": { + "type": "object", + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + } + }, + "responseValue": { + "oneOf": [ + { + "$ref": "#/definitions/response" + }, + { + "$ref": "#/definitions/jsonReference" + } + ] + }, + "response": { + "type": "object", + "required": [ + "description" + ], + "properties": { + "description": { + "type": "string" + }, + "schema": { + "oneOf": [ + { + "$ref": "#/definitions/schema" + }, + { + "$ref": "#/definitions/fileSchema" + } + ] + }, + "headers": { + "$ref": "#/definitions/headers" + }, + "examples": { + "$ref": "#/definitions/examples" + } + }, + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "headers": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/header" + } + }, + "header": { + "type": "object", + "additionalProperties": false, + "required": [ + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "string", + "number", + "integer", + "boolean", + "array" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormat" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "vendorExtension": { + "description": "Any property starting with x- is valid.", + "additionalProperties": true, + "additionalItems": true + }, + "bodyParameter": { + "type": "object", + "required": [ + "name", + "in", + "schema" + ], + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "description": { + "type": "string", + "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + "name": { + "type": "string", + "description": "The name of the parameter." + }, + "in": { + "type": "string", + "description": "Determines the location of the parameter.", + "enum": [ + "body" + ] + }, + "required": { + "type": "boolean", + "description": "Determines whether or not this parameter is required or optional.", + "default": false + }, + "schema": { + "$ref": "#/definitions/schema" + } + }, + "additionalProperties": false + }, + "headerParameterSubSchema": { + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "required": { + "type": "boolean", + "description": "Determines whether or not this parameter is required or optional.", + "default": false + }, + "in": { + "type": "string", + "description": "Determines the location of the parameter.", + "enum": [ + "header" + ] + }, + "description": { + "type": "string", + "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + "name": { + "type": "string", + "description": "The name of the parameter." + }, + "type": { + "type": "string", + "enum": [ + "string", + "number", + "boolean", + "integer", + "array" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormat" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + } + } + }, + "queryParameterSubSchema": { + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "required": { + "type": "boolean", + "description": "Determines whether or not this parameter is required or optional.", + "default": false + }, + "in": { + "type": "string", + "description": "Determines the location of the parameter.", + "enum": [ + "query" + ] + }, + "description": { + "type": "string", + "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + "name": { + "type": "string", + "description": "The name of the parameter." + }, + "allowEmptyValue": { + "type": "boolean", + "default": false, + "description": "allows sending a parameter by name only or with an empty value." + }, + "type": { + "type": "string", + "enum": [ + "string", + "number", + "boolean", + "integer", + "array" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormatWithMulti" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + } + } + }, + "formDataParameterSubSchema": { + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "required": { + "type": "boolean", + "description": "Determines whether or not this parameter is required or optional.", + "default": false + }, + "in": { + "type": "string", + "description": "Determines the location of the parameter.", + "enum": [ + "formData" + ] + }, + "description": { + "type": "string", + "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + "name": { + "type": "string", + "description": "The name of the parameter." + }, + "allowEmptyValue": { + "type": "boolean", + "default": false, + "description": "allows sending a parameter by name only or with an empty value." + }, + "type": { + "type": "string", + "enum": [ + "string", + "number", + "boolean", + "integer", + "array", + "file" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormatWithMulti" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + } + } + }, + "pathParameterSubSchema": { + "additionalProperties": false, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "required": [ + "required" + ], + "properties": { + "required": { + "type": "boolean", + "enum": [ + true + ], + "description": "Determines whether or not this parameter is required or optional." + }, + "in": { + "type": "string", + "description": "Determines the location of the parameter.", + "enum": [ + "path" + ] + }, + "description": { + "type": "string", + "description": "A brief description of the parameter. This could contain examples of use. GitHub Flavored Markdown is allowed." + }, + "name": { + "type": "string", + "description": "The name of the parameter." + }, + "type": { + "type": "string", + "enum": [ + "string", + "number", + "boolean", + "integer", + "array" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormat" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + } + } + }, + "nonBodyParameter": { + "type": "object", + "required": [ + "name", + "in", + "type" + ], + "oneOf": [ + { + "$ref": "#/definitions/headerParameterSubSchema" + }, + { + "$ref": "#/definitions/formDataParameterSubSchema" + }, + { + "$ref": "#/definitions/queryParameterSubSchema" + }, + { + "$ref": "#/definitions/pathParameterSubSchema" + } + ] + }, + "parameter": { + "oneOf": [ + { + "$ref": "#/definitions/bodyParameter" + }, + { + "$ref": "#/definitions/nonBodyParameter" + } + ] + }, + "schema": { + "type": "object", + "description": "A deterministic version of a JSON Schema object.", + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "properties": { + "$ref": { + "type": "string" + }, + "format": { + "type": "string" + }, + "title": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/title" + }, + "description": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/description" + }, + "default": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/default" + }, + "multipleOf": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf" + }, + "maximum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum" + }, + "exclusiveMaximum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum" + }, + "minimum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/minimum" + }, + "exclusiveMinimum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum" + }, + "maxLength": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + "minLength": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + "pattern": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/pattern" + }, + "maxItems": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + "minItems": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + "uniqueItems": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/uniqueItems" + }, + "maxProperties": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + "minProperties": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + "required": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/stringArray" + }, + "enum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/enum" + }, + "additionalProperties": { + "anyOf": [ + { + "$ref": "#/definitions/schema" + }, + { + "type": "boolean" + } + ], + "default": {} + }, + "type": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/type" + }, + "items": { + "anyOf": [ + { + "$ref": "#/definitions/schema" + }, + { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/definitions/schema" + } + } + ], + "default": {} + }, + "allOf": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "#/definitions/schema" + } + }, + "properties": { + "type": "object", + "additionalProperties": { + "$ref": "#/definitions/schema" + }, + "default": {} + }, + "discriminator": { + "type": "string" + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "xml": { + "$ref": "#/definitions/xml" + }, + "externalDocs": { + "$ref": "#/definitions/externalDocs" + }, + "example": {} + }, + "additionalProperties": false + }, + "fileSchema": { + "type": "object", + "description": "A deterministic version of a JSON Schema object.", + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + }, + "required": [ + "type" + ], + "properties": { + "format": { + "type": "string" + }, + "title": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/title" + }, + "description": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/description" + }, + "default": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/default" + }, + "required": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/stringArray" + }, + "type": { + "type": "string", + "enum": [ + "file" + ] + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "externalDocs": { + "$ref": "#/definitions/externalDocs" + }, + "example": {} + }, + "additionalProperties": false + }, + "primitivesItems": { + "type": "object", + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": [ + "string", + "number", + "integer", + "boolean", + "array" + ] + }, + "format": { + "type": "string" + }, + "items": { + "$ref": "#/definitions/primitivesItems" + }, + "collectionFormat": { + "$ref": "#/definitions/collectionFormat" + }, + "default": { + "$ref": "#/definitions/default" + }, + "maximum": { + "$ref": "#/definitions/maximum" + }, + "exclusiveMaximum": { + "$ref": "#/definitions/exclusiveMaximum" + }, + "minimum": { + "$ref": "#/definitions/minimum" + }, + "exclusiveMinimum": { + "$ref": "#/definitions/exclusiveMinimum" + }, + "maxLength": { + "$ref": "#/definitions/maxLength" + }, + "minLength": { + "$ref": "#/definitions/minLength" + }, + "pattern": { + "$ref": "#/definitions/pattern" + }, + "maxItems": { + "$ref": "#/definitions/maxItems" + }, + "minItems": { + "$ref": "#/definitions/minItems" + }, + "uniqueItems": { + "$ref": "#/definitions/uniqueItems" + }, + "enum": { + "$ref": "#/definitions/enum" + }, + "multipleOf": { + "$ref": "#/definitions/multipleOf" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "security": { + "type": "array", + "items": { + "$ref": "#/definitions/securityRequirement" + }, + "uniqueItems": true + }, + "securityRequirement": { + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + }, + "uniqueItems": true + } + }, + "xml": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "namespace": { + "type": "string" + }, + "prefix": { + "type": "string" + }, + "attribute": { + "type": "boolean", + "default": false + }, + "wrapped": { + "type": "boolean", + "default": false + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "tag": { + "type": "object", + "additionalProperties": false, + "required": [ + "name" + ], + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "externalDocs": { + "$ref": "#/definitions/externalDocs" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "securityDefinitions": { + "type": "object", + "additionalProperties": { + "oneOf": [ + { + "$ref": "#/definitions/basicAuthenticationSecurity" + }, + { + "$ref": "#/definitions/apiKeySecurity" + }, + { + "$ref": "#/definitions/oauth2ImplicitSecurity" + }, + { + "$ref": "#/definitions/oauth2PasswordSecurity" + }, + { + "$ref": "#/definitions/oauth2ApplicationSecurity" + }, + { + "$ref": "#/definitions/oauth2AccessCodeSecurity" + } + ] + } + }, + "basicAuthenticationSecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "basic" + ] + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "apiKeySecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "name", + "in" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "apiKey" + ] + }, + "name": { + "type": "string" + }, + "in": { + "type": "string", + "enum": [ + "header", + "query" + ] + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "oauth2ImplicitSecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "flow", + "authorizationUrl" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "oauth2" + ] + }, + "flow": { + "type": "string", + "enum": [ + "implicit" + ] + }, + "scopes": { + "$ref": "#/definitions/oauth2Scopes" + }, + "authorizationUrl": { + "type": "string", + "format": "uri" + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "oauth2PasswordSecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "flow", + "tokenUrl" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "oauth2" + ] + }, + "flow": { + "type": "string", + "enum": [ + "password" + ] + }, + "scopes": { + "$ref": "#/definitions/oauth2Scopes" + }, + "tokenUrl": { + "type": "string", + "format": "uri" + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "oauth2ApplicationSecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "flow", + "tokenUrl" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "oauth2" + ] + }, + "flow": { + "type": "string", + "enum": [ + "application" + ] + }, + "scopes": { + "$ref": "#/definitions/oauth2Scopes" + }, + "tokenUrl": { + "type": "string", + "format": "uri" + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "oauth2AccessCodeSecurity": { + "type": "object", + "additionalProperties": false, + "required": [ + "type", + "flow", + "authorizationUrl", + "tokenUrl" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "oauth2" + ] + }, + "flow": { + "type": "string", + "enum": [ + "accessCode" + ] + }, + "scopes": { + "$ref": "#/definitions/oauth2Scopes" + }, + "authorizationUrl": { + "type": "string", + "format": "uri" + }, + "tokenUrl": { + "type": "string", + "format": "uri" + }, + "description": { + "type": "string" + } + }, + "patternProperties": { + "^x-": { + "$ref": "#/definitions/vendorExtension" + } + } + }, + "oauth2Scopes": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "mediaTypeList": { + "type": "array", + "items": { + "$ref": "#/definitions/mimeType" + }, + "uniqueItems": true + }, + "parametersList": { + "type": "array", + "description": "The parameters needed to send a valid API call.", + "additionalItems": false, + "items": { + "oneOf": [ + { + "$ref": "#/definitions/parameter" + }, + { + "$ref": "#/definitions/jsonReference" + } + ] + }, + "uniqueItems": true + }, + "schemesList": { + "type": "array", + "description": "The transfer protocol of the API.", + "items": { + "type": "string", + "enum": [ + "http", + "https", + "ws", + "wss" + ] + }, + "uniqueItems": true + }, + "collectionFormat": { + "type": "string", + "enum": [ + "csv", + "ssv", + "tsv", + "pipes" + ], + "default": "csv" + }, + "collectionFormatWithMulti": { + "type": "string", + "enum": [ + "csv", + "ssv", + "tsv", + "pipes", + "multi" + ], + "default": "csv" + }, + "title": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/title" + }, + "description": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/description" + }, + "default": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/default" + }, + "multipleOf": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/multipleOf" + }, + "maximum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/maximum" + }, + "exclusiveMaximum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum" + }, + "minimum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/minimum" + }, + "exclusiveMinimum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum" + }, + "maxLength": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + "minLength": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + "pattern": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/pattern" + }, + "maxItems": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveInteger" + }, + "minItems": { + "$ref": "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0" + }, + "uniqueItems": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/uniqueItems" + }, + "enum": { + "$ref": "http://json-schema.org/draft-04/schema#/properties/enum" + }, + "jsonReference": { + "type": "object", + "required": [ + "$ref" + ], + "additionalProperties": false, + "properties": { + "$ref": { + "type": "string" + } + } + } + } + }, + "tests": [ + { + "description": "Example petsore", + "data": { + "swagger": "2.0", + "info": { + "description": "This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.", + "version": "1.0.0", + "title": "Swagger Petstore", + "termsOfService": "http://swagger.io/terms/", + "contact": { + "email": "apiteam@swagger.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host": "petstore.swagger.io", + "basePath": "/v2", + "tags": [ + { + "name": "pet", + "description": "Everything about your Pets", + "externalDocs": { + "description": "Find out more", + "url": "http://swagger.io" + } + }, + { + "name": "store", + "description": "Access to Petstore orders" + }, + { + "name": "user", + "description": "Operations about user", + "externalDocs": { + "description": "Find out more about our store", + "url": "http://swagger.io" + } + } + ], + "schemes": [ + "http" + ], + "paths": { + "/pet": { + "post": { + "tags": [ + "pet" + ], + "summary": "Add a new pet to the store", + "description": "", + "operationId": "addPet", + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": true, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "put": { + "tags": [ + "pet" + ], + "summary": "Update an existing pet", + "description": "", + "operationId": "updatePet", + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": true, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + }, + "405": { + "description": "Validation exception" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/findByStatus": { + "get": { + "tags": [ + "pet" + ], + "summary": "Finds Pets by status", + "description": "Multiple status values can be provided with comma separated strings", + "operationId": "findPetsByStatus", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "status", + "in": "query", + "description": "Status values that need to be considered for filter", + "required": true, + "type": "array", + "items": { + "type": "string", + "enum": [ + "available", + "pending", + "sold" + ], + "default": "available" + }, + "collectionFormat": "multi" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid status value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/findByTags": { + "get": { + "tags": [ + "pet" + ], + "summary": "Finds Pets by tags", + "description": "Muliple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", + "operationId": "findPetsByTags", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "Tags to filter by", + "required": true, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "multi" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid tag value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ], + "deprecated": true + } + }, + "/pet/{petId}": { + "get": { + "tags": [ + "pet" + ], + "summary": "Find pet by ID", + "description": "Returns a single pet", + "operationId": "getPetById", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet to return", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + } + }, + "security": [ + { + "api_key": [] + } + ] + }, + "post": { + "tags": [ + "pet" + ], + "summary": "Updates a pet in the store with form data", + "description": "", + "operationId": "updatePetWithForm", + "consumes": [ + "application/x-www-form-urlencoded" + ], + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "name", + "in": "formData", + "description": "Updated name of the pet", + "required": false, + "type": "string" + }, + { + "name": "status", + "in": "formData", + "description": "Updated status of the pet", + "required": false, + "type": "string" + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "delete": { + "tags": [ + "pet" + ], + "summary": "Deletes a pet", + "description": "", + "operationId": "deletePet", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "api_key", + "in": "header", + "required": false, + "type": "string" + }, + { + "name": "petId", + "in": "path", + "description": "Pet id to delete", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Pet not found" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/{petId}/uploadImage": { + "post": { + "tags": [ + "pet" + ], + "summary": "uploads an image", + "description": "", + "operationId": "uploadFile", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet to update", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "additionalMetadata", + "in": "formData", + "description": "Additional data to pass to server", + "required": false, + "type": "string" + }, + { + "name": "file", + "in": "formData", + "description": "file to upload", + "required": false, + "type": "file" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/ApiResponse" + } + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/store/inventory": { + "get": { + "tags": [ + "store" + ], + "summary": "Returns pet inventories by status", + "description": "Returns a map of status codes to quantities", + "operationId": "getInventory", + "produces": [ + "application/json" + ], + "parameters": [], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "object", + "additionalProperties": { + "type": "integer", + "format": "int32" + } + } + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/store/order": { + "post": { + "tags": [ + "store" + ], + "summary": "Place an order for a pet", + "description": "", + "operationId": "placeOrder", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "order placed for purchasing the pet", + "required": true, + "schema": { + "$ref": "#/definitions/Order" + } + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid Order" + } + } + } + }, + "/store/order/{orderId}": { + "get": { + "tags": [ + "store" + ], + "summary": "Find purchase order by ID", + "description": "For valid response try integer IDs with value >= 1 and <= 10. Other values will generated exceptions", + "operationId": "getOrderById", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of pet that needs to be fetched", + "required": true, + "type": "integer", + "maximum": 10.0, + "minimum": 1.0, + "format": "int64" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Order not found" + } + } + }, + "delete": { + "tags": [ + "store" + ], + "summary": "Delete purchase order by ID", + "description": "For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors", + "operationId": "deleteOrder", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of the order that needs to be deleted", + "required": true, + "type": "integer", + "minimum": 1.0, + "format": "int64" + } + ], + "responses": { + "400": { + "description": "Invalid ID supplied" + }, + "404": { + "description": "Order not found" + } + } + } + }, + "/user": { + "post": { + "tags": [ + "user" + ], + "summary": "Create user", + "description": "This can only be done by the logged in user.", + "operationId": "createUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Created user object", + "required": true, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithArray": { + "post": { + "tags": [ + "user" + ], + "summary": "Creates list of users with given input array", + "description": "", + "operationId": "createUsersWithArrayInput", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": true, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithList": { + "post": { + "tags": [ + "user" + ], + "summary": "Creates list of users with given input array", + "description": "", + "operationId": "createUsersWithListInput", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": true, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/login": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs user into the system", + "description": "", + "operationId": "loginUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "query", + "description": "The user name for login", + "required": true, + "type": "string" + }, + { + "name": "password", + "in": "query", + "description": "The password for login in clear text", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "string" + }, + "headers": { + "X-Rate-Limit": { + "type": "integer", + "format": "int32", + "description": "calls per hour allowed by the user" + }, + "X-Expires-After": { + "type": "string", + "format": "date-time", + "description": "date in UTC when token expires" + } + } + }, + "400": { + "description": "Invalid username/password supplied" + } + } + } + }, + "/user/logout": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs out current logged in user session", + "description": "", + "operationId": "logoutUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/{username}": { + "get": { + "tags": [ + "user" + ], + "summary": "Get user by user name", + "description": "", + "operationId": "getUserByName", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be fetched. Use user1 for testing. ", + "required": true, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/User" + } + }, + "400": { + "description": "Invalid username supplied" + }, + "404": { + "description": "User not found" + } + } + }, + "put": { + "tags": [ + "user" + ], + "summary": "Updated user", + "description": "This can only be done by the logged in user.", + "operationId": "updateUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "name that need to be updated", + "required": true, + "type": "string" + }, + { + "in": "body", + "name": "body", + "description": "Updated user object", + "required": true, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "400": { + "description": "Invalid user supplied" + }, + "404": { + "description": "User not found" + } + } + }, + "delete": { + "tags": [ + "user" + ], + "summary": "Delete user", + "description": "This can only be done by the logged in user.", + "operationId": "deleteUser", + "produces": [ + "application/xml", + "application/json" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "400": { + "description": "Invalid username supplied" + }, + "404": { + "description": "User not found" + } + } + } + } + }, + "securityDefinitions": { + "petstore_auth": { + "type": "oauth2", + "authorizationUrl": "http://petstore.swagger.io/oauth/dialog", + "flow": "implicit", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + }, + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + } + }, + "definitions": { + "Order": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "petId": { + "type": "integer", + "format": "int64" + }, + "quantity": { + "type": "integer", + "format": "int32" + }, + "shipDate": { + "type": "string", + "format": "date-time" + }, + "status": { + "type": "string", + "description": "Order Status", + "enum": [ + "placed", + "approved", + "delivered" + ] + }, + "complete": { + "type": "boolean", + "default": false + } + }, + "xml": { + "name": "Order" + } + }, + "Category": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Category" + } + }, + "User": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "username": { + "type": "string" + }, + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "email": { + "type": "string" + }, + "password": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "userStatus": { + "type": "integer", + "format": "int32", + "description": "User Status" + } + }, + "xml": { + "name": "User" + } + }, + "Tag": { + "type": "object", + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Tag" + } + }, + "Pet": { + "type": "object", + "required": [ + "name", + "photoUrls" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "category": { + "$ref": "#/definitions/Category" + }, + "name": { + "type": "string", + "example": "doggie" + }, + "photoUrls": { + "type": "array", + "xml": { + "name": "photoUrl", + "wrapped": true + }, + "items": { + "type": "string" + } + }, + "tags": { + "type": "array", + "xml": { + "name": "tag", + "wrapped": true + }, + "items": { + "$ref": "#/definitions/Tag" + } + }, + "status": { + "type": "string", + "description": "pet status in the store", + "enum": [ + "available", + "pending", + "sold" + ] + } + }, + "xml": { + "name": "Pet" + } + }, + "ApiResponse": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "format": "int32" + }, + "type": { + "type": "string" + }, + "message": { + "type": "string" + } + } + } + }, + "externalDocs": { + "description": "Find out more about Swagger", + "url": "http://swagger.io" + } + }, + "valid": true + } + ] + } +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/json_schema_test_suite.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/json_schema_test_suite.py new file mode 100644 index 0000000000000000000000000000000000000000..905fb6a3b88faf56e3288f7eb5053172f97abe8b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/json_schema_test_suite.py @@ -0,0 +1,12 @@ +""" +A performance benchmark using the official test suite. + +This benchmarks jsonschema using every valid example in the +JSON-Schema-Test-Suite. It will take some time to complete. +""" +from pyperf import Runner + +from jsonschema.tests._suite import Suite + +if __name__ == "__main__": + Suite().benchmark(runner=Runner()) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/nested_schemas.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/nested_schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..b025c47cfd6736b0ea3d36856c1e2c8de35dde79 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/nested_schemas.py @@ -0,0 +1,56 @@ +""" +Validating highly nested schemas shouldn't cause exponential time blowups. + +See https://github.com/python-jsonschema/jsonschema/issues/1097. +""" +from itertools import cycle + +from jsonschema.validators import validator_for + +metaschemaish = { + "$id": "https://example.com/draft/2020-12/schema/strict", + "$schema": "https://json-schema.org/draft/2020-12/schema", + + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": True, + "https://json-schema.org/draft/2020-12/vocab/applicator": True, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": True, + "https://json-schema.org/draft/2020-12/vocab/validation": True, + "https://json-schema.org/draft/2020-12/vocab/meta-data": True, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": True, + "https://json-schema.org/draft/2020-12/vocab/content": True, + }, + "$dynamicAnchor": "meta", + + "$ref": "https://json-schema.org/draft/2020-12/schema", + "unevaluatedProperties": False, +} + + +def nested_schema(levels): + """ + Produce a schema which validates deeply nested objects and arrays. + """ + + names = cycle(["foo", "bar", "baz", "quux", "spam", "eggs"]) + schema = {"type": "object", "properties": {"ham": {"type": "string"}}} + for _, name in zip(range(levels - 1), names): + schema = {"type": "object", "properties": {name: schema}} + return schema + + +validator = validator_for(metaschemaish)(metaschemaish) + +if __name__ == "__main__": + from pyperf import Runner + runner = Runner() + + not_nested = nested_schema(levels=1) + runner.bench_func("not nested", lambda: validator.is_valid(not_nested)) + + for levels in range(1, 11, 3): + schema = nested_schema(levels=levels) + runner.bench_func( + f"nested * {levels}", + lambda schema=schema: validator.is_valid(schema), + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/subcomponents.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/subcomponents.py new file mode 100644 index 0000000000000000000000000000000000000000..6d78c7be6c88d177b89dfc80e52acae7820156a5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/subcomponents.py @@ -0,0 +1,42 @@ +""" +A benchmark which tries to compare the possible slow subparts of validation. +""" +from referencing import Registry +from referencing.jsonschema import DRAFT202012 +from rpds import HashTrieMap, HashTrieSet + +from jsonschema import Draft202012Validator + +schema = { + "type": "array", + "minLength": 1, + "maxLength": 1, + "items": {"type": "integer"}, +} + +hmap = HashTrieMap() +hset = HashTrieSet() + +registry = Registry() + +v = Draft202012Validator(schema) + + +def registry_data_structures(): + return hmap.insert("foo", "bar"), hset.insert("foo") + + +def registry_add(): + resource = DRAFT202012.create_resource(schema) + return registry.with_resource(uri="urn:example", resource=resource) + + +if __name__ == "__main__": + from pyperf import Runner + runner = Runner() + + runner.bench_func("HashMap/HashSet insertion", registry_data_structures) + runner.bench_func("Registry insertion", registry_add) + runner.bench_func("Success", lambda: v.is_valid([1])) + runner.bench_func("Failure", lambda: v.is_valid(["foo"])) + runner.bench_func("Metaschema validation", lambda: v.check_schema(schema)) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/unused_registry.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/unused_registry.py new file mode 100644 index 0000000000000000000000000000000000000000..7b272c235625378b231d1c113bcb8ef45851cbc7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/unused_registry.py @@ -0,0 +1,35 @@ +""" +An unused schema registry should not cause slower validation. + +"Unused" here means one where no reference resolution is occurring anyhow. + +See https://github.com/python-jsonschema/jsonschema/issues/1088. +""" +from pyperf import Runner +from referencing import Registry +from referencing.jsonschema import DRAFT201909 + +from jsonschema import Draft201909Validator + +registry = Registry().with_resource( + "urn:example:foo", + DRAFT201909.create_resource({}), +) + +schema = {"$ref": "https://json-schema.org/draft/2019-09/schema"} +instance = {"maxLength": 4} + +no_registry = Draft201909Validator(schema) +with_useless_registry = Draft201909Validator(schema, registry=registry) + +if __name__ == "__main__": + runner = Runner() + + runner.bench_func( + "no registry", + lambda: no_registry.is_valid(instance), + ) + runner.bench_func( + "useless registry", + lambda: with_useless_registry.is_valid(instance), + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/useless_applicator_schemas.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/useless_applicator_schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..f3229c0b8b9341e80ed087297efe31b04aa77fd7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/useless_applicator_schemas.py @@ -0,0 +1,106 @@ + +""" +A benchmark for validation of applicators containing lots of useless schemas. + +Signals a small possible optimization to remove all such schemas ahead of time. +""" + +from pyperf import Runner + +from jsonschema import Draft202012Validator as Validator + +NUM_USELESS = 100000 + +subschema = {"const": 37} + +valid = 37 +invalid = 12 + +baseline = Validator(subschema) + + +# These should be indistinguishable from just `subschema` +by_name = { + "single subschema": { + "anyOf": Validator({"anyOf": [subschema]}), + "allOf": Validator({"allOf": [subschema]}), + "oneOf": Validator({"oneOf": [subschema]}), + }, + "redundant subschemas": { + "anyOf": Validator({"anyOf": [subschema] * NUM_USELESS}), + "allOf": Validator({"allOf": [subschema] * NUM_USELESS}), + }, + "useless successful subschemas (beginning)": { + "anyOf": Validator({"anyOf": [subschema, *[True] * NUM_USELESS]}), + "allOf": Validator({"allOf": [subschema, *[True] * NUM_USELESS]}), + }, + "useless successful subschemas (middle)": { + "anyOf": Validator( + { + "anyOf": [ + *[True] * (NUM_USELESS // 2), + subschema, + *[True] * (NUM_USELESS // 2), + ], + }, + ), + "allOf": Validator( + { + "allOf": [ + *[True] * (NUM_USELESS // 2), + subschema, + *[True] * (NUM_USELESS // 2), + ], + }, + ), + }, + "useless successful subschemas (end)": { + "anyOf": Validator({"anyOf": [*[True] * NUM_USELESS, subschema]}), + "allOf": Validator({"allOf": [*[True] * NUM_USELESS, subschema]}), + }, + "useless failing subschemas (beginning)": { + "anyOf": Validator({"anyOf": [subschema, *[False] * NUM_USELESS]}), + "oneOf": Validator({"oneOf": [subschema, *[False] * NUM_USELESS]}), + }, + "useless failing subschemas (middle)": { + "anyOf": Validator( + { + "anyOf": [ + *[False] * (NUM_USELESS // 2), + subschema, + *[False] * (NUM_USELESS // 2), + ], + }, + ), + "oneOf": Validator( + { + "oneOf": [ + *[False] * (NUM_USELESS // 2), + subschema, + *[False] * (NUM_USELESS // 2), + ], + }, + ), + }, + "useless failing subschemas (end)": { + "anyOf": Validator({"anyOf": [*[False] * NUM_USELESS, subschema]}), + "oneOf": Validator({"oneOf": [*[False] * NUM_USELESS, subschema]}), + }, +} + +if __name__ == "__main__": + runner = Runner() + + runner.bench_func("baseline valid", lambda: baseline.is_valid(valid)) + runner.bench_func("baseline invalid", lambda: baseline.is_valid(invalid)) + + for group, applicators in by_name.items(): + for applicator, validator in applicators.items(): + runner.bench_func( + f"{group}: {applicator} valid", + lambda validator=validator: validator.is_valid(valid), + ) + runner.bench_func( + f"{group}: {applicator} invalid", + lambda validator=validator: validator.is_valid(invalid), + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/useless_keywords.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/useless_keywords.py new file mode 100644 index 0000000000000000000000000000000000000000..50f435989dd14d34d804508067e91e5fae4a275c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/useless_keywords.py @@ -0,0 +1,32 @@ +""" +A benchmark for validation of schemas containing lots of useless keywords. + +Checks we filter them out once, ahead of time. +""" + +from pyperf import Runner + +from jsonschema import Draft202012Validator + +NUM_USELESS = 100000 +schema = dict( + [ + ("not", {"const": 42}), + *((str(i), i) for i in range(NUM_USELESS)), + ("type", "integer"), + *((str(i), i) for i in range(NUM_USELESS, NUM_USELESS)), + ("minimum", 37), + ], +) +validator = Draft202012Validator(schema) + +valid = 3737 +invalid = 12 + + +if __name__ == "__main__": + runner = Runner() + runner.bench_func("beginning of schema", lambda: validator.is_valid(42)) + runner.bench_func("middle of schema", lambda: validator.is_valid("foo")) + runner.bench_func("end of schema", lambda: validator.is_valid(12)) + runner.bench_func("valid", lambda: validator.is_valid(3737)) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/validator_creation.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/validator_creation.py new file mode 100644 index 0000000000000000000000000000000000000000..4baeb3a31641a027496732a6f10e200346551209 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/benchmarks/validator_creation.py @@ -0,0 +1,14 @@ +from pyperf import Runner + +from jsonschema import Draft202012Validator + +schema = { + "type": "array", + "minLength": 1, + "maxLength": 1, + "items": {"type": "integer"}, +} + + +if __name__ == "__main__": + Runner().bench_func("validator creation", Draft202012Validator, schema) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39a129c33bc4ceaae7189951b3b8d6674bccd139 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/_suite.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/_suite.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..370a64590636a7f40adfd89b03b726cd7299defb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/_suite.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/fuzz_validate.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/fuzz_validate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b13460728d57bd182e57031027ce7256ae1038cb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/fuzz_validate.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_cli.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_cli.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a40b85ecb18e1d1acf05f0478ecd41ca1d916c64 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_cli.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_deprecations.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_deprecations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e47f835657e30ad3ef6215666634260f5490504 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_deprecations.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_exceptions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6caabea1dc18e15a0633a8a5e6a4a2b3ee121211 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_exceptions.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_format.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_format.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d32139c25df05f2efdd9c41d02623c2bb4f91aa Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_format.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_jsonschema_test_suite.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_jsonschema_test_suite.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1af07faec518f4031b6a8baed53ea06b4bd60a46 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_jsonschema_test_suite.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..466bd64b1ae12f278120eb67ada4694148370441 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_types.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e0187fb8b6d564e1764b6c9768797bb571b7e53 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_validators.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_validators.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80dd795f15d002de2de4f3042973e115e2d5815c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/__pycache__/test_validators.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f85dad42c3e6833a418a2b16908d7f292ceaaef85226b2cd8e54059218b6d22 +size 132029 diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/_suite.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/_suite.py new file mode 100644 index 0000000000000000000000000000000000000000..d61d38277d31d3eba23f6681d92066b8dba3ffc6 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/_suite.py @@ -0,0 +1,285 @@ +""" +Python representations of the JSON Schema Test Suite tests. +""" +from __future__ import annotations + +from contextlib import suppress +from functools import partial +from pathlib import Path +from typing import TYPE_CHECKING, Any +import json +import os +import re +import sys +import unittest + +from attrs import field, frozen +from referencing import Registry +import referencing.jsonschema + +if TYPE_CHECKING: + from collections.abc import Iterable, Mapping, Sequence + + from referencing.jsonschema import Schema + import pyperf + +from jsonschema.validators import _VALIDATORS +import jsonschema + +MAGIC_REMOTE_URL = "http://localhost:1234" + +_DELIMITERS = re.compile(r"[\W\- ]+") + + +def _find_suite(): + root = os.environ.get("JSON_SCHEMA_TEST_SUITE") + if root is not None: + return Path(root) + + root = Path(jsonschema.__file__).parent.parent / "json" + if not root.is_dir(): # pragma: no cover + raise ValueError( + ( + "Can't find the JSON-Schema-Test-Suite directory. " + "Set the 'JSON_SCHEMA_TEST_SUITE' environment " + "variable or run the tests from alongside a checkout " + "of the suite." + ), + ) + return root + + +@frozen +class Suite: + + _root: Path = field(factory=_find_suite) + + + def benchmark(self, runner: pyperf.Runner): # pragma: no cover + for name, Validator in _VALIDATORS.items(): + self.version(name=name).benchmark( + runner=runner, + Validator=Validator, + ) + + def version(self, name) -> Version: + Validator = _VALIDATORS[name] + uri: str = Validator.ID_OF(Validator.META_SCHEMA) # type: ignore[assignment] + specification = referencing.jsonschema.specification_with(uri) + + registry = Registry().with_contents( + remotes_in(root=self._root / "remotes", name=name, uri=uri), + default_specification=specification, + ) + return Version( + name=name, + path=self._root / "tests" / name, + remotes=registry, + ) + + +@frozen +class Version: + + _path: Path + _remotes: referencing.jsonschema.SchemaRegistry + + name: str + + def benchmark(self, **kwargs): # pragma: no cover + for case in self.cases(): + case.benchmark(**kwargs) + + def cases(self) -> Iterable[_Case]: + return self._cases_in(paths=self._path.glob("*.json")) + + def format_cases(self) -> Iterable[_Case]: + return self._cases_in(paths=self._path.glob("optional/format/*.json")) + + def optional_cases_of(self, name: str) -> Iterable[_Case]: + return self._cases_in(paths=[self._path / "optional" / f"{name}.json"]) + + def to_unittest_testcase(self, *groups, **kwargs): + name = kwargs.pop("name", "Test" + self.name.title().replace("-", "")) + methods = { + method.__name__: method + for method in ( + test.to_unittest_method(**kwargs) + for group in groups + for case in group + for test in case.tests + ) + } + cls = type(name, (unittest.TestCase,), methods) + + # We're doing crazy things, so if they go wrong, like a function + # behaving differently on some other interpreter, just make them + # not happen. + with suppress(Exception): + cls.__module__ = _someone_save_us_the_module_of_the_caller() + + return cls + + def _cases_in(self, paths: Iterable[Path]) -> Iterable[_Case]: + for path in paths: + for case in json.loads(path.read_text(encoding="utf-8")): + yield _Case.from_dict( + case, + version=self, + subject=path.stem, + remotes=self._remotes, + ) + + +@frozen +class _Case: + + version: Version + + subject: str + description: str + schema: Mapping[str, Any] | bool + tests: list[_Test] + comment: str | None = None + specification: Sequence[dict[str, str]] = () + + @classmethod + def from_dict(cls, data, remotes, **kwargs): + data.update(kwargs) + tests = [ + _Test( + version=data["version"], + subject=data["subject"], + case_description=data["description"], + schema=data["schema"], + remotes=remotes, + **test, + ) for test in data.pop("tests") + ] + return cls(tests=tests, **data) + + def benchmark(self, runner: pyperf.Runner, **kwargs): # pragma: no cover + for test in self.tests: + runner.bench_func( + test.fully_qualified_name, + partial(test.validate_ignoring_errors, **kwargs), + ) + + +def remotes_in( + root: Path, + name: str, + uri: str, +) -> Iterable[tuple[str, Schema]]: + # This messy logic is because the test suite is terrible at indicating + # what remotes are needed for what drafts, and mixes in schemas which + # have no $schema and which are invalid under earlier versions, in with + # other schemas which are needed for tests. + + for each in root.rglob("*.json"): + schema = json.loads(each.read_text()) + + relative = str(each.relative_to(root)).replace("\\", "/") + + if ( + ( # invalid boolean schema + name in {"draft3", "draft4"} + and each.stem == "tree" + ) or + ( # draft/*.json + "$schema" not in schema + and relative.startswith("draft") + and not relative.startswith(name) + ) + ): + continue + yield f"{MAGIC_REMOTE_URL}/{relative}", schema + + +@frozen(repr=False) +class _Test: + + version: Version + + subject: str + case_description: str + description: str + + data: Any + schema: Mapping[str, Any] | bool + + valid: bool + + _remotes: referencing.jsonschema.SchemaRegistry + + comment: str | None = None + + def __repr__(self): # pragma: no cover + return f"" + + @property + def fully_qualified_name(self): # pragma: no cover + return " > ".join( # noqa: FLY002 + [ + self.version.name, + self.subject, + self.case_description, + self.description, + ], + ) + + def to_unittest_method(self, skip=lambda test: None, **kwargs): + if self.valid: + def fn(this): + self.validate(**kwargs) + else: + def fn(this): + with this.assertRaises(jsonschema.ValidationError): + self.validate(**kwargs) + + fn.__name__ = "_".join( + [ + "test", + _DELIMITERS.sub("_", self.subject), + _DELIMITERS.sub("_", self.case_description), + _DELIMITERS.sub("_", self.description), + ], + ) + reason = skip(self) + if reason is None or os.environ.get("JSON_SCHEMA_DEBUG", "0") != "0": + return fn + elif os.environ.get("JSON_SCHEMA_EXPECTED_FAILURES", "0") != "0": # pragma: no cover # noqa: E501 + return unittest.expectedFailure(fn) + else: + return unittest.skip(reason)(fn) + + def validate(self, Validator, **kwargs): + Validator.check_schema(self.schema) + validator = Validator( + schema=self.schema, + registry=self._remotes, + **kwargs, + ) + if os.environ.get("JSON_SCHEMA_DEBUG", "0") != "0": # pragma: no cover + breakpoint() # noqa: T100 + validator.validate(instance=self.data) + + def validate_ignoring_errors(self, Validator): # pragma: no cover + with suppress(jsonschema.ValidationError): + self.validate(Validator=Validator) + + +def _someone_save_us_the_module_of_the_caller(): + """ + The FQON of the module 2nd stack frames up from here. + + This is intended to allow us to dynamically return test case classes that + are indistinguishable from being defined in the module that wants them. + + Otherwise, trial will mis-print the FQON, and copy pasting it won't re-run + the class that really is running. + + Save us all, this is all so so so so so terrible. + """ + + return sys._getframe(2).f_globals["__name__"] diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/fuzz_validate.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/fuzz_validate.py new file mode 100644 index 0000000000000000000000000000000000000000..c12e88bcfe9bfdc0e0ffaab502789a6b585d4be2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/fuzz_validate.py @@ -0,0 +1,50 @@ +""" +Fuzzing setup for OSS-Fuzz. + +See https://github.com/google/oss-fuzz/tree/master/projects/jsonschema for the +other half of the setup here. +""" +import sys + +from hypothesis import given, strategies + +import jsonschema + +PRIM = strategies.one_of( + strategies.booleans(), + strategies.integers(), + strategies.floats(allow_nan=False, allow_infinity=False), + strategies.text(), +) +DICT = strategies.recursive( + base=strategies.one_of( + strategies.booleans(), + strategies.dictionaries(strategies.text(), PRIM), + ), + extend=lambda inner: strategies.dictionaries(strategies.text(), inner), +) + + +@given(obj1=DICT, obj2=DICT) +def test_schemas(obj1, obj2): + try: + jsonschema.validate(instance=obj1, schema=obj2) + except jsonschema.exceptions.ValidationError: + pass + except jsonschema.exceptions.SchemaError: + pass + + +def main(): + atheris.instrument_all() + atheris.Setup( + sys.argv, + test_schemas.hypothesis.fuzz_one_input, + enable_python_coverage=True, + ) + atheris.Fuzz() + + +if __name__ == "__main__": + import atheris + main() diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_cli.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..bed9f3e4c4089a4cc653ffdb02d3648042df4088 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_cli.py @@ -0,0 +1,904 @@ +from contextlib import redirect_stderr, redirect_stdout +from importlib import metadata +from io import StringIO +from json import JSONDecodeError +from pathlib import Path +from textwrap import dedent +from unittest import TestCase +import json +import os +import subprocess +import sys +import tempfile +import warnings + +from jsonschema import Draft4Validator, Draft202012Validator +from jsonschema.exceptions import ( + SchemaError, + ValidationError, + _RefResolutionError, +) +from jsonschema.validators import _LATEST_VERSION, validate + +with warnings.catch_warnings(): + warnings.simplefilter("ignore") + from jsonschema import cli + + +def fake_validator(*errors): + errors = list(reversed(errors)) + + class FakeValidator: + def __init__(self, *args, **kwargs): + pass + + def iter_errors(self, instance): + if errors: + return errors.pop() + return [] # pragma: no cover + + @classmethod + def check_schema(self, schema): + pass + + return FakeValidator + + +def fake_open(all_contents): + def open(path): + contents = all_contents.get(path) + if contents is None: + raise FileNotFoundError(path) + return StringIO(contents) + return open + + +def _message_for(non_json): + try: + json.loads(non_json) + except JSONDecodeError as error: + return str(error) + else: # pragma: no cover + raise RuntimeError("Tried and failed to capture a JSON dump error.") + + +class TestCLI(TestCase): + def run_cli( + self, argv, files=None, stdin=StringIO(), exit_code=0, **override, + ): + arguments = cli.parse_args(argv) + arguments.update(override) + + self.assertFalse(hasattr(cli, "open")) + cli.open = fake_open(files or {}) + try: + stdout, stderr = StringIO(), StringIO() + actual_exit_code = cli.run( + arguments, + stdin=stdin, + stdout=stdout, + stderr=stderr, + ) + finally: + del cli.open + + self.assertEqual( + actual_exit_code, exit_code, msg=dedent( + f""" + Expected an exit code of {exit_code} != {actual_exit_code}. + + stdout: {stdout.getvalue()} + + stderr: {stderr.getvalue()} + """, + ), + ) + return stdout.getvalue(), stderr.getvalue() + + def assertOutputs(self, stdout="", stderr="", **kwargs): + self.assertEqual( + self.run_cli(**kwargs), + (dedent(stdout), dedent(stderr)), + ) + + def test_invalid_instance(self): + error = ValidationError("I am an error!", instance=12) + self.assertOutputs( + files=dict( + some_schema='{"does not": "matter since it is stubbed"}', + some_instance=json.dumps(error.instance), + ), + validator=fake_validator([error]), + + argv=["-i", "some_instance", "some_schema"], + + exit_code=1, + stderr="12: I am an error!\n", + ) + + def test_invalid_instance_pretty_output(self): + error = ValidationError("I am an error!", instance=12) + self.assertOutputs( + files=dict( + some_schema='{"does not": "matter since it is stubbed"}', + some_instance=json.dumps(error.instance), + ), + validator=fake_validator([error]), + + argv=["-i", "some_instance", "--output", "pretty", "some_schema"], + + exit_code=1, + stderr="""\ + ===[ValidationError]===(some_instance)=== + + I am an error! + ----------------------------- + """, + ) + + def test_invalid_instance_explicit_plain_output(self): + error = ValidationError("I am an error!", instance=12) + self.assertOutputs( + files=dict( + some_schema='{"does not": "matter since it is stubbed"}', + some_instance=json.dumps(error.instance), + ), + validator=fake_validator([error]), + + argv=["--output", "plain", "-i", "some_instance", "some_schema"], + + exit_code=1, + stderr="12: I am an error!\n", + ) + + def test_invalid_instance_multiple_errors(self): + instance = 12 + first = ValidationError("First error", instance=instance) + second = ValidationError("Second error", instance=instance) + + self.assertOutputs( + files=dict( + some_schema='{"does not": "matter since it is stubbed"}', + some_instance=json.dumps(instance), + ), + validator=fake_validator([first, second]), + + argv=["-i", "some_instance", "some_schema"], + + exit_code=1, + stderr="""\ + 12: First error + 12: Second error + """, + ) + + def test_invalid_instance_multiple_errors_pretty_output(self): + instance = 12 + first = ValidationError("First error", instance=instance) + second = ValidationError("Second error", instance=instance) + + self.assertOutputs( + files=dict( + some_schema='{"does not": "matter since it is stubbed"}', + some_instance=json.dumps(instance), + ), + validator=fake_validator([first, second]), + + argv=["-i", "some_instance", "--output", "pretty", "some_schema"], + + exit_code=1, + stderr="""\ + ===[ValidationError]===(some_instance)=== + + First error + ----------------------------- + ===[ValidationError]===(some_instance)=== + + Second error + ----------------------------- + """, + ) + + def test_multiple_invalid_instances(self): + first_instance = 12 + first_errors = [ + ValidationError("An error", instance=first_instance), + ValidationError("Another error", instance=first_instance), + ] + second_instance = "foo" + second_errors = [ValidationError("BOOM", instance=second_instance)] + + self.assertOutputs( + files=dict( + some_schema='{"does not": "matter since it is stubbed"}', + some_first_instance=json.dumps(first_instance), + some_second_instance=json.dumps(second_instance), + ), + validator=fake_validator(first_errors, second_errors), + + argv=[ + "-i", "some_first_instance", + "-i", "some_second_instance", + "some_schema", + ], + + exit_code=1, + stderr="""\ + 12: An error + 12: Another error + foo: BOOM + """, + ) + + def test_multiple_invalid_instances_pretty_output(self): + first_instance = 12 + first_errors = [ + ValidationError("An error", instance=first_instance), + ValidationError("Another error", instance=first_instance), + ] + second_instance = "foo" + second_errors = [ValidationError("BOOM", instance=second_instance)] + + self.assertOutputs( + files=dict( + some_schema='{"does not": "matter since it is stubbed"}', + some_first_instance=json.dumps(first_instance), + some_second_instance=json.dumps(second_instance), + ), + validator=fake_validator(first_errors, second_errors), + + argv=[ + "--output", "pretty", + "-i", "some_first_instance", + "-i", "some_second_instance", + "some_schema", + ], + + exit_code=1, + stderr="""\ + ===[ValidationError]===(some_first_instance)=== + + An error + ----------------------------- + ===[ValidationError]===(some_first_instance)=== + + Another error + ----------------------------- + ===[ValidationError]===(some_second_instance)=== + + BOOM + ----------------------------- + """, + ) + + def test_custom_error_format(self): + first_instance = 12 + first_errors = [ + ValidationError("An error", instance=first_instance), + ValidationError("Another error", instance=first_instance), + ] + second_instance = "foo" + second_errors = [ValidationError("BOOM", instance=second_instance)] + + self.assertOutputs( + files=dict( + some_schema='{"does not": "matter since it is stubbed"}', + some_first_instance=json.dumps(first_instance), + some_second_instance=json.dumps(second_instance), + ), + validator=fake_validator(first_errors, second_errors), + + argv=[ + "--error-format", ":{error.message}._-_.{error.instance}:", + "-i", "some_first_instance", + "-i", "some_second_instance", + "some_schema", + ], + + exit_code=1, + stderr=":An error._-_.12::Another error._-_.12::BOOM._-_.foo:", + ) + + def test_invalid_schema(self): + self.assertOutputs( + files=dict(some_schema='{"type": 12}'), + argv=["some_schema"], + + exit_code=1, + stderr="""\ + 12: 12 is not valid under any of the given schemas + """, + ) + + def test_invalid_schema_pretty_output(self): + schema = {"type": 12} + + with self.assertRaises(SchemaError) as e: + validate(schema=schema, instance="") + error = str(e.exception) + + self.assertOutputs( + files=dict(some_schema=json.dumps(schema)), + argv=["--output", "pretty", "some_schema"], + + exit_code=1, + stderr=( + "===[SchemaError]===(some_schema)===\n\n" + + str(error) + + "\n-----------------------------\n" + ), + ) + + def test_invalid_schema_multiple_errors(self): + self.assertOutputs( + files=dict(some_schema='{"type": 12, "items": 57}'), + argv=["some_schema"], + + exit_code=1, + stderr="""\ + 57: 57 is not of type 'object', 'boolean' + """, + ) + + def test_invalid_schema_multiple_errors_pretty_output(self): + schema = {"type": 12, "items": 57} + + with self.assertRaises(SchemaError) as e: + validate(schema=schema, instance="") + error = str(e.exception) + + self.assertOutputs( + files=dict(some_schema=json.dumps(schema)), + argv=["--output", "pretty", "some_schema"], + + exit_code=1, + stderr=( + "===[SchemaError]===(some_schema)===\n\n" + + str(error) + + "\n-----------------------------\n" + ), + ) + + def test_invalid_schema_with_invalid_instance(self): + """ + "Validating" an instance that's invalid under an invalid schema + just shows the schema error. + """ + self.assertOutputs( + files=dict( + some_schema='{"type": 12, "minimum": 30}', + some_instance="13", + ), + argv=["-i", "some_instance", "some_schema"], + + exit_code=1, + stderr="""\ + 12: 12 is not valid under any of the given schemas + """, + ) + + def test_invalid_schema_with_invalid_instance_pretty_output(self): + instance, schema = 13, {"type": 12, "minimum": 30} + + with self.assertRaises(SchemaError) as e: + validate(schema=schema, instance=instance) + error = str(e.exception) + + self.assertOutputs( + files=dict( + some_schema=json.dumps(schema), + some_instance=json.dumps(instance), + ), + argv=["--output", "pretty", "-i", "some_instance", "some_schema"], + + exit_code=1, + stderr=( + "===[SchemaError]===(some_schema)===\n\n" + + str(error) + + "\n-----------------------------\n" + ), + ) + + def test_invalid_instance_continues_with_the_rest(self): + self.assertOutputs( + files=dict( + some_schema='{"minimum": 30}', + first_instance="not valid JSON!", + second_instance="12", + ), + argv=[ + "-i", "first_instance", + "-i", "second_instance", + "some_schema", + ], + + exit_code=1, + stderr="""\ + Failed to parse 'first_instance': {} + 12: 12 is less than the minimum of 30 + """.format(_message_for("not valid JSON!")), + ) + + def test_custom_error_format_applies_to_schema_errors(self): + instance, schema = 13, {"type": 12, "minimum": 30} + + with self.assertRaises(SchemaError): + validate(schema=schema, instance=instance) + + self.assertOutputs( + files=dict(some_schema=json.dumps(schema)), + + argv=[ + "--error-format", ":{error.message}._-_.{error.instance}:", + "some_schema", + ], + + exit_code=1, + stderr=":12 is not valid under any of the given schemas._-_.12:", + ) + + def test_instance_is_invalid_JSON(self): + instance = "not valid JSON!" + + self.assertOutputs( + files=dict(some_schema="{}", some_instance=instance), + argv=["-i", "some_instance", "some_schema"], + + exit_code=1, + stderr=f"""\ + Failed to parse 'some_instance': {_message_for(instance)} + """, + ) + + def test_instance_is_invalid_JSON_pretty_output(self): + stdout, stderr = self.run_cli( + files=dict( + some_schema="{}", + some_instance="not valid JSON!", + ), + + argv=["--output", "pretty", "-i", "some_instance", "some_schema"], + + exit_code=1, + ) + self.assertFalse(stdout) + self.assertIn( + "(some_instance)===\n\nTraceback (most recent call last):\n", + stderr, + ) + self.assertNotIn("some_schema", stderr) + + def test_instance_is_invalid_JSON_on_stdin(self): + instance = "not valid JSON!" + + self.assertOutputs( + files=dict(some_schema="{}"), + stdin=StringIO(instance), + + argv=["some_schema"], + + exit_code=1, + stderr=f"""\ + Failed to parse : {_message_for(instance)} + """, + ) + + def test_instance_is_invalid_JSON_on_stdin_pretty_output(self): + stdout, stderr = self.run_cli( + files=dict(some_schema="{}"), + stdin=StringIO("not valid JSON!"), + + argv=["--output", "pretty", "some_schema"], + + exit_code=1, + ) + self.assertFalse(stdout) + self.assertIn( + "()===\n\nTraceback (most recent call last):\n", + stderr, + ) + self.assertNotIn("some_schema", stderr) + + def test_schema_is_invalid_JSON(self): + schema = "not valid JSON!" + + self.assertOutputs( + files=dict(some_schema=schema), + + argv=["some_schema"], + + exit_code=1, + stderr=f"""\ + Failed to parse 'some_schema': {_message_for(schema)} + """, + ) + + def test_schema_is_invalid_JSON_pretty_output(self): + stdout, stderr = self.run_cli( + files=dict(some_schema="not valid JSON!"), + + argv=["--output", "pretty", "some_schema"], + + exit_code=1, + ) + self.assertFalse(stdout) + self.assertIn( + "(some_schema)===\n\nTraceback (most recent call last):\n", + stderr, + ) + + def test_schema_and_instance_are_both_invalid_JSON(self): + """ + Only the schema error is reported, as we abort immediately. + """ + schema, instance = "not valid JSON!", "also not valid JSON!" + self.assertOutputs( + files=dict(some_schema=schema, some_instance=instance), + + argv=["some_schema"], + + exit_code=1, + stderr=f"""\ + Failed to parse 'some_schema': {_message_for(schema)} + """, + ) + + def test_schema_and_instance_are_both_invalid_JSON_pretty_output(self): + """ + Only the schema error is reported, as we abort immediately. + """ + stdout, stderr = self.run_cli( + files=dict( + some_schema="not valid JSON!", + some_instance="also not valid JSON!", + ), + + argv=["--output", "pretty", "-i", "some_instance", "some_schema"], + + exit_code=1, + ) + self.assertFalse(stdout) + self.assertIn( + "(some_schema)===\n\nTraceback (most recent call last):\n", + stderr, + ) + self.assertNotIn("some_instance", stderr) + + def test_instance_does_not_exist(self): + self.assertOutputs( + files=dict(some_schema="{}"), + argv=["-i", "nonexisting_instance", "some_schema"], + + exit_code=1, + stderr="""\ + 'nonexisting_instance' does not exist. + """, + ) + + def test_instance_does_not_exist_pretty_output(self): + self.assertOutputs( + files=dict(some_schema="{}"), + argv=[ + "--output", "pretty", + "-i", "nonexisting_instance", + "some_schema", + ], + + exit_code=1, + stderr="""\ + ===[FileNotFoundError]===(nonexisting_instance)=== + + 'nonexisting_instance' does not exist. + ----------------------------- + """, + ) + + def test_schema_does_not_exist(self): + self.assertOutputs( + argv=["nonexisting_schema"], + + exit_code=1, + stderr="'nonexisting_schema' does not exist.\n", + ) + + def test_schema_does_not_exist_pretty_output(self): + self.assertOutputs( + argv=["--output", "pretty", "nonexisting_schema"], + + exit_code=1, + stderr="""\ + ===[FileNotFoundError]===(nonexisting_schema)=== + + 'nonexisting_schema' does not exist. + ----------------------------- + """, + ) + + def test_neither_instance_nor_schema_exist(self): + self.assertOutputs( + argv=["-i", "nonexisting_instance", "nonexisting_schema"], + + exit_code=1, + stderr="'nonexisting_schema' does not exist.\n", + ) + + def test_neither_instance_nor_schema_exist_pretty_output(self): + self.assertOutputs( + argv=[ + "--output", "pretty", + "-i", "nonexisting_instance", + "nonexisting_schema", + ], + + exit_code=1, + stderr="""\ + ===[FileNotFoundError]===(nonexisting_schema)=== + + 'nonexisting_schema' does not exist. + ----------------------------- + """, + ) + + def test_successful_validation(self): + self.assertOutputs( + files=dict(some_schema="{}", some_instance="{}"), + argv=["-i", "some_instance", "some_schema"], + stdout="", + stderr="", + ) + + def test_successful_validation_pretty_output(self): + self.assertOutputs( + files=dict(some_schema="{}", some_instance="{}"), + argv=["--output", "pretty", "-i", "some_instance", "some_schema"], + stdout="===[SUCCESS]===(some_instance)===\n", + stderr="", + ) + + def test_successful_validation_of_stdin(self): + self.assertOutputs( + files=dict(some_schema="{}"), + stdin=StringIO("{}"), + argv=["some_schema"], + stdout="", + stderr="", + ) + + def test_successful_validation_of_stdin_pretty_output(self): + self.assertOutputs( + files=dict(some_schema="{}"), + stdin=StringIO("{}"), + argv=["--output", "pretty", "some_schema"], + stdout="===[SUCCESS]===()===\n", + stderr="", + ) + + def test_successful_validation_of_just_the_schema(self): + self.assertOutputs( + files=dict(some_schema="{}", some_instance="{}"), + argv=["-i", "some_instance", "some_schema"], + stdout="", + stderr="", + ) + + def test_successful_validation_of_just_the_schema_pretty_output(self): + self.assertOutputs( + files=dict(some_schema="{}", some_instance="{}"), + argv=["--output", "pretty", "-i", "some_instance", "some_schema"], + stdout="===[SUCCESS]===(some_instance)===\n", + stderr="", + ) + + def test_successful_validation_via_explicit_base_uri(self): + ref_schema_file = tempfile.NamedTemporaryFile(delete=False) # noqa: SIM115 + ref_schema_file.close() + self.addCleanup(os.remove, ref_schema_file.name) + + ref_path = Path(ref_schema_file.name) + ref_path.write_text('{"definitions": {"num": {"type": "integer"}}}') + + schema = f'{{"$ref": "{ref_path.name}#/definitions/num"}}' + + self.assertOutputs( + files=dict(some_schema=schema, some_instance="1"), + argv=[ + "-i", "some_instance", + "--base-uri", ref_path.parent.as_uri() + "/", + "some_schema", + ], + stdout="", + stderr="", + ) + + def test_unsuccessful_validation_via_explicit_base_uri(self): + ref_schema_file = tempfile.NamedTemporaryFile(delete=False) # noqa: SIM115 + ref_schema_file.close() + self.addCleanup(os.remove, ref_schema_file.name) + + ref_path = Path(ref_schema_file.name) + ref_path.write_text('{"definitions": {"num": {"type": "integer"}}}') + + schema = f'{{"$ref": "{ref_path.name}#/definitions/num"}}' + + self.assertOutputs( + files=dict(some_schema=schema, some_instance='"1"'), + argv=[ + "-i", "some_instance", + "--base-uri", ref_path.parent.as_uri() + "/", + "some_schema", + ], + exit_code=1, + stdout="", + stderr="1: '1' is not of type 'integer'\n", + ) + + def test_nonexistent_file_with_explicit_base_uri(self): + schema = '{"$ref": "someNonexistentFile.json#definitions/num"}' + instance = "1" + + with self.assertRaises(_RefResolutionError) as e: + self.assertOutputs( + files=dict( + some_schema=schema, + some_instance=instance, + ), + argv=[ + "-i", "some_instance", + "--base-uri", Path.cwd().as_uri(), + "some_schema", + ], + ) + error = str(e.exception) + self.assertIn(f"{os.sep}someNonexistentFile.json'", error) + + def test_invalid_explicit_base_uri(self): + schema = '{"$ref": "foo.json#definitions/num"}' + instance = "1" + + with self.assertRaises(_RefResolutionError) as e: + self.assertOutputs( + files=dict( + some_schema=schema, + some_instance=instance, + ), + argv=[ + "-i", "some_instance", + "--base-uri", "not@UR1", + "some_schema", + ], + ) + error = str(e.exception) + self.assertEqual( + error, "unknown url type: 'foo.json'", + ) + + def test_it_validates_using_the_latest_validator_when_unspecified(self): + # There isn't a better way now I can think of to ensure that the + # latest version was used, given that the call to validator_for + # is hidden inside the CLI, so guard that that's the case, and + # this test will have to be updated when versions change until + # we can think of a better way to ensure this behavior. + self.assertIs(Draft202012Validator, _LATEST_VERSION) + + self.assertOutputs( + files=dict(some_schema='{"const": "check"}', some_instance='"a"'), + argv=["-i", "some_instance", "some_schema"], + exit_code=1, + stdout="", + stderr="a: 'check' was expected\n", + ) + + def test_it_validates_using_draft7_when_specified(self): + """ + Specifically, `const` validation applies for Draft 7. + """ + schema = """ + { + "$schema": "http://json-schema.org/draft-07/schema#", + "const": "check" + } + """ + instance = '"foo"' + self.assertOutputs( + files=dict(some_schema=schema, some_instance=instance), + argv=["-i", "some_instance", "some_schema"], + exit_code=1, + stdout="", + stderr="foo: 'check' was expected\n", + ) + + def test_it_validates_using_draft4_when_specified(self): + """ + Specifically, `const` validation *does not* apply for Draft 4. + """ + schema = """ + { + "$schema": "http://json-schema.org/draft-04/schema#", + "const": "check" + } + """ + instance = '"foo"' + self.assertOutputs( + files=dict(some_schema=schema, some_instance=instance), + argv=["-i", "some_instance", "some_schema"], + stdout="", + stderr="", + ) + + +class TestParser(TestCase): + + FakeValidator = fake_validator() + + def test_find_validator_by_fully_qualified_object_name(self): + arguments = cli.parse_args( + [ + "--validator", + "jsonschema.tests.test_cli.TestParser.FakeValidator", + "--instance", "mem://some/instance", + "mem://some/schema", + ], + ) + self.assertIs(arguments["validator"], self.FakeValidator) + + def test_find_validator_in_jsonschema(self): + arguments = cli.parse_args( + [ + "--validator", "Draft4Validator", + "--instance", "mem://some/instance", + "mem://some/schema", + ], + ) + self.assertIs(arguments["validator"], Draft4Validator) + + def cli_output_for(self, *argv): + stdout, stderr = StringIO(), StringIO() + with redirect_stdout(stdout), redirect_stderr(stderr): # noqa: SIM117 + with self.assertRaises(SystemExit): + cli.parse_args(argv) + return stdout.getvalue(), stderr.getvalue() + + def test_unknown_output(self): + stdout, stderr = self.cli_output_for( + "--output", "foo", + "mem://some/schema", + ) + self.assertIn("invalid choice: 'foo'", stderr) + self.assertFalse(stdout) + + def test_useless_error_format(self): + stdout, stderr = self.cli_output_for( + "--output", "pretty", + "--error-format", "foo", + "mem://some/schema", + ) + self.assertIn( + "--error-format can only be used with --output plain", + stderr, + ) + self.assertFalse(stdout) + + +class TestCLIIntegration(TestCase): + def test_license(self): + our_metadata = metadata.metadata("jsonschema") + self.assertEqual(our_metadata.get("License-Expression"), "MIT") + + def test_version(self): + version = subprocess.check_output( + [sys.executable, "-W", "ignore", "-m", "jsonschema", "--version"], + stderr=subprocess.STDOUT, + ) + version = version.decode("utf-8").strip() + self.assertEqual(version, metadata.version("jsonschema")) + + def test_no_arguments_shows_usage_notes(self): + output = subprocess.check_output( + [sys.executable, "-m", "jsonschema"], + stderr=subprocess.STDOUT, + ) + output_for_help = subprocess.check_output( + [sys.executable, "-m", "jsonschema", "--help"], + stderr=subprocess.STDOUT, + ) + self.assertEqual(output, output_for_help) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_deprecations.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_deprecations.py new file mode 100644 index 0000000000000000000000000000000000000000..a54b02f380ae098ba7b3f2c518a44935859f1ce6 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_deprecations.py @@ -0,0 +1,432 @@ +from contextlib import contextmanager +from io import BytesIO +from unittest import TestCase, mock +import importlib.metadata +import json +import subprocess +import sys +import urllib.request + +import referencing.exceptions + +from jsonschema import FormatChecker, exceptions, protocols, validators + + +class TestDeprecations(TestCase): + def test_version(self): + """ + As of v4.0.0, __version__ is deprecated in favor of importlib.metadata. + """ + + message = "Accessing jsonschema.__version__ is deprecated" + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import __version__ + + self.assertEqual(__version__, importlib.metadata.version("jsonschema")) + self.assertEqual(w.filename, __file__) + + def test_validators_ErrorTree(self): + """ + As of v4.0.0, importing ErrorTree from jsonschema.validators is + deprecated in favor of doing so from jsonschema.exceptions. + """ + + message = "Importing ErrorTree from jsonschema.validators is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema.validators import ErrorTree + + self.assertEqual(ErrorTree, exceptions.ErrorTree) + self.assertEqual(w.filename, __file__) + + def test_import_ErrorTree(self): + """ + As of v4.18.0, importing ErrorTree from the package root is + deprecated in favor of doing so from jsonschema.exceptions. + """ + + message = "Importing ErrorTree directly from the jsonschema package " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import ErrorTree + + self.assertEqual(ErrorTree, exceptions.ErrorTree) + self.assertEqual(w.filename, __file__) + + def test_ErrorTree_setitem(self): + """ + As of v4.20.0, setting items on an ErrorTree is deprecated. + """ + + e = exceptions.ValidationError("some error", path=["foo"]) + tree = exceptions.ErrorTree() + subtree = exceptions.ErrorTree(errors=[e]) + + message = "ErrorTree.__setitem__ is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + tree["foo"] = subtree + + self.assertEqual(tree["foo"], subtree) + self.assertEqual(w.filename, __file__) + + def test_import_FormatError(self): + """ + As of v4.18.0, importing FormatError from the package root is + deprecated in favor of doing so from jsonschema.exceptions. + """ + + message = "Importing FormatError directly from the jsonschema package " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import FormatError + + self.assertEqual(FormatError, exceptions.FormatError) + self.assertEqual(w.filename, __file__) + + def test_import_Validator(self): + """ + As of v4.19.0, importing Validator from the package root is + deprecated in favor of doing so from jsonschema.protocols. + """ + + message = "Importing Validator directly from the jsonschema package " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import Validator + + self.assertEqual(Validator, protocols.Validator) + self.assertEqual(w.filename, __file__) + + def test_validators_validators(self): + """ + As of v4.0.0, accessing jsonschema.validators.validators is + deprecated. + """ + + message = "Accessing jsonschema.validators.validators is deprecated" + with self.assertWarnsRegex(DeprecationWarning, message) as w: + value = validators.validators + + self.assertEqual(value, validators._VALIDATORS) + self.assertEqual(w.filename, __file__) + + def test_validators_meta_schemas(self): + """ + As of v4.0.0, accessing jsonschema.validators.meta_schemas is + deprecated. + """ + + message = "Accessing jsonschema.validators.meta_schemas is deprecated" + with self.assertWarnsRegex(DeprecationWarning, message) as w: + value = validators.meta_schemas + + self.assertEqual(value, validators._META_SCHEMAS) + self.assertEqual(w.filename, __file__) + + def test_RefResolver_in_scope(self): + """ + As of v4.0.0, RefResolver.in_scope is deprecated. + """ + + resolver = validators._RefResolver.from_schema({}) + message = "jsonschema.RefResolver.in_scope is deprecated " + with self.assertWarnsRegex(DeprecationWarning, message) as w: # noqa: SIM117 + with resolver.in_scope("foo"): + pass + + self.assertEqual(w.filename, __file__) + + def test_Validator_is_valid_two_arguments(self): + """ + As of v4.0.0, calling is_valid with two arguments (to provide a + different schema) is deprecated. + """ + + validator = validators.Draft7Validator({}) + message = "Passing a schema to Validator.is_valid is deprecated " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + result = validator.is_valid("foo", {"type": "number"}) + + self.assertFalse(result) + self.assertEqual(w.filename, __file__) + + def test_Validator_iter_errors_two_arguments(self): + """ + As of v4.0.0, calling iter_errors with two arguments (to provide a + different schema) is deprecated. + """ + + validator = validators.Draft7Validator({}) + message = "Passing a schema to Validator.iter_errors is deprecated " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + error, = validator.iter_errors("foo", {"type": "number"}) + + self.assertEqual(error.validator, "type") + self.assertEqual(w.filename, __file__) + + def test_Validator_resolver(self): + """ + As of v4.18.0, accessing Validator.resolver is deprecated. + """ + + validator = validators.Draft7Validator({}) + message = "Accessing Draft7Validator.resolver is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + self.assertIsInstance(validator.resolver, validators._RefResolver) + + self.assertEqual(w.filename, __file__) + + def test_RefResolver(self): + """ + As of v4.18.0, RefResolver is fully deprecated. + """ + + message = "jsonschema.RefResolver is deprecated" + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import RefResolver + self.assertEqual(w.filename, __file__) + + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema.validators import RefResolver # noqa: F401 + self.assertEqual(w.filename, __file__) + + def test_RefResolutionError(self): + """ + As of v4.18.0, RefResolutionError is deprecated in favor of directly + catching errors from the referencing library. + """ + + message = "jsonschema.exceptions.RefResolutionError is deprecated" + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import RefResolutionError + + self.assertEqual(RefResolutionError, exceptions._RefResolutionError) + self.assertEqual(w.filename, __file__) + + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema.exceptions import RefResolutionError + + self.assertEqual(RefResolutionError, exceptions._RefResolutionError) + self.assertEqual(w.filename, __file__) + + def test_catching_Unresolvable_directly(self): + """ + This behavior is the intended behavior (i.e. it's not deprecated), but + given we do "tricksy" things in the iterim to wrap exceptions in a + multiple inheritance subclass, we need to be extra sure it works and + stays working. + """ + validator = validators.Draft202012Validator({"$ref": "urn:nothing"}) + + with self.assertRaises(referencing.exceptions.Unresolvable) as e: + validator.validate(12) + + expected = referencing.exceptions.Unresolvable(ref="urn:nothing") + self.assertEqual( + (e.exception, str(e.exception)), + (expected, "Unresolvable: urn:nothing"), + ) + + def test_catching_Unresolvable_via_RefResolutionError(self): + """ + Until RefResolutionError is removed, it is still possible to catch + exceptions from reference resolution using it, even though they may + have been raised by referencing. + """ + with self.assertWarns(DeprecationWarning): + from jsonschema import RefResolutionError + + validator = validators.Draft202012Validator({"$ref": "urn:nothing"}) + + with self.assertRaises(referencing.exceptions.Unresolvable) as u: + validator.validate(12) + + with self.assertRaises(RefResolutionError) as e: + validator.validate(12) + + self.assertEqual( + (e.exception, str(e.exception)), + (u.exception, "Unresolvable: urn:nothing"), + ) + + def test_WrappedReferencingError_hashability(self): + """ + Ensure the wrapped referencing errors are hashable when possible. + """ + with self.assertWarns(DeprecationWarning): + from jsonschema import RefResolutionError + + validator = validators.Draft202012Validator({"$ref": "urn:nothing"}) + + with self.assertRaises(referencing.exceptions.Unresolvable) as u: + validator.validate(12) + + with self.assertRaises(RefResolutionError) as e: + validator.validate(12) + + self.assertIn(e.exception, {u.exception}) + self.assertIn(u.exception, {e.exception}) + + def test_Validator_subclassing(self): + """ + As of v4.12.0, subclassing a validator class produces an explicit + deprecation warning. + + This was never intended to be public API (and some comments over the + years in issues said so, but obviously that's not a great way to make + sure it's followed). + + A future version will explicitly raise an error. + """ + + message = "Subclassing validator classes is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + class Subclass(validators.Draft202012Validator): + pass + + self.assertEqual(w.filename, __file__) + + with self.assertWarnsRegex(DeprecationWarning, message) as w: + class AnotherSubclass(validators.create(meta_schema={})): + pass + + def test_FormatChecker_cls_checks(self): + """ + As of v4.14.0, FormatChecker.cls_checks is deprecated without + replacement. + """ + + self.addCleanup(FormatChecker.checkers.pop, "boom", None) + + message = "FormatChecker.cls_checks " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + FormatChecker.cls_checks("boom") + + self.assertEqual(w.filename, __file__) + + def test_draftN_format_checker(self): + """ + As of v4.16.0, accessing jsonschema.draftn_format_checker is deprecated + in favor of Validator.FORMAT_CHECKER. + """ + + message = "Accessing jsonschema.draft202012_format_checker is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import draft202012_format_checker + + self.assertIs( + draft202012_format_checker, + validators.Draft202012Validator.FORMAT_CHECKER, + ) + self.assertEqual(w.filename, __file__) + + message = "Accessing jsonschema.draft201909_format_checker is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import draft201909_format_checker + + self.assertIs( + draft201909_format_checker, + validators.Draft201909Validator.FORMAT_CHECKER, + ) + self.assertEqual(w.filename, __file__) + + message = "Accessing jsonschema.draft7_format_checker is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import draft7_format_checker + + self.assertIs( + draft7_format_checker, + validators.Draft7Validator.FORMAT_CHECKER, + ) + self.assertEqual(w.filename, __file__) + + message = "Accessing jsonschema.draft6_format_checker is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import draft6_format_checker + + self.assertIs( + draft6_format_checker, + validators.Draft6Validator.FORMAT_CHECKER, + ) + self.assertEqual(w.filename, __file__) + + message = "Accessing jsonschema.draft4_format_checker is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import draft4_format_checker + + self.assertIs( + draft4_format_checker, + validators.Draft4Validator.FORMAT_CHECKER, + ) + self.assertEqual(w.filename, __file__) + + message = "Accessing jsonschema.draft3_format_checker is " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + from jsonschema import draft3_format_checker + + self.assertIs( + draft3_format_checker, + validators.Draft3Validator.FORMAT_CHECKER, + ) + self.assertEqual(w.filename, __file__) + + with self.assertRaises(ImportError): + from jsonschema import draft1234_format_checker # noqa: F401 + + def test_import_cli(self): + """ + As of v4.17.0, importing jsonschema.cli is deprecated. + """ + + message = "The jsonschema CLI is deprecated and will be removed " + with self.assertWarnsRegex(DeprecationWarning, message) as w: + import jsonschema.cli + importlib.reload(jsonschema.cli) + + self.assertEqual(w.filename, importlib.__file__) + + def test_cli(self): + """ + As of v4.17.0, the jsonschema CLI is deprecated. + """ + + process = subprocess.run( + [sys.executable, "-m", "jsonschema"], + capture_output=True, + check=True, + ) + self.assertIn(b"The jsonschema CLI is deprecated ", process.stderr) + + def test_automatic_remote_retrieval(self): + """ + Automatic retrieval of remote references is deprecated as of v4.18.0. + """ + ref = "http://bar#/$defs/baz" + schema = {"$defs": {"baz": {"type": "integer"}}} + + if "requests" in sys.modules: # pragma: no cover + self.addCleanup( + sys.modules.__setitem__, "requests", sys.modules["requests"], + ) + sys.modules["requests"] = None + + @contextmanager + def fake_urlopen(request): + self.assertIsInstance(request, urllib.request.Request) + self.assertEqual(request.full_url, "http://bar") + + # Ha ha urllib.request.Request "normalizes" header names and + # Request.get_header does not also normalize them... + (header, value), = request.header_items() + self.assertEqual(header.lower(), "user-agent") + self.assertEqual( + value, "python-jsonschema (deprecated $ref resolution)", + ) + yield BytesIO(json.dumps(schema).encode("utf8")) + + validator = validators.Draft202012Validator({"$ref": ref}) + + message = "Automatically retrieving remote references " + patch = mock.patch.object(urllib.request, "urlopen", new=fake_urlopen) + + with patch, self.assertWarnsRegex(DeprecationWarning, message): + self.assertEqual( + (validator.is_valid({}), validator.is_valid(37)), + (False, True), + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_exceptions.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..8d515a998506e779b9e2f2340204bca33f73ae04 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_exceptions.py @@ -0,0 +1,759 @@ +from unittest import TestCase +import textwrap + +import jsonpath_ng + +from jsonschema import exceptions +from jsonschema.validators import _LATEST_VERSION + + +class TestBestMatch(TestCase): + def best_match_of(self, instance, schema): + errors = list(_LATEST_VERSION(schema).iter_errors(instance)) + msg = f"No errors found for {instance} under {schema!r}!" + self.assertTrue(errors, msg=msg) + + best = exceptions.best_match(iter(errors)) + reversed_best = exceptions.best_match(reversed(errors)) + + self.assertEqual( + best._contents(), + reversed_best._contents(), + f"No consistent best match!\nGot: {best}\n\nThen: {reversed_best}", + ) + return best + + def test_shallower_errors_are_better_matches(self): + schema = { + "properties": { + "foo": { + "minProperties": 2, + "properties": {"bar": {"type": "object"}}, + }, + }, + } + best = self.best_match_of(instance={"foo": {"bar": []}}, schema=schema) + self.assertEqual(best.validator, "minProperties") + + def test_oneOf_and_anyOf_are_weak_matches(self): + """ + A property you *must* match is probably better than one you have to + match a part of. + """ + + schema = { + "minProperties": 2, + "anyOf": [{"type": "string"}, {"type": "number"}], + "oneOf": [{"type": "string"}, {"type": "number"}], + } + best = self.best_match_of(instance={}, schema=schema) + self.assertEqual(best.validator, "minProperties") + + def test_if_the_most_relevant_error_is_anyOf_it_is_traversed(self): + """ + If the most relevant error is an anyOf, then we traverse its context + and select the otherwise *least* relevant error, since in this case + that means the most specific, deep, error inside the instance. + + I.e. since only one of the schemas must match, we look for the most + relevant one. + """ + + schema = { + "properties": { + "foo": { + "anyOf": [ + {"type": "string"}, + {"properties": {"bar": {"type": "array"}}}, + ], + }, + }, + } + best = self.best_match_of(instance={"foo": {"bar": 12}}, schema=schema) + self.assertEqual(best.validator_value, "array") + + def test_no_anyOf_traversal_for_equally_relevant_errors(self): + """ + We don't traverse into an anyOf (as above) if all of its context errors + seem to be equally "wrong" against the instance. + """ + + schema = { + "anyOf": [ + {"type": "string"}, + {"type": "integer"}, + {"type": "object"}, + ], + } + best = self.best_match_of(instance=[], schema=schema) + self.assertEqual(best.validator, "anyOf") + + def test_anyOf_traversal_for_single_equally_relevant_error(self): + """ + We *do* traverse anyOf with a single nested error, even though it is + vacuously equally relevant to itself. + """ + + schema = { + "anyOf": [ + {"type": "string"}, + ], + } + best = self.best_match_of(instance=[], schema=schema) + self.assertEqual(best.validator, "type") + + def test_anyOf_traversal_for_single_sibling_errors(self): + """ + We *do* traverse anyOf with a single subschema that fails multiple + times (e.g. on multiple items). + """ + + schema = { + "anyOf": [ + {"items": {"const": 37}}, + ], + } + best = self.best_match_of(instance=[12, 12], schema=schema) + self.assertEqual(best.validator, "const") + + def test_anyOf_traversal_for_non_type_matching_sibling_errors(self): + """ + We *do* traverse anyOf with multiple subschemas when one does not type + match. + """ + + schema = { + "anyOf": [ + {"type": "object"}, + {"items": {"const": 37}}, + ], + } + best = self.best_match_of(instance=[12, 12], schema=schema) + self.assertEqual(best.validator, "const") + + def test_if_the_most_relevant_error_is_oneOf_it_is_traversed(self): + """ + If the most relevant error is an oneOf, then we traverse its context + and select the otherwise *least* relevant error, since in this case + that means the most specific, deep, error inside the instance. + + I.e. since only one of the schemas must match, we look for the most + relevant one. + """ + + schema = { + "properties": { + "foo": { + "oneOf": [ + {"type": "string"}, + {"properties": {"bar": {"type": "array"}}}, + ], + }, + }, + } + best = self.best_match_of(instance={"foo": {"bar": 12}}, schema=schema) + self.assertEqual(best.validator_value, "array") + + def test_no_oneOf_traversal_for_equally_relevant_errors(self): + """ + We don't traverse into an oneOf (as above) if all of its context errors + seem to be equally "wrong" against the instance. + """ + + schema = { + "oneOf": [ + {"type": "string"}, + {"type": "integer"}, + {"type": "object"}, + ], + } + best = self.best_match_of(instance=[], schema=schema) + self.assertEqual(best.validator, "oneOf") + + def test_oneOf_traversal_for_single_equally_relevant_error(self): + """ + We *do* traverse oneOf with a single nested error, even though it is + vacuously equally relevant to itself. + """ + + schema = { + "oneOf": [ + {"type": "string"}, + ], + } + best = self.best_match_of(instance=[], schema=schema) + self.assertEqual(best.validator, "type") + + def test_oneOf_traversal_for_single_sibling_errors(self): + """ + We *do* traverse oneOf with a single subschema that fails multiple + times (e.g. on multiple items). + """ + + schema = { + "oneOf": [ + {"items": {"const": 37}}, + ], + } + best = self.best_match_of(instance=[12, 12], schema=schema) + self.assertEqual(best.validator, "const") + + def test_oneOf_traversal_for_non_type_matching_sibling_errors(self): + """ + We *do* traverse oneOf with multiple subschemas when one does not type + match. + """ + + schema = { + "oneOf": [ + {"type": "object"}, + {"items": {"const": 37}}, + ], + } + best = self.best_match_of(instance=[12, 12], schema=schema) + self.assertEqual(best.validator, "const") + + def test_if_the_most_relevant_error_is_allOf_it_is_traversed(self): + """ + Now, if the error is allOf, we traverse but select the *most* relevant + error from the context, because all schemas here must match anyways. + """ + + schema = { + "properties": { + "foo": { + "allOf": [ + {"type": "string"}, + {"properties": {"bar": {"type": "array"}}}, + ], + }, + }, + } + best = self.best_match_of(instance={"foo": {"bar": 12}}, schema=schema) + self.assertEqual(best.validator_value, "string") + + def test_nested_context_for_oneOf(self): + """ + We traverse into nested contexts (a oneOf containing an error in a + nested oneOf here). + """ + + schema = { + "properties": { + "foo": { + "oneOf": [ + {"type": "string"}, + { + "oneOf": [ + {"type": "string"}, + { + "properties": { + "bar": {"type": "array"}, + }, + }, + ], + }, + ], + }, + }, + } + best = self.best_match_of(instance={"foo": {"bar": 12}}, schema=schema) + self.assertEqual(best.validator_value, "array") + + def test_it_prioritizes_matching_types(self): + schema = { + "properties": { + "foo": { + "anyOf": [ + {"type": "array", "minItems": 2}, + {"type": "string", "minLength": 10}, + ], + }, + }, + } + best = self.best_match_of(instance={"foo": "bar"}, schema=schema) + self.assertEqual(best.validator, "minLength") + + reordered = { + "properties": { + "foo": { + "anyOf": [ + {"type": "string", "minLength": 10}, + {"type": "array", "minItems": 2}, + ], + }, + }, + } + best = self.best_match_of(instance={"foo": "bar"}, schema=reordered) + self.assertEqual(best.validator, "minLength") + + def test_it_prioritizes_matching_union_types(self): + schema = { + "properties": { + "foo": { + "anyOf": [ + {"type": ["array", "object"], "minItems": 2}, + {"type": ["integer", "string"], "minLength": 10}, + ], + }, + }, + } + best = self.best_match_of(instance={"foo": "bar"}, schema=schema) + self.assertEqual(best.validator, "minLength") + + reordered = { + "properties": { + "foo": { + "anyOf": [ + {"type": "string", "minLength": 10}, + {"type": "array", "minItems": 2}, + ], + }, + }, + } + best = self.best_match_of(instance={"foo": "bar"}, schema=reordered) + self.assertEqual(best.validator, "minLength") + + def test_boolean_schemas(self): + schema = {"properties": {"foo": False}} + best = self.best_match_of(instance={"foo": "bar"}, schema=schema) + self.assertIsNone(best.validator) + + def test_one_error(self): + validator = _LATEST_VERSION({"minProperties": 2}) + error, = validator.iter_errors({}) + self.assertEqual( + exceptions.best_match(validator.iter_errors({})).validator, + "minProperties", + ) + + def test_no_errors(self): + validator = _LATEST_VERSION({}) + self.assertIsNone(exceptions.best_match(validator.iter_errors({}))) + + +class TestByRelevance(TestCase): + def test_short_paths_are_better_matches(self): + shallow = exceptions.ValidationError("Oh no!", path=["baz"]) + deep = exceptions.ValidationError("Oh yes!", path=["foo", "bar"]) + match = max([shallow, deep], key=exceptions.relevance) + self.assertIs(match, shallow) + + match = max([deep, shallow], key=exceptions.relevance) + self.assertIs(match, shallow) + + def test_global_errors_are_even_better_matches(self): + shallow = exceptions.ValidationError("Oh no!", path=[]) + deep = exceptions.ValidationError("Oh yes!", path=["foo"]) + + errors = sorted([shallow, deep], key=exceptions.relevance) + self.assertEqual( + [list(error.path) for error in errors], + [["foo"], []], + ) + + errors = sorted([deep, shallow], key=exceptions.relevance) + self.assertEqual( + [list(error.path) for error in errors], + [["foo"], []], + ) + + def test_weak_keywords_are_lower_priority(self): + weak = exceptions.ValidationError("Oh no!", path=[], validator="a") + normal = exceptions.ValidationError("Oh yes!", path=[], validator="b") + + best_match = exceptions.by_relevance(weak="a") + + match = max([weak, normal], key=best_match) + self.assertIs(match, normal) + + match = max([normal, weak], key=best_match) + self.assertIs(match, normal) + + def test_strong_keywords_are_higher_priority(self): + weak = exceptions.ValidationError("Oh no!", path=[], validator="a") + normal = exceptions.ValidationError("Oh yes!", path=[], validator="b") + strong = exceptions.ValidationError("Oh fine!", path=[], validator="c") + + best_match = exceptions.by_relevance(weak="a", strong="c") + + match = max([weak, normal, strong], key=best_match) + self.assertIs(match, strong) + + match = max([strong, normal, weak], key=best_match) + self.assertIs(match, strong) + + +class TestErrorTree(TestCase): + def test_it_knows_how_many_total_errors_it_contains(self): + # FIXME: #442 + errors = [ + exceptions.ValidationError("Something", validator=i) + for i in range(8) + ] + tree = exceptions.ErrorTree(errors) + self.assertEqual(tree.total_errors, 8) + + def test_it_contains_an_item_if_the_item_had_an_error(self): + errors = [exceptions.ValidationError("a message", path=["bar"])] + tree = exceptions.ErrorTree(errors) + self.assertIn("bar", tree) + + def test_it_does_not_contain_an_item_if_the_item_had_no_error(self): + errors = [exceptions.ValidationError("a message", path=["bar"])] + tree = exceptions.ErrorTree(errors) + self.assertNotIn("foo", tree) + + def test_keywords_that_failed_appear_in_errors_dict(self): + error = exceptions.ValidationError("a message", validator="foo") + tree = exceptions.ErrorTree([error]) + self.assertEqual(tree.errors, {"foo": error}) + + def test_it_creates_a_child_tree_for_each_nested_path(self): + errors = [ + exceptions.ValidationError("a bar message", path=["bar"]), + exceptions.ValidationError("a bar -> 0 message", path=["bar", 0]), + ] + tree = exceptions.ErrorTree(errors) + self.assertIn(0, tree["bar"]) + self.assertNotIn(1, tree["bar"]) + + def test_children_have_their_errors_dicts_built(self): + e1, e2 = ( + exceptions.ValidationError("1", validator="foo", path=["bar", 0]), + exceptions.ValidationError("2", validator="quux", path=["bar", 0]), + ) + tree = exceptions.ErrorTree([e1, e2]) + self.assertEqual(tree["bar"][0].errors, {"foo": e1, "quux": e2}) + + def test_multiple_errors_with_instance(self): + e1, e2 = ( + exceptions.ValidationError( + "1", + validator="foo", + path=["bar", "bar2"], + instance="i1"), + exceptions.ValidationError( + "2", + validator="quux", + path=["foobar", 2], + instance="i2"), + ) + exceptions.ErrorTree([e1, e2]) + + def test_it_does_not_contain_subtrees_that_are_not_in_the_instance(self): + error = exceptions.ValidationError("123", validator="foo", instance=[]) + tree = exceptions.ErrorTree([error]) + + with self.assertRaises(IndexError): + tree[0] + + def test_if_its_in_the_tree_anyhow_it_does_not_raise_an_error(self): + """ + If a keyword refers to a path that isn't in the instance, the + tree still properly returns a subtree for that path. + """ + + error = exceptions.ValidationError( + "a message", validator="foo", instance={}, path=["foo"], + ) + tree = exceptions.ErrorTree([error]) + self.assertIsInstance(tree["foo"], exceptions.ErrorTree) + + def test_iter(self): + e1, e2 = ( + exceptions.ValidationError( + "1", + validator="foo", + path=["bar", "bar2"], + instance="i1"), + exceptions.ValidationError( + "2", + validator="quux", + path=["foobar", 2], + instance="i2"), + ) + tree = exceptions.ErrorTree([e1, e2]) + self.assertEqual(set(tree), {"bar", "foobar"}) + + def test_repr_single(self): + error = exceptions.ValidationError( + "1", + validator="foo", + path=["bar", "bar2"], + instance="i1", + ) + tree = exceptions.ErrorTree([error]) + self.assertEqual(repr(tree), "") + + def test_repr_multiple(self): + e1, e2 = ( + exceptions.ValidationError( + "1", + validator="foo", + path=["bar", "bar2"], + instance="i1"), + exceptions.ValidationError( + "2", + validator="quux", + path=["foobar", 2], + instance="i2"), + ) + tree = exceptions.ErrorTree([e1, e2]) + self.assertEqual(repr(tree), "") + + def test_repr_empty(self): + tree = exceptions.ErrorTree([]) + self.assertEqual(repr(tree), "") + + +class TestErrorInitReprStr(TestCase): + def make_error(self, **kwargs): + defaults = dict( + message="hello", + validator="type", + validator_value="string", + instance=5, + schema={"type": "string"}, + ) + defaults.update(kwargs) + return exceptions.ValidationError(**defaults) + + def assertShows(self, expected, **kwargs): + expected = textwrap.dedent(expected).rstrip("\n") + + error = self.make_error(**kwargs) + message_line, _, rest = str(error).partition("\n") + self.assertEqual(message_line, error.message) + self.assertEqual(rest, expected) + + def test_it_calls_super_and_sets_args(self): + error = self.make_error() + self.assertGreater(len(error.args), 1) + + def test_repr(self): + self.assertEqual( + repr(exceptions.ValidationError(message="Hello!")), + "", + ) + + def test_unset_error(self): + error = exceptions.ValidationError("message") + self.assertEqual(str(error), "message") + + kwargs = { + "validator": "type", + "validator_value": "string", + "instance": 5, + "schema": {"type": "string"}, + } + # Just the message should show if any of the attributes are unset + for attr in kwargs: + k = dict(kwargs) + del k[attr] + error = exceptions.ValidationError("message", **k) + self.assertEqual(str(error), "message") + + def test_empty_paths(self): + self.assertShows( + """ + Failed validating 'type' in schema: + {'type': 'string'} + + On instance: + 5 + """, + path=[], + schema_path=[], + ) + + def test_one_item_paths(self): + self.assertShows( + """ + Failed validating 'type' in schema: + {'type': 'string'} + + On instance[0]: + 5 + """, + path=[0], + schema_path=["items"], + ) + + def test_multiple_item_paths(self): + self.assertShows( + """ + Failed validating 'type' in schema['items'][0]: + {'type': 'string'} + + On instance[0]['a']: + 5 + """, + path=[0, "a"], + schema_path=["items", 0, 1], + ) + + def test_uses_pprint(self): + self.assertShows( + """ + Failed validating 'maxLength' in schema: + {0: 0, + 1: 1, + 2: 2, + 3: 3, + 4: 4, + 5: 5, + 6: 6, + 7: 7, + 8: 8, + 9: 9, + 10: 10, + 11: 11, + 12: 12, + 13: 13, + 14: 14, + 15: 15, + 16: 16, + 17: 17, + 18: 18, + 19: 19} + + On instance: + [0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24] + """, + instance=list(range(25)), + schema=dict(zip(range(20), range(20))), + validator="maxLength", + ) + + def test_does_not_reorder_dicts(self): + self.assertShows( + """ + Failed validating 'type' in schema: + {'do': 3, 'not': 7, 'sort': 37, 'me': 73} + + On instance: + {'here': 73, 'too': 37, 'no': 7, 'sorting': 3} + """, + schema={ + "do": 3, + "not": 7, + "sort": 37, + "me": 73, + }, + instance={ + "here": 73, + "too": 37, + "no": 7, + "sorting": 3, + }, + ) + + def test_str_works_with_instances_having_overriden_eq_operator(self): + """ + Check for #164 which rendered exceptions unusable when a + `ValidationError` involved instances with an `__eq__` method + that returned truthy values. + """ + + class DontEQMeBro: + def __eq__(this, other): # pragma: no cover + self.fail("Don't!") + + def __ne__(this, other): # pragma: no cover + self.fail("Don't!") + + instance = DontEQMeBro() + error = exceptions.ValidationError( + "a message", + validator="foo", + instance=instance, + validator_value="some", + schema="schema", + ) + self.assertIn(repr(instance), str(error)) + + +class TestHashable(TestCase): + def test_hashable(self): + {exceptions.ValidationError("")} + {exceptions.SchemaError("")} + + +class TestJsonPathRendering(TestCase): + def validate_json_path_rendering(self, property_name, expected_path): + error = exceptions.ValidationError( + path=[property_name], + message="1", + validator="foo", + instance="i1", + ) + + rendered_json_path = error.json_path + self.assertEqual(rendered_json_path, expected_path) + + re_parsed_name = jsonpath_ng.parse(rendered_json_path).right.fields[0] + self.assertEqual(re_parsed_name, property_name) + + def test_basic(self): + self.validate_json_path_rendering("x", "$.x") + + def test_empty(self): + self.validate_json_path_rendering("", "$['']") + + def test_number(self): + self.validate_json_path_rendering("1", "$['1']") + + def test_period(self): + self.validate_json_path_rendering(".", "$['.']") + + def test_single_quote(self): + self.validate_json_path_rendering("'", r"$['\'']") + + def test_space(self): + self.validate_json_path_rendering(" ", "$[' ']") + + def test_backslash(self): + self.validate_json_path_rendering("\\", r"$['\\']") + + def test_backslash_single_quote(self): + self.validate_json_path_rendering(r"\'", r"$['\\\'']") + + def test_underscore(self): + self.validate_json_path_rendering("_", r"$['_']") + + def test_double_quote(self): + self.validate_json_path_rendering('"', """$['"']""") + + def test_hyphen(self): + self.validate_json_path_rendering("-", "$['-']") + + def test_json_path_injection(self): + self.validate_json_path_rendering("a[0]", "$['a[0]']") + + def test_open_bracket(self): + self.validate_json_path_rendering("[", "$['[']") diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_format.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_format.py new file mode 100644 index 0000000000000000000000000000000000000000..d829f9848f51f882d5a3f9413c80e0dbdcdaf292 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_format.py @@ -0,0 +1,91 @@ +""" +Tests for the parts of jsonschema related to the :kw:`format` keyword. +""" + +from unittest import TestCase + +from jsonschema import FormatChecker, ValidationError +from jsonschema.exceptions import FormatError +from jsonschema.validators import Draft4Validator + +BOOM = ValueError("Boom!") +BANG = ZeroDivisionError("Bang!") + + +def boom(thing): + if thing == "bang": + raise BANG + raise BOOM + + +class TestFormatChecker(TestCase): + def test_it_can_validate_no_formats(self): + checker = FormatChecker(formats=()) + self.assertFalse(checker.checkers) + + def test_it_raises_a_key_error_for_unknown_formats(self): + with self.assertRaises(KeyError): + FormatChecker(formats=["o noes"]) + + def test_it_can_register_cls_checkers(self): + original = dict(FormatChecker.checkers) + self.addCleanup(FormatChecker.checkers.pop, "boom") + with self.assertWarns(DeprecationWarning): + FormatChecker.cls_checks("boom")(boom) + self.assertEqual( + FormatChecker.checkers, + dict(original, boom=(boom, ())), + ) + + def test_it_can_register_checkers(self): + checker = FormatChecker() + checker.checks("boom")(boom) + self.assertEqual( + checker.checkers, + dict(FormatChecker.checkers, boom=(boom, ())), + ) + + def test_it_catches_registered_errors(self): + checker = FormatChecker() + checker.checks("boom", raises=type(BOOM))(boom) + + with self.assertRaises(FormatError) as cm: + checker.check(instance=12, format="boom") + + self.assertIs(cm.exception.cause, BOOM) + self.assertIs(cm.exception.__cause__, BOOM) + self.assertEqual(str(cm.exception), "12 is not a 'boom'") + + # Unregistered errors should not be caught + with self.assertRaises(type(BANG)): + checker.check(instance="bang", format="boom") + + def test_format_error_causes_become_validation_error_causes(self): + checker = FormatChecker() + checker.checks("boom", raises=ValueError)(boom) + validator = Draft4Validator({"format": "boom"}, format_checker=checker) + + with self.assertRaises(ValidationError) as cm: + validator.validate("BOOM") + + self.assertIs(cm.exception.cause, BOOM) + self.assertIs(cm.exception.__cause__, BOOM) + + def test_format_checkers_come_with_defaults(self): + # This is bad :/ but relied upon. + # The docs for quite awhile recommended people do things like + # validate(..., format_checker=FormatChecker()) + # We should change that, but we can't without deprecation... + checker = FormatChecker() + with self.assertRaises(FormatError): + checker.check(instance="not-an-ipv4", format="ipv4") + + def test_repr(self): + checker = FormatChecker(formats=()) + checker.checks("foo")(lambda thing: True) # pragma: no cover + checker.checks("bar")(lambda thing: True) # pragma: no cover + checker.checks("baz")(lambda thing: True) # pragma: no cover + self.assertEqual( + repr(checker), + "", + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_jsonschema_test_suite.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_jsonschema_test_suite.py new file mode 100644 index 0000000000000000000000000000000000000000..41c982553688ab179dcb95eedc3aae78648e2a4d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_jsonschema_test_suite.py @@ -0,0 +1,262 @@ +""" +Test runner for the JSON Schema official test suite + +Tests comprehensive correctness of each draft's validator. + +See https://github.com/json-schema-org/JSON-Schema-Test-Suite for details. +""" + + +from jsonschema.tests._suite import Suite +import jsonschema + +SUITE = Suite() +DRAFT3 = SUITE.version(name="draft3") +DRAFT4 = SUITE.version(name="draft4") +DRAFT6 = SUITE.version(name="draft6") +DRAFT7 = SUITE.version(name="draft7") +DRAFT201909 = SUITE.version(name="draft2019-09") +DRAFT202012 = SUITE.version(name="draft2020-12") + + +def skip(message, **kwargs): + def skipper(test): + if all(value == getattr(test, attr) for attr, value in kwargs.items()): + return message + return skipper + + +def ecmascript_regex(test): + if test.subject == "ecmascript-regex": + return "ECMA regex support will be added in #1142." + + +def missing_format(Validator): + def missing_format(test): # pragma: no cover + schema = test.schema + if ( + schema is True + or schema is False + or "format" not in schema + or schema["format"] in Validator.FORMAT_CHECKER.checkers + or test.valid + ): + return + + return f"Format checker {schema['format']!r} not found." + return missing_format + + +def complex_email_validation(test): + if test.subject != "email": + return + + message = "Complex email validation is (intentionally) unsupported." + return skip( + message=message, + description="an invalid domain", + )(test) or skip( + message=message, + description="an invalid IPv4-address-literal", + )(test) or skip( + message=message, + description="dot after local part is not valid", + )(test) or skip( + message=message, + description="dot before local part is not valid", + )(test) or skip( + message=message, + description="two subsequent dots inside local part are not valid", + )(test) + + +def leap_second(test): + message = "Leap seconds are unsupported." + return skip( + message=message, + subject="time", + description="a valid time string with leap second", + )(test) or skip( + message=message, + subject="time", + description="a valid time string with leap second, Zulu", + )(test) or skip( + message=message, + subject="time", + description="a valid time string with leap second with offset", + )(test) or skip( + message=message, + subject="time", + description="valid leap second, positive time-offset", + )(test) or skip( + message=message, + subject="time", + description="valid leap second, negative time-offset", + )(test) or skip( + message=message, + subject="time", + description="valid leap second, large positive time-offset", + )(test) or skip( + message=message, + subject="time", + description="valid leap second, large negative time-offset", + )(test) or skip( + message=message, + subject="time", + description="valid leap second, zero time-offset", + )(test) or skip( + message=message, + subject="date-time", + description="a valid date-time with a leap second, UTC", + )(test) or skip( + message=message, + subject="date-time", + description="a valid date-time with a leap second, with minus offset", + )(test) + + +TestDraft3 = DRAFT3.to_unittest_testcase( + DRAFT3.cases(), + DRAFT3.format_cases(), + DRAFT3.optional_cases_of(name="bignum"), + DRAFT3.optional_cases_of(name="non-bmp-regex"), + DRAFT3.optional_cases_of(name="zeroTerminatedFloats"), + Validator=jsonschema.Draft3Validator, + format_checker=jsonschema.Draft3Validator.FORMAT_CHECKER, + skip=lambda test: ( + ecmascript_regex(test) + or missing_format(jsonschema.Draft3Validator)(test) + or complex_email_validation(test) + ), +) + + +TestDraft4 = DRAFT4.to_unittest_testcase( + DRAFT4.cases(), + DRAFT4.format_cases(), + DRAFT4.optional_cases_of(name="bignum"), + DRAFT4.optional_cases_of(name="float-overflow"), + DRAFT4.optional_cases_of(name="id"), + DRAFT4.optional_cases_of(name="non-bmp-regex"), + DRAFT4.optional_cases_of(name="zeroTerminatedFloats"), + Validator=jsonschema.Draft4Validator, + format_checker=jsonschema.Draft4Validator.FORMAT_CHECKER, + skip=lambda test: ( + ecmascript_regex(test) + or leap_second(test) + or missing_format(jsonschema.Draft4Validator)(test) + or complex_email_validation(test) + ), +) + + +TestDraft6 = DRAFT6.to_unittest_testcase( + DRAFT6.cases(), + DRAFT6.format_cases(), + DRAFT6.optional_cases_of(name="bignum"), + DRAFT6.optional_cases_of(name="float-overflow"), + DRAFT6.optional_cases_of(name="id"), + DRAFT6.optional_cases_of(name="non-bmp-regex"), + Validator=jsonschema.Draft6Validator, + format_checker=jsonschema.Draft6Validator.FORMAT_CHECKER, + skip=lambda test: ( + ecmascript_regex(test) + or leap_second(test) + or missing_format(jsonschema.Draft6Validator)(test) + or complex_email_validation(test) + ), +) + + +TestDraft7 = DRAFT7.to_unittest_testcase( + DRAFT7.cases(), + DRAFT7.format_cases(), + DRAFT7.optional_cases_of(name="bignum"), + DRAFT7.optional_cases_of(name="cross-draft"), + DRAFT7.optional_cases_of(name="float-overflow"), + DRAFT6.optional_cases_of(name="id"), + DRAFT7.optional_cases_of(name="non-bmp-regex"), + DRAFT7.optional_cases_of(name="unknownKeyword"), + Validator=jsonschema.Draft7Validator, + format_checker=jsonschema.Draft7Validator.FORMAT_CHECKER, + skip=lambda test: ( + ecmascript_regex(test) + or leap_second(test) + or missing_format(jsonschema.Draft7Validator)(test) + or complex_email_validation(test) + ), +) + + +TestDraft201909 = DRAFT201909.to_unittest_testcase( + DRAFT201909.cases(), + DRAFT201909.optional_cases_of(name="anchor"), + DRAFT201909.optional_cases_of(name="bignum"), + DRAFT201909.optional_cases_of(name="cross-draft"), + DRAFT201909.optional_cases_of(name="float-overflow"), + DRAFT201909.optional_cases_of(name="id"), + DRAFT201909.optional_cases_of(name="no-schema"), + DRAFT201909.optional_cases_of(name="non-bmp-regex"), + DRAFT201909.optional_cases_of(name="refOfUnknownKeyword"), + DRAFT201909.optional_cases_of(name="unknownKeyword"), + Validator=jsonschema.Draft201909Validator, + skip=skip( + message="Vocabulary support is still in-progress.", + subject="vocabulary", + description=( + "no validation: invalid number, but it still validates" + ), + ), +) + + +TestDraft201909Format = DRAFT201909.to_unittest_testcase( + DRAFT201909.format_cases(), + name="TestDraft201909Format", + Validator=jsonschema.Draft201909Validator, + format_checker=jsonschema.Draft201909Validator.FORMAT_CHECKER, + skip=lambda test: ( + complex_email_validation(test) + or ecmascript_regex(test) + or leap_second(test) + or missing_format(jsonschema.Draft201909Validator)(test) + or complex_email_validation(test) + ), +) + + +TestDraft202012 = DRAFT202012.to_unittest_testcase( + DRAFT202012.cases(), + DRAFT201909.optional_cases_of(name="anchor"), + DRAFT202012.optional_cases_of(name="bignum"), + DRAFT202012.optional_cases_of(name="cross-draft"), + DRAFT202012.optional_cases_of(name="float-overflow"), + DRAFT202012.optional_cases_of(name="id"), + DRAFT202012.optional_cases_of(name="no-schema"), + DRAFT202012.optional_cases_of(name="non-bmp-regex"), + DRAFT202012.optional_cases_of(name="refOfUnknownKeyword"), + DRAFT202012.optional_cases_of(name="unknownKeyword"), + Validator=jsonschema.Draft202012Validator, + skip=skip( + message="Vocabulary support is still in-progress.", + subject="vocabulary", + description=( + "no validation: invalid number, but it still validates" + ), + ), +) + + +TestDraft202012Format = DRAFT202012.to_unittest_testcase( + DRAFT202012.format_cases(), + name="TestDraft202012Format", + Validator=jsonschema.Draft202012Validator, + format_checker=jsonschema.Draft202012Validator.FORMAT_CHECKER, + skip=lambda test: ( + complex_email_validation(test) + or ecmascript_regex(test) + or leap_second(test) + or missing_format(jsonschema.Draft202012Validator)(test) + or complex_email_validation(test) + ), +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_types.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_types.py new file mode 100644 index 0000000000000000000000000000000000000000..bd97b180029ae05d7f3b22f1048f9adcb769f36f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_types.py @@ -0,0 +1,221 @@ +""" +Tests for the `TypeChecker`-based type interface. + +The actual correctness of the type checking is handled in +`test_jsonschema_test_suite`; these tests check that TypeChecker +functions correctly at a more granular level. +""" +from collections import namedtuple +from unittest import TestCase + +from jsonschema import ValidationError, _keywords +from jsonschema._types import TypeChecker +from jsonschema.exceptions import UndefinedTypeCheck, UnknownType +from jsonschema.validators import Draft202012Validator, extend + + +def equals_2(checker, instance): + return instance == 2 + + +def is_namedtuple(instance): + return isinstance(instance, tuple) and getattr(instance, "_fields", None) + + +def is_object_or_named_tuple(checker, instance): + if Draft202012Validator.TYPE_CHECKER.is_type(instance, "object"): + return True + return is_namedtuple(instance) + + +class TestTypeChecker(TestCase): + def test_is_type(self): + checker = TypeChecker({"two": equals_2}) + self.assertEqual( + ( + checker.is_type(instance=2, type="two"), + checker.is_type(instance="bar", type="two"), + ), + (True, False), + ) + + def test_is_unknown_type(self): + with self.assertRaises(UndefinedTypeCheck) as e: + TypeChecker().is_type(4, "foobar") + self.assertIn( + "'foobar' is unknown to this type checker", + str(e.exception), + ) + self.assertTrue( + e.exception.__suppress_context__, + msg="Expected the internal KeyError to be hidden.", + ) + + def test_checks_can_be_added_at_init(self): + checker = TypeChecker({"two": equals_2}) + self.assertEqual(checker, TypeChecker().redefine("two", equals_2)) + + def test_redefine_existing_type(self): + self.assertEqual( + TypeChecker().redefine("two", object()).redefine("two", equals_2), + TypeChecker().redefine("two", equals_2), + ) + + def test_remove(self): + self.assertEqual( + TypeChecker({"two": equals_2}).remove("two"), + TypeChecker(), + ) + + def test_remove_unknown_type(self): + with self.assertRaises(UndefinedTypeCheck) as context: + TypeChecker().remove("foobar") + self.assertIn("foobar", str(context.exception)) + + def test_redefine_many(self): + self.assertEqual( + TypeChecker().redefine_many({"foo": int, "bar": str}), + TypeChecker().redefine("foo", int).redefine("bar", str), + ) + + def test_remove_multiple(self): + self.assertEqual( + TypeChecker({"foo": int, "bar": str}).remove("foo", "bar"), + TypeChecker(), + ) + + def test_type_check_can_raise_key_error(self): + """ + Make sure no one writes: + + try: + self._type_checkers[type](...) + except KeyError: + + ignoring the fact that the function itself can raise that. + """ + + error = KeyError("Stuff") + + def raises_keyerror(checker, instance): + raise error + + with self.assertRaises(KeyError) as context: + TypeChecker({"foo": raises_keyerror}).is_type(4, "foo") + + self.assertIs(context.exception, error) + + def test_repr(self): + checker = TypeChecker({"foo": is_namedtuple, "bar": is_namedtuple}) + self.assertEqual(repr(checker), "") + + +class TestCustomTypes(TestCase): + def test_simple_type_can_be_extended(self): + def int_or_str_int(checker, instance): + if not isinstance(instance, (int, str)): + return False + try: + int(instance) + except ValueError: + return False + return True + + CustomValidator = extend( + Draft202012Validator, + type_checker=Draft202012Validator.TYPE_CHECKER.redefine( + "integer", int_or_str_int, + ), + ) + validator = CustomValidator({"type": "integer"}) + + validator.validate(4) + validator.validate("4") + + with self.assertRaises(ValidationError): + validator.validate(4.4) + + with self.assertRaises(ValidationError): + validator.validate("foo") + + def test_object_can_be_extended(self): + schema = {"type": "object"} + + Point = namedtuple("Point", ["x", "y"]) + + type_checker = Draft202012Validator.TYPE_CHECKER.redefine( + "object", is_object_or_named_tuple, + ) + + CustomValidator = extend( + Draft202012Validator, + type_checker=type_checker, + ) + validator = CustomValidator(schema) + + validator.validate(Point(x=4, y=5)) + + def test_object_extensions_require_custom_validators(self): + schema = {"type": "object", "required": ["x"]} + + type_checker = Draft202012Validator.TYPE_CHECKER.redefine( + "object", is_object_or_named_tuple, + ) + + CustomValidator = extend( + Draft202012Validator, + type_checker=type_checker, + ) + validator = CustomValidator(schema) + + Point = namedtuple("Point", ["x", "y"]) + # Cannot handle required + with self.assertRaises(ValidationError): + validator.validate(Point(x=4, y=5)) + + def test_object_extensions_can_handle_custom_validators(self): + schema = { + "type": "object", + "required": ["x"], + "properties": {"x": {"type": "integer"}}, + } + + type_checker = Draft202012Validator.TYPE_CHECKER.redefine( + "object", is_object_or_named_tuple, + ) + + def coerce_named_tuple(fn): + def coerced(validator, value, instance, schema): + if is_namedtuple(instance): + instance = instance._asdict() + return fn(validator, value, instance, schema) + return coerced + + required = coerce_named_tuple(_keywords.required) + properties = coerce_named_tuple(_keywords.properties) + + CustomValidator = extend( + Draft202012Validator, + type_checker=type_checker, + validators={"required": required, "properties": properties}, + ) + + validator = CustomValidator(schema) + + Point = namedtuple("Point", ["x", "y"]) + # Can now process required and properties + validator.validate(Point(x=4, y=5)) + + with self.assertRaises(ValidationError): + validator.validate(Point(x="not an integer", y=5)) + + # As well as still handle objects. + validator.validate({"x": 4, "y": 5}) + + with self.assertRaises(ValidationError): + validator.validate({"x": "not an integer", "y": 5}) + + def test_unknown_type(self): + with self.assertRaises(UnknownType) as e: + Draft202012Validator({}).is_type(12, "some unknown type") + self.assertIn("'some unknown type'", str(e.exception)) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_utils.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d9764b0f9e92edb38c19e1fc43b248a20186ef6b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_utils.py @@ -0,0 +1,138 @@ +from math import nan +from unittest import TestCase + +from jsonschema._utils import equal + + +class TestEqual(TestCase): + def test_none(self): + self.assertTrue(equal(None, None)) + + def test_nan(self): + self.assertTrue(equal(nan, nan)) + + +class TestDictEqual(TestCase): + def test_equal_dictionaries(self): + dict_1 = {"a": "b", "c": "d"} + dict_2 = {"c": "d", "a": "b"} + self.assertTrue(equal(dict_1, dict_2)) + + def test_equal_dictionaries_with_nan(self): + dict_1 = {"a": nan, "c": "d"} + dict_2 = {"c": "d", "a": nan} + self.assertTrue(equal(dict_1, dict_2)) + + def test_missing_key(self): + dict_1 = {"a": "b", "c": "d"} + dict_2 = {"c": "d", "x": "b"} + self.assertFalse(equal(dict_1, dict_2)) + + def test_additional_key(self): + dict_1 = {"a": "b", "c": "d"} + dict_2 = {"c": "d", "a": "b", "x": "x"} + self.assertFalse(equal(dict_1, dict_2)) + + def test_missing_value(self): + dict_1 = {"a": "b", "c": "d"} + dict_2 = {"c": "d", "a": "x"} + self.assertFalse(equal(dict_1, dict_2)) + + def test_empty_dictionaries(self): + dict_1 = {} + dict_2 = {} + self.assertTrue(equal(dict_1, dict_2)) + + def test_one_none(self): + dict_1 = None + dict_2 = {"a": "b", "c": "d"} + self.assertFalse(equal(dict_1, dict_2)) + + def test_same_item(self): + dict_1 = {"a": "b", "c": "d"} + self.assertTrue(equal(dict_1, dict_1)) + + def test_nested_equal(self): + dict_1 = {"a": {"a": "b", "c": "d"}, "c": "d"} + dict_2 = {"c": "d", "a": {"a": "b", "c": "d"}} + self.assertTrue(equal(dict_1, dict_2)) + + def test_nested_dict_unequal(self): + dict_1 = {"a": {"a": "b", "c": "d"}, "c": "d"} + dict_2 = {"c": "d", "a": {"a": "b", "c": "x"}} + self.assertFalse(equal(dict_1, dict_2)) + + def test_mixed_nested_equal(self): + dict_1 = {"a": ["a", "b", "c", "d"], "c": "d"} + dict_2 = {"c": "d", "a": ["a", "b", "c", "d"]} + self.assertTrue(equal(dict_1, dict_2)) + + def test_nested_list_unequal(self): + dict_1 = {"a": ["a", "b", "c", "d"], "c": "d"} + dict_2 = {"c": "d", "a": ["b", "c", "d", "a"]} + self.assertFalse(equal(dict_1, dict_2)) + + +class TestListEqual(TestCase): + def test_equal_lists(self): + list_1 = ["a", "b", "c"] + list_2 = ["a", "b", "c"] + self.assertTrue(equal(list_1, list_2)) + + def test_equal_lists_with_nan(self): + list_1 = ["a", nan, "c"] + list_2 = ["a", nan, "c"] + self.assertTrue(equal(list_1, list_2)) + + def test_unsorted_lists(self): + list_1 = ["a", "b", "c"] + list_2 = ["b", "b", "a"] + self.assertFalse(equal(list_1, list_2)) + + def test_first_list_larger(self): + list_1 = ["a", "b", "c"] + list_2 = ["a", "b"] + self.assertFalse(equal(list_1, list_2)) + + def test_second_list_larger(self): + list_1 = ["a", "b"] + list_2 = ["a", "b", "c"] + self.assertFalse(equal(list_1, list_2)) + + def test_list_with_none_unequal(self): + list_1 = ["a", "b", None] + list_2 = ["a", "b", "c"] + self.assertFalse(equal(list_1, list_2)) + + list_1 = ["a", "b", None] + list_2 = [None, "b", "c"] + self.assertFalse(equal(list_1, list_2)) + + def test_list_with_none_equal(self): + list_1 = ["a", None, "c"] + list_2 = ["a", None, "c"] + self.assertTrue(equal(list_1, list_2)) + + def test_empty_list(self): + list_1 = [] + list_2 = [] + self.assertTrue(equal(list_1, list_2)) + + def test_one_none(self): + list_1 = None + list_2 = [] + self.assertFalse(equal(list_1, list_2)) + + def test_same_list(self): + list_1 = ["a", "b", "c"] + self.assertTrue(equal(list_1, list_1)) + + def test_equal_nested_lists(self): + list_1 = ["a", ["b", "c"], "d"] + list_2 = ["a", ["b", "c"], "d"] + self.assertTrue(equal(list_1, list_2)) + + def test_unequal_nested_lists(self): + list_1 = ["a", ["b", "c"], "d"] + list_2 = ["a", [], "c"] + self.assertFalse(equal(list_1, list_2)) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_validators.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_validators.py new file mode 100644 index 0000000000000000000000000000000000000000..28cc4027372c10df1d071eb656102b3b81bc5ecc --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/test_validators.py @@ -0,0 +1,2575 @@ +from __future__ import annotations + +from collections import deque, namedtuple +from contextlib import contextmanager +from decimal import Decimal +from io import BytesIO +from typing import Any +from unittest import TestCase, mock +from urllib.request import pathname2url +import json +import os +import sys +import tempfile +import warnings + +from attrs import define, field +from referencing.jsonschema import DRAFT202012 +import referencing.exceptions + +from jsonschema import ( + FormatChecker, + TypeChecker, + exceptions, + protocols, + validators, +) + + +def fail(validator, errors, instance, schema): + for each in errors: + each.setdefault("message", "You told me to fail!") + yield exceptions.ValidationError(**each) + + +class TestCreateAndExtend(TestCase): + def setUp(self): + self.addCleanup( + self.assertEqual, + validators._META_SCHEMAS, + dict(validators._META_SCHEMAS), + ) + self.addCleanup( + self.assertEqual, + validators._VALIDATORS, + dict(validators._VALIDATORS), + ) + + self.meta_schema = {"$id": "some://meta/schema"} + self.validators = {"fail": fail} + self.type_checker = TypeChecker() + self.Validator = validators.create( + meta_schema=self.meta_schema, + validators=self.validators, + type_checker=self.type_checker, + ) + + def test_attrs(self): + self.assertEqual( + ( + self.Validator.VALIDATORS, + self.Validator.META_SCHEMA, + self.Validator.TYPE_CHECKER, + ), ( + self.validators, + self.meta_schema, + self.type_checker, + ), + ) + + def test_init(self): + schema = {"fail": []} + self.assertEqual(self.Validator(schema).schema, schema) + + def test_iter_errors_successful(self): + schema = {"fail": []} + validator = self.Validator(schema) + + errors = list(validator.iter_errors("hello")) + self.assertEqual(errors, []) + + def test_iter_errors_one_error(self): + schema = {"fail": [{"message": "Whoops!"}]} + validator = self.Validator(schema) + + expected_error = exceptions.ValidationError( + "Whoops!", + instance="goodbye", + schema=schema, + validator="fail", + validator_value=[{"message": "Whoops!"}], + schema_path=deque(["fail"]), + ) + + errors = list(validator.iter_errors("goodbye")) + self.assertEqual(len(errors), 1) + self.assertEqual(errors[0]._contents(), expected_error._contents()) + + def test_iter_errors_multiple_errors(self): + schema = { + "fail": [ + {"message": "First"}, + {"message": "Second!", "validator": "asdf"}, + {"message": "Third"}, + ], + } + validator = self.Validator(schema) + + errors = list(validator.iter_errors("goodbye")) + self.assertEqual(len(errors), 3) + + def test_if_a_version_is_provided_it_is_registered(self): + Validator = validators.create( + meta_schema={"$id": "something"}, + version="my version", + ) + self.addCleanup(validators._META_SCHEMAS.pop, "something") + self.addCleanup(validators._VALIDATORS.pop, "my version") + self.assertEqual(Validator.__name__, "MyVersionValidator") + self.assertEqual(Validator.__qualname__, "MyVersionValidator") + + def test_repr(self): + Validator = validators.create( + meta_schema={"$id": "something"}, + version="my version", + ) + self.addCleanup(validators._META_SCHEMAS.pop, "something") + self.addCleanup(validators._VALIDATORS.pop, "my version") + self.assertEqual( + repr(Validator({})), + "MyVersionValidator(schema={}, format_checker=None)", + ) + + def test_long_repr(self): + Validator = validators.create( + meta_schema={"$id": "something"}, + version="my version", + ) + self.addCleanup(validators._META_SCHEMAS.pop, "something") + self.addCleanup(validators._VALIDATORS.pop, "my version") + self.assertEqual( + repr(Validator({"a": list(range(1000))})), ( + "MyVersionValidator(schema={'a': [0, 1, 2, 3, 4, 5, ...]}, " + "format_checker=None)" + ), + ) + + def test_repr_no_version(self): + Validator = validators.create(meta_schema={}) + self.assertEqual( + repr(Validator({})), + "Validator(schema={}, format_checker=None)", + ) + + def test_dashes_are_stripped_from_validator_names(self): + Validator = validators.create( + meta_schema={"$id": "something"}, + version="foo-bar", + ) + self.addCleanup(validators._META_SCHEMAS.pop, "something") + self.addCleanup(validators._VALIDATORS.pop, "foo-bar") + self.assertEqual(Validator.__qualname__, "FooBarValidator") + + def test_if_a_version_is_not_provided_it_is_not_registered(self): + original = dict(validators._META_SCHEMAS) + validators.create(meta_schema={"id": "id"}) + self.assertEqual(validators._META_SCHEMAS, original) + + def test_validates_registers_meta_schema_id(self): + meta_schema_key = "meta schema id" + my_meta_schema = {"id": meta_schema_key} + + validators.create( + meta_schema=my_meta_schema, + version="my version", + id_of=lambda s: s.get("id", ""), + ) + self.addCleanup(validators._META_SCHEMAS.pop, meta_schema_key) + self.addCleanup(validators._VALIDATORS.pop, "my version") + + self.assertIn(meta_schema_key, validators._META_SCHEMAS) + + def test_validates_registers_meta_schema_draft6_id(self): + meta_schema_key = "meta schema $id" + my_meta_schema = {"$id": meta_schema_key} + + validators.create( + meta_schema=my_meta_schema, + version="my version", + ) + self.addCleanup(validators._META_SCHEMAS.pop, meta_schema_key) + self.addCleanup(validators._VALIDATORS.pop, "my version") + + self.assertIn(meta_schema_key, validators._META_SCHEMAS) + + def test_create_default_types(self): + Validator = validators.create(meta_schema={}, validators=()) + self.assertTrue( + all( + Validator({}).is_type(instance=instance, type=type) + for type, instance in [ + ("array", []), + ("boolean", True), + ("integer", 12), + ("null", None), + ("number", 12.0), + ("object", {}), + ("string", "foo"), + ] + ), + ) + + def test_check_schema_with_different_metaschema(self): + """ + One can create a validator class whose metaschema uses a different + dialect than itself. + """ + + NoEmptySchemasValidator = validators.create( + meta_schema={ + "$schema": validators.Draft202012Validator.META_SCHEMA["$id"], + "not": {"const": {}}, + }, + ) + NoEmptySchemasValidator.check_schema({"foo": "bar"}) + + with self.assertRaises(exceptions.SchemaError): + NoEmptySchemasValidator.check_schema({}) + + NoEmptySchemasValidator({"foo": "bar"}).validate("foo") + + def test_check_schema_with_different_metaschema_defaults_to_self(self): + """ + A validator whose metaschema doesn't declare $schema defaults to its + own validation behavior, not the latest "normal" specification. + """ + + NoEmptySchemasValidator = validators.create( + meta_schema={"fail": [{"message": "Meta schema whoops!"}]}, + validators={"fail": fail}, + ) + with self.assertRaises(exceptions.SchemaError): + NoEmptySchemasValidator.check_schema({}) + + def test_extend(self): + original = dict(self.Validator.VALIDATORS) + new = object() + + Extended = validators.extend( + self.Validator, + validators={"new": new}, + ) + self.assertEqual( + ( + Extended.VALIDATORS, + Extended.META_SCHEMA, + Extended.TYPE_CHECKER, + self.Validator.VALIDATORS, + ), ( + dict(original, new=new), + self.Validator.META_SCHEMA, + self.Validator.TYPE_CHECKER, + original, + ), + ) + + def test_extend_idof(self): + """ + Extending a validator preserves its notion of schema IDs. + """ + def id_of(schema): + return schema.get("__test__", self.Validator.ID_OF(schema)) + correct_id = "the://correct/id/" + meta_schema = { + "$id": "the://wrong/id/", + "__test__": correct_id, + } + Original = validators.create( + meta_schema=meta_schema, + validators=self.validators, + type_checker=self.type_checker, + id_of=id_of, + ) + self.assertEqual(Original.ID_OF(Original.META_SCHEMA), correct_id) + + Derived = validators.extend(Original) + self.assertEqual(Derived.ID_OF(Derived.META_SCHEMA), correct_id) + + def test_extend_applicable_validators(self): + """ + Extending a validator preserves its notion of applicable validators. + """ + + schema = { + "$defs": {"test": {"type": "number"}}, + "$ref": "#/$defs/test", + "maximum": 1, + } + + draft4 = validators.Draft4Validator(schema) + self.assertTrue(draft4.is_valid(37)) # as $ref ignores siblings + + Derived = validators.extend(validators.Draft4Validator) + self.assertTrue(Derived(schema).is_valid(37)) + + +class TestValidationErrorMessages(TestCase): + def message_for(self, instance, schema, *args, **kwargs): + cls = kwargs.pop("cls", validators._LATEST_VERSION) + cls.check_schema(schema) + validator = cls(schema, *args, **kwargs) + errors = list(validator.iter_errors(instance)) + self.assertTrue(errors, msg=f"No errors were raised for {instance!r}") + self.assertEqual( + len(errors), + 1, + msg=f"Expected exactly one error, found {errors!r}", + ) + return errors[0].message + + def test_single_type_failure(self): + message = self.message_for(instance=1, schema={"type": "string"}) + self.assertEqual(message, "1 is not of type 'string'") + + def test_single_type_list_failure(self): + message = self.message_for(instance=1, schema={"type": ["string"]}) + self.assertEqual(message, "1 is not of type 'string'") + + def test_multiple_type_failure(self): + types = "string", "object" + message = self.message_for(instance=1, schema={"type": list(types)}) + self.assertEqual(message, "1 is not of type 'string', 'object'") + + def test_object_with_named_type_failure(self): + schema = {"type": [{"name": "Foo", "minimum": 3}]} + message = self.message_for( + instance=1, + schema=schema, + cls=validators.Draft3Validator, + ) + self.assertEqual(message, "1 is not of type 'Foo'") + + def test_minimum(self): + message = self.message_for(instance=1, schema={"minimum": 2}) + self.assertEqual(message, "1 is less than the minimum of 2") + + def test_maximum(self): + message = self.message_for(instance=1, schema={"maximum": 0}) + self.assertEqual(message, "1 is greater than the maximum of 0") + + def test_dependencies_single_element(self): + depend, on = "bar", "foo" + schema = {"dependencies": {depend: on}} + message = self.message_for( + instance={"bar": 2}, + schema=schema, + cls=validators.Draft3Validator, + ) + self.assertEqual(message, "'foo' is a dependency of 'bar'") + + def test_object_without_title_type_failure_draft3(self): + type = {"type": [{"minimum": 3}]} + message = self.message_for( + instance=1, + schema={"type": [type]}, + cls=validators.Draft3Validator, + ) + self.assertEqual( + message, + "1 is not of type {'type': [{'minimum': 3}]}", + ) + + def test_dependencies_list_draft3(self): + depend, on = "bar", "foo" + schema = {"dependencies": {depend: [on]}} + message = self.message_for( + instance={"bar": 2}, + schema=schema, + cls=validators.Draft3Validator, + ) + self.assertEqual(message, "'foo' is a dependency of 'bar'") + + def test_dependencies_list_draft7(self): + depend, on = "bar", "foo" + schema = {"dependencies": {depend: [on]}} + message = self.message_for( + instance={"bar": 2}, + schema=schema, + cls=validators.Draft7Validator, + ) + self.assertEqual(message, "'foo' is a dependency of 'bar'") + + def test_additionalItems_single_failure(self): + message = self.message_for( + instance=[2], + schema={"items": [], "additionalItems": False}, + cls=validators.Draft3Validator, + ) + self.assertIn("(2 was unexpected)", message) + + def test_additionalItems_multiple_failures(self): + message = self.message_for( + instance=[1, 2, 3], + schema={"items": [], "additionalItems": False}, + cls=validators.Draft3Validator, + ) + self.assertIn("(1, 2, 3 were unexpected)", message) + + def test_additionalProperties_single_failure(self): + additional = "foo" + schema = {"additionalProperties": False} + message = self.message_for(instance={additional: 2}, schema=schema) + self.assertIn("('foo' was unexpected)", message) + + def test_additionalProperties_multiple_failures(self): + schema = {"additionalProperties": False} + message = self.message_for( + instance=dict.fromkeys(["foo", "bar"]), + schema=schema, + ) + + self.assertIn(repr("foo"), message) + self.assertIn(repr("bar"), message) + self.assertIn("were unexpected)", message) + + def test_const(self): + schema = {"const": 12} + message = self.message_for( + instance={"foo": "bar"}, + schema=schema, + ) + self.assertIn("12 was expected", message) + + def test_contains_draft_6(self): + schema = {"contains": {"const": 12}} + message = self.message_for( + instance=[2, {}, []], + schema=schema, + cls=validators.Draft6Validator, + ) + self.assertEqual( + message, + "None of [2, {}, []] are valid under the given schema", + ) + + def test_invalid_format_default_message(self): + checker = FormatChecker(formats=()) + checker.checks("thing")(lambda value: False) + + schema = {"format": "thing"} + message = self.message_for( + instance="bla", + schema=schema, + format_checker=checker, + ) + + self.assertIn(repr("bla"), message) + self.assertIn(repr("thing"), message) + self.assertIn("is not a", message) + + def test_additionalProperties_false_patternProperties(self): + schema = {"type": "object", + "additionalProperties": False, + "patternProperties": { + "^abc$": {"type": "string"}, + "^def$": {"type": "string"}, + }} + message = self.message_for( + instance={"zebra": 123}, + schema=schema, + cls=validators.Draft4Validator, + ) + self.assertEqual( + message, + "{} does not match any of the regexes: {}, {}".format( + repr("zebra"), repr("^abc$"), repr("^def$"), + ), + ) + message = self.message_for( + instance={"zebra": 123, "fish": 456}, + schema=schema, + cls=validators.Draft4Validator, + ) + self.assertEqual( + message, + "{}, {} do not match any of the regexes: {}, {}".format( + repr("fish"), repr("zebra"), repr("^abc$"), repr("^def$"), + ), + ) + + def test_False_schema(self): + message = self.message_for( + instance="something", + schema=False, + ) + self.assertEqual(message, "False schema does not allow 'something'") + + def test_multipleOf(self): + message = self.message_for( + instance=3, + schema={"multipleOf": 2}, + ) + self.assertEqual(message, "3 is not a multiple of 2") + + def test_minItems(self): + message = self.message_for(instance=[], schema={"minItems": 2}) + self.assertEqual(message, "[] is too short") + + def test_maxItems(self): + message = self.message_for(instance=[1, 2, 3], schema={"maxItems": 2}) + self.assertEqual(message, "[1, 2, 3] is too long") + + def test_minItems_1(self): + message = self.message_for(instance=[], schema={"minItems": 1}) + self.assertEqual(message, "[] should be non-empty") + + def test_maxItems_0(self): + message = self.message_for(instance=[1, 2, 3], schema={"maxItems": 0}) + self.assertEqual(message, "[1, 2, 3] is expected to be empty") + + def test_minLength(self): + message = self.message_for( + instance="", + schema={"minLength": 2}, + ) + self.assertEqual(message, "'' is too short") + + def test_maxLength(self): + message = self.message_for( + instance="abc", + schema={"maxLength": 2}, + ) + self.assertEqual(message, "'abc' is too long") + + def test_minLength_1(self): + message = self.message_for(instance="", schema={"minLength": 1}) + self.assertEqual(message, "'' should be non-empty") + + def test_maxLength_0(self): + message = self.message_for(instance="abc", schema={"maxLength": 0}) + self.assertEqual(message, "'abc' is expected to be empty") + + def test_minProperties(self): + message = self.message_for(instance={}, schema={"minProperties": 2}) + self.assertEqual(message, "{} does not have enough properties") + + def test_maxProperties(self): + message = self.message_for( + instance={"a": {}, "b": {}, "c": {}}, + schema={"maxProperties": 2}, + ) + self.assertEqual( + message, + "{'a': {}, 'b': {}, 'c': {}} has too many properties", + ) + + def test_minProperties_1(self): + message = self.message_for(instance={}, schema={"minProperties": 1}) + self.assertEqual(message, "{} should be non-empty") + + def test_maxProperties_0(self): + message = self.message_for( + instance={1: 2}, + schema={"maxProperties": 0}, + ) + self.assertEqual(message, "{1: 2} is expected to be empty") + + def test_prefixItems_with_items(self): + message = self.message_for( + instance=[1, 2, "foo"], + schema={"items": False, "prefixItems": [{}, {}]}, + ) + self.assertEqual( + message, + "Expected at most 2 items but found 1 extra: 'foo'", + ) + + def test_prefixItems_with_multiple_extra_items(self): + message = self.message_for( + instance=[1, 2, "foo", 5], + schema={"items": False, "prefixItems": [{}, {}]}, + ) + self.assertEqual( + message, + "Expected at most 2 items but found 2 extra: ['foo', 5]", + ) + + def test_pattern(self): + message = self.message_for( + instance="bbb", + schema={"pattern": "^a*$"}, + ) + self.assertEqual(message, "'bbb' does not match '^a*$'") + + def test_does_not_contain(self): + message = self.message_for( + instance=[], + schema={"contains": {"type": "string"}}, + ) + self.assertEqual( + message, + "[] does not contain items matching the given schema", + ) + + def test_contains_too_few(self): + message = self.message_for( + instance=["foo", 1], + schema={"contains": {"type": "string"}, "minContains": 2}, + ) + self.assertEqual( + message, + "Too few items match the given schema " + "(expected at least 2 but only 1 matched)", + ) + + def test_contains_too_few_both_constrained(self): + message = self.message_for( + instance=["foo", 1], + schema={ + "contains": {"type": "string"}, + "minContains": 2, + "maxContains": 4, + }, + ) + self.assertEqual( + message, + "Too few items match the given schema (expected at least 2 but " + "only 1 matched)", + ) + + def test_contains_too_many(self): + message = self.message_for( + instance=["foo", "bar", "baz"], + schema={"contains": {"type": "string"}, "maxContains": 2}, + ) + self.assertEqual( + message, + "Too many items match the given schema (expected at most 2)", + ) + + def test_contains_too_many_both_constrained(self): + message = self.message_for( + instance=["foo"] * 5, + schema={ + "contains": {"type": "string"}, + "minContains": 2, + "maxContains": 4, + }, + ) + self.assertEqual( + message, + "Too many items match the given schema (expected at most 4)", + ) + + def test_exclusiveMinimum(self): + message = self.message_for( + instance=3, + schema={"exclusiveMinimum": 5}, + ) + self.assertEqual( + message, + "3 is less than or equal to the minimum of 5", + ) + + def test_exclusiveMaximum(self): + message = self.message_for(instance=3, schema={"exclusiveMaximum": 2}) + self.assertEqual( + message, + "3 is greater than or equal to the maximum of 2", + ) + + def test_required(self): + message = self.message_for(instance={}, schema={"required": ["foo"]}) + self.assertEqual(message, "'foo' is a required property") + + def test_dependentRequired(self): + message = self.message_for( + instance={"foo": {}}, + schema={"dependentRequired": {"foo": ["bar"]}}, + ) + self.assertEqual(message, "'bar' is a dependency of 'foo'") + + def test_oneOf_matches_none(self): + message = self.message_for(instance={}, schema={"oneOf": [False]}) + self.assertEqual( + message, + "{} is not valid under any of the given schemas", + ) + + def test_oneOf_matches_too_many(self): + message = self.message_for(instance={}, schema={"oneOf": [True, True]}) + self.assertEqual(message, "{} is valid under each of True, True") + + def test_unevaluated_items(self): + schema = {"type": "array", "unevaluatedItems": False} + message = self.message_for(instance=["foo", "bar"], schema=schema) + self.assertIn( + message, + "Unevaluated items are not allowed ('foo', 'bar' were unexpected)", + ) + + def test_unevaluated_items_on_invalid_type(self): + schema = {"type": "array", "unevaluatedItems": False} + message = self.message_for(instance="foo", schema=schema) + self.assertEqual(message, "'foo' is not of type 'array'") + + def test_unevaluated_properties_invalid_against_subschema(self): + schema = { + "properties": {"foo": {"type": "string"}}, + "unevaluatedProperties": {"const": 12}, + } + message = self.message_for( + instance={ + "foo": "foo", + "bar": "bar", + "baz": 12, + }, + schema=schema, + ) + self.assertEqual( + message, + "Unevaluated properties are not valid under the given schema " + "('bar' was unevaluated and invalid)", + ) + + def test_unevaluated_properties_disallowed(self): + schema = {"type": "object", "unevaluatedProperties": False} + message = self.message_for( + instance={ + "foo": "foo", + "bar": "bar", + }, + schema=schema, + ) + self.assertEqual( + message, + "Unevaluated properties are not allowed " + "('bar', 'foo' were unexpected)", + ) + + def test_unevaluated_properties_on_invalid_type(self): + schema = {"type": "object", "unevaluatedProperties": False} + message = self.message_for(instance="foo", schema=schema) + self.assertEqual(message, "'foo' is not of type 'object'") + + def test_single_item(self): + schema = {"prefixItems": [{}], "items": False} + message = self.message_for( + instance=["foo", "bar", "baz"], + schema=schema, + ) + self.assertEqual( + message, + "Expected at most 1 item but found 2 extra: ['bar', 'baz']", + ) + + def test_heterogeneous_additionalItems_with_Items(self): + schema = {"items": [{}], "additionalItems": False} + message = self.message_for( + instance=["foo", "bar", 37], + schema=schema, + cls=validators.Draft7Validator, + ) + self.assertEqual( + message, + "Additional items are not allowed ('bar', 37 were unexpected)", + ) + + def test_heterogeneous_items_prefixItems(self): + schema = {"prefixItems": [{}], "items": False} + message = self.message_for( + instance=["foo", "bar", 37], + schema=schema, + ) + self.assertEqual( + message, + "Expected at most 1 item but found 2 extra: ['bar', 37]", + ) + + def test_heterogeneous_unevaluatedItems_prefixItems(self): + schema = {"prefixItems": [{}], "unevaluatedItems": False} + message = self.message_for( + instance=["foo", "bar", 37], + schema=schema, + ) + self.assertEqual( + message, + "Unevaluated items are not allowed ('bar', 37 were unexpected)", + ) + + def test_heterogeneous_properties_additionalProperties(self): + """ + Not valid deserialized JSON, but this should not blow up. + """ + schema = {"properties": {"foo": {}}, "additionalProperties": False} + message = self.message_for( + instance={"foo": {}, "a": "baz", 37: 12}, + schema=schema, + ) + self.assertEqual( + message, + "Additional properties are not allowed (37, 'a' were unexpected)", + ) + + def test_heterogeneous_properties_unevaluatedProperties(self): + """ + Not valid deserialized JSON, but this should not blow up. + """ + schema = {"properties": {"foo": {}}, "unevaluatedProperties": False} + message = self.message_for( + instance={"foo": {}, "a": "baz", 37: 12}, + schema=schema, + ) + self.assertEqual( + message, + "Unevaluated properties are not allowed (37, 'a' were unexpected)", + ) + + +class TestValidationErrorDetails(TestCase): + # TODO: These really need unit tests for each individual keyword, rather + # than just these higher level tests. + def test_anyOf(self): + instance = 5 + schema = { + "anyOf": [ + {"minimum": 20}, + {"type": "string"}, + ], + } + + validator = validators.Draft4Validator(schema) + errors = list(validator.iter_errors(instance)) + self.assertEqual(len(errors), 1) + e = errors[0] + + self.assertEqual(e.validator, "anyOf") + self.assertEqual(e.validator_value, schema["anyOf"]) + self.assertEqual(e.instance, instance) + self.assertEqual(e.schema, schema) + self.assertIsNone(e.parent) + + self.assertEqual(e.path, deque([])) + self.assertEqual(e.relative_path, deque([])) + self.assertEqual(e.absolute_path, deque([])) + self.assertEqual(e.json_path, "$") + + self.assertEqual(e.schema_path, deque(["anyOf"])) + self.assertEqual(e.relative_schema_path, deque(["anyOf"])) + self.assertEqual(e.absolute_schema_path, deque(["anyOf"])) + + self.assertEqual(len(e.context), 2) + + e1, e2 = sorted_errors(e.context) + + self.assertEqual(e1.validator, "minimum") + self.assertEqual(e1.validator_value, schema["anyOf"][0]["minimum"]) + self.assertEqual(e1.instance, instance) + self.assertEqual(e1.schema, schema["anyOf"][0]) + self.assertIs(e1.parent, e) + + self.assertEqual(e1.path, deque([])) + self.assertEqual(e1.absolute_path, deque([])) + self.assertEqual(e1.relative_path, deque([])) + self.assertEqual(e1.json_path, "$") + + self.assertEqual(e1.schema_path, deque([0, "minimum"])) + self.assertEqual(e1.relative_schema_path, deque([0, "minimum"])) + self.assertEqual( + e1.absolute_schema_path, deque(["anyOf", 0, "minimum"]), + ) + + self.assertFalse(e1.context) + + self.assertEqual(e2.validator, "type") + self.assertEqual(e2.validator_value, schema["anyOf"][1]["type"]) + self.assertEqual(e2.instance, instance) + self.assertEqual(e2.schema, schema["anyOf"][1]) + self.assertIs(e2.parent, e) + + self.assertEqual(e2.path, deque([])) + self.assertEqual(e2.relative_path, deque([])) + self.assertEqual(e2.absolute_path, deque([])) + self.assertEqual(e2.json_path, "$") + + self.assertEqual(e2.schema_path, deque([1, "type"])) + self.assertEqual(e2.relative_schema_path, deque([1, "type"])) + self.assertEqual(e2.absolute_schema_path, deque(["anyOf", 1, "type"])) + + self.assertEqual(len(e2.context), 0) + + def test_type(self): + instance = {"foo": 1} + schema = { + "type": [ + {"type": "integer"}, + { + "type": "object", + "properties": {"foo": {"enum": [2]}}, + }, + ], + } + + validator = validators.Draft3Validator(schema) + errors = list(validator.iter_errors(instance)) + self.assertEqual(len(errors), 1) + e = errors[0] + + self.assertEqual(e.validator, "type") + self.assertEqual(e.validator_value, schema["type"]) + self.assertEqual(e.instance, instance) + self.assertEqual(e.schema, schema) + self.assertIsNone(e.parent) + + self.assertEqual(e.path, deque([])) + self.assertEqual(e.relative_path, deque([])) + self.assertEqual(e.absolute_path, deque([])) + self.assertEqual(e.json_path, "$") + + self.assertEqual(e.schema_path, deque(["type"])) + self.assertEqual(e.relative_schema_path, deque(["type"])) + self.assertEqual(e.absolute_schema_path, deque(["type"])) + + self.assertEqual(len(e.context), 2) + + e1, e2 = sorted_errors(e.context) + + self.assertEqual(e1.validator, "type") + self.assertEqual(e1.validator_value, schema["type"][0]["type"]) + self.assertEqual(e1.instance, instance) + self.assertEqual(e1.schema, schema["type"][0]) + self.assertIs(e1.parent, e) + + self.assertEqual(e1.path, deque([])) + self.assertEqual(e1.relative_path, deque([])) + self.assertEqual(e1.absolute_path, deque([])) + self.assertEqual(e1.json_path, "$") + + self.assertEqual(e1.schema_path, deque([0, "type"])) + self.assertEqual(e1.relative_schema_path, deque([0, "type"])) + self.assertEqual(e1.absolute_schema_path, deque(["type", 0, "type"])) + + self.assertFalse(e1.context) + + self.assertEqual(e2.validator, "enum") + self.assertEqual(e2.validator_value, [2]) + self.assertEqual(e2.instance, 1) + self.assertEqual(e2.schema, {"enum": [2]}) + self.assertIs(e2.parent, e) + + self.assertEqual(e2.path, deque(["foo"])) + self.assertEqual(e2.relative_path, deque(["foo"])) + self.assertEqual(e2.absolute_path, deque(["foo"])) + self.assertEqual(e2.json_path, "$.foo") + + self.assertEqual( + e2.schema_path, deque([1, "properties", "foo", "enum"]), + ) + self.assertEqual( + e2.relative_schema_path, deque([1, "properties", "foo", "enum"]), + ) + self.assertEqual( + e2.absolute_schema_path, + deque(["type", 1, "properties", "foo", "enum"]), + ) + + self.assertFalse(e2.context) + + def test_single_nesting(self): + instance = {"foo": 2, "bar": [1], "baz": 15, "quux": "spam"} + schema = { + "properties": { + "foo": {"type": "string"}, + "bar": {"minItems": 2}, + "baz": {"maximum": 10, "enum": [2, 4, 6, 8]}, + }, + } + + validator = validators.Draft3Validator(schema) + errors = validator.iter_errors(instance) + e1, e2, e3, e4 = sorted_errors(errors) + + self.assertEqual(e1.path, deque(["bar"])) + self.assertEqual(e2.path, deque(["baz"])) + self.assertEqual(e3.path, deque(["baz"])) + self.assertEqual(e4.path, deque(["foo"])) + + self.assertEqual(e1.relative_path, deque(["bar"])) + self.assertEqual(e2.relative_path, deque(["baz"])) + self.assertEqual(e3.relative_path, deque(["baz"])) + self.assertEqual(e4.relative_path, deque(["foo"])) + + self.assertEqual(e1.absolute_path, deque(["bar"])) + self.assertEqual(e2.absolute_path, deque(["baz"])) + self.assertEqual(e3.absolute_path, deque(["baz"])) + self.assertEqual(e4.absolute_path, deque(["foo"])) + + self.assertEqual(e1.json_path, "$.bar") + self.assertEqual(e2.json_path, "$.baz") + self.assertEqual(e3.json_path, "$.baz") + self.assertEqual(e4.json_path, "$.foo") + + self.assertEqual(e1.validator, "minItems") + self.assertEqual(e2.validator, "enum") + self.assertEqual(e3.validator, "maximum") + self.assertEqual(e4.validator, "type") + + def test_multiple_nesting(self): + instance = [1, {"foo": 2, "bar": {"baz": [1]}}, "quux"] + schema = { + "type": "string", + "items": { + "type": ["string", "object"], + "properties": { + "foo": {"enum": [1, 3]}, + "bar": { + "type": "array", + "properties": { + "bar": {"required": True}, + "baz": {"minItems": 2}, + }, + }, + }, + }, + } + + validator = validators.Draft3Validator(schema) + errors = validator.iter_errors(instance) + e1, e2, e3, e4, e5, e6 = sorted_errors(errors) + + self.assertEqual(e1.path, deque([])) + self.assertEqual(e2.path, deque([0])) + self.assertEqual(e3.path, deque([1, "bar"])) + self.assertEqual(e4.path, deque([1, "bar", "bar"])) + self.assertEqual(e5.path, deque([1, "bar", "baz"])) + self.assertEqual(e6.path, deque([1, "foo"])) + + self.assertEqual(e1.json_path, "$") + self.assertEqual(e2.json_path, "$[0]") + self.assertEqual(e3.json_path, "$[1].bar") + self.assertEqual(e4.json_path, "$[1].bar.bar") + self.assertEqual(e5.json_path, "$[1].bar.baz") + self.assertEqual(e6.json_path, "$[1].foo") + + self.assertEqual(e1.schema_path, deque(["type"])) + self.assertEqual(e2.schema_path, deque(["items", "type"])) + self.assertEqual( + list(e3.schema_path), ["items", "properties", "bar", "type"], + ) + self.assertEqual( + list(e4.schema_path), + ["items", "properties", "bar", "properties", "bar", "required"], + ) + self.assertEqual( + list(e5.schema_path), + ["items", "properties", "bar", "properties", "baz", "minItems"], + ) + self.assertEqual( + list(e6.schema_path), ["items", "properties", "foo", "enum"], + ) + + self.assertEqual(e1.validator, "type") + self.assertEqual(e2.validator, "type") + self.assertEqual(e3.validator, "type") + self.assertEqual(e4.validator, "required") + self.assertEqual(e5.validator, "minItems") + self.assertEqual(e6.validator, "enum") + + def test_recursive(self): + schema = { + "definitions": { + "node": { + "anyOf": [{ + "type": "object", + "required": ["name", "children"], + "properties": { + "name": { + "type": "string", + }, + "children": { + "type": "object", + "patternProperties": { + "^.*$": { + "$ref": "#/definitions/node", + }, + }, + }, + }, + }], + }, + }, + "type": "object", + "required": ["root"], + "properties": {"root": {"$ref": "#/definitions/node"}}, + } + + instance = { + "root": { + "name": "root", + "children": { + "a": { + "name": "a", + "children": { + "ab": { + "name": "ab", + # missing "children" + }, + }, + }, + }, + }, + } + validator = validators.Draft4Validator(schema) + + e, = validator.iter_errors(instance) + self.assertEqual(e.absolute_path, deque(["root"])) + self.assertEqual( + e.absolute_schema_path, deque(["properties", "root", "anyOf"]), + ) + self.assertEqual(e.json_path, "$.root") + + e1, = e.context + self.assertEqual(e1.absolute_path, deque(["root", "children", "a"])) + self.assertEqual( + e1.absolute_schema_path, deque( + [ + "properties", + "root", + "anyOf", + 0, + "properties", + "children", + "patternProperties", + "^.*$", + "anyOf", + ], + ), + ) + self.assertEqual(e1.json_path, "$.root.children.a") + + e2, = e1.context + self.assertEqual( + e2.absolute_path, deque( + ["root", "children", "a", "children", "ab"], + ), + ) + self.assertEqual( + e2.absolute_schema_path, deque( + [ + "properties", + "root", + "anyOf", + 0, + "properties", + "children", + "patternProperties", + "^.*$", + "anyOf", + 0, + "properties", + "children", + "patternProperties", + "^.*$", + "anyOf", + ], + ), + ) + self.assertEqual(e2.json_path, "$.root.children.a.children.ab") + + def test_additionalProperties(self): + instance = {"bar": "bar", "foo": 2} + schema = {"additionalProperties": {"type": "integer", "minimum": 5}} + + validator = validators.Draft3Validator(schema) + errors = validator.iter_errors(instance) + e1, e2 = sorted_errors(errors) + + self.assertEqual(e1.path, deque(["bar"])) + self.assertEqual(e2.path, deque(["foo"])) + + self.assertEqual(e1.json_path, "$.bar") + self.assertEqual(e2.json_path, "$.foo") + + self.assertEqual(e1.validator, "type") + self.assertEqual(e2.validator, "minimum") + + def test_patternProperties(self): + instance = {"bar": 1, "foo": 2} + schema = { + "patternProperties": { + "bar": {"type": "string"}, + "foo": {"minimum": 5}, + }, + } + + validator = validators.Draft3Validator(schema) + errors = validator.iter_errors(instance) + e1, e2 = sorted_errors(errors) + + self.assertEqual(e1.path, deque(["bar"])) + self.assertEqual(e2.path, deque(["foo"])) + + self.assertEqual(e1.json_path, "$.bar") + self.assertEqual(e2.json_path, "$.foo") + + self.assertEqual(e1.validator, "type") + self.assertEqual(e2.validator, "minimum") + + def test_additionalItems(self): + instance = ["foo", 1] + schema = { + "items": [], + "additionalItems": {"type": "integer", "minimum": 5}, + } + + validator = validators.Draft3Validator(schema) + errors = validator.iter_errors(instance) + e1, e2 = sorted_errors(errors) + + self.assertEqual(e1.path, deque([0])) + self.assertEqual(e2.path, deque([1])) + + self.assertEqual(e1.json_path, "$[0]") + self.assertEqual(e2.json_path, "$[1]") + + self.assertEqual(e1.validator, "type") + self.assertEqual(e2.validator, "minimum") + + def test_additionalItems_with_items(self): + instance = ["foo", "bar", 1] + schema = { + "items": [{}], + "additionalItems": {"type": "integer", "minimum": 5}, + } + + validator = validators.Draft3Validator(schema) + errors = validator.iter_errors(instance) + e1, e2 = sorted_errors(errors) + + self.assertEqual(e1.path, deque([1])) + self.assertEqual(e2.path, deque([2])) + + self.assertEqual(e1.json_path, "$[1]") + self.assertEqual(e2.json_path, "$[2]") + + self.assertEqual(e1.validator, "type") + self.assertEqual(e2.validator, "minimum") + + def test_propertyNames(self): + instance = {"foo": 12} + schema = {"propertyNames": {"not": {"const": "foo"}}} + + validator = validators.Draft7Validator(schema) + error, = validator.iter_errors(instance) + + self.assertEqual(error.validator, "not") + self.assertEqual( + error.message, + "'foo' should not be valid under {'const': 'foo'}", + ) + self.assertEqual(error.path, deque([])) + self.assertEqual(error.json_path, "$") + self.assertEqual(error.schema_path, deque(["propertyNames", "not"])) + + def test_if_then(self): + schema = { + "if": {"const": 12}, + "then": {"const": 13}, + } + + validator = validators.Draft7Validator(schema) + error, = validator.iter_errors(12) + + self.assertEqual(error.validator, "const") + self.assertEqual(error.message, "13 was expected") + self.assertEqual(error.path, deque([])) + self.assertEqual(error.json_path, "$") + self.assertEqual(error.schema_path, deque(["then", "const"])) + + def test_if_else(self): + schema = { + "if": {"const": 12}, + "else": {"const": 13}, + } + + validator = validators.Draft7Validator(schema) + error, = validator.iter_errors(15) + + self.assertEqual(error.validator, "const") + self.assertEqual(error.message, "13 was expected") + self.assertEqual(error.path, deque([])) + self.assertEqual(error.json_path, "$") + self.assertEqual(error.schema_path, deque(["else", "const"])) + + def test_boolean_schema_False(self): + validator = validators.Draft7Validator(False) + error, = validator.iter_errors(12) + + self.assertEqual( + ( + error.message, + error.validator, + error.validator_value, + error.instance, + error.schema, + error.schema_path, + error.json_path, + ), + ( + "False schema does not allow 12", + None, + None, + 12, + False, + deque([]), + "$", + ), + ) + + def test_ref(self): + ref, schema = "someRef", {"additionalProperties": {"type": "integer"}} + validator = validators.Draft7Validator( + {"$ref": ref}, + resolver=validators._RefResolver("", {}, store={ref: schema}), + ) + error, = validator.iter_errors({"foo": "notAnInteger"}) + + self.assertEqual( + ( + error.message, + error.validator, + error.validator_value, + error.instance, + error.absolute_path, + error.schema, + error.schema_path, + error.json_path, + ), + ( + "'notAnInteger' is not of type 'integer'", + "type", + "integer", + "notAnInteger", + deque(["foo"]), + {"type": "integer"}, + deque(["additionalProperties", "type"]), + "$.foo", + ), + ) + + def test_prefixItems(self): + schema = {"prefixItems": [{"type": "string"}, {}, {}, {"maximum": 3}]} + validator = validators.Draft202012Validator(schema) + type_error, min_error = validator.iter_errors([1, 2, "foo", 5]) + self.assertEqual( + ( + type_error.message, + type_error.validator, + type_error.validator_value, + type_error.instance, + type_error.absolute_path, + type_error.schema, + type_error.schema_path, + type_error.json_path, + ), + ( + "1 is not of type 'string'", + "type", + "string", + 1, + deque([0]), + {"type": "string"}, + deque(["prefixItems", 0, "type"]), + "$[0]", + ), + ) + self.assertEqual( + ( + min_error.message, + min_error.validator, + min_error.validator_value, + min_error.instance, + min_error.absolute_path, + min_error.schema, + min_error.schema_path, + min_error.json_path, + ), + ( + "5 is greater than the maximum of 3", + "maximum", + 3, + 5, + deque([3]), + {"maximum": 3}, + deque(["prefixItems", 3, "maximum"]), + "$[3]", + ), + ) + + def test_prefixItems_with_items(self): + schema = { + "items": {"type": "string"}, + "prefixItems": [{}], + } + validator = validators.Draft202012Validator(schema) + e1, e2 = validator.iter_errors(["foo", 2, "bar", 4, "baz"]) + self.assertEqual( + ( + e1.message, + e1.validator, + e1.validator_value, + e1.instance, + e1.absolute_path, + e1.schema, + e1.schema_path, + e1.json_path, + ), + ( + "2 is not of type 'string'", + "type", + "string", + 2, + deque([1]), + {"type": "string"}, + deque(["items", "type"]), + "$[1]", + ), + ) + self.assertEqual( + ( + e2.message, + e2.validator, + e2.validator_value, + e2.instance, + e2.absolute_path, + e2.schema, + e2.schema_path, + e2.json_path, + ), + ( + "4 is not of type 'string'", + "type", + "string", + 4, + deque([3]), + {"type": "string"}, + deque(["items", "type"]), + "$[3]", + ), + ) + + def test_contains_too_many(self): + """ + `contains` + `maxContains` produces only one error, even if there are + many more incorrectly matching elements. + """ + schema = {"contains": {"type": "string"}, "maxContains": 2} + validator = validators.Draft202012Validator(schema) + error, = validator.iter_errors(["foo", 2, "bar", 4, "baz", "quux"]) + self.assertEqual( + ( + error.message, + error.validator, + error.validator_value, + error.instance, + error.absolute_path, + error.schema, + error.schema_path, + error.json_path, + ), + ( + "Too many items match the given schema (expected at most 2)", + "maxContains", + 2, + ["foo", 2, "bar", 4, "baz", "quux"], + deque([]), + {"contains": {"type": "string"}, "maxContains": 2}, + deque(["contains"]), + "$", + ), + ) + + def test_contains_too_few(self): + schema = {"contains": {"type": "string"}, "minContains": 2} + validator = validators.Draft202012Validator(schema) + error, = validator.iter_errors(["foo", 2, 4]) + self.assertEqual( + ( + error.message, + error.validator, + error.validator_value, + error.instance, + error.absolute_path, + error.schema, + error.schema_path, + error.json_path, + ), + ( + ( + "Too few items match the given schema " + "(expected at least 2 but only 1 matched)" + ), + "minContains", + 2, + ["foo", 2, 4], + deque([]), + {"contains": {"type": "string"}, "minContains": 2}, + deque(["contains"]), + "$", + ), + ) + + def test_contains_none(self): + schema = {"contains": {"type": "string"}, "minContains": 2} + validator = validators.Draft202012Validator(schema) + error, = validator.iter_errors([2, 4]) + self.assertEqual( + ( + error.message, + error.validator, + error.validator_value, + error.instance, + error.absolute_path, + error.schema, + error.schema_path, + error.json_path, + ), + ( + "[2, 4] does not contain items matching the given schema", + "contains", + {"type": "string"}, + [2, 4], + deque([]), + {"contains": {"type": "string"}, "minContains": 2}, + deque(["contains"]), + "$", + ), + ) + + def test_ref_sibling(self): + schema = { + "$defs": {"foo": {"required": ["bar"]}}, + "properties": { + "aprop": { + "$ref": "#/$defs/foo", + "required": ["baz"], + }, + }, + } + + validator = validators.Draft202012Validator(schema) + e1, e2 = validator.iter_errors({"aprop": {}}) + self.assertEqual( + ( + e1.message, + e1.validator, + e1.validator_value, + e1.instance, + e1.absolute_path, + e1.schema, + e1.schema_path, + e1.relative_schema_path, + e1.json_path, + ), + ( + "'bar' is a required property", + "required", + ["bar"], + {}, + deque(["aprop"]), + {"required": ["bar"]}, + deque(["properties", "aprop", "required"]), + deque(["properties", "aprop", "required"]), + "$.aprop", + ), + ) + self.assertEqual( + ( + e2.message, + e2.validator, + e2.validator_value, + e2.instance, + e2.absolute_path, + e2.schema, + e2.schema_path, + e2.relative_schema_path, + e2.json_path, + ), + ( + "'baz' is a required property", + "required", + ["baz"], + {}, + deque(["aprop"]), + {"$ref": "#/$defs/foo", "required": ["baz"]}, + deque(["properties", "aprop", "required"]), + deque(["properties", "aprop", "required"]), + "$.aprop", + ), + ) + + +class MetaSchemaTestsMixin: + # TODO: These all belong upstream + def test_invalid_properties(self): + with self.assertRaises(exceptions.SchemaError): + self.Validator.check_schema({"properties": 12}) + + def test_minItems_invalid_string(self): + with self.assertRaises(exceptions.SchemaError): + # needs to be an integer + self.Validator.check_schema({"minItems": "1"}) + + def test_enum_allows_empty_arrays(self): + """ + Technically, all the spec says is they SHOULD have elements, not MUST. + + (As of Draft 6. Previous drafts do say MUST). + + See #529. + """ + if self.Validator in { + validators.Draft3Validator, + validators.Draft4Validator, + }: + with self.assertRaises(exceptions.SchemaError): + self.Validator.check_schema({"enum": []}) + else: + self.Validator.check_schema({"enum": []}) + + def test_enum_allows_non_unique_items(self): + """ + Technically, all the spec says is they SHOULD be unique, not MUST. + + (As of Draft 6. Previous drafts do say MUST). + + See #529. + """ + if self.Validator in { + validators.Draft3Validator, + validators.Draft4Validator, + }: + with self.assertRaises(exceptions.SchemaError): + self.Validator.check_schema({"enum": [12, 12]}) + else: + self.Validator.check_schema({"enum": [12, 12]}) + + def test_schema_with_invalid_regex(self): + with self.assertRaises(exceptions.SchemaError): + self.Validator.check_schema({"pattern": "*notaregex"}) + + def test_schema_with_invalid_regex_with_disabled_format_validation(self): + self.Validator.check_schema( + {"pattern": "*notaregex"}, + format_checker=None, + ) + + +class ValidatorTestMixin(MetaSchemaTestsMixin): + def test_it_implements_the_validator_protocol(self): + self.assertIsInstance(self.Validator({}), protocols.Validator) + + def test_valid_instances_are_valid(self): + schema, instance = self.valid + self.assertTrue(self.Validator(schema).is_valid(instance)) + + def test_invalid_instances_are_not_valid(self): + schema, instance = self.invalid + self.assertFalse(self.Validator(schema).is_valid(instance)) + + def test_non_existent_properties_are_ignored(self): + self.Validator({object(): object()}).validate(instance=object()) + + def test_evolve(self): + schema, format_checker = {"type": "integer"}, FormatChecker() + original = self.Validator( + schema, + format_checker=format_checker, + ) + new = original.evolve( + schema={"type": "string"}, + format_checker=self.Validator.FORMAT_CHECKER, + ) + + expected = self.Validator( + {"type": "string"}, + format_checker=self.Validator.FORMAT_CHECKER, + _resolver=new._resolver, + ) + + self.assertEqual(new, expected) + self.assertNotEqual(new, original) + + def test_evolve_with_subclass(self): + """ + Subclassing validators isn't supported public API, but some users have + done it, because we don't actually error entirely when it's done :/ + + We need to deprecate doing so first to help as many of these users + ensure they can move to supported APIs, but this test ensures that in + the interim, we haven't broken those users. + """ + + with self.assertWarns(DeprecationWarning): + @define + class OhNo(self.Validator): + foo = field(factory=lambda: [1, 2, 3]) + _bar = field(default=37) + + validator = OhNo({}, bar=12) + self.assertEqual(validator.foo, [1, 2, 3]) + + new = validator.evolve(schema={"type": "integer"}) + self.assertEqual(new.foo, [1, 2, 3]) + self.assertEqual(new._bar, 12) + + def test_is_type_is_true_for_valid_type(self): + self.assertTrue(self.Validator({}).is_type("foo", "string")) + + def test_is_type_is_false_for_invalid_type(self): + self.assertFalse(self.Validator({}).is_type("foo", "array")) + + def test_is_type_evades_bool_inheriting_from_int(self): + self.assertFalse(self.Validator({}).is_type(True, "integer")) + self.assertFalse(self.Validator({}).is_type(True, "number")) + + def test_it_can_validate_with_decimals(self): + schema = {"items": {"type": "number"}} + Validator = validators.extend( + self.Validator, + type_checker=self.Validator.TYPE_CHECKER.redefine( + "number", + lambda checker, thing: isinstance( + thing, (int, float, Decimal), + ) and not isinstance(thing, bool), + ), + ) + + validator = Validator(schema) + validator.validate([1, 1.1, Decimal(1) / Decimal(8)]) + + invalid = ["foo", {}, [], True, None] + self.assertEqual( + [error.instance for error in validator.iter_errors(invalid)], + invalid, + ) + + def test_it_returns_true_for_formats_it_does_not_know_about(self): + validator = self.Validator( + {"format": "carrot"}, format_checker=FormatChecker(), + ) + validator.validate("bugs") + + def test_it_does_not_validate_formats_by_default(self): + validator = self.Validator({}) + self.assertIsNone(validator.format_checker) + + def test_it_validates_formats_if_a_checker_is_provided(self): + checker = FormatChecker() + bad = ValueError("Bad!") + + @checker.checks("foo", raises=ValueError) + def check(value): + if value == "good": + return True + elif value == "bad": + raise bad + else: # pragma: no cover + self.fail(f"What is {value}? [Baby Don't Hurt Me]") + + validator = self.Validator( + {"format": "foo"}, format_checker=checker, + ) + + validator.validate("good") + with self.assertRaises(exceptions.ValidationError) as cm: + validator.validate("bad") + + # Make sure original cause is attached + self.assertIs(cm.exception.cause, bad) + + def test_non_string_custom_type(self): + non_string_type = object() + schema = {"type": [non_string_type]} + Crazy = validators.extend( + self.Validator, + type_checker=self.Validator.TYPE_CHECKER.redefine( + non_string_type, + lambda checker, thing: isinstance(thing, int), + ), + ) + Crazy(schema).validate(15) + + def test_it_properly_formats_tuples_in_errors(self): + """ + A tuple instance properly formats validation errors for uniqueItems. + + See #224 + """ + TupleValidator = validators.extend( + self.Validator, + type_checker=self.Validator.TYPE_CHECKER.redefine( + "array", + lambda checker, thing: isinstance(thing, tuple), + ), + ) + with self.assertRaises(exceptions.ValidationError) as e: + TupleValidator({"uniqueItems": True}).validate((1, 1)) + self.assertIn("(1, 1) has non-unique elements", str(e.exception)) + + def test_check_redefined_sequence(self): + """ + Allow array to validate against another defined sequence type + """ + schema = {"type": "array", "uniqueItems": True} + MyMapping = namedtuple("MyMapping", "a, b") + Validator = validators.extend( + self.Validator, + type_checker=self.Validator.TYPE_CHECKER.redefine_many( + { + "array": lambda checker, thing: isinstance( + thing, (list, deque), + ), + "object": lambda checker, thing: isinstance( + thing, (dict, MyMapping), + ), + }, + ), + ) + validator = Validator(schema) + + valid_instances = [ + deque(["a", None, "1", "", True]), + deque([[False], [0]]), + [deque([False]), deque([0])], + [[deque([False])], [deque([0])]], + [[[[[deque([False])]]]], [[[[deque([0])]]]]], + [deque([deque([False])]), deque([deque([0])])], + [MyMapping("a", 0), MyMapping("a", False)], + [ + MyMapping("a", [deque([0])]), + MyMapping("a", [deque([False])]), + ], + [ + MyMapping("a", [MyMapping("a", deque([0]))]), + MyMapping("a", [MyMapping("a", deque([False]))]), + ], + [deque(deque(deque([False]))), deque(deque(deque([0])))], + ] + + for instance in valid_instances: + validator.validate(instance) + + invalid_instances = [ + deque(["a", "b", "a"]), + deque([[False], [False]]), + [deque([False]), deque([False])], + [[deque([False])], [deque([False])]], + [[[[[deque([False])]]]], [[[[deque([False])]]]]], + [deque([deque([False])]), deque([deque([False])])], + [MyMapping("a", False), MyMapping("a", False)], + [ + MyMapping("a", [deque([False])]), + MyMapping("a", [deque([False])]), + ], + [ + MyMapping("a", [MyMapping("a", deque([False]))]), + MyMapping("a", [MyMapping("a", deque([False]))]), + ], + [deque(deque(deque([False]))), deque(deque(deque([False])))], + ] + + for instance in invalid_instances: + with self.assertRaises(exceptions.ValidationError): + validator.validate(instance) + + def test_it_creates_a_ref_resolver_if_not_provided(self): + with self.assertWarns(DeprecationWarning): + resolver = self.Validator({}).resolver + self.assertIsInstance(resolver, validators._RefResolver) + + def test_it_upconverts_from_deprecated_RefResolvers(self): + ref, schema = "someCoolRef", {"type": "integer"} + resolver = validators._RefResolver("", {}, store={ref: schema}) + validator = self.Validator({"$ref": ref}, resolver=resolver) + + with self.assertRaises(exceptions.ValidationError): + validator.validate(None) + + def test_it_upconverts_from_yet_older_deprecated_legacy_RefResolvers(self): + """ + Legacy RefResolvers support only the context manager form of + resolution. + """ + + class LegacyRefResolver: + @contextmanager + def resolving(this, ref): + self.assertEqual(ref, "the ref") + yield {"type": "integer"} + + resolver = LegacyRefResolver() + schema = {"$ref": "the ref"} + + with self.assertRaises(exceptions.ValidationError): + self.Validator(schema, resolver=resolver).validate(None) + + +class AntiDraft6LeakMixin: + """ + Make sure functionality from draft 6 doesn't leak backwards in time. + """ + + def test_True_is_not_a_schema(self): + with self.assertRaises(exceptions.SchemaError) as e: + self.Validator.check_schema(True) + self.assertIn("True is not of type", str(e.exception)) + + def test_False_is_not_a_schema(self): + with self.assertRaises(exceptions.SchemaError) as e: + self.Validator.check_schema(False) + self.assertIn("False is not of type", str(e.exception)) + + def test_True_is_not_a_schema_even_if_you_forget_to_check(self): + with self.assertRaises(Exception) as e: + self.Validator(True).validate(12) + self.assertNotIsInstance(e.exception, exceptions.ValidationError) + + def test_False_is_not_a_schema_even_if_you_forget_to_check(self): + with self.assertRaises(Exception) as e: + self.Validator(False).validate(12) + self.assertNotIsInstance(e.exception, exceptions.ValidationError) + + +class TestDraft3Validator(AntiDraft6LeakMixin, ValidatorTestMixin, TestCase): + Validator = validators.Draft3Validator + valid: tuple[dict, dict] = ({}, {}) + invalid = {"type": "integer"}, "foo" + + def test_any_type_is_valid_for_type_any(self): + validator = self.Validator({"type": "any"}) + validator.validate(object()) + + def test_any_type_is_redefinable(self): + """ + Sigh, because why not. + """ + Crazy = validators.extend( + self.Validator, + type_checker=self.Validator.TYPE_CHECKER.redefine( + "any", lambda checker, thing: isinstance(thing, int), + ), + ) + validator = Crazy({"type": "any"}) + validator.validate(12) + with self.assertRaises(exceptions.ValidationError): + validator.validate("foo") + + def test_is_type_is_true_for_any_type(self): + self.assertTrue(self.Validator({"type": "any"}).is_valid(object())) + + def test_is_type_does_not_evade_bool_if_it_is_being_tested(self): + self.assertTrue(self.Validator({}).is_type(True, "boolean")) + self.assertTrue(self.Validator({"type": "any"}).is_valid(True)) + + +class TestDraft4Validator(AntiDraft6LeakMixin, ValidatorTestMixin, TestCase): + Validator = validators.Draft4Validator + valid: tuple[dict, dict] = ({}, {}) + invalid = {"type": "integer"}, "foo" + + +class TestDraft6Validator(ValidatorTestMixin, TestCase): + Validator = validators.Draft6Validator + valid: tuple[dict, dict] = ({}, {}) + invalid = {"type": "integer"}, "foo" + + +class TestDraft7Validator(ValidatorTestMixin, TestCase): + Validator = validators.Draft7Validator + valid: tuple[dict, dict] = ({}, {}) + invalid = {"type": "integer"}, "foo" + + +class TestDraft201909Validator(ValidatorTestMixin, TestCase): + Validator = validators.Draft201909Validator + valid: tuple[dict, dict] = ({}, {}) + invalid = {"type": "integer"}, "foo" + + +class TestDraft202012Validator(ValidatorTestMixin, TestCase): + Validator = validators.Draft202012Validator + valid: tuple[dict, dict] = ({}, {}) + invalid = {"type": "integer"}, "foo" + + +class TestLatestValidator(TestCase): + """ + These really apply to multiple versions but are easiest to test on one. + """ + + def test_ref_resolvers_may_have_boolean_schemas_stored(self): + ref = "someCoolRef" + schema = {"$ref": ref} + resolver = validators._RefResolver("", {}, store={ref: False}) + validator = validators._LATEST_VERSION(schema, resolver=resolver) + + with self.assertRaises(exceptions.ValidationError): + validator.validate(None) + + +class TestValidatorFor(TestCase): + def test_draft_3(self): + schema = {"$schema": "http://json-schema.org/draft-03/schema"} + self.assertIs( + validators.validator_for(schema), + validators.Draft3Validator, + ) + + schema = {"$schema": "http://json-schema.org/draft-03/schema#"} + self.assertIs( + validators.validator_for(schema), + validators.Draft3Validator, + ) + + def test_draft_4(self): + schema = {"$schema": "http://json-schema.org/draft-04/schema"} + self.assertIs( + validators.validator_for(schema), + validators.Draft4Validator, + ) + + schema = {"$schema": "http://json-schema.org/draft-04/schema#"} + self.assertIs( + validators.validator_for(schema), + validators.Draft4Validator, + ) + + def test_draft_6(self): + schema = {"$schema": "http://json-schema.org/draft-06/schema"} + self.assertIs( + validators.validator_for(schema), + validators.Draft6Validator, + ) + + schema = {"$schema": "http://json-schema.org/draft-06/schema#"} + self.assertIs( + validators.validator_for(schema), + validators.Draft6Validator, + ) + + def test_draft_7(self): + schema = {"$schema": "http://json-schema.org/draft-07/schema"} + self.assertIs( + validators.validator_for(schema), + validators.Draft7Validator, + ) + + schema = {"$schema": "http://json-schema.org/draft-07/schema#"} + self.assertIs( + validators.validator_for(schema), + validators.Draft7Validator, + ) + + def test_draft_201909(self): + schema = {"$schema": "https://json-schema.org/draft/2019-09/schema"} + self.assertIs( + validators.validator_for(schema), + validators.Draft201909Validator, + ) + + schema = {"$schema": "https://json-schema.org/draft/2019-09/schema#"} + self.assertIs( + validators.validator_for(schema), + validators.Draft201909Validator, + ) + + def test_draft_202012(self): + schema = {"$schema": "https://json-schema.org/draft/2020-12/schema"} + self.assertIs( + validators.validator_for(schema), + validators.Draft202012Validator, + ) + + schema = {"$schema": "https://json-schema.org/draft/2020-12/schema#"} + self.assertIs( + validators.validator_for(schema), + validators.Draft202012Validator, + ) + + def test_True(self): + self.assertIs( + validators.validator_for(True), + validators._LATEST_VERSION, + ) + + def test_False(self): + self.assertIs( + validators.validator_for(False), + validators._LATEST_VERSION, + ) + + def test_custom_validator(self): + Validator = validators.create( + meta_schema={"id": "meta schema id"}, + version="12", + id_of=lambda s: s.get("id", ""), + ) + schema = {"$schema": "meta schema id"} + self.assertIs( + validators.validator_for(schema), + Validator, + ) + + def test_custom_validator_draft6(self): + Validator = validators.create( + meta_schema={"$id": "meta schema $id"}, + version="13", + ) + schema = {"$schema": "meta schema $id"} + self.assertIs( + validators.validator_for(schema), + Validator, + ) + + def test_validator_for_jsonschema_default(self): + self.assertIs(validators.validator_for({}), validators._LATEST_VERSION) + + def test_validator_for_custom_default(self): + self.assertIs(validators.validator_for({}, default=None), None) + + def test_warns_if_meta_schema_specified_was_not_found(self): + with self.assertWarns(DeprecationWarning) as cm: + validators.validator_for(schema={"$schema": "unknownSchema"}) + + self.assertEqual(cm.filename, __file__) + self.assertEqual( + str(cm.warning), + "The metaschema specified by $schema was not found. " + "Using the latest draft to validate, but this will raise " + "an error in the future.", + ) + + def test_does_not_warn_if_meta_schema_is_unspecified(self): + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + validators.validator_for(schema={}, default={}) + self.assertFalse(w) + + def test_validator_for_custom_default_with_schema(self): + schema, default = {"$schema": "mailto:foo@example.com"}, object() + self.assertIs(validators.validator_for(schema, default), default) + + +class TestValidate(TestCase): + def assertUses(self, schema, Validator): + result = [] + with mock.patch.object(Validator, "check_schema", result.append): + validators.validate({}, schema) + self.assertEqual(result, [schema]) + + def test_draft3_validator_is_chosen(self): + self.assertUses( + schema={"$schema": "http://json-schema.org/draft-03/schema#"}, + Validator=validators.Draft3Validator, + ) + # Make sure it works without the empty fragment + self.assertUses( + schema={"$schema": "http://json-schema.org/draft-03/schema"}, + Validator=validators.Draft3Validator, + ) + + def test_draft4_validator_is_chosen(self): + self.assertUses( + schema={"$schema": "http://json-schema.org/draft-04/schema#"}, + Validator=validators.Draft4Validator, + ) + # Make sure it works without the empty fragment + self.assertUses( + schema={"$schema": "http://json-schema.org/draft-04/schema"}, + Validator=validators.Draft4Validator, + ) + + def test_draft6_validator_is_chosen(self): + self.assertUses( + schema={"$schema": "http://json-schema.org/draft-06/schema#"}, + Validator=validators.Draft6Validator, + ) + # Make sure it works without the empty fragment + self.assertUses( + schema={"$schema": "http://json-schema.org/draft-06/schema"}, + Validator=validators.Draft6Validator, + ) + + def test_draft7_validator_is_chosen(self): + self.assertUses( + schema={"$schema": "http://json-schema.org/draft-07/schema#"}, + Validator=validators.Draft7Validator, + ) + # Make sure it works without the empty fragment + self.assertUses( + schema={"$schema": "http://json-schema.org/draft-07/schema"}, + Validator=validators.Draft7Validator, + ) + + def test_draft202012_validator_is_chosen(self): + self.assertUses( + schema={ + "$schema": "https://json-schema.org/draft/2020-12/schema#", + }, + Validator=validators.Draft202012Validator, + ) + # Make sure it works without the empty fragment + self.assertUses( + schema={ + "$schema": "https://json-schema.org/draft/2020-12/schema", + }, + Validator=validators.Draft202012Validator, + ) + + def test_draft202012_validator_is_the_default(self): + self.assertUses(schema={}, Validator=validators.Draft202012Validator) + + def test_validation_error_message(self): + with self.assertRaises(exceptions.ValidationError) as e: + validators.validate(12, {"type": "string"}) + self.assertRegex( + str(e.exception), + "(?s)Failed validating '.*' in schema.*On instance", + ) + + def test_schema_error_message(self): + with self.assertRaises(exceptions.SchemaError) as e: + validators.validate(12, {"type": 12}) + self.assertRegex( + str(e.exception), + "(?s)Failed validating '.*' in metaschema.*On schema", + ) + + def test_it_uses_best_match(self): + schema = { + "oneOf": [ + {"type": "number", "minimum": 20}, + {"type": "array"}, + ], + } + with self.assertRaises(exceptions.ValidationError) as e: + validators.validate(12, schema) + self.assertIn("12 is less than the minimum of 20", str(e.exception)) + + +class TestThreading(TestCase): + """ + Threading-related functionality tests. + + jsonschema doesn't promise thread safety, and its validation behavior + across multiple threads may change at any time, but that means it isn't + safe to share *validators* across threads, not that anytime one has + multiple threads that jsonschema won't work (it certainly is intended to). + + These tests ensure that this minimal level of functionality continues to + work. + """ + + def test_validation_across_a_second_thread(self): + failed = [] + + def validate(): + try: + validators.validate(instance=37, schema=True) + except: # pragma: no cover # noqa: E722 + failed.append(sys.exc_info()) + + validate() # just verify it succeeds + + from threading import Thread + thread = Thread(target=validate) + thread.start() + thread.join() + self.assertEqual((thread.is_alive(), failed), (False, [])) + + +class TestReferencing(TestCase): + def test_registry_with_retrieve(self): + def retrieve(uri): + return DRAFT202012.create_resource({"type": "integer"}) + + registry = referencing.Registry(retrieve=retrieve) + schema = {"$ref": "https://example.com/"} + validator = validators.Draft202012Validator(schema, registry=registry) + + self.assertEqual( + (validator.is_valid(12), validator.is_valid("foo")), + (True, False), + ) + + def test_custom_registries_do_not_autoretrieve_remote_resources(self): + registry = referencing.Registry() + schema = {"$ref": "https://example.com/"} + validator = validators.Draft202012Validator(schema, registry=registry) + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + with self.assertRaises(referencing.exceptions.Unresolvable): + validator.validate(12) + self.assertFalse(w) + + +class TestRefResolver(TestCase): + + base_uri = "" + stored_uri = "foo://stored" + stored_schema = {"stored": "schema"} + + def setUp(self): + self.referrer = {} + self.store = {self.stored_uri: self.stored_schema} + self.resolver = validators._RefResolver( + self.base_uri, self.referrer, self.store, + ) + + def test_it_does_not_retrieve_schema_urls_from_the_network(self): + ref = validators.Draft3Validator.META_SCHEMA["id"] + with mock.patch.object(self.resolver, "resolve_remote") as patched: # noqa: SIM117 + with self.resolver.resolving(ref) as resolved: + pass + self.assertEqual(resolved, validators.Draft3Validator.META_SCHEMA) + self.assertFalse(patched.called) + + def test_it_resolves_local_refs(self): + ref = "#/properties/foo" + self.referrer["properties"] = {"foo": object()} + with self.resolver.resolving(ref) as resolved: + self.assertEqual(resolved, self.referrer["properties"]["foo"]) + + def test_it_resolves_local_refs_with_id(self): + schema = {"id": "http://bar/schema#", "a": {"foo": "bar"}} + resolver = validators._RefResolver.from_schema( + schema, + id_of=lambda schema: schema.get("id", ""), + ) + with resolver.resolving("#/a") as resolved: + self.assertEqual(resolved, schema["a"]) + with resolver.resolving("http://bar/schema#/a") as resolved: + self.assertEqual(resolved, schema["a"]) + + def test_it_retrieves_stored_refs(self): + with self.resolver.resolving(self.stored_uri) as resolved: + self.assertIs(resolved, self.stored_schema) + + self.resolver.store["cached_ref"] = {"foo": 12} + with self.resolver.resolving("cached_ref#/foo") as resolved: + self.assertEqual(resolved, 12) + + def test_it_retrieves_unstored_refs_via_requests(self): + ref = "http://bar#baz" + schema = {"baz": 12} + + if "requests" in sys.modules: # pragma: no cover + self.addCleanup( + sys.modules.__setitem__, "requests", sys.modules["requests"], + ) + sys.modules["requests"] = ReallyFakeRequests({"http://bar": schema}) + + with self.resolver.resolving(ref) as resolved: + self.assertEqual(resolved, 12) + + def test_it_retrieves_unstored_refs_via_urlopen(self): + ref = "http://bar#baz" + schema = {"baz": 12} + + if "requests" in sys.modules: # pragma: no cover + self.addCleanup( + sys.modules.__setitem__, "requests", sys.modules["requests"], + ) + sys.modules["requests"] = None + + @contextmanager + def fake_urlopen(url): + self.assertEqual(url, "http://bar") + yield BytesIO(json.dumps(schema).encode("utf8")) + + self.addCleanup(setattr, validators, "urlopen", validators.urlopen) + validators.urlopen = fake_urlopen + + with self.resolver.resolving(ref) as resolved: + pass + self.assertEqual(resolved, 12) + + def test_it_retrieves_local_refs_via_urlopen(self): + with tempfile.NamedTemporaryFile(delete=False, mode="wt") as tempf: + self.addCleanup(os.remove, tempf.name) + json.dump({"foo": "bar"}, tempf) + + ref = f"file://{pathname2url(tempf.name)}#foo" + with self.resolver.resolving(ref) as resolved: + self.assertEqual(resolved, "bar") + + def test_it_can_construct_a_base_uri_from_a_schema(self): + schema = {"id": "foo"} + resolver = validators._RefResolver.from_schema( + schema, + id_of=lambda schema: schema.get("id", ""), + ) + self.assertEqual(resolver.base_uri, "foo") + self.assertEqual(resolver.resolution_scope, "foo") + with resolver.resolving("") as resolved: + self.assertEqual(resolved, schema) + with resolver.resolving("#") as resolved: + self.assertEqual(resolved, schema) + with resolver.resolving("foo") as resolved: + self.assertEqual(resolved, schema) + with resolver.resolving("foo#") as resolved: + self.assertEqual(resolved, schema) + + def test_it_can_construct_a_base_uri_from_a_schema_without_id(self): + schema = {} + resolver = validators._RefResolver.from_schema(schema) + self.assertEqual(resolver.base_uri, "") + self.assertEqual(resolver.resolution_scope, "") + with resolver.resolving("") as resolved: + self.assertEqual(resolved, schema) + with resolver.resolving("#") as resolved: + self.assertEqual(resolved, schema) + + def test_custom_uri_scheme_handlers(self): + def handler(url): + self.assertEqual(url, ref) + return schema + + schema = {"foo": "bar"} + ref = "foo://bar" + resolver = validators._RefResolver("", {}, handlers={"foo": handler}) + with resolver.resolving(ref) as resolved: + self.assertEqual(resolved, schema) + + def test_cache_remote_on(self): + response = [object()] + + def handler(url): + try: + return response.pop() + except IndexError: # pragma: no cover + self.fail("Response must not have been cached!") + + ref = "foo://bar" + resolver = validators._RefResolver( + "", {}, cache_remote=True, handlers={"foo": handler}, + ) + with resolver.resolving(ref): + pass + with resolver.resolving(ref): + pass + + def test_cache_remote_off(self): + response = [object()] + + def handler(url): + try: + return response.pop() + except IndexError: # pragma: no cover + self.fail("Handler called twice!") + + ref = "foo://bar" + resolver = validators._RefResolver( + "", {}, cache_remote=False, handlers={"foo": handler}, + ) + with resolver.resolving(ref): + pass + + def test_if_you_give_it_junk_you_get_a_resolution_error(self): + error = ValueError("Oh no! What's this?") + + def handler(url): + raise error + + ref = "foo://bar" + resolver = validators._RefResolver("", {}, handlers={"foo": handler}) + with self.assertRaises(exceptions._RefResolutionError) as err: # noqa: SIM117 + with resolver.resolving(ref): + self.fail("Shouldn't get this far!") # pragma: no cover + self.assertEqual(err.exception, exceptions._RefResolutionError(error)) + + def test_helpful_error_message_on_failed_pop_scope(self): + resolver = validators._RefResolver("", {}) + resolver.pop_scope() + with self.assertRaises(exceptions._RefResolutionError) as exc: + resolver.pop_scope() + self.assertIn("Failed to pop the scope", str(exc.exception)) + + def test_pointer_within_schema_with_different_id(self): + """ + See #1085. + """ + schema = validators.Draft7Validator.META_SCHEMA + one = validators._RefResolver("", schema) + validator = validators.Draft7Validator(schema, resolver=one) + self.assertFalse(validator.is_valid({"maxLength": "foo"})) + + another = { + "allOf": [{"$ref": validators.Draft7Validator.META_SCHEMA["$id"]}], + } + two = validators._RefResolver("", another) + validator = validators.Draft7Validator(another, resolver=two) + self.assertFalse(validator.is_valid({"maxLength": "foo"})) + + def test_newly_created_validator_with_ref_resolver(self): + """ + See https://github.com/python-jsonschema/jsonschema/issues/1061#issuecomment-1624266555. + """ + + def handle(uri): + self.assertEqual(uri, "http://example.com/foo") + return {"type": "integer"} + + resolver = validators._RefResolver("", {}, handlers={"http": handle}) + Validator = validators.create( + meta_schema={}, + validators=validators.Draft4Validator.VALIDATORS, + ) + schema = {"$id": "http://example.com/bar", "$ref": "foo"} + validator = Validator(schema, resolver=resolver) + self.assertEqual( + (validator.is_valid({}), validator.is_valid(37)), + (False, True), + ) + + def test_refresolver_with_pointer_in_schema_with_no_id(self): + """ + See https://github.com/python-jsonschema/jsonschema/issues/1124#issuecomment-1632574249. + """ + + schema = { + "properties": {"x": {"$ref": "#/definitions/x"}}, + "definitions": {"x": {"type": "integer"}}, + } + + validator = validators.Draft202012Validator( + schema, + resolver=validators._RefResolver("", schema), + ) + self.assertEqual( + (validator.is_valid({"x": "y"}), validator.is_valid({"x": 37})), + (False, True), + ) + + + +def sorted_errors(errors): + def key(error): + return ( + [str(e) for e in error.path], + [str(e) for e in error.schema_path], + ) + return sorted(errors, key=key) + + +@define +class ReallyFakeRequests: + + _responses: dict[str, Any] + + def get(self, url): + response = self._responses.get(url) + if url is None: # pragma: no cover + raise ValueError("Unknown URL: " + repr(url)) + return _ReallyFakeJSONResponse(json.dumps(response)) + + +@define +class _ReallyFakeJSONResponse: + + _response: str + + def json(self): + return json.loads(self._response) diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/typing/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/typing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/typing/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/typing/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99ead012a7601e216825003019ba71356b21defb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/typing/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/typing/__pycache__/test_all_concrete_validators_match_protocol.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/typing/__pycache__/test_all_concrete_validators_match_protocol.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2b231094e702bbc153f4b09544ef07d986b7905 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/typing/__pycache__/test_all_concrete_validators_match_protocol.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/typing/test_all_concrete_validators_match_protocol.py b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/typing/test_all_concrete_validators_match_protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..63e8bd4052055e387854ae8a4bb906d78502cb69 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/jsonschema/tests/typing/test_all_concrete_validators_match_protocol.py @@ -0,0 +1,38 @@ +""" +This module acts as a test that type checkers will allow each validator +class to be assigned to a variable of type `type[Validator]` + +The assignation is only valid if type checkers recognize each Validator +implementation as a valid implementer of the protocol. +""" +from jsonschema.protocols import Validator +from jsonschema.validators import ( + Draft3Validator, + Draft4Validator, + Draft6Validator, + Draft7Validator, + Draft201909Validator, + Draft202012Validator, +) + +my_validator: type[Validator] + +my_validator = Draft3Validator +my_validator = Draft4Validator +my_validator = Draft6Validator +my_validator = Draft7Validator +my_validator = Draft201909Validator +my_validator = Draft202012Validator + + +# in order to confirm that none of the above were incorrectly typed as 'Any' +# ensure that each of these assignments to a non-validator variable requires an +# ignore +none_var: None + +none_var = Draft3Validator # type: ignore[assignment] +none_var = Draft4Validator # type: ignore[assignment] +none_var = Draft6Validator # type: ignore[assignment] +none_var = Draft7Validator # type: ignore[assignment] +none_var = Draft201909Validator # type: ignore[assignment] +none_var = Draft202012Validator # type: ignore[assignment] diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai-1.105.0.dist-info/licenses/LICENSE b/tool_server/.venv/lib/python3.12/site-packages/openai-1.105.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f011417af6f72ab5e00e7f48931028fa202ca7cb --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai-1.105.0.dist-info/licenses/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2025 OpenAI + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/message_creation_step_details.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/message_creation_step_details.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52a7999a710d9779a4cffe927cd73d3ebf74dde4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/message_creation_step_details.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/run_step.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/run_step.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17a21f4631780da6cafd122484eb01bec4c89420 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/run_step.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3c2c958e5316f9b2db1f299c7443275aa8703c4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e4aac67d5217f96aa0353c27909311a0b10de17 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta_message_delta.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta_message_delta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..126b4874a1e3d63cc8e0989684418bf3f518f9ba Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_delta_message_delta.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_include.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_include.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89f889c7bbe60b68eb36e96e889cdf90e46d5526 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/run_step_include.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/step_list_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/step_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75b8d18c1ff325e736f25d96e8818d7d5d33889a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/step_list_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/step_retrieve_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/step_retrieve_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae49be61ca976dc81d741a847aff837b7b061900 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/step_retrieve_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6506e86d5fed7ef9b260064f63e064799357bf80 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call_delta.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call_delta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7003470e0035b9af7fc00196c3c406e145601eb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call_delta.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call_delta_object.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call_delta_object.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8df65da9f9dd1c28f7c64e8a91933ed6e7ce589b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/tool_call_delta_object.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/tool_calls_step_details.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/tool_calls_step_details.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fc85258f0cc3f88fde7eadc8b7ac093881928d1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/beta/threads/runs/__pycache__/tool_calls_step_details.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70cb1aaec5977b7507eecc1b3e64d34c53601621 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b834c74e697aa8a720b2d63e3ce662f7744ba9b7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_allowed_tool_choice_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_allowed_tool_choice_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98976262619bb20a099ab6a8c44eb61d6e1285be Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_allowed_tool_choice_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_allowed_tools_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_allowed_tools_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0a08eba74879edf5f6f4ff78f7cbb906cc3a996 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_allowed_tools_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_assistant_message_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_assistant_message_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..597705c2ff7301c9139cd15717fde72d634d6c6e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_assistant_message_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_audio.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_audio.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ae2190901c3f75e9d1e25e37b2e88c4432d299c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_audio.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_audio_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_audio_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..054f9ea95986b9df4385b9179d7baa661aad2bfb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_audio_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_chunk.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_chunk.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6278bda7acc774f6c8b6eb3e51fc245d51994567 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_chunk.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_image.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_image.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee0f9251b25d76240ffb40199e0be9ac53a72bd1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_image.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_image_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_image_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c04689d62fc62948e267d78ec6a12881a506e650 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_image_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_input_audio_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_input_audio_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ad64a062fa59f3cd911061aff131d5324e4db7d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_input_audio_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9810bf429c2eb1a6337ae7d666697dd372e09248 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_refusal_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_refusal_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98ab53ba5744ec0724616a624d1a071d8348b8b4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_refusal_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_text.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_text.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..002c53db2bbddc43f02e8f0ac9ae3bd7f5d79bc9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_text.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_text_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_text_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3cffea73fbb32305c93bf099f1566507ed2e3e5b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_content_part_text_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_custom_tool_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_custom_tool_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28d74492c5109e708821c169d786b5692d3fe8aa Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_custom_tool_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_deleted.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_deleted.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df5df1a484e99bc5d8c63cb9bb24a0c13384118e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_deleted.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_developer_message_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_developer_message_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22c4f727520c0e848770f7f9613884346f1e0d78 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_developer_message_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_function_call_option_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_function_call_option_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..705ed172050164d714fa4362b7e51e69a254dbbb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_function_call_option_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_function_message_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_function_message_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9be007e6f2aad1daa78530ec1a11d12f368b7cb9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_function_message_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_function_tool.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_function_tool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aac4ec601579c720c91cc74800128386d490dbc7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_function_tool.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_function_tool_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_function_tool_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ae73cbed999a4f9d22831090ade73323c173537 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_function_tool_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc1de371b937356316fe0112ee76ba6f9eacb5c1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_custom_tool_call.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_custom_tool_call.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..981e6c5b2e24681ac3a67dee6297705d61b2b7b3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_custom_tool_call.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_custom_tool_call_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_custom_tool_call_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb53b38843e9f0c50344d63a1a385eb0d7cc5c68 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_custom_tool_call_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_function_tool_call.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_function_tool_call.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1ca0e205586a6d7f8911b7a5233ac7ea2fad377 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_function_tool_call.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_function_tool_call_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_function_tool_call_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5de4ac36382272971192ec2e37b4c9b712525bcd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_function_tool_call_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e9f9b4f105c9da11365ac23b69ef7651f0c7b9c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..69ca71ef39ea6ddfd330fff09caf6b83305a469b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c44fde6b32810605f9d359a3dedd0624e857767 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call_union_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call_union_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e064c78bd49ee2ea790fe2fd9d0eb80e529ae33 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_message_tool_call_union_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_modality.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_modality.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..617f9d655b1e40134a37dc49384f2fe8c11a7daa Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_modality.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_named_tool_choice_custom_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_named_tool_choice_custom_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ad35976c095653cb198a25c0bafe49eb6ec9b81 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_named_tool_choice_custom_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_named_tool_choice_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_named_tool_choice_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..324a54b23c4c0489427853f187bdaf2426cf3fe8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_named_tool_choice_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_prediction_content_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_prediction_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8f29908a061cb4f6e73f72c77e8afc8cd64e08a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_prediction_content_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_reasoning_effort.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_reasoning_effort.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3585926244b52c51dda45cb2e7f3961c0b788773 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_reasoning_effort.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_role.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_role.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f95a4f7eecd5b5904a6e2bd2aa5dec67930d20c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_role.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_store_message.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_store_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c7165e9b506d5bcccd2da409c1262862b80a32b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_store_message.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_stream_options_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_stream_options_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..974aecaa2182e79735deb5cf5cc35e996767642d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_stream_options_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_system_message_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_system_message_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82171008d335177365c63f3fda05ca8727a6ce24 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_system_message_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_token_logprob.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_token_logprob.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf075cefc1aab090207a4deed3c56701af65b8da Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_token_logprob.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_tool_choice_option_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_tool_choice_option_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dba88075427b45470bbf88f27af762de408ac6ca Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_tool_choice_option_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_tool_message_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_tool_message_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd2d121309085b0b9bb3efe72e6988a70b4b5ac1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_tool_message_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_tool_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_tool_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc857b841122fa436a4592a2cedb27beef05579b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_tool_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_tool_union_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_tool_union_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87eb6744e896455a395474c4d1ecb8f8da6ce8db Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_tool_union_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_user_message_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_user_message_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64096814c2987241f44e123637d3aa93f71f2425 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/chat_completion_user_message_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/completion_create_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/completion_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ba8700169c93dd5cd9bd9abb43bfe872228f920 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/completion_create_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/completion_list_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/completion_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdd050881b9a8bf78afc8d230dae0e617db4c52e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/completion_list_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/completion_update_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/completion_update_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60f6500b67a80661985bf911e1c74edea829d20c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/completion_update_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/parsed_chat_completion.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/parsed_chat_completion.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f7ab091d8bdba600371c3f4849d26853b5a00fd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/parsed_chat_completion.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/parsed_function_tool_call.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/parsed_function_tool_call.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6eb52c7b45206a7a8c0251ab9e359d4e9eed04c1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/__pycache__/parsed_function_tool_call.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/completions/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/completions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b8e62d6a64afa1627c8b4b2b660e02965180841c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/completions/__init__.py @@ -0,0 +1,5 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .message_list_params import MessageListParams as MessageListParams diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/completions/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/completions/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0dad20d741548385ed0e9509382f72bc39391877 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/completions/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/completions/__pycache__/message_list_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/completions/__pycache__/message_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7ea95937e67718685c322162ec7583835552390 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/completions/__pycache__/message_list_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/completions/message_list_params.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/completions/message_list_params.py new file mode 100644 index 0000000000000000000000000000000000000000..4e694e83ea271846b1c2533e38300da78a55c367 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/chat/completions/message_list_params.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["MessageListParams"] + + +class MessageListParams(TypedDict, total=False): + after: str + """Identifier for the last message from the previous pagination request.""" + + limit: int + """Number of messages to retrieve.""" + + order: Literal["asc", "desc"] + """Sort order for messages by timestamp. + + Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. + """ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dcd6ddf3b16117c8f9351374d7a7d2bbce0bf5e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/file_create_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/file_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68aa0a455946eeaa828b492185bdefc78356b1e2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/file_create_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/file_create_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/file_create_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe3335319ce954295bef503a773d46b677176289 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/file_create_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/file_list_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/file_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02716dcffa1cc031cb6bd3f318ff0a407346201c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/file_list_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/file_list_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/file_list_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1be814f0d1d1a7e9a1aa2c5ff91810ab5cf32a3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/file_list_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/file_retrieve_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/file_retrieve_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a4ff9cb12756bfdbe71e5e6c505c4418ac9af1e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/__pycache__/file_retrieve_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/files/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/files/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f8ee8b14b1c9672e41196e26a6080eebf45914b6 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/files/__init__.py @@ -0,0 +1,3 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/files/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/files/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2063361c4c5a24aef0992ee4ee2a87aa56f97f5b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/containers/files/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a16887fe0bc6c337782c38e4bf5de43191abec71 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/computer_screenshot_content.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/computer_screenshot_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f848c22a89f09f1fa5c83ee3cba9256cd8a32f7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/computer_screenshot_content.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/container_file_citation_body.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/container_file_citation_body.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2327c28829982d1ddc8e77ea91d474db5015105a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/container_file_citation_body.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce45c72055b1607584af258cfbe3d9ad3a4e1a24 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation_create_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0be18891c830f57033ce3ff0276d191c8e859a0c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation_create_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation_deleted_resource.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation_deleted_resource.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5f529e7681c5fe4af2b494aac5a4b3add553edd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation_deleted_resource.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation_item.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation_item.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c220c66aa661682a1d9b4a1a00bf56b469fca602 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation_item.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation_item_list.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation_item_list.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19111efe2027b5a4af7eca03e388e145bb2598b1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation_item_list.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation_update_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation_update_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32061ee82ac62d5c3bdf6005f0f59b980f50f66b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/conversation_update_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/file_citation_body.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/file_citation_body.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d917bb627c933c04bd45d61a08bb6870686655bf Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/file_citation_body.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/input_file_content.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/input_file_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45d8b47ff0a2885f6566f99babcaaa0cc3f2b14b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/input_file_content.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/input_image_content.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/input_image_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1644e7cc9b361f04af350e10fe41b30ea80f4698 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/input_image_content.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/input_text_content.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/input_text_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03aae395cf6a46c0953dceffcc06d2a3ec19fadb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/input_text_content.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/item_create_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/item_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6349a4a442092acf8fee8fd0dc05cd81866b7b5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/item_create_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/item_list_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/item_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b37ed43b001f3b84bbf99ef899cd9b7597c4fa4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/item_list_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/item_retrieve_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/item_retrieve_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44a36835fb561fd56e9f5906b0eeaaf27ba5c98d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/item_retrieve_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/lob_prob.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/lob_prob.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c7f5f484c8ee7523fbb6c0d43c811f75fab2785 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/lob_prob.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/message.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a2217511ac4ba952ccb95b385d2d42b232303c8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/message.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/output_text_content.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/output_text_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de3cd813a789676b6491b34d4a60ae348ee1d9ab Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/output_text_content.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/refusal_content.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/refusal_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ee54bdde3b03803cecaeb77b99c988a6f960c34 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/refusal_content.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/summary_text_content.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/summary_text_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9483f2229e1fb69b60b4a1abdc3aed1767cc5e0a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/summary_text_content.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/text_content.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/text_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9dbb93355552fb9215830b215bae1911aea04b2a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/text_content.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/top_log_prob.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/top_log_prob.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfb8e3b156844ad9c1ff4486440cd089e1042b5b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/top_log_prob.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/url_citation_body.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/url_citation_body.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5154673a2f19a9fd1f2df54a44fb2050acddce9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/conversations/__pycache__/url_citation_body.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d84d0864adeaaa3f66ceedc32687f2f20199a0e9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/create_eval_completions_run_data_source.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/create_eval_completions_run_data_source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3377f93233fc334978b6dd2f42c971327218b5e9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/create_eval_completions_run_data_source.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/create_eval_completions_run_data_source_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/create_eval_completions_run_data_source_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..87f7fe5bbc92dfca31595402ee5afc13062e09d3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/create_eval_completions_run_data_source_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/create_eval_jsonl_run_data_source.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/create_eval_jsonl_run_data_source.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb3a77f9caa3da15e68596b496f1482d24d993b5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/create_eval_jsonl_run_data_source.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/create_eval_jsonl_run_data_source_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/create_eval_jsonl_run_data_source_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fba2ee3b645f38057cde0ff163e9548d027044a8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/create_eval_jsonl_run_data_source_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/eval_api_error.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/eval_api_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef6e15000c293540e36e3692cc9f2d92c4c1e64e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/eval_api_error.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_cancel_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_cancel_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4fa5cf32fcd1f706f6941d17a57e6699241b8e6a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_cancel_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_create_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ffaa30b8d707a6468e7f3f8d60b036efbbd38c29 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_create_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_create_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_create_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b26efa67d71b79987ab496e6377750bc523ddb2e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_create_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_delete_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_delete_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a02124619a0ab0ecd60818d9b99a71ede5c9acdb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_delete_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_list_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78d6d0c4495bc271dd75ef8388d3c37595fb3e63 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_list_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_list_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_list_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..382d84138abf8a29cd33f289a5541f104343052c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_list_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_retrieve_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_retrieve_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb09a00e41387e74b7ff7ef3857237ba2d5c57d1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/__pycache__/run_retrieve_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b77cbb6acd6081ad51ac61921a9c93a51a9ff67a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/__init__.py @@ -0,0 +1,7 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .output_item_list_params import OutputItemListParams as OutputItemListParams +from .output_item_list_response import OutputItemListResponse as OutputItemListResponse +from .output_item_retrieve_response import OutputItemRetrieveResponse as OutputItemRetrieveResponse diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a439cdfbda83f6d5921b4d03a5a36bc110b0150 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/__pycache__/output_item_list_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/__pycache__/output_item_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83e0c41caa6225ded981f78e1d02aa990150cac1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/__pycache__/output_item_list_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/__pycache__/output_item_list_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/__pycache__/output_item_list_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce257e5e89a9e4b16937722c681b0641c54d76d8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/__pycache__/output_item_list_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/__pycache__/output_item_retrieve_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/__pycache__/output_item_retrieve_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5cf20ceeb7120e991d2a7f2f655b15c4c4a75ff Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/__pycache__/output_item_retrieve_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/output_item_list_params.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/output_item_list_params.py new file mode 100644 index 0000000000000000000000000000000000000000..073bfc69a7ae83145b0807448bc2d031541015e3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/output_item_list_params.py @@ -0,0 +1,30 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, Required, TypedDict + +__all__ = ["OutputItemListParams"] + + +class OutputItemListParams(TypedDict, total=False): + eval_id: Required[str] + + after: str + """Identifier for the last output item from the previous pagination request.""" + + limit: int + """Number of output items to retrieve.""" + + order: Literal["asc", "desc"] + """Sort order for output items by timestamp. + + Use `asc` for ascending order or `desc` for descending order. Defaults to `asc`. + """ + + status: Literal["fail", "pass"] + """Filter output items by status. + + Use `failed` to filter by failed output items or `pass` to filter by passed + output items. + """ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/output_item_list_response.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/output_item_list_response.py new file mode 100644 index 0000000000000000000000000000000000000000..72b1049f7b1c604ee3e0df7fed698178d709a91e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/output_item_list_response.py @@ -0,0 +1,104 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import builtins +from typing import Dict, List, Optional +from typing_extensions import Literal + +from ...._models import BaseModel +from ..eval_api_error import EvalAPIError + +__all__ = ["OutputItemListResponse", "Sample", "SampleInput", "SampleOutput", "SampleUsage"] + + +class SampleInput(BaseModel): + content: str + """The content of the message.""" + + role: str + """The role of the message sender (e.g., system, user, developer).""" + + +class SampleOutput(BaseModel): + content: Optional[str] = None + """The content of the message.""" + + role: Optional[str] = None + """The role of the message (e.g. "system", "assistant", "user").""" + + +class SampleUsage(BaseModel): + cached_tokens: int + """The number of tokens retrieved from cache.""" + + completion_tokens: int + """The number of completion tokens generated.""" + + prompt_tokens: int + """The number of prompt tokens used.""" + + total_tokens: int + """The total number of tokens used.""" + + +class Sample(BaseModel): + error: EvalAPIError + """An object representing an error response from the Eval API.""" + + finish_reason: str + """The reason why the sample generation was finished.""" + + input: List[SampleInput] + """An array of input messages.""" + + max_completion_tokens: int + """The maximum number of tokens allowed for completion.""" + + model: str + """The model used for generating the sample.""" + + output: List[SampleOutput] + """An array of output messages.""" + + seed: int + """The seed used for generating the sample.""" + + temperature: float + """The sampling temperature used.""" + + top_p: float + """The top_p value used for sampling.""" + + usage: SampleUsage + """Token usage details for the sample.""" + + +class OutputItemListResponse(BaseModel): + id: str + """Unique identifier for the evaluation run output item.""" + + created_at: int + """Unix timestamp (in seconds) when the evaluation run was created.""" + + datasource_item: Dict[str, object] + """Details of the input data source item.""" + + datasource_item_id: int + """The identifier for the data source item.""" + + eval_id: str + """The identifier of the evaluation group.""" + + object: Literal["eval.run.output_item"] + """The type of the object. Always "eval.run.output_item".""" + + results: List[Dict[str, builtins.object]] + """A list of results from the evaluation run.""" + + run_id: str + """The identifier of the evaluation run associated with this output item.""" + + sample: Sample + """A sample containing the input and output of the evaluation run.""" + + status: str + """The status of the evaluation run.""" diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/output_item_retrieve_response.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/output_item_retrieve_response.py new file mode 100644 index 0000000000000000000000000000000000000000..63aab5565fc55196147efe8dc7bdbe8909708557 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/evals/runs/output_item_retrieve_response.py @@ -0,0 +1,104 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +import builtins +from typing import Dict, List, Optional +from typing_extensions import Literal + +from ...._models import BaseModel +from ..eval_api_error import EvalAPIError + +__all__ = ["OutputItemRetrieveResponse", "Sample", "SampleInput", "SampleOutput", "SampleUsage"] + + +class SampleInput(BaseModel): + content: str + """The content of the message.""" + + role: str + """The role of the message sender (e.g., system, user, developer).""" + + +class SampleOutput(BaseModel): + content: Optional[str] = None + """The content of the message.""" + + role: Optional[str] = None + """The role of the message (e.g. "system", "assistant", "user").""" + + +class SampleUsage(BaseModel): + cached_tokens: int + """The number of tokens retrieved from cache.""" + + completion_tokens: int + """The number of completion tokens generated.""" + + prompt_tokens: int + """The number of prompt tokens used.""" + + total_tokens: int + """The total number of tokens used.""" + + +class Sample(BaseModel): + error: EvalAPIError + """An object representing an error response from the Eval API.""" + + finish_reason: str + """The reason why the sample generation was finished.""" + + input: List[SampleInput] + """An array of input messages.""" + + max_completion_tokens: int + """The maximum number of tokens allowed for completion.""" + + model: str + """The model used for generating the sample.""" + + output: List[SampleOutput] + """An array of output messages.""" + + seed: int + """The seed used for generating the sample.""" + + temperature: float + """The sampling temperature used.""" + + top_p: float + """The top_p value used for sampling.""" + + usage: SampleUsage + """Token usage details for the sample.""" + + +class OutputItemRetrieveResponse(BaseModel): + id: str + """Unique identifier for the evaluation run output item.""" + + created_at: int + """Unix timestamp (in seconds) when the evaluation run was created.""" + + datasource_item: Dict[str, object] + """Details of the input data source item.""" + + datasource_item_id: int + """The identifier for the data source item.""" + + eval_id: str + """The identifier of the evaluation group.""" + + object: Literal["eval.run.output_item"] + """The type of the object. Always "eval.run.output_item".""" + + results: List[Dict[str, builtins.object]] + """A list of results from the evaluation run.""" + + run_id: str + """The identifier of the evaluation run associated with this output item.""" + + sample: Sample + """A sample containing the input and output of the evaluation run.""" + + status: str + """The status of the evaluation run.""" diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c586a328b8d1ea3ad8f8e9b9bbc22e0422a932f0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/dpo_hyperparameters.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/dpo_hyperparameters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9c1be73f052b3f36a19b2a5e64c380ac252d2b49 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/dpo_hyperparameters.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/dpo_hyperparameters_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/dpo_hyperparameters_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..794c340a5cb6f05f774843f81fc849afefb2247c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/dpo_hyperparameters_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/dpo_method.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/dpo_method.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41300ddc9269c176739472afb70f9fbcd129041b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/dpo_method.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/dpo_method_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/dpo_method_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf15d7595a89a34f5744ec9a552b9de4250d3480 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/dpo_method_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4590d1642fe6d9aee4a62ed7fab4bd100bdada00 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fae033ea0629a8368ac4c72a5a2625ffe7680b08 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_integration.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_integration.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3221ea4de97fa333e626528dd0c14a3e189abe39 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_integration.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_wandb_integration.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_wandb_integration.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..060c97d3ba828ff2f0702565cc604cc57fd92ef5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_wandb_integration.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_wandb_integration_object.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_wandb_integration_object.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34cbc9d118d613c79834648a1a8757b3b6f3f8b9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/fine_tuning_job_wandb_integration_object.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/job_create_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/job_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f5c1a05cb10dbdd74069c7af1bfe0992a948564 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/job_create_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/job_list_events_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/job_list_events_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1373155e551433518171234f7a5854c426629e4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/job_list_events_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/job_list_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/job_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2cab9076761bb539a5fb2922d57c30053ab9d91 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/job_list_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_hyperparameters.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_hyperparameters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1047fe550c0ac77eeaa2a24865e3528fc90bc069 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_hyperparameters.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_hyperparameters_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_hyperparameters_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa83ed949371b775b07bc5088f698d4a0895e0d4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_hyperparameters_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_method.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_method.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a66bfdcb1665f2f63b8934732b85a40ecfc7a8b2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_method.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_method_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_method_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0fb2309f0f459f1b17f72172e12e17ec63a010e3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/reinforcement_method_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/supervised_hyperparameters.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/supervised_hyperparameters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6155dca6d41a563f8fa4f29a97a2372a8916d0a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/supervised_hyperparameters.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/supervised_hyperparameters_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/supervised_hyperparameters_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54e1ad2003bbdb16fdcc6d4676308d55e8ab8a02 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/supervised_hyperparameters_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/supervised_method.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/supervised_method.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..365272b5d60f793be9c970234f94eb0f72d0b40b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/supervised_method.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/supervised_method_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/supervised_method_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a04473de0a2a07ed832bac8c7e2ce6574598a6ce Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/__pycache__/supervised_method_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6394961b0b76af24d7c75fdfa5d8d50f8ff9319e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__init__.py @@ -0,0 +1,8 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .grader_run_params import GraderRunParams as GraderRunParams +from .grader_run_response import GraderRunResponse as GraderRunResponse +from .grader_validate_params import GraderValidateParams as GraderValidateParams +from .grader_validate_response import GraderValidateResponse as GraderValidateResponse diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..644c995eeb20de08ef82e3573d5d77c7bbf97c0a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_run_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_run_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c734b6ab28b267f8a8548238eff8660cc7ed1ea0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_run_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_run_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_run_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3dd8ece4deabfce122b4f969bfbb95f7d06336f6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_run_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_validate_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_validate_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b382b35a9b5218444cd78f5d51612a9da1442acc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_validate_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_validate_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_validate_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32b735e22d8a6b539e3c7c9594549eec882c8978 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/__pycache__/grader_validate_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/grader_run_params.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/grader_run_params.py new file mode 100644 index 0000000000000000000000000000000000000000..646407fe0924f41c13585013a3193e6d6fbe75b1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/grader_run_params.py @@ -0,0 +1,40 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Required, TypeAlias, TypedDict + +from ...graders.multi_grader_param import MultiGraderParam +from ...graders.python_grader_param import PythonGraderParam +from ...graders.score_model_grader_param import ScoreModelGraderParam +from ...graders.string_check_grader_param import StringCheckGraderParam +from ...graders.text_similarity_grader_param import TextSimilarityGraderParam + +__all__ = ["GraderRunParams", "Grader"] + + +class GraderRunParams(TypedDict, total=False): + grader: Required[Grader] + """The grader used for the fine-tuning job.""" + + model_sample: Required[str] + """The model sample to be evaluated. + + This value will be used to populate the `sample` namespace. See + [the guide](https://platform.openai.com/docs/guides/graders) for more details. + The `output_json` variable will be populated if the model sample is a valid JSON + string. + """ + + item: object + """The dataset item provided to the grader. + + This will be used to populate the `item` namespace. See + [the guide](https://platform.openai.com/docs/guides/graders) for more details. + """ + + +Grader: TypeAlias = Union[ + StringCheckGraderParam, TextSimilarityGraderParam, PythonGraderParam, ScoreModelGraderParam, MultiGraderParam +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/grader_run_response.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/grader_run_response.py new file mode 100644 index 0000000000000000000000000000000000000000..8ef046d1334ed33e5ef92e15b7076f2caa4e3d82 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/grader_run_response.py @@ -0,0 +1,67 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Dict, Optional + +from pydantic import Field as FieldInfo + +from ...._models import BaseModel + +__all__ = ["GraderRunResponse", "Metadata", "MetadataErrors"] + + +class MetadataErrors(BaseModel): + formula_parse_error: bool + + invalid_variable_error: bool + + api_model_grader_parse_error: bool = FieldInfo(alias="model_grader_parse_error") + + api_model_grader_refusal_error: bool = FieldInfo(alias="model_grader_refusal_error") + + api_model_grader_server_error: bool = FieldInfo(alias="model_grader_server_error") + + api_model_grader_server_error_details: Optional[str] = FieldInfo( + alias="model_grader_server_error_details", default=None + ) + + other_error: bool + + python_grader_runtime_error: bool + + python_grader_runtime_error_details: Optional[str] = None + + python_grader_server_error: bool + + python_grader_server_error_type: Optional[str] = None + + sample_parse_error: bool + + truncated_observation_error: bool + + unresponsive_reward_error: bool + + +class Metadata(BaseModel): + errors: MetadataErrors + + execution_time: float + + name: str + + sampled_model_name: Optional[str] = None + + scores: Dict[str, object] + + token_usage: Optional[int] = None + + type: str + + +class GraderRunResponse(BaseModel): + metadata: Metadata + + api_model_grader_token_usage_per_model: Dict[str, object] = FieldInfo(alias="model_grader_token_usage_per_model") + + reward: float + + sub_rewards: Dict[str, object] diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/grader_validate_params.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/grader_validate_params.py new file mode 100644 index 0000000000000000000000000000000000000000..fe9eb44e328399f9979c6067d74d3ec959c0cc1f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/grader_validate_params.py @@ -0,0 +1,24 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing import Union +from typing_extensions import Required, TypeAlias, TypedDict + +from ...graders.multi_grader_param import MultiGraderParam +from ...graders.python_grader_param import PythonGraderParam +from ...graders.score_model_grader_param import ScoreModelGraderParam +from ...graders.string_check_grader_param import StringCheckGraderParam +from ...graders.text_similarity_grader_param import TextSimilarityGraderParam + +__all__ = ["GraderValidateParams", "Grader"] + + +class GraderValidateParams(TypedDict, total=False): + grader: Required[Grader] + """The grader used for the fine-tuning job.""" + + +Grader: TypeAlias = Union[ + StringCheckGraderParam, TextSimilarityGraderParam, PythonGraderParam, ScoreModelGraderParam, MultiGraderParam +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/grader_validate_response.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/grader_validate_response.py new file mode 100644 index 0000000000000000000000000000000000000000..b373292d80ca94b22240e4f10641855f1fd404c9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/alpha/grader_validate_response.py @@ -0,0 +1,20 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Union, Optional +from typing_extensions import TypeAlias + +from ...._models import BaseModel +from ...graders.multi_grader import MultiGrader +from ...graders.python_grader import PythonGrader +from ...graders.score_model_grader import ScoreModelGrader +from ...graders.string_check_grader import StringCheckGrader +from ...graders.text_similarity_grader import TextSimilarityGrader + +__all__ = ["GraderValidateResponse", "Grader"] + +Grader: TypeAlias = Union[StringCheckGrader, TextSimilarityGrader, PythonGrader, ScoreModelGrader, MultiGrader] + + +class GraderValidateResponse(BaseModel): + grader: Optional[Grader] = None + """The grader used for the fine-tuning job.""" diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2947b33145f8a3f494f400198127e9f11c21b952 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__init__.py @@ -0,0 +1,9 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .permission_create_params import PermissionCreateParams as PermissionCreateParams +from .permission_create_response import PermissionCreateResponse as PermissionCreateResponse +from .permission_delete_response import PermissionDeleteResponse as PermissionDeleteResponse +from .permission_retrieve_params import PermissionRetrieveParams as PermissionRetrieveParams +from .permission_retrieve_response import PermissionRetrieveResponse as PermissionRetrieveResponse diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fe07e33e9aaf626bb978d79fd4744193f03e89e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_create_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e0cb3e2b9c7f2e961a4f37a5f8926b54b9329cb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_create_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_create_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_create_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0da299c008997701869eb563261a4d8378d1d7bb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_create_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_delete_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_delete_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b00308c5bb5113f84dec90d8cb0ffb5f570109ed Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_delete_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_retrieve_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_retrieve_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f801fa2d90f47fcd7fe523bc4086eae7af9aac3b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_retrieve_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_retrieve_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_retrieve_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ebdbf760b260cfbf86122b1364aec8d738cfe865 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/__pycache__/permission_retrieve_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/permission_create_params.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/permission_create_params.py new file mode 100644 index 0000000000000000000000000000000000000000..e7cf4e4ee401767a5cb8d2c838b46070197972f9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/permission_create_params.py @@ -0,0 +1,14 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Required, TypedDict + +from ...._types import SequenceNotStr + +__all__ = ["PermissionCreateParams"] + + +class PermissionCreateParams(TypedDict, total=False): + project_ids: Required[SequenceNotStr[str]] + """The project identifiers to grant access to.""" diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/permission_create_response.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/permission_create_response.py new file mode 100644 index 0000000000000000000000000000000000000000..9bc14c00cc3179edfeba861b8cced4d022180037 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/permission_create_response.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["PermissionCreateResponse"] + + +class PermissionCreateResponse(BaseModel): + id: str + """The permission identifier, which can be referenced in the API endpoints.""" + + created_at: int + """The Unix timestamp (in seconds) for when the permission was created.""" + + object: Literal["checkpoint.permission"] + """The object type, which is always "checkpoint.permission".""" + + project_id: str + """The project identifier that the permission is for.""" diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/permission_delete_response.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/permission_delete_response.py new file mode 100644 index 0000000000000000000000000000000000000000..1a92d912facbc602d271b8e346e52b595d7df1a1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/permission_delete_response.py @@ -0,0 +1,18 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["PermissionDeleteResponse"] + + +class PermissionDeleteResponse(BaseModel): + id: str + """The ID of the fine-tuned model checkpoint permission that was deleted.""" + + deleted: bool + """Whether the fine-tuned model checkpoint permission was successfully deleted.""" + + object: Literal["checkpoint.permission"] + """The object type, which is always "checkpoint.permission".""" diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/permission_retrieve_params.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/permission_retrieve_params.py new file mode 100644 index 0000000000000000000000000000000000000000..6e66a867ca4f01cec6f467ff27826ef24c147723 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/permission_retrieve_params.py @@ -0,0 +1,21 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import Literal, TypedDict + +__all__ = ["PermissionRetrieveParams"] + + +class PermissionRetrieveParams(TypedDict, total=False): + after: str + """Identifier for the last permission ID from the previous pagination request.""" + + limit: int + """Number of permissions to retrieve.""" + + order: Literal["ascending", "descending"] + """The order in which to retrieve permissions.""" + + project_id: str + """The ID of the project to get permissions for.""" diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/permission_retrieve_response.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/permission_retrieve_response.py new file mode 100644 index 0000000000000000000000000000000000000000..14c73b55d0656f49800bd655e8a72db3b4d900e3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/checkpoints/permission_retrieve_response.py @@ -0,0 +1,34 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import List, Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["PermissionRetrieveResponse", "Data"] + + +class Data(BaseModel): + id: str + """The permission identifier, which can be referenced in the API endpoints.""" + + created_at: int + """The Unix timestamp (in seconds) for when the permission was created.""" + + object: Literal["checkpoint.permission"] + """The object type, which is always "checkpoint.permission".""" + + project_id: str + """The project identifier that the permission is for.""" + + +class PermissionRetrieveResponse(BaseModel): + data: List[Data] + + has_more: bool + + object: Literal["list"] + + first_id: Optional[str] = None + + last_id: Optional[str] = None diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6c93da1b69f90552c97167f86cd345fd8dc05867 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/__init__.py @@ -0,0 +1,6 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from .checkpoint_list_params import CheckpointListParams as CheckpointListParams +from .fine_tuning_job_checkpoint import FineTuningJobCheckpoint as FineTuningJobCheckpoint diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c80d377485b7ba2d8abb5d69848af1dc87c9dfd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/__pycache__/checkpoint_list_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/__pycache__/checkpoint_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5949f70bf4d6692b005f6fcc1a0c7e0049047e89 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/__pycache__/checkpoint_list_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/__pycache__/fine_tuning_job_checkpoint.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/__pycache__/fine_tuning_job_checkpoint.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccd5d0b7e8fe4e97755ae0aed93a42e896616011 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/__pycache__/fine_tuning_job_checkpoint.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/checkpoint_list_params.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/checkpoint_list_params.py new file mode 100644 index 0000000000000000000000000000000000000000..adceb3b218c8c2cf5eb6c6ce8b975766e5a93c7a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/checkpoint_list_params.py @@ -0,0 +1,15 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from __future__ import annotations + +from typing_extensions import TypedDict + +__all__ = ["CheckpointListParams"] + + +class CheckpointListParams(TypedDict, total=False): + after: str + """Identifier for the last checkpoint ID from the previous pagination request.""" + + limit: int + """Number of checkpoints to retrieve.""" diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/fine_tuning_job_checkpoint.py b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/fine_tuning_job_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..bd07317a3e94bff0f2943504d6058da9026d1588 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/openai/types/fine_tuning/jobs/fine_tuning_job_checkpoint.py @@ -0,0 +1,47 @@ +# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +from typing import Optional +from typing_extensions import Literal + +from ...._models import BaseModel + +__all__ = ["FineTuningJobCheckpoint", "Metrics"] + + +class Metrics(BaseModel): + full_valid_loss: Optional[float] = None + + full_valid_mean_token_accuracy: Optional[float] = None + + step: Optional[float] = None + + train_loss: Optional[float] = None + + train_mean_token_accuracy: Optional[float] = None + + valid_loss: Optional[float] = None + + valid_mean_token_accuracy: Optional[float] = None + + +class FineTuningJobCheckpoint(BaseModel): + id: str + """The checkpoint identifier, which can be referenced in the API endpoints.""" + + created_at: int + """The Unix timestamp (in seconds) for when the checkpoint was created.""" + + fine_tuned_model_checkpoint: str + """The name of the fine-tuned checkpoint model that is created.""" + + fine_tuning_job_id: str + """The name of the fine-tuning job that this checkpoint was created from.""" + + metrics: Metrics + """Metrics at the step number during the fine-tuning job.""" + + object: Literal["fine_tuning.job.checkpoint"] + """The object type, which is always "fine_tuning.job.checkpoint".""" + + step_number: int + """The step number that the checkpoint was created at.""" diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f38be9243ac9bce7d7cccdfd649d428a25599da2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/label_model_grader.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/label_model_grader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47b838eb6be7fb2670629349596f4d2ad7288234 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/label_model_grader.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/label_model_grader_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/label_model_grader_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1a0a9588070b3e4ffb5c6a9df66f5b4c8797018 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/label_model_grader_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/multi_grader.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/multi_grader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..032a7f8330291574b7e45a507c5a78e2122a9a3b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/multi_grader.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/multi_grader_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/multi_grader_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4121ab187d5b2f6332c2185977bc05dc83c9c1ee Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/multi_grader_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/python_grader.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/python_grader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d639b9910e5500422514337cc8868585b3e32dd7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/python_grader.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/python_grader_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/python_grader_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a06dc960dbf170bddf50011644323a1df7b503e2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/python_grader_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/score_model_grader.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/score_model_grader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53f66607e3da73f91f47048f59c565bd9a4d9d31 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/score_model_grader.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/score_model_grader_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/score_model_grader_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7519eb2e19a98158648ab3229b58b70fbc18c5c5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/score_model_grader_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/string_check_grader.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/string_check_grader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cc404f28c6fbefd9638af7aae70e31facbefc1f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/string_check_grader.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/string_check_grader_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/string_check_grader_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d61a10afb1ba9b1b15a598737de325a0d1dc8673 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/string_check_grader_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/text_similarity_grader.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/text_similarity_grader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bca329b6ff9fa27593bb758a9f12f5775373938f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/text_similarity_grader.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/text_similarity_grader_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/text_similarity_grader_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35df3d0190499bf77e0a366f84374a852a3a4125 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/graders/__pycache__/text_similarity_grader_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a99538164a53b248acfcf4217ce4c66932fb6e98 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/client_secret_create_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/client_secret_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c61fc66c6260fa645ecf34b6ca5110a47e82cc65 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/client_secret_create_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/client_secret_create_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/client_secret_create_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3408d9574b82e9364adb36f18d37dba8d93ef1df Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/client_secret_create_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_created_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_created_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9aee59ed27599aaa103c48704e9c8db0a0833ae3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_created_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9b3fee9bdce0b1935092f78d100934cfdaf383c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_added.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_added.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b01e47225a03fc0dde4e4c1fdf3006a911cb2e79 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_added.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_create_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_create_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2775a4bf0e2fea79b33cd91ac90c7962d2990a4d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_create_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_create_event_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_create_event_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c7259b40a028f1d1a7fd7dfd19c442e3a82f098 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_create_event_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_created_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_created_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df226d34a1515e1c9e7ffa779596b559cf24475a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_created_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_delete_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_delete_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e53a3d20239895b376c024c2c5e61c5923ae3f2a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_delete_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_delete_event_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_delete_event_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..771880f84828904f9f2139372d3ec19d3bf3dce2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_delete_event_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_deleted_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_deleted_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ceac5b0be26499ac56a6a8e4fdb622fe1e84f412 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_deleted_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_done.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_done.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1861270b94cdb3616c8c12eaceed3ae093a7aefe Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_done.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_input_audio_transcription_completed_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_input_audio_transcription_completed_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e054ec878c35a3e40788de53c99cc22f41497a7a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_input_audio_transcription_completed_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_input_audio_transcription_delta_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_input_audio_transcription_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17c42b1afe1e04235d77e598ae899cfc64687e0b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_input_audio_transcription_delta_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_input_audio_transcription_failed_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_input_audio_transcription_failed_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7415a8b1ea42e6f4b29e2546da1dff284adf8487 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_input_audio_transcription_failed_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_input_audio_transcription_segment.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_input_audio_transcription_segment.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cdb40ba70c211ca1d878d30ada64f391e8726f52 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_input_audio_transcription_segment.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73ce31bf7f1fab26eeef2c3ca6c330b9b016fe90 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_retrieve_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_retrieve_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f328a953a25a9ec6b53a939c68d792ea652d20b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_retrieve_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_retrieve_event_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_retrieve_event_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfa84cc50a78150266d8e10b32359c25c670fe94 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_retrieve_event_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_truncate_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_truncate_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a543e04b5ef68354b05a42017fc5f0122ac0681 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_truncate_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_truncate_event_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_truncate_event_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a7a7a2187aa0a05a7413de0af239aaf1b994a8b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_truncate_event_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_truncated_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_truncated_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee8a532a561a8c2e32a692de2da44c898372b296 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/conversation_item_truncated_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_append_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_append_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef3907f3c7339d1f7997722e78eb4bd23cfa5155 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_append_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_append_event_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_append_event_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a01a6c6946e0648e242e5d5693806692faa563b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_append_event_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_clear_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_clear_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab5ecbb187bd67fd197ba5092dfdf172cbb6cd1d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_clear_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_clear_event_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_clear_event_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..27eaabb027c1dad49e541da79aa7aed11794637f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_clear_event_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_cleared_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_cleared_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e92b11bbeddedc83a41eee120f684984c5618041 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_cleared_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_commit_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_commit_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76e4526fe662e269159db2cdec03e0f2639f8451 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_commit_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_commit_event_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_commit_event_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13502c51ac3e70f3ab9a713a88d6699dad095ae8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_commit_event_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_committed_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_committed_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6033a4a74fb52131f4378174f12462b2fa62740c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_committed_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_speech_started_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_speech_started_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b70475fd3e6cda69475367afd7c9041a3a862d6f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_speech_started_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_speech_stopped_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_speech_stopped_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddecc3e67a649a8d761c0b8db06c3ed07f3af359 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_speech_stopped_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_timeout_triggered.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_timeout_triggered.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a40e6b29326838a58ecc86a78e503212bf304485 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/input_audio_buffer_timeout_triggered.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/log_prob_properties.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/log_prob_properties.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6f416bf54e223df9e1f579f7e979a7428d2f399 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/log_prob_properties.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/mcp_list_tools_completed.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/mcp_list_tools_completed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d21d4de198b7a1c2e1c31803ba58f4236e4383a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/mcp_list_tools_completed.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/mcp_list_tools_failed.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/mcp_list_tools_failed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7a4b94fee75965e9b5ea5002cc648f40df0b51a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/mcp_list_tools_failed.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/mcp_list_tools_in_progress.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/mcp_list_tools_in_progress.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02aee25e6bcb714028613880d0257e48fa10616e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/mcp_list_tools_in_progress.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/output_audio_buffer_clear_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/output_audio_buffer_clear_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cbd6c9dddad548df4e59e664b6e020730b9edb5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/output_audio_buffer_clear_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/output_audio_buffer_clear_event_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/output_audio_buffer_clear_event_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89eb582845dea204d1532dd5d5a9856a0dbcd5bc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/output_audio_buffer_clear_event_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/rate_limits_updated_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/rate_limits_updated_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9709418e2b227a0d126065c71abbb0bd5a4ff28e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/rate_limits_updated_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_audio_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_audio_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..986052ab0bf20b948fcf276e38e27aaa47f4238f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_audio_config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_audio_config_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_audio_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09cf39bc5160bcbf1df6a50a08355c9f85b5dee0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_audio_config_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_client_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_client_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ebb27350172133fc0f5db83e89c514d72a3e3d7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_client_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_client_event_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_client_event_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2711e7b152f50ad0908a0213b47f5de2f1fe8b3e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_client_event_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_client_secret_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_client_secret_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..344233787c47b01a26ba674eeffd1cc271be44ad Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_client_secret_config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_client_secret_config_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_client_secret_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c19932d23d6f20b5b3b9cd211d314343932cc89 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_client_secret_config_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_connect_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_connect_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dd03ef5173678676cb80ce045fe27a7ddcb2bb1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_connect_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_assistant_message.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_assistant_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61e2684912db49d88116d91bd8edd264f971849b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_assistant_message.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_assistant_message_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_assistant_message_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9188e17c1e0f506ef53ca64ed2b538053434a9ed Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_assistant_message_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_function_call.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_function_call.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a93a526103e9577a05e479a48523b1c8a412410 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_function_call.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_function_call_output.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_function_call_output.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2ca8b757dbbea91758a1a387698b198c70cc06d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_function_call_output.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_function_call_output_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_function_call_output_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4564f6869f9f6fb26d3285ca968a71dc56fce662 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_function_call_output_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_function_call_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_function_call_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..702a3496a1ce2148c59a2b419105aad969e91b81 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_function_call_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_system_message.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_system_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fde024983ec5bcfd1335cfd77a69afd41806c1be Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_system_message.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_system_message_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_system_message_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78f6690a2781ffab43b07c46be2c14f4a40376e2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_system_message_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_user_message.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_user_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64b3ca3a8e3d2840f2aead4a2e6da29f5d0267f4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_user_message.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_user_message_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_user_message_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68eea6fa8cdfecdb38230fdb74464d6695f3eec9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_conversation_item_user_message_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_error.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21182a99444bff49fa22ec8a6abc7f1a6c8ab380 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_error.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_error_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_error_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3797a6a2ed85911a118ba159d508f08b830cd6a3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_error_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_approval_request.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_approval_request.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d796a28e3fd4a1af710efd6f4e84fe51e075a348 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_approval_request.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_approval_request_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_approval_request_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b8b67add45a47e3119090a1326c491434bb06ac Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_approval_request_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_approval_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_approval_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3008df7cf199afcbc757bc9b5f142c3343f5a487 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_approval_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_approval_response_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_approval_response_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6297beb4814c822e4701d6c7b7b27250cc063a6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_approval_response_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_list_tools.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_list_tools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5f1b72ed153e1c169d3ac132947c34360e8314a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_list_tools.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_list_tools_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_list_tools_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59062c68ed66dbe8e7cf7b308f81deaddb03a958 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_list_tools_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_protocol_error.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_protocol_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da4710d23cd0335faaf87a043a59ad4cc4446617 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_protocol_error.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_protocol_error_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_protocol_error_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3af487b05a55cd2089b9b0a59a2487521553c82 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_protocol_error_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_tool_call.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_tool_call.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f910a4a9425d1289ef63b04f3fd89020bae397b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_tool_call.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_tool_call_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_tool_call_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eab079de245cd95c18353f2db010f0e223fd5517 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_tool_call_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_tool_execution_error.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_tool_execution_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2242da6981596551ac49f8a097adf882c84e7e3b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_tool_execution_error.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_tool_execution_error_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_tool_execution_error_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0cc8a3b8b26d945bd7028f25de388b4974fd3e54 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcp_tool_execution_error_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcphttp_error.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcphttp_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51c320d5e99772f35fe0af2b7230c7f28b580a4e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcphttp_error.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcphttp_error_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcphttp_error_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1322f59387cc73685c3489301ab57c654d15bc1f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_mcphttp_error_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ff4c02a969093bf4cb8895cd65e0a6cbbc7c5e5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_response_status.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_response_status.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9203a9214a1674925612c8369bfe56845ec70240 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_response_status.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_response_usage.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_response_usage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02720d0ac38be4609f1bdcbcee1403e8f9a58000 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_response_usage.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_response_usage_input_token_details.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_response_usage_input_token_details.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e3aa4415b40f18cdfad177058e7e93b82e4d15c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_response_usage_input_token_details.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_response_usage_output_token_details.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_response_usage_output_token_details.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31fcef797f31c27b3899c54b92b593c56835d4a0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_response_usage_output_token_details.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_server_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_server_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7d43d7853a3a330efeed8f13ed9382aaaaf1a1c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_server_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_session.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_session.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2110e3fddaf1e403b38a6c87ac0de6ab9c5e09d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_session.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_session_create_request.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_session_create_request.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1625408e9694498f0c92df1b256ad20f1d8d8638 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_session_create_request.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_session_create_request_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_session_create_request_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2547d331a950b2c7658b7949e5ef897eae527271 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_session_create_request_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_session_create_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_session_create_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9760ef0cfb721408d37cd1e884950ed641888119 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_session_create_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tool_choice_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tool_choice_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2f56e188c75f69a56291ee94caed6b19b0b92ad Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tool_choice_config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tool_choice_config_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tool_choice_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2437dbb5339ef901e369e5522df135a80d53ccad Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tool_choice_config_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tools_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tools_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..86f72f1dfc11017b921b1d080c636c9d8b6ffd39 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tools_config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tools_config_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tools_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17cedd4df6cb768da2d54fd1b980ff6b4c424586 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tools_config_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tools_config_union.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tools_config_union.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5d26d0ce87d30ee90346a8c130d8455a3d55c21c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tools_config_union.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tools_config_union_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tools_config_union_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94f9770eff929686a79307e3c814f4464f174ae4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tools_config_union_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tracing_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tracing_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1429b51f1cc32fdf4436b578d9e9a8fd62242cf2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tracing_config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tracing_config_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tracing_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b35f57fc58079a6149acf925b9d612a9eb521a7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_tracing_config_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_transcription_session_create_request.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_transcription_session_create_request.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f65e94dc615c6ac86190f597de30f67bb659fdaf Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_transcription_session_create_request.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_transcription_session_create_request_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_transcription_session_create_request_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb3fd0bf4cf15bb1a429a01a0a03a91ec709f93e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_transcription_session_create_request_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_truncation.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_truncation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26d2c1915b1acaa12082cbd73a6367ea631c519a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_truncation.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_truncation_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_truncation_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..597c563d807429a5d1b48e2786103ebdcae6ff68 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/realtime_truncation_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_audio_delta_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_audio_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b65e5d0e0a6f3a7cc89784d41b893318c9b8caa Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_audio_delta_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_audio_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_audio_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..409e0546f306c1b8c068e79e37160d4c6d3e82e3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_audio_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_audio_transcript_delta_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_audio_transcript_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..decc0c90da2028831399f78ec52c0567e2dde9e9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_audio_transcript_delta_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_audio_transcript_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_audio_transcript_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a6c50cb43fd2c0b0484d55372ffcfdc7fa7a7f8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_audio_transcript_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_cancel_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_cancel_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b21b7ac0f5486eca8f0bebd4bb6944e20bc30c59 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_cancel_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_cancel_event_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_cancel_event_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43cc52698909df7e2a1c37219f19c0b79187fab1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_cancel_event_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_content_part_added_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_content_part_added_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc0a355bbc1392cab9c5d36370aeff72241e05c2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_content_part_added_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_content_part_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_content_part_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..139bb9b340bd5fc31ea8f72645f0b9857963ee26 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_content_part_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_create_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_create_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9c965559cad20e5e2465876a3a6e9a3c4c86dd6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_create_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_create_event_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_create_event_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d346c5cf8e5cec219c006e46f12bd17e65ad093d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_create_event_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_created_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_created_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..24d59475661b1b058a4bc312f98fab8ac84a0878 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_created_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0056bf7e143c8cc74e95193d650c9fdda4bc2ffe Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_function_call_arguments_delta_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_function_call_arguments_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d44888c1e52fda62591184fcd3777c907c604b46 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_function_call_arguments_delta_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_function_call_arguments_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_function_call_arguments_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1bede809ecfa216a0f622d11fcfc9b973c3f8b89 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_function_call_arguments_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_mcp_call_arguments_delta.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_mcp_call_arguments_delta.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30ebf3eba27fa579735f541f209ae8b3bff960e2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_mcp_call_arguments_delta.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_mcp_call_arguments_done.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_mcp_call_arguments_done.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..333453ea92237a82b1a02089516bd0c854385994 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_mcp_call_arguments_done.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_mcp_call_completed.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_mcp_call_completed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd1c16718f64188d3d0206541730affa8a001d3f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_mcp_call_completed.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_mcp_call_failed.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_mcp_call_failed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef7abbf6e29a22b3ee7800b982ed9b866b4daf17 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_mcp_call_failed.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_mcp_call_in_progress.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_mcp_call_in_progress.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f6455d8390d13ee05c37e1c2a8c22f76f044e62 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_mcp_call_in_progress.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_output_item_added_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_output_item_added_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2599224d11776f6f19515b7519b94e6c9c3995d8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_output_item_added_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_output_item_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_output_item_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..396f817749d9a170cd706fb211744260a6f90d4f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_output_item_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_text_delta_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_text_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1900b08cd237336c7010ec7aff24687e7cbd40c5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_text_delta_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_text_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_text_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d29c57c0353fa77a2ab26ae542d08e3be861434 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/response_text_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/session_created_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/session_created_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2b85d58baddecf8728579bbcb75d65f83283965 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/session_created_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/session_update_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/session_update_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..feb1c56fb5570fae157bae05a6b657bd3af0cbb3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/session_update_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/session_update_event_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/session_update_event_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ace30e158b44f430530c30bd1c9a364c9d5e5af6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/session_update_event_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/session_updated_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/session_updated_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..168587a744e57ba80e6354128460c06b87efddac Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/session_updated_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/transcription_session_created.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/transcription_session_created.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0412b6d979b5d6eb47d12cac134780cd5816f1d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/transcription_session_created.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/transcription_session_update.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/transcription_session_update.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39573db452560063a7410ff7e633aeb0035c5377 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/transcription_session_update.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/transcription_session_update_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/transcription_session_update_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbee7d127a16932ac0d0ee91a4a87ac81cfe53b1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/transcription_session_update_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/transcription_session_updated_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/transcription_session_updated_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37803367110a86bf25f39df0699bc6e73a7d3522 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/realtime/__pycache__/transcription_session_updated_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e962f63a956964d3de52aec9572bfd7030ba78a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/computer_tool.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/computer_tool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3bce1003eac1a18f94150b02fef2f669164f2ef Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/computer_tool.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/computer_tool_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/computer_tool_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd85764ccd2d658d3dc53671cabdfa98f36f40f0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/computer_tool_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/custom_tool.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/custom_tool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33aa2b33114efe7688f7980930d60424ba00f809 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/custom_tool.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/custom_tool_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/custom_tool_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1539911d5bf84712fe75190082e72df91382819b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/custom_tool_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/easy_input_message.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/easy_input_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc2f3565ea39ef9795b06a3c77cefa5b197a11ef Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/easy_input_message.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/easy_input_message_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/easy_input_message_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3520b92c91ab72d7061c476c79fa1125b0f4a9e0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/easy_input_message_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/file_search_tool.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/file_search_tool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..225eb9eaf4f6e8561aa709e128852838faa1dbab Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/file_search_tool.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/file_search_tool_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/file_search_tool_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ddb16b9946da180340835895f3982b113368f4c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/file_search_tool_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/function_tool.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/function_tool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d35c738d25211ae28256cb89314e61232544612 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/function_tool.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/function_tool_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/function_tool_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16ccb7cca80aa139a6778eab8a2648c714926a7b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/function_tool_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/input_item_list_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/input_item_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57238f51cf4fb93325cb326823a5c7b357f08cf9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/input_item_list_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/parsed_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/parsed_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4060fec5706379ca0e7ef9826b3c2f9b1e4d92ed Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/parsed_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1738a46a635cf654ef480af2e9fa752ce0a22329 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_audio_delta_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_audio_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4099c2e61ca334c997d16c1ce7c3b08f4150ada1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_audio_delta_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_audio_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_audio_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c1962c20314eb84e40b05a03be80f4fe8bf6702 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_audio_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_audio_transcript_delta_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_audio_transcript_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96fa30f7c274d3961293a3396a6de996f8d63b1f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_audio_transcript_delta_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_audio_transcript_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_audio_transcript_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50c17ae0dcf507c4b53a6709a57053f837845798 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_audio_transcript_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_code_delta_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_code_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ead60e438874d5d114dbeeda87b9eec74d8ecd3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_code_delta_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_code_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_code_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02c98ef3f843cb3a40300e1cf316ef9cba43b579 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_code_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_completed_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_completed_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6829578462da21ae92cd3e52aca86e379d681a55 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_completed_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_in_progress_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_in_progress_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b4c903c9eb99bc5e148be2ce9138a23087bbf4a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_in_progress_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_interpreting_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_interpreting_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0993920a69e954caa52455d899ca2a670419cfdb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_call_interpreting_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_tool_call.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_tool_call.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6dc0e2f3f2c0a23a7867a7ae09a367534df82a6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_tool_call.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_tool_call_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_tool_call_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35658b35a578424969aa007e18b9147a65811eec Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_code_interpreter_tool_call_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_completed_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_completed_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ece0c43438067819166c29240a97161502be893 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_completed_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_computer_tool_call.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_computer_tool_call.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f66c552429f63dda6b8f0e33fcd571543b9afb87 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_computer_tool_call.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_item.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_item.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a6743a37d017cb109cb786c7f76a1f8665884ba Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_item.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_screenshot.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_screenshot.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff1d478e0e8da500abe8054089c663d75693857b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_screenshot.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_screenshot_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_screenshot_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6be357ea309fb2d9579db1cf4377756e2be403ca Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_output_screenshot_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5fba015f6791d600652d1f2493a69204821dc52 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_computer_tool_call_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_content_part_added_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_content_part_added_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0da9ae77003a84ff865f96ee69915a4bcdc4617d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_content_part_added_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_content_part_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_content_part_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43bf9b42675fc50f714ad8d2e81a2b010f8ae9d0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_content_part_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_conversation_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_conversation_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd5c12a0245cc455758298a022dfbbbc80df903c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_conversation_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_create_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfbe7c67784abae65a68c148b5d6d08106277187 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_create_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_created_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_created_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d35f4c6f367a8d132ee91348f1daa1ff04da0a47 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_created_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d01aa753ad1f0cc8e46aa32c0cbc5f4b7ce7a359 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call_input_delta_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call_input_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea7bee65685eaefeceaa5e00adfbf3d288e64c58 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call_input_delta_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call_input_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call_input_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4db8a10893dc6d316751065291cca5765c473df Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call_input_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call_output.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call_output.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16c8d1bbd7b75cb823339b70b923ed0aaccb2eeb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call_output.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call_output_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call_output_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fd4399faa4e77005a7e448fbc06ff7539532fb8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call_output_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c61a106d10e2b263434f0a7c134bbd116e2ac03 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_custom_tool_call_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_error.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_error.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c72cb1ad9b471b592482297b5b1d3e5c5765a679 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_error.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_error_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_error_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0fd2f4cd043fce6a0855d1c5f5af45182c8d0fc8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_error_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_failed_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_failed_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f75eb3eba3b7d6985df5c6d0e176b5de255de847 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_failed_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_file_search_call_completed_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_file_search_call_completed_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ade3b22e0b77e4de3bb791e46406b930e34fafa9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_file_search_call_completed_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_file_search_call_in_progress_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_file_search_call_in_progress_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..750747eba88c068b0b8da2179974a921de4cfbc8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_file_search_call_in_progress_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_file_search_call_searching_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_file_search_call_searching_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e74f90793c5b9dd70a1685ba2a8591c086bbc273 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_file_search_call_searching_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_file_search_tool_call.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_file_search_tool_call.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff591d741374ca948f0b0c8267904fe33d19d2d7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_file_search_tool_call.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_file_search_tool_call_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_file_search_tool_call_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..576822a5ba341d44af32f78614f74b8e61664ca4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_file_search_tool_call_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_format_text_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_format_text_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9bdabf99f6521bd02248e28d9c61adb3850441a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_format_text_config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_format_text_config_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_format_text_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51117dc3a8a15fe0a544244b96c2f8f4bf2f541f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_format_text_config_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_format_text_json_schema_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_format_text_json_schema_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d341fdebbc8aa63cde161b05a91df7fc24f947a2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_format_text_json_schema_config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_format_text_json_schema_config_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_format_text_json_schema_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cac73f5ad960d9befd61e199599e0c18255fda6f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_format_text_json_schema_config_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_call_arguments_delta_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_call_arguments_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f13a57c4922c535a8cb7857719a3bdeeb44417ac Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_call_arguments_delta_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_call_arguments_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_call_arguments_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..444a6d321b20c909f9fed05e8defdfa086b3b59b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_call_arguments_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_tool_call.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_tool_call.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9c28275b2d2d08b4a9efcf295e7a596a9a7dcd9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_tool_call.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_tool_call_item.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_tool_call_item.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b17e0bfb0dc6f6c3d9ce4f0fe04307c4105a08ff Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_tool_call_item.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_tool_call_output_item.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_tool_call_output_item.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f1ebec379b1cfaadad42d38be419fda40174fa5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_tool_call_output_item.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_tool_call_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_tool_call_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ab422d7ad65b63ed6c087ee12fb634aa1621420 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_tool_call_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_web_search.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_web_search.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c6c9ee57a3e438eb35133e0df8c072fc50aa194c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_web_search.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_web_search_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_web_search_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fac7a54c77fb3a96d543a3651e92fda2eff487ee Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_function_web_search_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_image_gen_call_completed_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_image_gen_call_completed_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..469aa72a9e286819ce06c5d79a0f21642c6ad4ec Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_image_gen_call_completed_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_image_gen_call_generating_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_image_gen_call_generating_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f8f164a33466f562e4fc14b5c5121b6d92f4c09 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_image_gen_call_generating_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_image_gen_call_in_progress_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_image_gen_call_in_progress_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5f2eed250120011f22ff8b848b38258f44d63a9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_image_gen_call_in_progress_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_image_gen_call_partial_image_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_image_gen_call_partial_image_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbcabcb0f1729c9a5cd001c629b19acf5a954306 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_image_gen_call_partial_image_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_in_progress_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_in_progress_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6b499f84c24cde9cbada52028c27405bd173af9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_in_progress_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_includable.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_includable.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..550a7c5d6335dfab0b7554576eadaaaabff39de3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_includable.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_incomplete_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_incomplete_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ee89a67ce3f3d85917ab7507fc4d8a5c3843131d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_incomplete_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_audio.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_audio.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2437b7f5bb6d5547717de1a7bd2320c18b8c11a7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_audio.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_audio_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_audio_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76a5bdb0e4fef1731513507ca577c884e5f1a500 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_audio_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_content.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_content.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a64963c5a66700b106ddb7387c43fd1d86efc99 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_content.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_content_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_content_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c1c0a4de0c48e04dee450b554a5658f4c5e72e6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_content_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_file.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_file.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f5707747b189d44679f5987959874be2f8f8643 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_file.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_file_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_file_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e0efacc1a332bd74408b4c95f26224fad5d0b0c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_file_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_image.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_image.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2e0d94b9259a77fc785a8378469ab86b9c7ae62 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_image.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_image_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_image_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e67a52f6d9c12628384107649608315810540d4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_image_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_item.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_item.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..067d09296925685da94f397ac030ebcadcd51838 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_item.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_item_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_item_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0b8511dcaaec62e257186e3d13d11482620dc511 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_item_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_message_content_list.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_message_content_list.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95ffd7b0829e410956ed8df557ba3227f6b7832f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_message_content_list.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_message_content_list_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_message_content_list_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..261a6b29e6456d57230709bbb454e66fc39459df Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_message_content_list_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_message_item.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_message_item.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9814e2f3970df965793d95d8e3336f13f4d081f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_message_item.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ab34fe269780b39dbe327caee3b74e215295285 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_text.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_text.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c9ba80295963a59c394b94e28dbdf72b4f87e1e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_text.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_text_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_text_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10385b5c5e03e3a56ff4a7035e0215daebfe215e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_input_text_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_item.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_item.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..145259610d37fc2b8d4f51e6d93722a2673c0efd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_item.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_item_list.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_item_list.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7be51b9b70e9ef058e926ddc95716fba18d9aed0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_item_list.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_call_arguments_delta_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_call_arguments_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bff5a732541c833b922d921d30168b23aea99961 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_call_arguments_delta_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_call_arguments_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_call_arguments_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01b022be7eed60d83f050658aeb1b0e1ce36f398 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_call_arguments_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_call_completed_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_call_completed_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a5de1ce632a745577e467c06d1dfcf7154c73e7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_call_completed_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_call_failed_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_call_failed_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d007cfde86d33674c5174c6eb5570fe4b04bd5c8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_call_failed_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_call_in_progress_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_call_in_progress_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59eef48b98539446d39d9d119c6144c75e96e20d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_call_in_progress_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_completed_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_completed_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7715ee697a428c63720f5581a79eefd438eda2c9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_completed_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_failed_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_failed_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eec4bf5212824ffc3603600ec6d1b7035d68b8ad Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_failed_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_in_progress_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_in_progress_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18d99a7b76dfb5d3ea74b8117e25a5cf23b119c2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_mcp_list_tools_in_progress_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_item.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_item.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d484b901efc57276562f14206aba3991a674a913 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_item.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_item_added_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_item_added_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfc7c759ebb62732164163c3dc553a3fd60ddb9e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_item_added_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_item_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_item_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6bed5f3cefee6a1066d3c42c50bd33e568640ede Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_item_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_message.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_message.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01763bb69abda247e7f803bcfce50d75466c4c37 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_message.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_message_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_message_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf33ba77fd75c31d9fcb8d237d917f6855e810b4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_message_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_refusal.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_refusal.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de75d6450bfaea5714bd009fab26886763570874 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_refusal.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_refusal_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_refusal_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a65e94ac3323f474197ccda705e435d4dfc2b4d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_refusal_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_text.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_text.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99588ab16cea46a2e8f415386ab7664a349b3676 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_text.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_text_annotation_added_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_text_annotation_added_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..656893f8bc3bbb8f9d28a83ec3e97b8473b0dfc0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_text_annotation_added_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_text_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_text_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a022c2c845e803fa9186d446e61ae16b363585c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_output_text_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_prompt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_prompt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2d341c56791884b84615937be24665a33a730f9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_prompt.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_prompt_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_prompt_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2500b418bf6a16b76ac1826affc769e1e54b721 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_prompt_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_queued_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_queued_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88c416276d9103acec1c395896ea2bfa56e3a7d1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_queued_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_item.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_item.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b2dcc69281b9beb016599b583668ae966d423b7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_item.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_item_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_item_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c62ab2fad28b6abd2b1addbca1b70c39946edba6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_item_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_part_added_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_part_added_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1133b4289cd70c0900038689150435f12aab96f2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_part_added_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_part_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_part_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9764d701e5fd8b071d473efbd8a9cd3196910a7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_part_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_text_delta_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_text_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b947a85c5d26e84b5dca2773f3d6b4f05b895704 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_text_delta_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_text_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_text_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0085acdd7ad52396dcd46f2d2f0fc107d6565af Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_summary_text_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_text_delta_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_text_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e09163d4d8f527c6c2db458c604306faf75121a5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_text_delta_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_text_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_text_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..90e509f7989211ddd37dd6f58399301030ee42d2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_reasoning_text_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_refusal_delta_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_refusal_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23912d1df72734383f74f4d3719eb6a83a4ecd1f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_refusal_delta_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_refusal_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_refusal_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d69f4e1866fdda8c0bd0ea82f87ce44b14dc116 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_refusal_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_retrieve_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_retrieve_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bd8e55f14d19974fa8e39d647abcf8949db60f9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_retrieve_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_status.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_status.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1beacea0b784167374f4d45d0fe47f7c2946828b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_status.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_stream_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_stream_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec9d237a78f35f9a8e9a20c2d5a51ff08b1836b4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_stream_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_text_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_text_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1ba53dd0dd2f563c3e377570c98ee6bf72d5427 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_text_config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_text_config_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_text_config_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ba95557feaf9676c30efa5ec025eff08e8afef0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_text_config_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_text_delta_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_text_delta_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3dfcc63dd3f12297c6880b150f7380a6493e8456 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_text_delta_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_text_done_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_text_done_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e61f903bce8ca91c42397d3639733cbaa30f6637 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_text_done_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_usage.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_usage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f0bc116bc1e30b8a31eb8fd47fa2f9d3b5f517e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_usage.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_web_search_call_completed_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_web_search_call_completed_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a563684c7759514b77f874cf025dc62f80c6a522 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_web_search_call_completed_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_web_search_call_in_progress_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_web_search_call_in_progress_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6a9ae929a3a4f91eec00f9165c00a1fabd71756 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_web_search_call_in_progress_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_web_search_call_searching_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_web_search_call_searching_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..924f6301d1fb06831127bcc9af7628a1a41ce2bd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/response_web_search_call_searching_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c62e4c7395152d033f3e941588fc0b0aee8c075f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_allowed.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_allowed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0bb175da7c6fad89c7a5c13dbcbbd4c0d31e104 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_allowed.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_allowed_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_allowed_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff454b9edec27bf8efce767f9d3c018887efd11e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_allowed_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_custom.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_custom.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..538891be02a62f40304ad1580bfe8a739864d87e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_custom.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_custom_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_custom_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ae005c9f4e3727291cf28ac85efe502b28687dc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_custom_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_function.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b920bbce8b8265c3e231c479ee2898af1e07433f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_function.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_function_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_function_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e8f30d623a3b846d47e5abfa070405547988fbd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_function_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_mcp.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_mcp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c599f6560caa99dccdce2f0385e3c743b8282354 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_mcp.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_mcp_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_mcp_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a49e3097620a6402be27bb8dfd3721539220a50 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_mcp_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_options.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_options.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e55251666149fc3c71a3badc81186c17bc407b9e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_options.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_types.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26bd5b0741302b231af1d4aefe5d9d2e4bab5202 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_types.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_types_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_types_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2be21429493ef1b723b2db7d1e37b2786918d3b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_choice_types_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cb656e60cc6ec623a8457dab7cf6627787f7e344 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/tool_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/web_search_preview_tool.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/web_search_preview_tool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3221d6e4f3cca9389815fad7a8ea53c61ec5b263 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/web_search_preview_tool.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/web_search_preview_tool_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/web_search_preview_tool_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..866aff7c1afd06ca2b5b741976ce185797535678 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/web_search_preview_tool_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/web_search_tool.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/web_search_tool.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c52f5903b749013f2626373968975d6916b485b8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/web_search_tool.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/web_search_tool_param.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/web_search_tool_param.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21e4caa3a7fa1f79d4d699987c56e92a9e9315db Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/responses/__pycache__/web_search_tool_param.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1945d8c2eb6974ccd9fd121eab29b5383cb7220 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/all_models.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/all_models.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b43c9080572105cc0792bc4f6694f0fb7a575f1c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/all_models.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/chat_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/chat_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0aa6078db744a58b6f3e70b549730dd3fbf54be7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/chat_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/comparison_filter.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/comparison_filter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a24a7502bf7387d3aa2d56eb89c8af5a16887a3b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/comparison_filter.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/compound_filter.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/compound_filter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7f087b4857d8a2a999e9fff0942fecb51298f81c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/compound_filter.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/custom_tool_input_format.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/custom_tool_input_format.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af6fbf06bf337ce1c29d3d838889c84a744ff29f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/custom_tool_input_format.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/error_object.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/error_object.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1445aac96c347b495de7ac5784c40b6e838f4b25 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/error_object.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/function_definition.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/function_definition.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..058b8512fb310a199cf47278bfd808e0b6faddfb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/function_definition.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/function_parameters.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/function_parameters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0f53af3a1dd110330d6a77ba90cbce187dd6892 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/function_parameters.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/metadata.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/metadata.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e049c9109681ab2a01dbe1cd7d8f8269ccde140f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/metadata.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/reasoning.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/reasoning.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d188ec1e42e9821ad4edeecac303a2546e92831 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/reasoning.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/reasoning_effort.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/reasoning_effort.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..241d7b3a6ba1d7b9dbef8accf282b0c4650885d0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/reasoning_effort.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/response_format_json_object.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/response_format_json_object.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88b03ea8d95c3b4134033d8010437f86e9671435 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/response_format_json_object.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/response_format_json_schema.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/response_format_json_schema.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f32c26672432447e8d7d48e1edc614b75b75554 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/response_format_json_schema.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/response_format_text.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/response_format_text.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13769b3b7889624b63d7110ecb4fb1345af15a12 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/response_format_text.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/response_format_text_grammar.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/response_format_text_grammar.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20bf69847708d3a83f19a450b48550304f4bd3f8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/response_format_text_grammar.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/response_format_text_python.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/response_format_text_python.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4afc35dab7c19e3d7edd75a475b10d1a835559a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/response_format_text_python.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/responses_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/responses_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03aaab85b4a7463cc7f880bafb29d934306c7aa8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared/__pycache__/responses_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e3dc6fcd3e96260889ad7105dc78d53e9a66c34 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/chat_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/chat_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a99990e06f8d70ec9a27e786546d682b966df345 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/chat_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/comparison_filter.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/comparison_filter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa2dba7ddda77b7a805303c792b42be66e222ecb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/comparison_filter.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/compound_filter.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/compound_filter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff9ff16feeeba2fbcbfa88a08bafee5b49bc19a8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/compound_filter.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/custom_tool_input_format.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/custom_tool_input_format.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4e29f725680b22172efbea431f4846a85e00b09 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/custom_tool_input_format.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/function_definition.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/function_definition.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dc9e82e3c2eca9b902c94c9f65fc5f0acff4664 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/function_definition.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/function_parameters.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/function_parameters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78c375f9e42d72fd83c0ffbfe3801b2e2175f364 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/function_parameters.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/metadata.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/metadata.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0264d96b30a111d52fd8699f0c34a057c14da5c7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/metadata.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/reasoning.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/reasoning.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9936a3ad201fc9722553aac59b83780227c9450f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/reasoning.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/reasoning_effort.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/reasoning_effort.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adcbf2396bee0014dca10b80621a6ef01dfe8d3e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/reasoning_effort.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/response_format_json_object.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/response_format_json_object.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c16856a7ef46d69c25329699fc022fb63d585c6c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/response_format_json_object.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/response_format_json_schema.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/response_format_json_schema.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca94cf14edf5585aa94a9351c14c3f7bbb92bae5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/response_format_json_schema.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/response_format_text.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/response_format_text.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e93f6999b827be18265bd3d1326ddbec52be401 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/response_format_text.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/responses_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/responses_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdd7b0e4f4b1fb241a43430d87fc88db9005cfb9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/shared_params/__pycache__/responses_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/uploads/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/uploads/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d688bb19fae7a6620e24c34019820ab3b8a18d51 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/uploads/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/uploads/__pycache__/part_create_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/uploads/__pycache__/part_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31ef7d58b29878b174f8cddaed453d85790e3103 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/uploads/__pycache__/part_create_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/uploads/__pycache__/upload_part.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/uploads/__pycache__/upload_part.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00979bdacb7e661f99cb8ca1025c85b2b195d9c3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/uploads/__pycache__/upload_part.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d61ca4ced218cb3b4ee3503a55953363deb10d80 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_batch_create_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_batch_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa0d61f4e58b16f4bda7a039e082fb9a6f33c69f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_batch_create_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_batch_list_files_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_batch_list_files_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2eb1d829b77eee35cdccda53b06d5bec174a2f25 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_batch_list_files_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_content_response.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_content_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14cd874486e87a94b8bed2df2be371dbf9d4f867 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_content_response.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_create_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_create_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..80feba6b09f7b6452cb1382775af6e1983589b21 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_create_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_list_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_list_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19b55ed8f50bc29bce71ec5a539ca382b3fa1e8f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_list_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_update_params.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_update_params.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4cf8d30bc73574478e5a10c08c9ea1cdb807c75d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/file_update_params.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/vector_store_file.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/vector_store_file.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07fc123c17802c7a5aa4c20338677cfa9567d712 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/vector_store_file.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/vector_store_file_batch.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/vector_store_file_batch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93dc2a1199cf2ee3f7748cbb1d2d81f77e36c69c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/vector_store_file_batch.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/vector_store_file_deleted.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/vector_store_file_deleted.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82830e50c555335f5d5b800e4af1e32363ac8a73 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/vector_stores/__pycache__/vector_store_file_deleted.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b102a14cc504989cac0fe4bc777d1f9e94f39008 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/batch_cancelled_webhook_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/batch_cancelled_webhook_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ae943d9d5d2d97d82c78c8434f189ebf6d572ef Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/batch_cancelled_webhook_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/batch_completed_webhook_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/batch_completed_webhook_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36fd1b543c9fca40be83ccdefec68a8341301c54 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/batch_completed_webhook_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/batch_expired_webhook_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/batch_expired_webhook_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a187df04be6435f0f358689d68e1ea54ccb357c8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/batch_expired_webhook_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/batch_failed_webhook_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/batch_failed_webhook_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa88596a91f57f33e113edbeef49777123e27a07 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/batch_failed_webhook_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/eval_run_canceled_webhook_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/eval_run_canceled_webhook_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c94f4d7a3105ee7c94ac6ddb9d213752dab20e83 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/eval_run_canceled_webhook_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/eval_run_failed_webhook_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/eval_run_failed_webhook_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7afa06d2982af26ce79e23203f86006838f1743c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/eval_run_failed_webhook_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/eval_run_succeeded_webhook_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/eval_run_succeeded_webhook_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dace7cd0ab2b8787f39e7f799bc580f7c9048c4a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/eval_run_succeeded_webhook_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/fine_tuning_job_cancelled_webhook_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/fine_tuning_job_cancelled_webhook_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d215292db777ba1ec52c966e5fa7d6658c122d2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/fine_tuning_job_cancelled_webhook_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/fine_tuning_job_failed_webhook_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/fine_tuning_job_failed_webhook_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1684c9a17947559d4926a76a70a95dff692083d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/fine_tuning_job_failed_webhook_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/fine_tuning_job_succeeded_webhook_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/fine_tuning_job_succeeded_webhook_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0044f0bc19d9a6819dbea1593b6d7a99cc08b24e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/fine_tuning_job_succeeded_webhook_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/realtime_call_incoming_webhook_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/realtime_call_incoming_webhook_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b051b1c5a7324e3b0724b03fde76f286ec9444c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/realtime_call_incoming_webhook_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/response_cancelled_webhook_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/response_cancelled_webhook_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8571c8b024e7d0ba83ad71b1e60ced9afe15d9e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/response_cancelled_webhook_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/response_completed_webhook_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/response_completed_webhook_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62aa64637ad3fa441819389c676c0bc7454ef493 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/response_completed_webhook_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/response_failed_webhook_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/response_failed_webhook_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56e25b1089c0d25e89ba1a251ad40debc013a077 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/response_failed_webhook_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/response_incomplete_webhook_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/response_incomplete_webhook_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9600671fabd8fe9c7cbd78353f164a2590b1bf57 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/response_incomplete_webhook_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/unwrap_webhook_event.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/unwrap_webhook_event.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..221028f33f25c9df45ddbb055478a2f839cdf294 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/openai/types/webhooks/__pycache__/unwrap_webhook_event.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/commands/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/commands/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa5d95a85b538171ec9cf4fa16e892df1efdef6b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/commands/__init__.py @@ -0,0 +1,27 @@ +# Copyright 2020 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from abc import ABC, abstractmethod +from argparse import ArgumentParser + + +class BaseTransformersCLICommand(ABC): + @staticmethod + @abstractmethod + def register_subcommand(parser: ArgumentParser): + raise NotImplementedError() + + @abstractmethod + def run(self): + raise NotImplementedError() diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/commands/add_fast_image_processor.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/commands/add_fast_image_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..90c911525f7773a34ca9f97f180d5b127649f3c2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/commands/add_fast_image_processor.py @@ -0,0 +1,530 @@ +# Copyright 2024 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import re +from argparse import ArgumentParser, Namespace +from datetime import date +from pathlib import Path + +from ..utils import logging +from . import BaseTransformersCLICommand + + +logger = logging.get_logger(__name__) # pylint: disable=invalid-name + + +CURRENT_YEAR = date.today().year +TRANSFORMERS_PATH = Path(__file__).parent.parent +REPO_PATH = TRANSFORMERS_PATH.parent.parent + + +def add_fast_image_processor_to_model_init( + fast_image_processing_module_file: str, fast_image_processor_name, model_name: str +): + """ + Add the fast image processor to the __init__.py file of the model. + """ + with open(TRANSFORMERS_PATH / "models" / model_name / "__init__.py", "r", encoding="utf-8") as f: + content = f.read() + + fast_image_processing_module_file = fast_image_processing_module_file.split(os.sep)[-1].replace(".py", "") + + if "import *" in content: + # we have an init file in the updated format + # get the indented block after if TYPE_CHECKING: and before else:, append the new import, sort the imports and write the updated content + # Step 1: Find the block + block_regex = re.compile( + r"if TYPE_CHECKING:\n(?P.*?)(?=\s*else:)", + re.DOTALL, + ) + match = block_regex.search(content) + + if not match: + raise ValueError("Couldn't find the 'if TYPE_CHECKING' block.") + + block_content = match.group("if_block") # The captured import block + + # Step 2: Parse existing entries + entries = block_content.split("\n") + indent = " " * (len(entries[0]) - len(entries[0].lstrip())) + new_entry = f"{indent}from .{fast_image_processing_module_file} import *" + if new_entry not in entries: + entries.append(new_entry) + entries.sort() + updated_block = "\n".join(entry for entry in entries) + + # Replace the original block in the content + updated_content = content[: match.start("if_block")] + updated_block + content[match.end("if_block") :] + else: + # we have an init file in the old format + + # add "is_torchvision_available" import to from ...utils import ( + # Regex to match import statements from transformers.utils + pattern = r""" + from\s+\.\.\.utils\s+import\s+ + (?: # Non-capturing group for either: + ([\w, ]+) # 1. Single-line imports (e.g., 'a, b') + | # OR + \((.*?)\) # 2. Multi-line imports (e.g., '(a, ... b)') + ) + """ + regex = re.compile(pattern, re.VERBOSE | re.DOTALL) + + def replacement_function(match): + # Extract existing imports + imports = (match.group(1) or match.group(2)).split(",") + imports = imports[:-1] if imports[-1] == "\n" else imports + imports = [imp.strip() for imp in imports] + + # Add the new import if not already present + if "is_torchvision_available" not in imports: + imports.append("is_torchvision_available") + imports.sort() + + # Convert to multi-line import in all cases + updated_imports = "(\n " + ",\n ".join(imports) + ",\n)" + + return f"from ...utils import {updated_imports}" + + # Replace all matches in the file content + updated_content = regex.sub(replacement_function, content) + + vision_import_structure_block = f' _import_structure["{fast_image_processing_module_file[:-5]}"] = ["{fast_image_processor_name[:-4]}"]\n' + + added_import_structure_block = ( + "try:\n if not is_torchvision_available():\n" + " raise OptionalDependencyNotAvailable()\n" + "except OptionalDependencyNotAvailable:\n" + " pass\n" + "else:\n" + f' _import_structure["{fast_image_processing_module_file}"] = ["{fast_image_processor_name}"]\n' + ) + + if vision_import_structure_block not in updated_content: + raise ValueError("Couldn't find the 'vision _import_structure block' block.") + + if added_import_structure_block not in updated_content: + updated_content = updated_content.replace( + vision_import_structure_block, vision_import_structure_block + "\n" + added_import_structure_block + ) + + vision_import_statement_block = ( + f" from .{fast_image_processing_module_file[:-5]} import {fast_image_processor_name[:-4]}\n" + ) + + added_import_statement_block = ( + " try:\n if not is_torchvision_available():\n" + " raise OptionalDependencyNotAvailable()\n" + " except OptionalDependencyNotAvailable:\n" + " pass\n" + " else:\n" + f" from .{fast_image_processing_module_file} import {fast_image_processor_name}\n" + ) + + if vision_import_statement_block not in updated_content: + raise ValueError("Couldn't find the 'vision _import_structure block' block.") + + if added_import_statement_block not in updated_content: + updated_content = updated_content.replace( + vision_import_statement_block, vision_import_statement_block + "\n" + added_import_statement_block + ) + + # write the updated content + with open(TRANSFORMERS_PATH / "models" / model_name / "__init__.py", "w", encoding="utf-8") as f: + f.write(updated_content) + + +def add_fast_image_processor_to_auto(image_processor_name: str, fast_image_processor_name: str): + """ + Add the fast image processor to the auto module. + """ + with open(TRANSFORMERS_PATH / "models" / "auto" / "image_processing_auto.py", "r", encoding="utf-8") as f: + content = f.read() + + # get all lines containing the image processor name + updated_content = content.replace( + f'("{image_processor_name}",)', f'("{image_processor_name}", "{fast_image_processor_name}")' + ) + + # write the updated content + with open(TRANSFORMERS_PATH / "models" / "auto" / "image_processing_auto.py", "w", encoding="utf-8") as f: + f.write(updated_content) + + +def add_fast_image_processor_to_doc(fast_image_processor_name: str, model_name: str): + """ + Add the fast image processor to the model's doc file. + """ + doc_source = REPO_PATH / "docs" / "source" + # find the doc files + doc_files = list(doc_source.glob(f"*/model_doc/{model_name}.md")) + if not doc_files: + # try again with "-" + doc_files = list(doc_source.glob(f"*/model_doc/{model_name.replace('_', '-')}.md")) + if not doc_files: + raise ValueError(f"No doc files found for {model_name}") + + base_doc_string = ( + f"## {fast_image_processor_name[:-4]}\n\n[[autodoc]] {fast_image_processor_name[:-4]}\n - preprocess" + ) + fast_doc_string = f"## {fast_image_processor_name}\n\n[[autodoc]] {fast_image_processor_name}\n - preprocess" + + for doc_file in doc_files: + with open(doc_file, "r", encoding="utf-8") as f: + content = f.read() + + if fast_doc_string not in content: + # add the fast image processor to the doc + updated_content = content.replace( + base_doc_string, + base_doc_string + "\n\n" + fast_doc_string, + ) + + # write the updated content + with open(doc_file, "w", encoding="utf-8") as f: + f.write(updated_content) + + +def add_fast_image_processor_to_tests(fast_image_processor_name: str, model_name: str): + """ + Add the fast image processor to the image processing tests. + """ + tests_path = REPO_PATH / "tests" / "models" / model_name + test_file = tests_path / f"test_image_processing_{model_name}.py" + if not os.path.exists(test_file): + logger.warning(f"No test file found for {model_name}. Skipping.") + return + + with open(test_file, "r", encoding="utf-8") as f: + content = f.read() + + # add is_torchvision_available import to the imports + # Regex to match import statements from transformers.utils + pattern = r""" + from\s+transformers\.utils\s+import\s+ + (?: # Non-capturing group for either: + ([\w, ]+) # 1. Single-line imports (e.g., 'a, b') + | # OR + \((.*?)\) # 2. Multi-line imports (e.g., '(a, ... b)') + ) + """ + regex = re.compile(pattern, re.VERBOSE | re.DOTALL) + + def replacement_function(match): + # Extract existing imports + existing_imports = (match.group(1) or match.group(2)).split(",") + existing_imports = existing_imports[:-1] if existing_imports[-1] == "\n" else existing_imports + existing_imports = [imp.strip() for imp in existing_imports] + + # Add the new import if not already present + if "is_torchvision_available" not in existing_imports: + existing_imports.append("is_torchvision_available") + existing_imports.sort() + + # Rebuild the import statement + if match.group(1): # Single-line import + updated_imports = ", ".join(existing_imports) + else: # Multi-line import + updated_imports = "(\n " + ",\n ".join(existing_imports) + ",\n)" + + return f"from transformers.utils import {updated_imports}" + + # Replace all matches in the file content + updated_content = regex.sub(replacement_function, content) + + # add the fast image processor to the imports + base_import_string = f" from transformers import {fast_image_processor_name[:-4]}" + fast_import_string = ( + f" if is_torchvision_available():\n from transformers import {fast_image_processor_name}" + ) + if fast_import_string not in updated_content: + updated_content = updated_content.replace(base_import_string, base_import_string + "\n\n" + fast_import_string) + + # get line starting with " image_processing_class = " and add a line after it starting with " fast_image_processing_class = " + image_processing_class_line = re.search(r" image_processing_class = .*", updated_content) + if not image_processing_class_line: + logger.warning(f"Couldn't find the 'image_processing_class' line in {test_file}. Skipping.") + return + + fast_image_processing_class_line = ( + f" fast_image_processing_class = {fast_image_processor_name} if is_torchvision_available() else None" + ) + if " fast_image_processing_class = " not in updated_content: + updated_content = updated_content.replace( + image_processing_class_line.group(0), + image_processing_class_line.group(0) + "\n" + fast_image_processing_class_line, + ) + + # write the updated content + with open(test_file, "w", encoding="utf-8") as f: + f.write(updated_content) + + +def get_fast_image_processing_content_header(content: str) -> str: + """ + Get the header of the slow image processor file. + """ + # get all the commented lines at the beginning of the file + content_header = re.search(r"^# coding=utf-8\n(#[^\n]*\n)*", content, re.MULTILINE) + if not content_header: + logger.warning("Couldn't find the content header in the slow image processor file. Using a default header.") + return ( + f"# coding=utf-8\n" + f"# Copyright {CURRENT_YEAR} The HuggingFace Team. All rights reserved.\n" + f"#\n" + f'# Licensed under the Apache License, Version 2.0 (the "License");\n' + f"# you may not use this file except in compliance with the License.\n" + f"# You may obtain a copy of the License at\n" + f"#\n" + f"# http://www.apache.org/licenses/LICENSE-2.0\n" + f"#\n" + f"# Unless required by applicable law or agreed to in writing, software\n" + f'# distributed under the License is distributed on an "AS IS" BASIS,\n' + f"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + f"# See the License for the specific language governing permissions and\n" + f"# limitations under the License.\n" + f"\n" + ) + content_header = content_header.group(0) + # replace the year in the copyright + content_header = re.sub(r"# Copyright (\d+)\s", f"# Copyright {CURRENT_YEAR} ", content_header) + # get the line starting with """Image processor in content if it exists + match = re.search(r'^"""Image processor.*$', content, re.MULTILINE) + if match: + content_header += match.group(0).replace("Image processor", "Fast Image processor") + + return content_header + + +def write_default_fast_image_processor_file( + fast_image_processing_module_file: str, fast_image_processor_name: str, content_base_file: str +): + """ + Write a default fast image processor file. Used when encountering a problem while parsing the slow image processor file. + """ + imports = "\n\nfrom ...image_processing_utils_fast import BaseImageProcessorFast\n\n\n" + content_header = get_fast_image_processing_content_header(content_base_file) + content_base_file = ( + f"class {fast_image_processor_name}(BaseImageProcessorFast):\n" + " # To be implemented\n" + " resample = None\n" + " image_mean = None\n" + " image_std = None\n" + " size = None\n" + " default_to_square = None\n" + " crop_size = None\n" + " do_resize = None\n" + " do_center_crop = None\n" + " do_rescale = None\n" + " do_normalize = None\n" + " do_convert_rgb = None\n\n\n" + f'__all__ = ["{fast_image_processor_name}"]\n' + ) + + content = content_header + imports + content_base_file + + with open(fast_image_processing_module_file, "w", encoding="utf-8") as f: + f.write(content) + + +def add_fast_image_processor_file( + fast_image_processing_module_file: str, fast_image_processor_name: str, content_base_file: str +): + """ + Add the fast image processor file to the model's folder. + """ + # if the file already exists, do nothing + if os.path.exists(fast_image_processing_module_file): + print(f"{fast_image_processing_module_file} already exists. Skipping.") + return + + regex = rf"class {fast_image_processor_name[:-4]}.*?(\n\S|$)" + match = re.search(regex, content_base_file, re.DOTALL) + if not match: + print(f"Couldn't find the {fast_image_processor_name[:-4]} class in {fast_image_processing_module_file}") + print("Creating a new file with the default content.") + return write_default_fast_image_processor_file( + fast_image_processing_module_file, fast_image_processor_name, content_base_file + ) + # Exclude the last unindented line + slow_class_content = match.group(0).rstrip() + # get default args: + # find the __init__ block which start with def __init__ and ends with def + match = re.search(r"def __init__.*?def ", slow_class_content, re.DOTALL) + if not match: + print( + f"Couldn't find the __init__ block for {fast_image_processor_name[:-4]} in {fast_image_processing_module_file}" + ) + print("Creating a new file with the default content.") + return write_default_fast_image_processor_file( + fast_image_processing_module_file, fast_image_processor_name, content_base_file + ) + init = match.group(0) + init_signature_block = init.split(")")[0] + arg_names = init_signature_block.split(":") + arg_names = [arg_name.split("\n")[-1].strip() for arg_name in arg_names] + # get the default values + default_args = re.findall(r"= (.*?)(?:,|\))", init_signature_block) + + # build default args dict + default_args_dict = dict(zip(arg_names, default_args)) + pattern_default_size = r"size = size if size is not None else\s+(.*)" + match_default_size = re.findall(pattern_default_size, init) + default_args_dict["size"] = match_default_size[0] if match_default_size else None + pattern_default_crop_size = r"crop_size = crop_size if crop_size is not None else\s+(.*)" + match_default_crop_size = re.findall(pattern_default_crop_size, init) + default_args_dict["crop_size"] = match_default_crop_size[0] if match_default_crop_size else None + pattern_default_image_mean = r"self.image_mean = image_mean if image_mean is not None else\s+(.*)" + match_default_image_mean = re.findall(pattern_default_image_mean, init) + default_args_dict["image_mean"] = match_default_image_mean[0] if match_default_image_mean else None + pattern_default_image_std = r"self.image_std = image_std if image_std is not None else\s+(.*)" + match_default_image_std = re.findall(pattern_default_image_std, init) + default_args_dict["image_std"] = match_default_image_std[0] if match_default_image_std else None + default_args_dict["default_to_square"] = False if "(size, default_to_square=False" in init else None + + content_header = get_fast_image_processing_content_header(content_base_file) + content_base_file = ( + f"@auto_docstring\n" + f"class {fast_image_processor_name}(BaseImageProcessorFast):\n" + " # This generated class can be used as a starting point for the fast image processor.\n" + " # if the image processor is only used for simple augmentations, such as resizing, center cropping, rescaling, or normalizing,\n" + " # only the default values should be set in the class.\n" + " # If the image processor requires more complex augmentations, methods from BaseImageProcessorFast can be overridden.\n" + " # In most cases, only the `_preprocess` method should be overridden.\n\n" + " # For an example of a fast image processor requiring more complex augmentations, see `LlavaNextImageProcessorFast`.\n\n" + " # Default values should be checked against the slow image processor\n" + " # None values left after checking can be removed\n" + f" resample = {default_args_dict.get('resample')}\n" + f" image_mean = {default_args_dict.get('image_mean')}\n" + f" image_std = {default_args_dict.get('image_std')}\n" + f" size = {default_args_dict.get('size')}\n" + f" default_to_square = {default_args_dict.get('default_to_square')}\n" + f" crop_size = {default_args_dict.get('crop_size')}\n" + f" do_resize = {default_args_dict.get('do_resize')}\n" + f" do_center_crop = {default_args_dict.get('do_center_crop')}\n" + f" do_rescale = {default_args_dict.get('do_rescale')}\n" + f" do_normalize = {default_args_dict.get('do_normalize')}\n" + f" do_convert_rgb = {default_args_dict.get('do_convert_rgb')}\n\n\n" + f'__all__ = ["{fast_image_processor_name}"]\n' + ) + + imports = "\n\nfrom ...image_processing_utils_fast import BaseImageProcessorFast\n" + image_utils_imports = [] + if default_args_dict.get("resample") is not None and "PILImageResampling" in default_args_dict.get("resample"): + image_utils_imports.append("PILImageResampling") + if default_args_dict.get("image_mean") is not None and not any( + char.isdigit() for char in default_args_dict.get("image_mean") + ): + image_utils_imports.append(default_args_dict.get("image_mean")) + if default_args_dict.get("image_std") is not None and not any( + char.isdigit() for char in default_args_dict.get("image_std") + ): + image_utils_imports.append(default_args_dict.get("image_std")) + + if image_utils_imports: + # sort imports + image_utils_imports.sort() + imports += f"from ...image_utils import {', '.join(image_utils_imports)}\n" + + imports += "from ...utils import auto_docstring\n" + + content = content_header + imports + "\n\n" + content_base_file + + with open(fast_image_processing_module_file, "w", encoding="utf-8") as f: + f.write(content) + + +def add_fast_image_processor(model_name: str): + """ + Add the necessary references to the fast image processor in the transformers package, + and create the fast image processor file in the model's folder. + """ + model_module = TRANSFORMERS_PATH / "models" / model_name + image_processing_module_file = list(model_module.glob("image_processing*.py")) + if not image_processing_module_file: + raise ValueError(f"No image processing module found in {model_module}") + elif len(image_processing_module_file) > 1: + for file_name in image_processing_module_file: + if not str(file_name).endswith("_fast.py"): + image_processing_module_file = str(file_name) + break + else: + image_processing_module_file = str(image_processing_module_file[0]) + + with open(image_processing_module_file, "r", encoding="utf-8") as f: + content_base_file = f.read() + + # regex to find object starting with "class " and ending with "ImageProcessor", including "ImageProcessor" in the match + image_processor_name = re.findall(r"class (\w*ImageProcessor)", content_base_file) + if not image_processor_name: + raise ValueError(f"No ImageProcessor class found in {image_processing_module_file}") + elif len(image_processor_name) > 1: + raise ValueError(f"Multiple ImageProcessor classes found in {image_processing_module_file}") + + image_processor_name = image_processor_name[0] + fast_image_processor_name = image_processor_name + "Fast" + fast_image_processing_module_file = image_processing_module_file.replace(".py", "_fast.py") + + print(f"Adding {fast_image_processor_name} to {fast_image_processing_module_file}") + + add_fast_image_processor_to_model_init( + fast_image_processing_module_file=fast_image_processing_module_file, + fast_image_processor_name=fast_image_processor_name, + model_name=model_name, + ) + + add_fast_image_processor_to_auto( + image_processor_name=image_processor_name, + fast_image_processor_name=fast_image_processor_name, + ) + + add_fast_image_processor_to_doc( + fast_image_processor_name=fast_image_processor_name, + model_name=model_name, + ) + + add_fast_image_processor_to_tests( + fast_image_processor_name=fast_image_processor_name, + model_name=model_name, + ) + + add_fast_image_processor_file( + fast_image_processing_module_file=fast_image_processing_module_file, + fast_image_processor_name=fast_image_processor_name, + content_base_file=content_base_file, + ) + + +def add_new_model_like_command_factory(args: Namespace): + return AddFastImageProcessorCommand(model_name=args.model_name) + + +class AddFastImageProcessorCommand(BaseTransformersCLICommand): + @staticmethod + def register_subcommand(parser: ArgumentParser): + add_fast_image_processor_parser = parser.add_parser("add-fast-image-processor") + add_fast_image_processor_parser.add_argument( + "--model-name", + type=str, + required=True, + help="The name of the folder containing the model's implementation.", + ) + add_fast_image_processor_parser.set_defaults(func=add_new_model_like_command_factory) + + def __init__(self, model_name: str, *args): + self.model_name = model_name + + def run(self): + add_fast_image_processor(model_name=self.model_name) diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/commands/add_new_model_like.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/commands/add_new_model_like.py new file mode 100644 index 0000000000000000000000000000000000000000..c90a55b44bf85cfaccf06107d492b202e1a9db45 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/commands/add_new_model_like.py @@ -0,0 +1,783 @@ +# Copyright 2021 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import difflib +import os +import re +import subprocess +import textwrap +from argparse import ArgumentParser, Namespace +from datetime import date +from pathlib import Path +from typing import Any, Callable, Optional, Union + +from ..models.auto.configuration_auto import CONFIG_MAPPING_NAMES, MODEL_NAMES_MAPPING +from ..models.auto.feature_extraction_auto import FEATURE_EXTRACTOR_MAPPING_NAMES +from ..models.auto.image_processing_auto import IMAGE_PROCESSOR_MAPPING_NAMES +from ..models.auto.processing_auto import PROCESSOR_MAPPING_NAMES +from ..models.auto.tokenization_auto import TOKENIZER_MAPPING_NAMES +from ..models.auto.video_processing_auto import VIDEO_PROCESSOR_MAPPING_NAMES +from ..utils import is_libcst_available +from . import BaseTransformersCLICommand +from .add_fast_image_processor import add_fast_image_processor + + +# We protect this import to avoid requiring it for all `transformers` CLI commands - however it is actually +# strictly required for this one (we need it both for modular and for the following Visitor) +if is_libcst_available(): + import libcst as cst + from libcst import CSTVisitor + from libcst import matchers as m + + class ClassFinder(CSTVisitor): + """ + A visitor to find all classes in a python module. + """ + + def __init__(self): + self.classes: list = [] + self.public_classes: list = [] + self.is_in_class = False + + def visit_ClassDef(self, node: cst.ClassDef) -> None: + """Record class names. We assume classes always only appear at top-level (i.e. no class definition in function or similar)""" + self.classes.append(node.name.value) + self.is_in_class = True + + def leave_ClassDef(self, node: cst.ClassDef): + self.is_in_class = False + + def visit_SimpleStatementLine(self, node: cst.SimpleStatementLine): + """Record all public classes inside the `__all__` assignment.""" + simple_top_level_assign_structure = m.SimpleStatementLine( + body=[m.Assign(targets=[m.AssignTarget(target=m.Name())])] + ) + if not self.is_in_class and m.matches(node, simple_top_level_assign_structure): + assigned_variable = node.body[0].targets[0].target.value + if assigned_variable == "__all__": + elements = node.body[0].value.elements + self.public_classes = [element.value.value for element in elements] + + +CURRENT_YEAR = date.today().year +TRANSFORMERS_PATH = Path(__file__).parent.parent +REPO_PATH = TRANSFORMERS_PATH.parent.parent + +COPYRIGHT = f""" +# coding=utf-8 +# Copyright {CURRENT_YEAR} the HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""".lstrip() + + +class ModelInfos: + """ + Retrieve the basic informations about an existing model classes. + """ + + def __init__(self, lowercase_name: str): + # Just to make sure it's indeed lowercase + self.lowercase_name = lowercase_name.lower().replace(" ", "_").replace("-", "_") + if self.lowercase_name not in CONFIG_MAPPING_NAMES: + self.lowercase_name.replace("_", "-") + if self.lowercase_name not in CONFIG_MAPPING_NAMES: + raise ValueError(f"{lowercase_name} is not a valid model name") + + self.paper_name = MODEL_NAMES_MAPPING[self.lowercase_name] + self.config_class = CONFIG_MAPPING_NAMES[self.lowercase_name] + self.camelcase_name = self.config_class.replace("Config", "") + + # Get tokenizer class + if self.lowercase_name in TOKENIZER_MAPPING_NAMES: + self.tokenizer_class, self.fast_tokenizer_class = TOKENIZER_MAPPING_NAMES[self.lowercase_name] + self.fast_tokenizer_class = ( + None if self.fast_tokenizer_class == "PreTrainedTokenizerFast" else self.fast_tokenizer_class + ) + else: + self.tokenizer_class, self.fast_tokenizer_class = None, None + + self.image_processor_class, self.fast_image_processor_class = IMAGE_PROCESSOR_MAPPING_NAMES.get( + self.lowercase_name, (None, None) + ) + self.video_processor_class = VIDEO_PROCESSOR_MAPPING_NAMES.get(self.lowercase_name, None) + self.feature_extractor_class = FEATURE_EXTRACTOR_MAPPING_NAMES.get(self.lowercase_name, None) + self.processor_class = PROCESSOR_MAPPING_NAMES.get(self.lowercase_name, None) + + +def add_content_to_file(file_name: Union[str, os.PathLike], new_content: str, add_after: str): + """ + A utility to add some content inside a given file. + + Args: + file_name (`str` or `os.PathLike`): + The name of the file in which we want to insert some content. + new_content (`str`): + The content to add. + add_after (`str`): + The new content is added just after the first instance matching it. + """ + with open(file_name, "r", encoding="utf-8") as f: + old_content = f.read() + + before, after = old_content.split(add_after, 1) + new_content = before + add_after + new_content + after + + with open(file_name, "w", encoding="utf-8") as f: + f.write(new_content) + + +def add_model_to_auto_mappings( + old_model_infos: ModelInfos, + new_lowercase_name: str, + new_model_paper_name: str, + filenames_to_add: list[tuple[str, bool]], +): + """ + Add a model to all the relevant mappings in the auto module. + + Args: + old_model_infos (`ModelInfos`): + The structure containing the class informations of the old model. + new_lowercase_name (`str`): + The new lowercase model name. + new_model_paper_name (`str`): + The fully cased name (as in the official paper name) of the new model. + filenames_to_add (`list[tuple[str, bool]]`): + A list of tuples of all potential filenames to add for a new model, along a boolean flag describing if we + should add this file or not. For example, [(`modeling_xxx.px`, True), (`configuration_xxx.py`, True), (`tokenization_xxx.py`, False),...] + """ + new_cased_name = "".join(x.title() for x in new_lowercase_name.replace("-", "_").split("_")) + old_lowercase_name = old_model_infos.lowercase_name + old_cased_name = old_model_infos.camelcase_name + filenames_to_add = [ + (filename.replace(old_lowercase_name, "auto"), to_add) for filename, to_add in filenames_to_add[1:] + ] + # fast tokenizer/image processor have the same auto mappings as normal ones + corrected_filenames_to_add = [] + for file, to_add in filenames_to_add: + if re.search(r"(?:tokenization)|(?:image_processing)_auto_fast.py", file): + previous_file, previous_to_add = corrected_filenames_to_add[-1] + corrected_filenames_to_add[-1] = (previous_file, previous_to_add or to_add) + else: + corrected_filenames_to_add.append((file, to_add)) + + # Add the config mappings directly as the handling for config is a bit different + add_content_to_file( + TRANSFORMERS_PATH / "models" / "auto" / "configuration_auto.py", + new_content=f' ("{new_lowercase_name}", "{new_cased_name}Config"),\n', + add_after="CONFIG_MAPPING_NAMES = OrderedDict[str, str](\n [\n # Add configs here\n", + ) + add_content_to_file( + TRANSFORMERS_PATH / "models" / "auto" / "configuration_auto.py", + new_content=f' ("{new_lowercase_name}", "{new_model_paper_name}"),\n', + add_after="MODEL_NAMES_MAPPING = OrderedDict[str, str](\n [\n # Add full (and cased) model names here\n", + ) + + for filename, to_add in corrected_filenames_to_add: + if to_add: + # The auto mapping + filename = filename.replace("_fast.py", ".py") + with open(TRANSFORMERS_PATH / "models" / "auto" / filename) as f: + file = f.read() + # The regex has to be a bit complex like this as the tokenizer mapping has new lines everywhere + matching_lines = re.findall( + rf'( {{8,12}}\(\s*"{old_lowercase_name}",.*?\),\n)(?: {{4,12}}\(|\])', file, re.DOTALL + ) + for match in matching_lines: + add_content_to_file( + TRANSFORMERS_PATH / "models" / "auto" / filename, + new_content=match.replace(old_lowercase_name, new_lowercase_name).replace( + old_cased_name, new_cased_name + ), + add_after=match, + ) + + +def create_doc_file(new_paper_name: str, public_classes: list[str]): + """ + Create a new doc file to fill for the new model. + + Args: + new_paper_name (`str`): + The fully cased name (as in the official paper name) of the new model. + public_classes (`list[str]`): + A list of all the public classes that the model will have in the library. + """ + added_note = ( + "\n\n⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that " + "may not be rendered properly in your Markdown viewer.\n\n-->\n\n" + ) + copyright_for_markdown = re.sub(r"# ?", "", COPYRIGHT).replace("coding=utf-8\n", " [{"score":x, ...}, ...] + keys = ["score", "label", "box"] + annotation = [ + dict(zip(keys, vals)) + for vals in zip(raw_annotation["scores"], raw_annotation["labels"], raw_annotation["boxes"]) + ] + + return annotation + + def _get_bounding_box(self, box: "torch.Tensor") -> dict[str, int]: + """ + Turns list [xmin, xmax, ymin, ymax] into dict { "xmin": xmin, ... } + + Args: + box (`torch.Tensor`): Tensor containing the coordinates in corners format. + + Returns: + bbox (`dict[str, int]`): Dict containing the coordinates in corners format. + """ + if self.framework != "pt": + raise ValueError("The ObjectDetectionPipeline is only available in PyTorch.") + xmin, ymin, xmax, ymax = box.int().tolist() + bbox = { + "xmin": xmin, + "ymin": ymin, + "xmax": xmax, + "ymax": ymax, + } + return bbox diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/pt_utils.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/pt_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..3857805962a93f796e407ed88c89495b46fd0bd0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/pt_utils.py @@ -0,0 +1,323 @@ +import numpy as np +import torch +from torch.utils.data import Dataset, IterableDataset + +from ..utils.generic import ModelOutput + + +class PipelineDataset(Dataset): + def __init__(self, dataset, process, params): + self.dataset = dataset + self.process = process + self.params = params + + def __len__(self): + return len(self.dataset) + + def __getitem__(self, i): + item = self.dataset[i] + processed = self.process(item, **self.params) + return processed + + +class PipelineIterator(IterableDataset): + def __init__(self, loader, infer, params, loader_batch_size=None): + """ + Roughly equivalent to + + ``` + for item in loader: + yield infer(item, **params) + ``` + + Arguments: + loader (`torch.utils.data.DataLoader` or `Iterable`): + The iterator that will be used to apply `infer` on. + infer (any function): + The function to apply of each element of `loader`. + params (`dict`): + The parameters passed to `infer` along with every item + loader_batch_size (`int`, *optional*): + If specified, the items of `loader` are supposed to come as batch, and are loader_batched here + making it roughly behave as + + + ``` + for items in loader: + for i in loader_batch_size: + item = items[i] + yield infer(item, **params) + ```""" + self.loader = loader + self.infer = infer + self.params = params + if loader_batch_size == 1: + # Let's spare some time by deactivating altogether + loader_batch_size = None + self.loader_batch_size = loader_batch_size + + # Internal bookkeeping + self._loader_batch_index = None + self._loader_batch_data = None + + def __len__(self): + return len(self.loader) + + def __iter__(self): + self.iterator = iter(self.loader) + return self + + def loader_batch_item(self): + """ + Return item located at `loader_batch_index` within the current `loader_batch_data`. + """ + if isinstance(self._loader_batch_data, torch.Tensor): + # Batch data is simple tensor, just fetch the slice + result = self._loader_batch_data[self._loader_batch_index].unsqueeze(0) + else: + # Batch data is assumed to be BaseModelOutput (or dict) + loader_batched = {} + for k, element in self._loader_batch_data.items(): + if isinstance(element, ModelOutput): + # Convert ModelOutput to tuple first + element = element.to_tuple() + if isinstance(element[0], torch.Tensor): + loader_batched[k] = tuple(el[self._loader_batch_index].unsqueeze(0) for el in element) + elif isinstance(element[0], np.ndarray): + loader_batched[k] = tuple(np.expand_dims(el[self._loader_batch_index], 0) for el in element) + continue + if k in {"hidden_states", "attentions"} and isinstance(element, tuple): + # Those are stored as lists of tensors so need specific unbatching. + if isinstance(element[0], torch.Tensor): + loader_batched[k] = tuple(el[self._loader_batch_index].unsqueeze(0) for el in element) + elif isinstance(element[0], np.ndarray): + loader_batched[k] = tuple(np.expand_dims(el[self._loader_batch_index], 0) for el in element) + continue + if k == "past_key_values": + continue + if element is None: + # This can happen for optional data that get passed around + loader_batched[k] = None + elif isinstance(element[self._loader_batch_index], torch.Tensor): + # Take correct batch data, but make it looked like batch_size=1 + # For compatibility with other methods within transformers + + loader_batched[k] = element[self._loader_batch_index].unsqueeze(0) + elif isinstance(element[self._loader_batch_index], np.ndarray): + # Take correct batch data, but make it looked like batch_size=1 + # For compatibility with other methods within transformers + loader_batched[k] = np.expand_dims(element[self._loader_batch_index], 0) + else: + # This is typically a list, so no need to `unsqueeze`. + loader_batched[k] = element[self._loader_batch_index] + # Recreate the element by reusing the original class to make it look + # batch_size=1 + result = self._loader_batch_data.__class__(loader_batched) + self._loader_batch_index += 1 + return result + + def __next__(self): + if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: + # We are currently unrolling a batch so we just need to return + # the current item within a batch + return self.loader_batch_item() + + # We're out of items within a batch + item = next(self.iterator) + processed = self.infer(item, **self.params) + # We now have a batch of "inferred things". + if self.loader_batch_size is not None: + # Try to infer the size of the batch + if isinstance(processed, torch.Tensor): + first_tensor = processed + elif isinstance(processed, tuple): + first_tensor = processed[0] + else: + key = list(processed.keys())[0] + first_tensor = processed[key] + + if isinstance(first_tensor, list): + observed_batch_size = len(first_tensor) + else: + observed_batch_size = first_tensor.shape[0] + if 0 < observed_batch_size < self.loader_batch_size: + # could be last batch so we can't unroll as many + # elements. + self.loader_batch_size = observed_batch_size + # Setting internal index to unwrap the batch + self._loader_batch_data = processed[0] if isinstance(processed, tuple) else processed + self._loader_batch_index = 0 + return self.loader_batch_item() + else: + # We're not unrolling batches + return processed + + +class PipelineChunkIterator(PipelineIterator): + def __init__(self, loader, infer, params, loader_batch_size=None): + """ + Roughly equivalent to + + ``` + for iterator in loader: + for item in iterator: + yield infer(item, **params) + ``` + + Arguments: + loader (`torch.utils.data.DataLoader` or `Iterable`): + The iterator that will be used to apply `infer` on. + infer (any function): + The function to apply of each element of `loader`. + params (`dict`): + The parameters passed to `infer` along with every item + """ + super().__init__(loader, infer, params) + + def __iter__(self): + self.iterator = iter(self.loader) + self.subiterator = None + return self + + def __next__(self): + if self.subiterator is None: + "Subiterator None means we haven't started a `preprocess` iterator. so start it" + self.subiterator = self.infer(next(self.iterator), **self.params) + try: + # Try to return next item + processed = next(self.subiterator) + except StopIteration: + # When a preprocess iterator ends, we can start looking at the next item + # ChunkIterator will keep feeding until ALL elements of iterator + # all have created their subiterator and have been iterating against. + # + # Another way to look at it, is we're basically flattening lists of lists + # into a single list, but with generators + self.subiterator = self.infer(next(self.iterator), **self.params) + processed = next(self.subiterator) + return processed + + +class PipelinePackIterator(PipelineIterator): + """ + Roughly equivalent to + + ``` + packed = [] + for item in loader: + packed.append(item) + if item["is_last"]: + yield packed + packed = [] + ``` + + but it also handles cases where `item` are batched (meaning it's a dict of Tensor with first dimension > 1. In + that case it does + + ``` + packed = [] + for batch in loader: + # item is batched + for item in batch: + packed.append(item) + if item["is_last"]: + yield packed + packed = [] + ``` + + Arguments: + loader (`torch.utils.data.DataLoader` or `Iterable`): + The iterator that will be used to apply `infer` on. + infer (any function): + The function to apply of each element of `loader`. + params (`dict`): + The parameters passed to `infer` along with every item + loader_batch_size (`int`, *optional*): + If specified, the items of `loader` are supposed to come as batch, and are loader_batched here making + it roughly behave as + + + ``` + for items in loader: + for i in loader_batch_size: + item = items[i] + yield infer(item, **params) + ```""" + + def __iter__(self): + self.iterator = iter(self.loader) + return self + + def __next__(self): + # Extremely similar to PipelineIterator in its unpacking mechanism + # BUT, we have an extra required item which is the presence of `is_last` + # That is because everything is flattened by `PipelineChunkIterator` we + # need to keep track of how to regroup here in the original `process` + # boundaries so that `process` and `postprocess` see the same data. + + # This iterator accumulates items (possibly while unbatching) until it + # its a `is_last` and then just passes it on to the caller. + is_last = False + accumulator = [] + if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: + while self._loader_batch_index < self.loader_batch_size: + item = self.loader_batch_item() + is_last = item.pop("is_last") + accumulator.append(item) + if is_last: + return accumulator + + while not is_last: + processed = self.infer(next(self.iterator), **self.params) + if self.loader_batch_size is not None: + if isinstance(processed, torch.Tensor): + first_tensor = processed + else: + key = list(processed.keys())[0] + first_tensor = processed[key] + if isinstance(first_tensor, list): + observed_batch_size = len(first_tensor) + else: + observed_batch_size = first_tensor.shape[0] + if 0 < observed_batch_size < self.loader_batch_size: + # could be last batch so we can't unroll as many + # elements. + self.loader_batch_size = observed_batch_size + self._loader_batch_data = processed + self._loader_batch_index = 0 + while self._loader_batch_index < self.loader_batch_size: + item = self.loader_batch_item() + is_last = item.pop("is_last") + accumulator.append(item) + if is_last: + return accumulator + else: + item = processed + is_last = item.pop("is_last") + accumulator.append(item) + return accumulator + + +class KeyDataset(Dataset): + def __init__(self, dataset: Dataset, key: str): + self.dataset = dataset + self.key = key + + def __len__(self): + return len(self.dataset) + + def __getitem__(self, i): + return self.dataset[i][self.key] + + +class KeyPairDataset(Dataset): + def __init__(self, dataset: Dataset, key1: str, key2: str): + self.dataset = dataset + self.key1 = key1 + self.key2 = key2 + + def __len__(self): + return len(self.dataset) + + def __getitem__(self, i): + return {"text": self.dataset[i][self.key1], "text_pair": self.dataset[i][self.key2]} diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/question_answering.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/question_answering.py new file mode 100644 index 0000000000000000000000000000000000000000..ee86074a4c5804a890c5d488f35cfa3106b58ca4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/question_answering.py @@ -0,0 +1,707 @@ +import inspect +import types +import warnings +from collections.abc import Iterable +from typing import TYPE_CHECKING, Optional, Union + +import numpy as np + +from ..data import SquadExample, SquadFeatures, squad_convert_examples_to_features +from ..modelcard import ModelCard +from ..tokenization_utils import PreTrainedTokenizer +from ..utils import ( + PaddingStrategy, + add_end_docstrings, + is_tf_available, + is_tokenizers_available, + is_torch_available, + logging, +) +from .base import ArgumentHandler, ChunkPipeline, build_pipeline_init_args + + +logger = logging.get_logger(__name__) + +if TYPE_CHECKING: + from ..modeling_tf_utils import TFPreTrainedModel + from ..modeling_utils import PreTrainedModel + + if is_tokenizers_available(): + import tokenizers + +if is_tf_available(): + import tensorflow as tf + + from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES + + Dataset = None + +if is_torch_available(): + import torch + from torch.utils.data import Dataset + + from ..models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES + + +def decode_spans( + start: np.ndarray, end: np.ndarray, topk: int, max_answer_len: int, undesired_tokens: np.ndarray +) -> tuple: + """ + Take the output of any `ModelForQuestionAnswering` and will generate probabilities for each span to be the actual + answer. + + In addition, it filters out some unwanted/impossible cases like answer len being greater than max_answer_len or + answer end position being before the starting position. The method supports output the k-best answer through the + topk argument. + + Args: + start (`np.ndarray`): Individual start probabilities for each token. + end (`np.ndarray`): Individual end probabilities for each token. + topk (`int`): Indicates how many possible answer span(s) to extract from the model output. + max_answer_len (`int`): Maximum size of the answer to extract from the model's output. + undesired_tokens (`np.ndarray`): Mask determining tokens that can be part of the answer + """ + # Ensure we have batch axis + if start.ndim == 1: + start = start[None] + + if end.ndim == 1: + end = end[None] + + # Compute the score of each tuple(start, end) to be the real answer + outer = np.matmul(np.expand_dims(start, -1), np.expand_dims(end, 1)) + + # Remove candidate with end < start and end - start > max_answer_len + candidates = np.tril(np.triu(outer), max_answer_len - 1) + + # Inspired by Chen & al. (https://github.com/facebookresearch/DrQA) + scores_flat = candidates.flatten() + if topk == 1: + idx_sort = [np.argmax(scores_flat)] + elif len(scores_flat) < topk: + idx_sort = np.argsort(-scores_flat) + else: + idx = np.argpartition(-scores_flat, topk)[0:topk] + idx_sort = idx[np.argsort(-scores_flat[idx])] + + starts, ends = np.unravel_index(idx_sort, candidates.shape)[1:] + desired_spans = np.isin(starts, undesired_tokens.nonzero()) & np.isin(ends, undesired_tokens.nonzero()) + starts = starts[desired_spans] + ends = ends[desired_spans] + scores = candidates[0, starts, ends] + + return starts, ends, scores + + +def select_starts_ends( + start, + end, + p_mask, + attention_mask, + min_null_score=1000000, + top_k=1, + handle_impossible_answer=False, + max_answer_len=15, +): + """ + Takes the raw output of any `ModelForQuestionAnswering` and first normalizes its outputs and then uses + `decode_spans()` to generate probabilities for each span to be the actual answer. + + Args: + start (`np.ndarray`): Individual start logits for each token. + end (`np.ndarray`): Individual end logits for each token. + p_mask (`np.ndarray`): A mask with 1 for values that cannot be in the answer + attention_mask (`np.ndarray`): The attention mask generated by the tokenizer + min_null_score(`float`): The minimum null (empty) answer score seen so far. + topk (`int`): Indicates how many possible answer span(s) to extract from the model output. + handle_impossible_answer(`bool`): Whether to allow null (empty) answers + max_answer_len (`int`): Maximum size of the answer to extract from the model's output. + """ + # Ensure padded tokens & question tokens cannot belong to the set of candidate answers. + undesired_tokens = np.abs(np.array(p_mask) - 1) + + if attention_mask is not None: + undesired_tokens = undesired_tokens & attention_mask + + # Generate mask + undesired_tokens_mask = undesired_tokens == 0.0 + + # Make sure non-context indexes in the tensor cannot contribute to the softmax + start = np.where(undesired_tokens_mask, -10000.0, start) + end = np.where(undesired_tokens_mask, -10000.0, end) + + # Normalize logits and spans to retrieve the answer + start = np.exp(start - start.max(axis=-1, keepdims=True)) + start = start / start.sum() + + end = np.exp(end - end.max(axis=-1, keepdims=True)) + end = end / end.sum() + + if handle_impossible_answer: + min_null_score = min(min_null_score, (start[0, 0] * end[0, 0]).item()) + + # Mask CLS + start[0, 0] = end[0, 0] = 0.0 + + starts, ends, scores = decode_spans(start, end, top_k, max_answer_len, undesired_tokens) + return starts, ends, scores, min_null_score + + +class QuestionAnsweringArgumentHandler(ArgumentHandler): + """ + QuestionAnsweringPipeline requires the user to provide multiple arguments (i.e. question & context) to be mapped to + internal [`SquadExample`]. + + QuestionAnsweringArgumentHandler manages all the possible to create a [`SquadExample`] from the command-line + supplied arguments. + """ + + _load_processor = False + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = True + + def normalize(self, item): + if isinstance(item, SquadExample): + return item + elif isinstance(item, dict): + for k in ["question", "context"]: + if k not in item: + raise KeyError("You need to provide a dictionary with keys {question:..., context:...}") + elif item[k] is None: + raise ValueError(f"`{k}` cannot be None") + elif isinstance(item[k], str) and len(item[k]) == 0: + raise ValueError(f"`{k}` cannot be empty") + + return QuestionAnsweringPipeline.create_sample(**item) + raise ValueError(f"{item} argument needs to be of type (SquadExample, dict)") + + def __call__(self, *args, **kwargs): + # Detect where the actual inputs are + if args is not None and len(args) > 0: + if len(args) == 1: + inputs = args[0] + elif len(args) == 2 and {type(el) for el in args} == {str}: + inputs = [{"question": args[0], "context": args[1]}] + else: + inputs = list(args) + # Generic compatibility with sklearn and Keras + # Batched data + elif "X" in kwargs: + warnings.warn( + "Passing the `X` argument to the pipeline is deprecated and will be removed in v5. Inputs should be passed using the `question` and `context` keyword arguments instead.", + FutureWarning, + ) + inputs = kwargs["X"] + elif "data" in kwargs: + warnings.warn( + "Passing the `data` argument to the pipeline is deprecated and will be removed in v5. Inputs should be passed using the `question` and `context` keyword arguments instead.", + FutureWarning, + ) + inputs = kwargs["data"] + elif "question" in kwargs and "context" in kwargs: + if isinstance(kwargs["question"], list) and isinstance(kwargs["context"], str): + inputs = [{"question": Q, "context": kwargs["context"]} for Q in kwargs["question"]] + elif isinstance(kwargs["question"], list) and isinstance(kwargs["context"], list): + if len(kwargs["question"]) != len(kwargs["context"]): + raise ValueError("Questions and contexts don't have the same lengths") + + inputs = [{"question": Q, "context": C} for Q, C in zip(kwargs["question"], kwargs["context"])] + elif isinstance(kwargs["question"], str) and isinstance(kwargs["context"], str): + inputs = [{"question": kwargs["question"], "context": kwargs["context"]}] + else: + raise ValueError("Arguments can't be understood") + else: + raise ValueError(f"Unknown arguments {kwargs}") + + # When user is sending a generator we need to trust it's a valid example + generator_types = (types.GeneratorType, Dataset) if Dataset is not None else (types.GeneratorType,) + if isinstance(inputs, generator_types): + return inputs + + # Normalize inputs + if isinstance(inputs, dict): + inputs = [inputs] + elif isinstance(inputs, Iterable): + # Copy to avoid overriding arguments + inputs = list(inputs) + else: + raise ValueError(f"Invalid arguments {kwargs}") + + for i, item in enumerate(inputs): + inputs[i] = self.normalize(item) + + return inputs + + +@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True)) +class QuestionAnsweringPipeline(ChunkPipeline): + """ + Question Answering pipeline using any `ModelForQuestionAnswering`. See the [question answering + examples](../task_summary#question-answering) for more information. + + Example: + + ```python + >>> from transformers import pipeline + + >>> oracle = pipeline(model="deepset/roberta-base-squad2") + >>> oracle(question="Where do I live?", context="My name is Wolfgang and I live in Berlin") + {'score': 0.9191, 'start': 34, 'end': 40, 'answer': 'Berlin'} + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This question answering pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"question-answering"`. + + The models that this pipeline can use are models that have been fine-tuned on a question answering task. See the + up-to-date list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=question-answering). + """ + + default_input_names = "question,context" + handle_impossible_answer = False + + def __init__( + self, + model: Union["PreTrainedModel", "TFPreTrainedModel"], + tokenizer: PreTrainedTokenizer, + modelcard: Optional[ModelCard] = None, + framework: Optional[str] = None, + task: str = "", + **kwargs, + ): + super().__init__( + model=model, + tokenizer=tokenizer, + modelcard=modelcard, + framework=framework, + task=task, + **kwargs, + ) + + self._args_parser = QuestionAnsweringArgumentHandler() + self.check_model_type( + TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES + if self.framework == "tf" + else MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES + ) + + @staticmethod + def create_sample( + question: Union[str, list[str]], context: Union[str, list[str]] + ) -> Union[SquadExample, list[SquadExample]]: + """ + QuestionAnsweringPipeline leverages the [`SquadExample`] internally. This helper method encapsulate all the + logic for converting question(s) and context(s) to [`SquadExample`]. + + We currently support extractive question answering. + + Arguments: + question (`str` or `list[str]`): The question(s) asked. + context (`str` or `list[str]`): The context(s) in which we will look for the answer. + + Returns: + One or a list of [`SquadExample`]: The corresponding [`SquadExample`] grouping question and context. + """ + if isinstance(question, list): + return [SquadExample(None, q, c, None, None, None) for q, c in zip(question, context)] + else: + return SquadExample(None, question, context, None, None, None) + + def _sanitize_parameters( + self, + padding=None, + topk=None, + top_k=None, + doc_stride=None, + max_answer_len=None, + max_seq_len=None, + max_question_len=None, + handle_impossible_answer=None, + align_to_words=None, + **kwargs, + ): + # Set defaults values + preprocess_params = {} + if padding is not None: + preprocess_params["padding"] = padding + if doc_stride is not None: + preprocess_params["doc_stride"] = doc_stride + if max_question_len is not None: + preprocess_params["max_question_len"] = max_question_len + if max_seq_len is not None: + preprocess_params["max_seq_len"] = max_seq_len + + postprocess_params = {} + if topk is not None and top_k is None: + warnings.warn("topk parameter is deprecated, use top_k instead", UserWarning) + top_k = topk + if top_k is not None: + if top_k < 1: + raise ValueError(f"top_k parameter should be >= 1 (got {top_k})") + postprocess_params["top_k"] = top_k + if max_answer_len is not None: + if max_answer_len < 1: + raise ValueError(f"max_answer_len parameter should be >= 1 (got {max_answer_len}") + postprocess_params["max_answer_len"] = max_answer_len + if handle_impossible_answer is not None: + postprocess_params["handle_impossible_answer"] = handle_impossible_answer + if align_to_words is not None: + postprocess_params["align_to_words"] = align_to_words + return preprocess_params, {}, postprocess_params + + def __call__(self, *args, **kwargs): + """ + Answer the question(s) given as inputs by using the context(s). + + Args: + question (`str` or `list[str]`): + One or several question(s) (must be used in conjunction with the `context` argument). + context (`str` or `list[str]`): + One or several context(s) associated with the question(s) (must be used in conjunction with the + `question` argument). + top_k (`int`, *optional*, defaults to 1): + The number of answers to return (will be chosen by order of likelihood). Note that we return less than + top_k answers if there are not enough options available within the context. + doc_stride (`int`, *optional*, defaults to 128): + If the context is too long to fit with the question for the model, it will be split in several chunks + with some overlap. This argument controls the size of that overlap. + max_answer_len (`int`, *optional*, defaults to 15): + The maximum length of predicted answers (e.g., only answers with a shorter length are considered). + max_seq_len (`int`, *optional*, defaults to 384): + The maximum length of the total sentence (context + question) in tokens of each chunk passed to the + model. The context will be split in several chunks (using `doc_stride` as overlap) if needed. + max_question_len (`int`, *optional*, defaults to 64): + The maximum length of the question after tokenization. It will be truncated if needed. + handle_impossible_answer (`bool`, *optional*, defaults to `False`): + Whether or not we accept impossible as an answer. + align_to_words (`bool`, *optional*, defaults to `True`): + Attempts to align the answer to real words. Improves quality on space separated languages. Might hurt on + non-space-separated languages (like Japanese or Chinese) + + Return: + A `dict` or a list of `dict`: Each result comes as a dictionary with the following keys: + + - **score** (`float`) -- The probability associated to the answer. + - **start** (`int`) -- The character start index of the answer (in the tokenized version of the input). + - **end** (`int`) -- The character end index of the answer (in the tokenized version of the input). + - **answer** (`str`) -- The answer to the question. + """ + + # Convert inputs to features + if args: + warnings.warn( + "Passing a list of SQuAD examples to the pipeline is deprecated and will be removed in v5. Inputs should be passed using the `question` and `context` keyword arguments instead.", + FutureWarning, + ) + + examples = self._args_parser(*args, **kwargs) + if isinstance(examples, (list, tuple)) and len(examples) == 1: + return super().__call__(examples[0], **kwargs) + return super().__call__(examples, **kwargs) + + def preprocess(self, example, padding="do_not_pad", doc_stride=None, max_question_len=64, max_seq_len=None): + # XXX: This is special, args_parser will not handle anything generator or dataset like + # For those we expect user to send a simple valid example either directly as a SquadExample or simple dict. + # So we still need a little sanitation here. + if isinstance(example, dict): + example = SquadExample(None, example["question"], example["context"], None, None, None) + + if max_seq_len is None: + max_seq_len = min(self.tokenizer.model_max_length, 384) + if doc_stride is None: + doc_stride = min(max_seq_len // 2, 128) + + if doc_stride > max_seq_len: + raise ValueError(f"`doc_stride` ({doc_stride}) is larger than `max_seq_len` ({max_seq_len})") + + if not self.tokenizer.is_fast: + features = squad_convert_examples_to_features( + examples=[example], + tokenizer=self.tokenizer, + max_seq_length=max_seq_len, + doc_stride=doc_stride, + max_query_length=max_question_len, + padding_strategy=PaddingStrategy.MAX_LENGTH, + is_training=False, + tqdm_enabled=False, + ) + else: + # Define the side we want to truncate / pad and the text/pair sorting + question_first = self.tokenizer.padding_side == "right" + + encoded_inputs = self.tokenizer( + text=example.question_text if question_first else example.context_text, + text_pair=example.context_text if question_first else example.question_text, + padding=padding, + truncation="only_second" if question_first else "only_first", + max_length=max_seq_len, + stride=doc_stride, + return_token_type_ids=True, + return_overflowing_tokens=True, + return_offsets_mapping=True, + return_special_tokens_mask=True, + ) + # When the input is too long, it's converted in a batch of inputs with overflowing tokens + # and a stride of overlap between the inputs. If a batch of inputs is given, a special output + # "overflow_to_sample_mapping" indicate which member of the encoded batch belong to which original batch sample. + # Here we tokenize examples one-by-one so we don't need to use "overflow_to_sample_mapping". + # "num_span" is the number of output samples generated from the overflowing tokens. + num_spans = len(encoded_inputs["input_ids"]) + + # p_mask: mask with 1 for token than cannot be in the answer (0 for token which can be in an answer) + # We put 0 on the tokens from the context and 1 everywhere else (question and special tokens) + p_mask = [ + [tok != 1 if question_first else 0 for tok in encoded_inputs.sequence_ids(span_id)] + for span_id in range(num_spans) + ] + + features = [] + for span_idx in range(num_spans): + input_ids_span_idx = encoded_inputs["input_ids"][span_idx] + attention_mask_span_idx = ( + encoded_inputs["attention_mask"][span_idx] if "attention_mask" in encoded_inputs else None + ) + token_type_ids_span_idx = ( + encoded_inputs["token_type_ids"][span_idx] if "token_type_ids" in encoded_inputs else None + ) + # keep the cls_token unmasked (some models use it to indicate unanswerable questions) + if self.tokenizer.cls_token_id is not None: + cls_indices = np.nonzero(np.array(input_ids_span_idx) == self.tokenizer.cls_token_id)[0] + for cls_index in cls_indices: + p_mask[span_idx][cls_index] = 0 + submask = p_mask[span_idx] + features.append( + SquadFeatures( + input_ids=input_ids_span_idx, + attention_mask=attention_mask_span_idx, + token_type_ids=token_type_ids_span_idx, + p_mask=submask, + encoding=encoded_inputs[span_idx], + # We don't use the rest of the values - and actually + # for Fast tokenizer we could totally avoid using SquadFeatures and SquadExample + cls_index=None, + token_to_orig_map={}, + example_index=0, + unique_id=0, + paragraph_len=0, + token_is_max_context=0, + tokens=[], + start_position=0, + end_position=0, + is_impossible=False, + qas_id=None, + ) + ) + + for i, feature in enumerate(features): + fw_args = {} + others = {} + model_input_names = self.tokenizer.model_input_names + ["p_mask", "token_type_ids"] + + for k, v in feature.__dict__.items(): + if k in model_input_names: + if self.framework == "tf": + tensor = tf.constant(v) + if tensor.dtype == tf.int64: + tensor = tf.cast(tensor, tf.int32) + fw_args[k] = tf.expand_dims(tensor, 0) + elif self.framework == "pt": + tensor = torch.tensor(v) + if tensor.dtype == torch.int32: + tensor = tensor.long() + fw_args[k] = tensor.unsqueeze(0) + else: + others[k] = v + + is_last = i == len(features) - 1 + yield {"example": example, "is_last": is_last, **fw_args, **others} + + def _forward(self, inputs): + example = inputs["example"] + model_inputs = {k: inputs[k] for k in self.tokenizer.model_input_names} + # `XXXForSequenceClassification` models should not use `use_cache=True` even if it's supported + model_forward = self.model.forward if self.framework == "pt" else self.model.call + if "use_cache" in inspect.signature(model_forward).parameters: + model_inputs["use_cache"] = False + output = self.model(**model_inputs) + if isinstance(output, dict): + return {"start": output["start_logits"], "end": output["end_logits"], "example": example, **inputs} + else: + start, end = output[:2] + return {"start": start, "end": end, "example": example, **inputs} + + def postprocess( + self, + model_outputs, + top_k=1, + handle_impossible_answer=False, + max_answer_len=15, + align_to_words=True, + ): + min_null_score = 1000000 # large and positive + answers = [] + for output in model_outputs: + if self.framework == "pt" and output["start"].dtype == torch.bfloat16: + start_ = output["start"].to(torch.float32) + end_ = output["end"].to(torch.float32) + else: + start_ = output["start"] + end_ = output["end"] + example = output["example"] + p_mask = output["p_mask"] + attention_mask = ( + output["attention_mask"].numpy() if output.get("attention_mask", None) is not None else None + ) + + pre_topk = ( + top_k * 2 + 10 if align_to_words else top_k + ) # Some candidates may be deleted if we align to words + starts, ends, scores, min_null_score = select_starts_ends( + start_, + end_, + p_mask, + attention_mask, + min_null_score, + pre_topk, + handle_impossible_answer, + max_answer_len, + ) + + if not self.tokenizer.is_fast: + char_to_word = np.array(example.char_to_word_offset) + + # Convert the answer (tokens) back to the original text + # Score: score from the model + # Start: Index of the first character of the answer in the context string + # End: Index of the character following the last character of the answer in the context string + # Answer: Plain text of the answer + for s, e, score in zip(starts, ends, scores): + token_to_orig_map = output["token_to_orig_map"] + answers.append( + { + "score": score.item(), + "start": np.where(char_to_word == token_to_orig_map[s])[0][0].item(), + "end": np.where(char_to_word == token_to_orig_map[e])[0][-1].item(), + "answer": " ".join(example.doc_tokens[token_to_orig_map[s] : token_to_orig_map[e] + 1]), + } + ) + else: + # Convert the answer (tokens) back to the original text + # Score: score from the model + # Start: Index of the first character of the answer in the context string + # End: Index of the character following the last character of the answer in the context string + # Answer: Plain text of the answer + question_first = self.tokenizer.padding_side == "right" + enc = output["encoding"] + + # Encoding was *not* padded, input_ids *might*. + # It doesn't make a difference unless we're padding on + # the left hand side, since now we have different offsets + # everywhere. + if self.tokenizer.padding_side == "left": + offset = (output["input_ids"] == self.tokenizer.pad_token_id).numpy().sum() + else: + offset = 0 + + # Sometimes the max probability token is in the middle of a word so: + # - we start by finding the right word containing the token with `token_to_word` + # - then we convert this word in a character span with `word_to_chars` + sequence_index = 1 if question_first else 0 + + for s, e, score in zip(starts, ends, scores): + s = s - offset + e = e - offset + + start_index, end_index = self.get_indices(enc, s, e, sequence_index, align_to_words) + + target_answer = example.context_text[start_index:end_index] + answer = self.get_answer(answers, target_answer) + + if answer: + answer["score"] += score.item() + else: + answers.append( + { + "score": score.item(), + "start": start_index, + "end": end_index, + "answer": example.context_text[start_index:end_index], + } + ) + + if handle_impossible_answer: + answers.append({"score": min_null_score, "start": 0, "end": 0, "answer": ""}) + answers = sorted(answers, key=lambda x: x["score"], reverse=True)[:top_k] + if len(answers) == 1: + return answers[0] + return answers + + def get_answer(self, answers: list[dict], target: str) -> Optional[dict]: + for answer in answers: + if answer["answer"].lower() == target.lower(): + return answer + return None + + def get_indices( + self, enc: "tokenizers.Encoding", s: int, e: int, sequence_index: int, align_to_words: bool + ) -> tuple[int, int]: + if align_to_words: + try: + start_word = enc.token_to_word(s) + end_word = enc.token_to_word(e) + start_index = enc.word_to_chars(start_word, sequence_index=sequence_index)[0] + end_index = enc.word_to_chars(end_word, sequence_index=sequence_index)[1] + except Exception: + # Some tokenizers don't really handle words. Keep to offsets then. + start_index = enc.offsets[s][0] + end_index = enc.offsets[e][1] + else: + start_index = enc.offsets[s][0] + end_index = enc.offsets[e][1] + return start_index, end_index + + def span_to_answer(self, text: str, start: int, end: int) -> dict[str, Union[str, int]]: + """ + When decoding from token probabilities, this method maps token indexes to actual word in the initial context. + + Args: + text (`str`): The actual context to extract the answer from. + start (`int`): The answer starting token index. + end (`int`): The answer end token index. + + Returns: + Dictionary like `{'answer': str, 'start': int, 'end': int}` + """ + words = [] + token_idx = char_start_idx = char_end_idx = chars_idx = 0 + + for i, word in enumerate(text.split(" ")): + token = self.tokenizer.tokenize(word) + + # Append words if they are in the span + if start <= token_idx <= end: + if token_idx == start: + char_start_idx = chars_idx + + if token_idx == end: + char_end_idx = chars_idx + len(word) + + words += [word] + + # Stop if we went over the end of the answer + if token_idx > end: + break + + # Append the subtokenization length to the running index + token_idx += len(token) + chars_idx += len(word) + 1 + + # Join text with spaces + return { + "answer": " ".join(words), + "start": max(0, char_start_idx), + "end": min(len(text), char_end_idx), + } diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/table_question_answering.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/table_question_answering.py new file mode 100644 index 0000000000000000000000000000000000000000..da579423d2d4f92944ab0bb7430dfdddb190f5ac --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/table_question_answering.py @@ -0,0 +1,457 @@ +import collections +import types + +import numpy as np + +from ..generation import GenerationConfig +from ..utils import ( + add_end_docstrings, + is_tf_available, + is_torch_available, + requires_backends, +) +from .base import ArgumentHandler, Dataset, Pipeline, PipelineException, build_pipeline_init_args + + +if is_torch_available(): + import torch + + from ..models.auto.modeling_auto import ( + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, + MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES, + ) + +if is_tf_available(): + import tensorflow as tf + + from ..models.auto.modeling_tf_auto import ( + TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, + TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES, + ) + + +class TableQuestionAnsweringArgumentHandler(ArgumentHandler): + """ + Handles arguments for the TableQuestionAnsweringPipeline + """ + + def __call__(self, table=None, query=None, **kwargs): + # Returns tqa_pipeline_inputs of shape: + # [ + # {"table": pd.DataFrame, "query": list[str]}, + # ..., + # {"table": pd.DataFrame, "query" : list[str]} + # ] + requires_backends(self, "pandas") + import pandas as pd + + if table is None: + raise ValueError("Keyword argument `table` cannot be None.") + elif query is None: + if isinstance(table, dict) and table.get("query") is not None and table.get("table") is not None: + tqa_pipeline_inputs = [table] + elif isinstance(table, list) and len(table) > 0: + if not all(isinstance(d, dict) for d in table): + raise ValueError( + f"Keyword argument `table` should be a list of dict, but is {(type(d) for d in table)}" + ) + + if table[0].get("query") is not None and table[0].get("table") is not None: + tqa_pipeline_inputs = table + else: + raise ValueError( + "If keyword argument `table` is a list of dictionaries, each dictionary should have a `table`" + f" and `query` key, but only dictionary has keys {table[0].keys()} `table` and `query` keys." + ) + elif Dataset is not None and isinstance(table, Dataset) or isinstance(table, types.GeneratorType): + return table + else: + raise ValueError( + "Invalid input. Keyword argument `table` should be either of type `dict` or `list`, but " + f"is {type(table)})" + ) + else: + tqa_pipeline_inputs = [{"table": table, "query": query}] + + for tqa_pipeline_input in tqa_pipeline_inputs: + if not isinstance(tqa_pipeline_input["table"], pd.DataFrame): + if tqa_pipeline_input["table"] is None: + raise ValueError("Table cannot be None.") + + tqa_pipeline_input["table"] = pd.DataFrame(tqa_pipeline_input["table"]) + + return tqa_pipeline_inputs + + +@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True)) +class TableQuestionAnsweringPipeline(Pipeline): + """ + Table Question Answering pipeline using a `ModelForTableQuestionAnswering`. This pipeline is only available in + PyTorch. + + Unless the model you're using explicitly sets these generation parameters in its configuration files + (`generation_config.json`), the following default values will be used: + - max_new_tokens: 256 + + Example: + + ```python + >>> from transformers import pipeline + + >>> oracle = pipeline(model="google/tapas-base-finetuned-wtq") + >>> table = { + ... "Repository": ["Transformers", "Datasets", "Tokenizers"], + ... "Stars": ["36542", "4512", "3934"], + ... "Contributors": ["651", "77", "34"], + ... "Programming language": ["Python", "Python", "Rust, Python and NodeJS"], + ... } + >>> oracle(query="How many stars does the transformers repository have?", table=table) + {'answer': 'AVERAGE > 36542', 'coordinates': [(0, 1)], 'cells': ['36542'], 'aggregator': 'AVERAGE'} + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This tabular question answering pipeline can currently be loaded from [`pipeline`] using the following task + identifier: `"table-question-answering"`. + + The models that this pipeline can use are models that have been fine-tuned on a tabular question answering task. + See the up-to-date list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=table-question-answering). + """ + + default_input_names = "table,query" + + _pipeline_calls_generate = True + _load_processor = False + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = True + # Make sure the docstring is updated when the default generation config is changed + _default_generation_config = GenerationConfig( + max_new_tokens=256, + ) + + def __init__(self, args_parser=TableQuestionAnsweringArgumentHandler(), *args, **kwargs): + super().__init__(*args, **kwargs) + self._args_parser = args_parser + + if self.framework == "tf": + mapping = TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES.copy() + mapping.update(TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES) + else: + mapping = MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES.copy() + mapping.update(MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES) + self.check_model_type(mapping) + + self.aggregate = getattr(self.model.config, "aggregation_labels", None) and getattr( + self.model.config, "num_aggregation_labels", None + ) + self.type = "tapas" if hasattr(self.model.config, "aggregation_labels") else None + + def batch_inference(self, **inputs): + return self.model(**inputs) + + def sequential_inference(self, **inputs): + """ + Inference used for models that need to process sequences in a sequential fashion, like the SQA models which + handle conversational query related to a table. + """ + if self.framework == "pt": + all_logits = [] + all_aggregations = [] + prev_answers = None + batch_size = inputs["input_ids"].shape[0] + + input_ids = inputs["input_ids"].to(self.device) + attention_mask = inputs["attention_mask"].to(self.device) + token_type_ids = inputs["token_type_ids"].to(self.device) + token_type_ids_example = None + + for index in range(batch_size): + # If sequences have already been processed, the token type IDs will be created according to the previous + # answer. + if prev_answers is not None: + prev_labels_example = token_type_ids_example[:, 3] # shape (seq_len,) + model_labels = np.zeros_like(prev_labels_example.cpu().numpy()) # shape (seq_len,) + + token_type_ids_example = token_type_ids[index] # shape (seq_len, 7) + for i in range(model_labels.shape[0]): + segment_id = token_type_ids_example[:, 0].tolist()[i] + col_id = token_type_ids_example[:, 1].tolist()[i] - 1 + row_id = token_type_ids_example[:, 2].tolist()[i] - 1 + + if row_id >= 0 and col_id >= 0 and segment_id == 1: + model_labels[i] = int(prev_answers[(col_id, row_id)]) + + token_type_ids_example[:, 3] = torch.from_numpy(model_labels).type(torch.long).to(self.device) + + input_ids_example = input_ids[index] + attention_mask_example = attention_mask[index] # shape (seq_len,) + token_type_ids_example = token_type_ids[index] # shape (seq_len, 7) + outputs = self.model( + input_ids=input_ids_example.unsqueeze(0), + attention_mask=attention_mask_example.unsqueeze(0), + token_type_ids=token_type_ids_example.unsqueeze(0), + ) + logits = outputs.logits + + if self.aggregate: + all_aggregations.append(outputs.logits_aggregation) + + all_logits.append(logits) + + dist_per_token = torch.distributions.Bernoulli(logits=logits) + probabilities = dist_per_token.probs * attention_mask_example.type(torch.float32).to( + dist_per_token.probs.device + ) + + coords_to_probs = collections.defaultdict(list) + for i, p in enumerate(probabilities.squeeze().tolist()): + segment_id = token_type_ids_example[:, 0].tolist()[i] + col = token_type_ids_example[:, 1].tolist()[i] - 1 + row = token_type_ids_example[:, 2].tolist()[i] - 1 + if col >= 0 and row >= 0 and segment_id == 1: + coords_to_probs[(col, row)].append(p) + + prev_answers = {key: np.array(coords_to_probs[key]).mean() > 0.5 for key in coords_to_probs} + + logits_batch = torch.cat(tuple(all_logits), 0) + + return (logits_batch,) if not self.aggregate else (logits_batch, torch.cat(tuple(all_aggregations), 0)) + else: + all_logits = [] + all_aggregations = [] + prev_answers = None + batch_size = inputs["input_ids"].shape[0] + + input_ids = inputs["input_ids"] + attention_mask = inputs["attention_mask"] + token_type_ids = inputs["token_type_ids"].numpy() + token_type_ids_example = None + + for index in range(batch_size): + # If sequences have already been processed, the token type IDs will be created according to the previous + # answer. + if prev_answers is not None: + prev_labels_example = token_type_ids_example[:, 3] # shape (seq_len,) + model_labels = np.zeros_like(prev_labels_example, dtype=np.int32) # shape (seq_len,) + + token_type_ids_example = token_type_ids[index] # shape (seq_len, 7) + for i in range(model_labels.shape[0]): + segment_id = token_type_ids_example[:, 0].tolist()[i] + col_id = token_type_ids_example[:, 1].tolist()[i] - 1 + row_id = token_type_ids_example[:, 2].tolist()[i] - 1 + + if row_id >= 0 and col_id >= 0 and segment_id == 1: + model_labels[i] = int(prev_answers[(col_id, row_id)]) + + token_type_ids_example[:, 3] = model_labels + + input_ids_example = input_ids[index] + attention_mask_example = attention_mask[index] # shape (seq_len,) + token_type_ids_example = token_type_ids[index] # shape (seq_len, 7) + outputs = self.model( + input_ids=np.expand_dims(input_ids_example, axis=0), + attention_mask=np.expand_dims(attention_mask_example, axis=0), + token_type_ids=np.expand_dims(token_type_ids_example, axis=0), + ) + logits = outputs.logits + + if self.aggregate: + all_aggregations.append(outputs.logits_aggregation) + + all_logits.append(logits) + + probabilities = tf.math.sigmoid(tf.cast(logits, tf.float32)) * tf.cast( + attention_mask_example, tf.float32 + ) + + coords_to_probs = collections.defaultdict(list) + for i, p in enumerate(tf.squeeze(probabilities).numpy().tolist()): + segment_id = token_type_ids_example[:, 0].tolist()[i] + col = token_type_ids_example[:, 1].tolist()[i] - 1 + row = token_type_ids_example[:, 2].tolist()[i] - 1 + if col >= 0 and row >= 0 and segment_id == 1: + coords_to_probs[(col, row)].append(p) + + prev_answers = {key: np.array(coords_to_probs[key]).mean() > 0.5 for key in coords_to_probs} + + logits_batch = tf.concat(tuple(all_logits), 0) + + return (logits_batch,) if not self.aggregate else (logits_batch, tf.concat(tuple(all_aggregations), 0)) + + def __call__(self, *args, **kwargs): + r""" + Answers queries according to a table. The pipeline accepts several types of inputs which are detailed below: + + - `pipeline(table, query)` + - `pipeline(table, [query])` + - `pipeline(table=table, query=query)` + - `pipeline(table=table, query=[query])` + - `pipeline({"table": table, "query": query})` + - `pipeline({"table": table, "query": [query]})` + - `pipeline([{"table": table, "query": query}, {"table": table, "query": query}])` + + The `table` argument should be a dict or a DataFrame built from that dict, containing the whole table: + + Example: + + ```python + data = { + "actors": ["brad pitt", "leonardo di caprio", "george clooney"], + "age": ["56", "45", "59"], + "number of movies": ["87", "53", "69"], + "date of birth": ["7 february 1967", "10 june 1996", "28 november 1967"], + } + ``` + + This dictionary can be passed in as such, or can be converted to a pandas DataFrame: + + Example: + + ```python + import pandas as pd + + table = pd.DataFrame.from_dict(data) + ``` + + Args: + table (`pd.DataFrame` or `Dict`): + Pandas DataFrame or dictionary that will be converted to a DataFrame containing all the table values. + See above for an example of dictionary. + query (`str` or `list[str]`): + Query or list of queries that will be sent to the model alongside the table. + sequential (`bool`, *optional*, defaults to `False`): + Whether to do inference sequentially or as a batch. Batching is faster, but models like SQA require the + inference to be done sequentially to extract relations within sequences, given their conversational + nature. + padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`): + Activates and controls padding. Accepts the following values: + + - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single + sequence if provided). + - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum + acceptable input length for the model if that argument is not provided. + - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different + lengths). + + truncation (`bool`, `str` or [`TapasTruncationStrategy`], *optional*, defaults to `False`): + Activates and controls truncation. Accepts the following values: + + - `True` or `'drop_rows_to_fit'`: Truncate to a maximum length specified with the argument `max_length` + or to the maximum acceptable input length for the model if that argument is not provided. This will + truncate row by row, removing rows from the table. + - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths + greater than the model maximum admissible input size). + + + Return: + A dictionary or a list of dictionaries containing results: Each result is a dictionary with the following + keys: + + - **answer** (`str`) -- The answer of the query given the table. If there is an aggregator, the answer will + be preceded by `AGGREGATOR >`. + - **coordinates** (`list[tuple[int, int]]`) -- Coordinates of the cells of the answers. + - **cells** (`list[str]`) -- List of strings made up of the answer cell values. + - **aggregator** (`str`) -- If the model has an aggregator, this returns the aggregator. + """ + pipeline_inputs = self._args_parser(*args, **kwargs) + + results = super().__call__(pipeline_inputs, **kwargs) + if len(results) == 1: + return results[0] + return results + + def _sanitize_parameters(self, sequential=None, padding=None, truncation=None, **kwargs): + preprocess_params = {} + if padding is not None: + preprocess_params["padding"] = padding + if truncation is not None: + preprocess_params["truncation"] = truncation + + forward_params = {} + if sequential is not None: + forward_params["sequential"] = sequential + + if getattr(self, "assistant_model", None) is not None: + forward_params["assistant_model"] = self.assistant_model + if getattr(self, "assistant_tokenizer", None) is not None: + forward_params["tokenizer"] = self.tokenizer + forward_params["assistant_tokenizer"] = self.assistant_tokenizer + + return preprocess_params, forward_params, {} + + def preprocess(self, pipeline_input, sequential=None, padding=True, truncation=None): + if truncation is None: + if self.type == "tapas": + truncation = "drop_rows_to_fit" + else: + truncation = "do_not_truncate" + + table, query = pipeline_input["table"], pipeline_input["query"] + if table.empty: + raise ValueError("table is empty") + if query is None or query == "": + raise ValueError("query is empty") + inputs = self.tokenizer(table, query, return_tensors=self.framework, truncation=truncation, padding=padding) + inputs["table"] = table + return inputs + + def _forward(self, model_inputs, sequential=False, **generate_kwargs): + table = model_inputs.pop("table") + + if self.type == "tapas": + if sequential: + outputs = self.sequential_inference(**model_inputs) + else: + outputs = self.batch_inference(**model_inputs) + else: + # User-defined `generation_config` passed to the pipeline call take precedence + if "generation_config" not in generate_kwargs: + generate_kwargs["generation_config"] = self.generation_config + + outputs = self.model.generate(**model_inputs, **generate_kwargs) + model_outputs = {"model_inputs": model_inputs, "table": table, "outputs": outputs} + return model_outputs + + def postprocess(self, model_outputs): + inputs = model_outputs["model_inputs"] + table = model_outputs["table"] + outputs = model_outputs["outputs"] + if self.type == "tapas": + if self.aggregate: + logits, logits_agg = outputs[:2] + predictions = self.tokenizer.convert_logits_to_predictions(inputs, logits, logits_agg) + answer_coordinates_batch, agg_predictions = predictions + aggregators = {i: self.model.config.aggregation_labels[pred] for i, pred in enumerate(agg_predictions)} + + no_agg_label_index = self.model.config.no_aggregation_label_index + aggregators_prefix = { + i: aggregators[i] + " > " for i, pred in enumerate(agg_predictions) if pred != no_agg_label_index + } + else: + logits = outputs[0] + predictions = self.tokenizer.convert_logits_to_predictions(inputs, logits) + answer_coordinates_batch = predictions[0] + aggregators = {} + aggregators_prefix = {} + answers = [] + for index, coordinates in enumerate(answer_coordinates_batch): + cells = [table.iat[coordinate] for coordinate in coordinates] + aggregator = aggregators.get(index, "") + aggregator_prefix = aggregators_prefix.get(index, "") + answer = { + "answer": aggregator_prefix + ", ".join(cells), + "coordinates": coordinates, + "cells": [table.iat[coordinate] for coordinate in coordinates], + } + if aggregator: + answer["aggregator"] = aggregator + + answers.append(answer) + if len(answer) == 0: + raise PipelineException("Table question answering", self.model.name_or_path, "Empty answer") + else: + answers = [{"answer": answer} for answer in self.tokenizer.batch_decode(outputs, skip_special_tokens=True)] + + return answers if len(answers) > 1 else answers[0] diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/text2text_generation.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/text2text_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..8952b58208677ec1984b163ff2a34318ff6f8267 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/text2text_generation.py @@ -0,0 +1,410 @@ +import enum +import warnings +from typing import Any, Union + +from ..generation import GenerationConfig +from ..tokenization_utils import TruncationStrategy +from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging +from .base import Pipeline, build_pipeline_init_args + + +if is_tf_available(): + import tensorflow as tf + + from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES + +if is_torch_available(): + from ..models.auto.modeling_auto import MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES + +logger = logging.get_logger(__name__) + + +class ReturnType(enum.Enum): + TENSORS = 0 + TEXT = 1 + + +@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True)) +class Text2TextGenerationPipeline(Pipeline): + """ + Pipeline for text to text generation using seq2seq models. + + Unless the model you're using explicitly sets these generation parameters in its configuration files + (`generation_config.json`), the following default values will be used: + - max_new_tokens: 256 + - num_beams: 4 + + Example: + + ```python + >>> from transformers import pipeline + + >>> generator = pipeline(model="mrm8488/t5-base-finetuned-question-generation-ap") + >>> generator( + ... "answer: Manuel context: Manuel has created RuPERTa-base with the support of HF-Transformers and Google" + ... ) + [{'generated_text': 'question: Who created the RuPERTa-base?'}] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial). You can pass text + generation parameters to this pipeline to control stopping criteria, decoding strategy, and more. Learn more about + text generation parameters in [Text generation strategies](../generation_strategies) and [Text + generation](text_generation). + + This Text2TextGenerationPipeline pipeline can currently be loaded from [`pipeline`] using the following task + identifier: `"text2text-generation"`. + + The models that this pipeline can use are models that have been fine-tuned on a translation task. See the + up-to-date list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=text2text-generation). For a list of available + parameters, see the [following + documentation](https://huggingface.co/docs/transformers/en/main_classes/text_generation#transformers.generation.GenerationMixin.generate) + + Usage: + + ```python + text2text_generator = pipeline("text2text-generation") + text2text_generator("question: What is 42 ? context: 42 is the answer to life, the universe and everything") + ```""" + + _pipeline_calls_generate = True + _load_processor = False + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = True + # Make sure the docstring is updated when the default generation config is changed (in all pipelines in this file) + _default_generation_config = GenerationConfig( + max_new_tokens=256, + num_beams=4, + ) + + # Used in the return key of the pipeline. + return_name = "generated" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + self.check_model_type( + TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES + if self.framework == "tf" + else MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES + ) + + def _sanitize_parameters( + self, + return_tensors=None, + return_text=None, + return_type=None, + clean_up_tokenization_spaces=None, + truncation=None, + stop_sequence=None, + **generate_kwargs, + ): + preprocess_params = {} + if truncation is not None: + preprocess_params["truncation"] = truncation + + forward_params = generate_kwargs + + postprocess_params = {} + if return_tensors is not None and return_type is None: + return_type = ReturnType.TENSORS if return_tensors else ReturnType.TEXT + if return_type is not None: + postprocess_params["return_type"] = return_type + + if clean_up_tokenization_spaces is not None: + postprocess_params["clean_up_tokenization_spaces"] = clean_up_tokenization_spaces + + if stop_sequence is not None: + stop_sequence_ids = self.tokenizer.encode(stop_sequence, add_special_tokens=False) + if len(stop_sequence_ids) > 1: + warnings.warn( + "Stopping on a multiple token sequence is not yet supported on transformers. The first token of" + " the stop sequence will be used as the stop sequence string in the interim." + ) + generate_kwargs["eos_token_id"] = stop_sequence_ids[0] + + if self.assistant_model is not None: + forward_params["assistant_model"] = self.assistant_model + if self.assistant_tokenizer is not None: + forward_params["tokenizer"] = self.tokenizer + forward_params["assistant_tokenizer"] = self.assistant_tokenizer + + return preprocess_params, forward_params, postprocess_params + + def check_inputs(self, input_length: int, min_length: int, max_length: int): + """ + Checks whether there might be something wrong with given input with regard to the model. + """ + return True + + def _parse_and_tokenize(self, *args, truncation): + prefix = self.prefix if self.prefix is not None else "" + if isinstance(args[0], list): + if self.tokenizer.pad_token_id is None: + raise ValueError("Please make sure that the tokenizer has a pad_token_id when using a batch input") + args = ([prefix + arg for arg in args[0]],) + padding = True + + elif isinstance(args[0], str): + args = (prefix + args[0],) + padding = False + else: + raise TypeError( + f" `args[0]`: {args[0]} have the wrong format. The should be either of type `str` or type `list`" + ) + inputs = self.tokenizer(*args, padding=padding, truncation=truncation, return_tensors=self.framework) + # This is produced by tokenizers but is an invalid generate kwargs + if "token_type_ids" in inputs: + del inputs["token_type_ids"] + return inputs + + def __call__(self, *args: Union[str, list[str]], **kwargs: Any) -> list[dict[str, str]]: + r""" + Generate the output text(s) using text(s) given as inputs. + + Args: + args (`str` or `list[str]`): + Input text for the encoder. + return_tensors (`bool`, *optional*, defaults to `False`): + Whether or not to include the tensors of predictions (as token indices) in the outputs. + return_text (`bool`, *optional*, defaults to `True`): + Whether or not to include the decoded texts in the outputs. + clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`): + Whether or not to clean up the potential extra spaces in the text output. + truncation (`TruncationStrategy`, *optional*, defaults to `TruncationStrategy.DO_NOT_TRUNCATE`): + The truncation strategy for the tokenization within the pipeline. `TruncationStrategy.DO_NOT_TRUNCATE` + (default) will never truncate, but it is sometimes desirable to truncate the input to fit the model's + max_length instead of throwing an error down the line. + generate_kwargs: + Additional keyword arguments to pass along to the generate method of the model (see the generate method + corresponding to your framework [here](./text_generation)). + + Return: + A list or a list of list of `dict`: Each result comes as a dictionary with the following keys: + + - **generated_text** (`str`, present when `return_text=True`) -- The generated text. + - **generated_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) -- The token + ids of the generated text. + """ + + result = super().__call__(*args, **kwargs) + if ( + isinstance(args[0], list) + and all(isinstance(el, str) for el in args[0]) + and all(len(res) == 1 for res in result) + ): + return [res[0] for res in result] + return result + + def preprocess(self, inputs, truncation=TruncationStrategy.DO_NOT_TRUNCATE, **kwargs): + inputs = self._parse_and_tokenize(inputs, truncation=truncation, **kwargs) + return inputs + + def _forward(self, model_inputs, **generate_kwargs): + if self.framework == "pt": + in_b, input_length = model_inputs["input_ids"].shape + elif self.framework == "tf": + in_b, input_length = tf.shape(model_inputs["input_ids"]).numpy() + + self.check_inputs( + input_length, + generate_kwargs.get("min_length", self.generation_config.min_length), + generate_kwargs.get("max_length", self.generation_config.max_length), + ) + + # User-defined `generation_config` passed to the pipeline call take precedence + if "generation_config" not in generate_kwargs: + generate_kwargs["generation_config"] = self.generation_config + + output_ids = self.model.generate(**model_inputs, **generate_kwargs) + out_b = output_ids.shape[0] + if self.framework == "pt": + output_ids = output_ids.reshape(in_b, out_b // in_b, *output_ids.shape[1:]) + elif self.framework == "tf": + output_ids = tf.reshape(output_ids, (in_b, out_b // in_b, *output_ids.shape[1:])) + return {"output_ids": output_ids} + + def postprocess(self, model_outputs, return_type=ReturnType.TEXT, clean_up_tokenization_spaces=False): + records = [] + for output_ids in model_outputs["output_ids"][0]: + if return_type == ReturnType.TENSORS: + record = {f"{self.return_name}_token_ids": output_ids} + elif return_type == ReturnType.TEXT: + record = { + f"{self.return_name}_text": self.tokenizer.decode( + output_ids, + skip_special_tokens=True, + clean_up_tokenization_spaces=clean_up_tokenization_spaces, + ) + } + records.append(record) + return records + + +@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True)) +class SummarizationPipeline(Text2TextGenerationPipeline): + """ + Summarize news articles and other documents. + + This summarizing pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"summarization"`. + + The models that this pipeline can use are models that have been fine-tuned on a summarization task, which is + currently, '*bart-large-cnn*', '*google-t5/t5-small*', '*google-t5/t5-base*', '*google-t5/t5-large*', '*google-t5/t5-3b*', '*google-t5/t5-11b*'. See the up-to-date + list of available models on [huggingface.co/models](https://huggingface.co/models?filter=summarization). For a list + of available parameters, see the [following + documentation](https://huggingface.co/docs/transformers/en/main_classes/text_generation#transformers.generation.GenerationMixin.generate) + + Unless the model you're using explicitly sets these generation parameters in its configuration files + (`generation_config.json`), the following default values will be used: + - max_new_tokens: 256 + - num_beams: 4 + + Usage: + + ```python + # use bart in pytorch + summarizer = pipeline("summarization") + summarizer("An apple a day, keeps the doctor away", min_length=5, max_length=20) + + # use t5 in tf + summarizer = pipeline("summarization", model="google-t5/t5-base", tokenizer="google-t5/t5-base", framework="tf") + summarizer("An apple a day, keeps the doctor away", min_length=5, max_length=20) + ```""" + + # Used in the return key of the pipeline. + return_name = "summary" + + def __call__(self, *args, **kwargs): + r""" + Summarize the text(s) given as inputs. + + Args: + documents (*str* or `list[str]`): + One or several articles (or one list of articles) to summarize. + return_text (`bool`, *optional*, defaults to `True`): + Whether or not to include the decoded texts in the outputs + return_tensors (`bool`, *optional*, defaults to `False`): + Whether or not to include the tensors of predictions (as token indices) in the outputs. + clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`): + Whether or not to clean up the potential extra spaces in the text output. + generate_kwargs: + Additional keyword arguments to pass along to the generate method of the model (see the generate method + corresponding to your framework [here](./text_generation)). + + Return: + A list or a list of list of `dict`: Each result comes as a dictionary with the following keys: + + - **summary_text** (`str`, present when `return_text=True`) -- The summary of the corresponding input. + - **summary_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) -- The token + ids of the summary. + """ + return super().__call__(*args, **kwargs) + + def check_inputs(self, input_length: int, min_length: int, max_length: int) -> bool: + """ + Checks whether there might be something wrong with given input with regard to the model. + """ + if max_length < min_length: + logger.warning(f"Your min_length={min_length} must be inferior than your max_length={max_length}.") + + if input_length < max_length: + logger.warning( + f"Your max_length is set to {max_length}, but your input_length is only {input_length}. Since this is " + "a summarization task, where outputs shorter than the input are typically wanted, you might " + f"consider decreasing max_length manually, e.g. summarizer('...', max_length={input_length // 2})" + ) + + +@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True)) +class TranslationPipeline(Text2TextGenerationPipeline): + """ + Translates from one language to another. + + This translation pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"translation_xx_to_yy"`. + + The models that this pipeline can use are models that have been fine-tuned on a translation task. See the + up-to-date list of available models on [huggingface.co/models](https://huggingface.co/models?filter=translation). + For a list of available parameters, see the [following + documentation](https://huggingface.co/docs/transformers/en/main_classes/text_generation#transformers.generation.GenerationMixin.generate) + + Unless the model you're using explicitly sets these generation parameters in its configuration files + (`generation_config.json`), the following default values will be used: + - max_new_tokens: 256 + - num_beams: 4 + + Usage: + + ```python + en_fr_translator = pipeline("translation_en_to_fr") + en_fr_translator("How old are you?") + ```""" + + # Used in the return key of the pipeline. + return_name = "translation" + + def check_inputs(self, input_length: int, min_length: int, max_length: int): + if input_length > 0.9 * max_length: + logger.warning( + f"Your input_length: {input_length} is bigger than 0.9 * max_length: {max_length}. You might consider " + "increasing your max_length manually, e.g. translator('...', max_length=400)" + ) + return True + + def preprocess(self, *args, truncation=TruncationStrategy.DO_NOT_TRUNCATE, src_lang=None, tgt_lang=None): + if getattr(self.tokenizer, "_build_translation_inputs", None): + return self.tokenizer._build_translation_inputs( + *args, return_tensors=self.framework, truncation=truncation, src_lang=src_lang, tgt_lang=tgt_lang + ) + else: + return super()._parse_and_tokenize(*args, truncation=truncation) + + def _sanitize_parameters(self, src_lang=None, tgt_lang=None, **kwargs): + preprocess_params, forward_params, postprocess_params = super()._sanitize_parameters(**kwargs) + if src_lang is not None: + preprocess_params["src_lang"] = src_lang + if tgt_lang is not None: + preprocess_params["tgt_lang"] = tgt_lang + if src_lang is None and tgt_lang is None: + # Backward compatibility, direct arguments use is preferred. + task = kwargs.get("task", self.task) + items = task.split("_") + if task and len(items) == 4: + # translation, XX, to YY + preprocess_params["src_lang"] = items[1] + preprocess_params["tgt_lang"] = items[3] + return preprocess_params, forward_params, postprocess_params + + def __call__(self, *args, **kwargs): + r""" + Translate the text(s) given as inputs. + + Args: + args (`str` or `list[str]`): + Texts to be translated. + return_tensors (`bool`, *optional*, defaults to `False`): + Whether or not to include the tensors of predictions (as token indices) in the outputs. + return_text (`bool`, *optional*, defaults to `True`): + Whether or not to include the decoded texts in the outputs. + clean_up_tokenization_spaces (`bool`, *optional*, defaults to `False`): + Whether or not to clean up the potential extra spaces in the text output. + src_lang (`str`, *optional*): + The language of the input. Might be required for multilingual models. Will not have any effect for + single pair translation models + tgt_lang (`str`, *optional*): + The language of the desired output. Might be required for multilingual models. Will not have any effect + for single pair translation models + generate_kwargs: + Additional keyword arguments to pass along to the generate method of the model (see the generate method + corresponding to your framework [here](./text_generation)). + + Return: + A list or a list of list of `dict`: Each result comes as a dictionary with the following keys: + + - **translation_text** (`str`, present when `return_text=True`) -- The translation. + - **translation_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) -- The + token ids of the translation. + """ + return super().__call__(*args, **kwargs) diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/text_classification.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/text_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..6f11f3bc97418be6106b183a1925245a273cb085 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/text_classification.py @@ -0,0 +1,245 @@ +import inspect +import warnings +from typing import Any, Union + +import numpy as np + +from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available +from .base import GenericTensor, Pipeline, build_pipeline_init_args + + +if is_tf_available(): + from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES + +if is_torch_available(): + from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES + + +def sigmoid(_outputs): + return 1.0 / (1.0 + np.exp(-_outputs)) + + +def softmax(_outputs): + maxes = np.max(_outputs, axis=-1, keepdims=True) + shifted_exp = np.exp(_outputs - maxes) + return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True) + + +class ClassificationFunction(ExplicitEnum): + SIGMOID = "sigmoid" + SOFTMAX = "softmax" + NONE = "none" + + +@add_end_docstrings( + build_pipeline_init_args(has_tokenizer=True), + r""" + return_all_scores (`bool`, *optional*, defaults to `False`): + Whether to return all prediction scores or just the one of the predicted class. + function_to_apply (`str`, *optional*, defaults to `"default"`): + The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: + + - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model + has several labels, will apply the softmax function on the output. In case of regression tasks, will not + apply any function on the output. + - `"sigmoid"`: Applies the sigmoid function on the output. + - `"softmax"`: Applies the softmax function on the output. + - `"none"`: Does not apply any function on the output.""", +) +class TextClassificationPipeline(Pipeline): + """ + Text classification pipeline using any `ModelForSequenceClassification`. See the [sequence classification + examples](../task_summary#sequence-classification) for more information. + + Example: + + ```python + >>> from transformers import pipeline + + >>> classifier = pipeline(model="distilbert/distilbert-base-uncased-finetuned-sst-2-english") + >>> classifier("This movie is disgustingly good !") + [{'label': 'POSITIVE', 'score': 1.0}] + + >>> classifier("Director tried too much.") + [{'label': 'NEGATIVE', 'score': 0.996}] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This text classification pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"sentiment-analysis"` (for classifying sequences according to positive or negative sentiments). + + If multiple classification labels are available (`model.config.num_labels >= 2`), the pipeline will run a softmax + over the results. If there is a single label, the pipeline will run a sigmoid over the result. In case of regression + tasks (`model.config.problem_type == "regression"`), will not apply any function on the output. + + The models that this pipeline can use are models that have been fine-tuned on a sequence classification task. See + the up-to-date list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=text-classification). + """ + + _load_processor = False + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = True + + return_all_scores = False + function_to_apply = ClassificationFunction.NONE + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + self.check_model_type( + TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES + if self.framework == "tf" + else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES + ) + + def _sanitize_parameters(self, return_all_scores=None, function_to_apply=None, top_k="", **tokenizer_kwargs): + # Using "" as default argument because we're going to use `top_k=None` in user code to declare + # "No top_k" + preprocess_params = tokenizer_kwargs + + postprocess_params = {} + if hasattr(self.model.config, "return_all_scores") and return_all_scores is None: + return_all_scores = self.model.config.return_all_scores + + if isinstance(top_k, int) or top_k is None: + postprocess_params["top_k"] = top_k + postprocess_params["_legacy"] = False + elif return_all_scores is not None: + warnings.warn( + "`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of" + " `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.", + UserWarning, + ) + if return_all_scores: + postprocess_params["top_k"] = None + else: + postprocess_params["top_k"] = 1 + + if isinstance(function_to_apply, str): + function_to_apply = ClassificationFunction[function_to_apply.upper()] + + if function_to_apply is not None: + postprocess_params["function_to_apply"] = function_to_apply + return preprocess_params, {}, postprocess_params + + def __call__( + self, + inputs: Union[str, list[str], dict[str, str], list[dict[str, str]]], + **kwargs: Any, + ) -> list[dict[str, Any]]: + """ + Classify the text(s) given as inputs. + + Args: + inputs (`str` or `list[str]` or `dict[str]`, or `list[dict[str]]`): + One or several texts to classify. In order to use text pairs for your classification, you can send a + dictionary containing `{"text", "text_pair"}` keys, or a list of those. + top_k (`int`, *optional*, defaults to `1`): + How many results to return. + function_to_apply (`str`, *optional*, defaults to `"default"`): + The function to apply to the model outputs in order to retrieve the scores. Accepts four different + values: + + If this argument is not specified, then it will apply the following functions according to the number + of labels: + + - If problem type is regression, will not apply any function on the output. + - If the model has a single label, will apply the sigmoid function on the output. + - If the model has several labels, will apply the softmax function on the output. + + Possible values are: + + - `"sigmoid"`: Applies the sigmoid function on the output. + - `"softmax"`: Applies the softmax function on the output. + - `"none"`: Does not apply any function on the output. + + Return: + A list of `dict`: Each result comes as list of dictionaries with the following keys: + + - **label** (`str`) -- The label predicted. + - **score** (`float`) -- The corresponding probability. + + If `top_k` is used, one such dictionary is returned per label. + """ + inputs = (inputs,) + result = super().__call__(*inputs, **kwargs) + # TODO try and retrieve it in a nicer way from _sanitize_parameters. + _legacy = "top_k" not in kwargs + if isinstance(inputs[0], str) and _legacy: + # This pipeline is odd, and return a list when single item is run + return [result] + else: + return result + + def preprocess(self, inputs, **tokenizer_kwargs) -> dict[str, GenericTensor]: + return_tensors = self.framework + if isinstance(inputs, dict): + return self.tokenizer(**inputs, return_tensors=return_tensors, **tokenizer_kwargs) + elif isinstance(inputs, list) and len(inputs) == 1 and isinstance(inputs[0], list) and len(inputs[0]) == 2: + # It used to be valid to use a list of list of list for text pairs, keeping this path for BC + return self.tokenizer( + text=inputs[0][0], text_pair=inputs[0][1], return_tensors=return_tensors, **tokenizer_kwargs + ) + elif isinstance(inputs, list): + # This is likely an invalid usage of the pipeline attempting to pass text pairs. + raise ValueError( + "The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a" + ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.' + ) + return self.tokenizer(inputs, return_tensors=return_tensors, **tokenizer_kwargs) + + def _forward(self, model_inputs): + # `XXXForSequenceClassification` models should not use `use_cache=True` even if it's supported + model_forward = self.model.forward if self.framework == "pt" else self.model.call + if "use_cache" in inspect.signature(model_forward).parameters: + model_inputs["use_cache"] = False + return self.model(**model_inputs) + + def postprocess(self, model_outputs, function_to_apply=None, top_k=1, _legacy=True): + # `_legacy` is used to determine if we're running the naked pipeline and in backward + # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running + # the more natural result containing the list. + # Default value before `set_parameters` + if function_to_apply is None: + if self.model.config.problem_type == "regression": + function_to_apply = ClassificationFunction.NONE + elif self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: + function_to_apply = ClassificationFunction.SIGMOID + elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: + function_to_apply = ClassificationFunction.SOFTMAX + elif hasattr(self.model.config, "function_to_apply") and function_to_apply is None: + function_to_apply = self.model.config.function_to_apply + else: + function_to_apply = ClassificationFunction.NONE + + outputs = model_outputs["logits"][0] + + if self.framework == "pt": + # To enable using fp16 and bf16 + outputs = outputs.float().numpy() + else: + outputs = outputs.numpy() + + if function_to_apply == ClassificationFunction.SIGMOID: + scores = sigmoid(outputs) + elif function_to_apply == ClassificationFunction.SOFTMAX: + scores = softmax(outputs) + elif function_to_apply == ClassificationFunction.NONE: + scores = outputs + else: + raise ValueError(f"Unrecognized `function_to_apply` argument: {function_to_apply}") + + if top_k == 1 and _legacy: + return {"label": self.model.config.id2label[scores.argmax().item()], "score": scores.max().item()} + + dict_scores = [ + {"label": self.model.config.id2label[i], "score": score.item()} for i, score in enumerate(scores) + ] + if not _legacy: + dict_scores.sort(key=lambda x: x["score"], reverse=True) + if top_k is not None: + dict_scores = dict_scores[:top_k] + return dict_scores diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/text_generation.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/text_generation.py new file mode 100644 index 0000000000000000000000000000000000000000..4f7dce96da17c60f7735b9644657f0f29ea55819 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/text_generation.py @@ -0,0 +1,546 @@ +import enum +import itertools +import types +from typing import Any, overload + +from ..generation import GenerationConfig +from ..utils import ModelOutput, add_end_docstrings, is_tf_available, is_torch_available +from .base import Pipeline, build_pipeline_init_args + + +if is_torch_available(): + import torch + + from ..models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES + from .pt_utils import KeyDataset + +if is_tf_available(): + import tensorflow as tf + + from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES + +ChatType = list[dict[str, str]] + + +class ReturnType(enum.Enum): + TENSORS = 0 + NEW_TEXT = 1 + FULL_TEXT = 2 + + +class Chat: + """This class is intended to just be used internally in this pipeline and not exposed to users. We convert chats + to this format because the rest of the pipeline code tends to assume that lists of messages are + actually a batch of samples rather than messages in the same conversation.""" + + def __init__(self, messages: dict): + for message in messages: + if not ("role" in message and "content" in message): + raise ValueError("When passing chat dicts as input, each dict must have a 'role' and 'content' key.") + self.messages = messages + + +@add_end_docstrings(build_pipeline_init_args(has_tokenizer=True)) +class TextGenerationPipeline(Pipeline): + """ + Language generation pipeline using any `ModelWithLMHead` or `ModelForCausalLM`. This pipeline predicts the words + that will follow a specified text prompt. When the underlying model is a conversational model, it can also accept + one or more chats, in which case the pipeline will operate in chat mode and will continue the chat(s) by adding + its response(s). Each chat takes the form of a list of dicts, where each dict contains "role" and "content" keys. + + Unless the model you're using explicitly sets these generation parameters in its configuration files + (`generation_config.json`), the following default values will be used: + - max_new_tokens: 256 + - do_sample: True + - temperature: 0.7 + + Examples: + + ```python + >>> from transformers import pipeline + + >>> generator = pipeline(model="openai-community/gpt2") + >>> generator("I can't believe you did such a ", do_sample=False) + [{'generated_text': "I can't believe you did such a icky thing to me. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I'm so sorry. I"}] + + >>> # These parameters will return suggestions, and only the newly created text making it easier for prompting suggestions. + >>> outputs = generator("My tart needs some", num_return_sequences=4, return_full_text=False) + ``` + + ```python + >>> from transformers import pipeline + + >>> generator = pipeline(model="HuggingFaceH4/zephyr-7b-beta") + >>> # Zephyr-beta is a conversational model, so let's pass it a chat instead of a single string + >>> generator([{"role": "user", "content": "What is the capital of France? Answer in one word."}], do_sample=False, max_new_tokens=2) + [{'generated_text': [{'role': 'user', 'content': 'What is the capital of France? Answer in one word.'}, {'role': 'assistant', 'content': 'Paris'}]}] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial). You can pass text + generation parameters to this pipeline to control stopping criteria, decoding strategy, and more. Learn more about + text generation parameters in [Text generation strategies](../generation_strategies) and [Text + generation](text_generation). + + This language generation pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"text-generation"`. + + The models that this pipeline can use are models that have been trained with an autoregressive language modeling + objective. See the list of available [text completion models](https://huggingface.co/models?filter=text-generation) + and the list of [conversational models](https://huggingface.co/models?other=conversational) + on [huggingface.co/models]. + """ + + # Prefix text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia + # in https://github.com/rusiaaman/XLNet-gen#methodology + # and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e + + XL_PREFIX = """ + In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The + voice of Nicholas's young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western + Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision + and denounces one of the men as a horse thief. Although his father initially slaps him for making such an + accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of + the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop, + begging for his blessing. + """ + + _pipeline_calls_generate = True + _load_processor = False + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = True + + # Make sure the docstring is updated when the default generation config is changed + _default_generation_config = GenerationConfig( + max_new_tokens=256, + do_sample=True, # free-form text generation often uses sampling + temperature=0.7, + ) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.check_model_type( + TF_MODEL_FOR_CAUSAL_LM_MAPPING_NAMES if self.framework == "tf" else MODEL_FOR_CAUSAL_LM_MAPPING_NAMES + ) + if "prefix" not in self._preprocess_params: + # This is very specific. The logic is quite complex and needs to be done + # as a "default". + # It also defines both some preprocess_kwargs and generate_kwargs + # which is why we cannot put them in their respective methods. + prefix = None + if self.prefix is not None: + prefix = self.prefix + if prefix is None and self.model.__class__.__name__ in [ + "XLNetLMHeadModel", + "TransfoXLLMHeadModel", + "TFXLNetLMHeadModel", + "TFTransfoXLLMHeadModel", + ]: + # For XLNet and TransformerXL we add an article to the prompt to give more state to the model. + prefix = self.XL_PREFIX + if prefix is not None: + # Recalculate some generate_kwargs linked to prefix. + preprocess_params, forward_params, _ = self._sanitize_parameters(prefix=prefix, **self._forward_params) + self._preprocess_params = {**self._preprocess_params, **preprocess_params} + self._forward_params = {**self._forward_params, **forward_params} + + def _sanitize_parameters( + self, + return_full_text=None, + return_tensors=None, + return_text=None, + return_type=None, + clean_up_tokenization_spaces=None, + prefix=None, + handle_long_generation=None, + stop_sequence=None, + truncation=None, + max_length=None, + continue_final_message=None, + skip_special_tokens=None, + tokenizer_encode_kwargs=None, + **generate_kwargs, + ): + # preprocess kwargs + preprocess_params = {} + add_special_tokens = False + if "add_special_tokens" in generate_kwargs: + add_special_tokens = preprocess_params["add_special_tokens"] = generate_kwargs.pop("add_special_tokens") + + if "padding" in generate_kwargs: + preprocess_params["padding"] = generate_kwargs.pop("padding") + + if truncation is not None: + preprocess_params["truncation"] = truncation + + if max_length is not None: + preprocess_params["max_length"] = max_length + generate_kwargs["max_length"] = max_length + + if prefix is not None: + preprocess_params["prefix"] = prefix + if prefix: + prefix_inputs = self.tokenizer( + prefix, padding=False, add_special_tokens=add_special_tokens, return_tensors=self.framework + ) + generate_kwargs["prefix_length"] = prefix_inputs["input_ids"].shape[-1] + + if handle_long_generation is not None: + if handle_long_generation not in {"hole"}: + raise ValueError( + f"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected" + " [None, 'hole']" + ) + preprocess_params["handle_long_generation"] = handle_long_generation + + if continue_final_message is not None: + preprocess_params["continue_final_message"] = continue_final_message + + if tokenizer_encode_kwargs is not None: + preprocess_params["tokenizer_encode_kwargs"] = tokenizer_encode_kwargs + + preprocess_params.update(generate_kwargs) + + # forward kwargs + if stop_sequence is not None: + stop_sequence_ids = self.tokenizer.encode(stop_sequence, add_special_tokens=False) + generate_kwargs["eos_token_id"] = stop_sequence_ids + forward_params = generate_kwargs + if self.assistant_model is not None: + forward_params["assistant_model"] = self.assistant_model + if self.assistant_tokenizer is not None: + forward_params["tokenizer"] = self.tokenizer + forward_params["assistant_tokenizer"] = self.assistant_tokenizer + + # postprocess kwargs + postprocess_params = {} + if return_full_text is not None and return_type is None: + if return_text is not None: + raise ValueError("`return_text` is mutually exclusive with `return_full_text`") + if return_tensors is not None: + raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`") + return_type = ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT + if return_tensors is not None and return_type is None: + if return_text is not None: + raise ValueError("`return_text` is mutually exclusive with `return_tensors`") + return_type = ReturnType.TENSORS + if return_type is not None: + postprocess_params["return_type"] = return_type + if clean_up_tokenization_spaces is not None: + postprocess_params["clean_up_tokenization_spaces"] = clean_up_tokenization_spaces + if continue_final_message is not None: + postprocess_params["continue_final_message"] = continue_final_message + if skip_special_tokens is not None: + postprocess_params["skip_special_tokens"] = skip_special_tokens + + return preprocess_params, forward_params, postprocess_params + + # overriding _parse_and_tokenize to allow for unusual language-modeling tokenizer arguments + def _parse_and_tokenize(self, *args, **kwargs): + """ + Parse arguments and tokenize + """ + # Parse arguments + if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]: + kwargs.update({"add_space_before_punct_symbol": True}) + + return super()._parse_and_tokenize(*args, **kwargs) + + @overload + def __call__(self, text_inputs: str, **kwargs: Any) -> list[dict[str, str]]: ... + + @overload + def __call__(self, text_inputs: list[str], **kwargs: Any) -> list[list[dict[str, str]]]: ... + + @overload + def __call__(self, text_inputs: ChatType, **kwargs: Any) -> list[dict[str, ChatType]]: ... + + @overload + def __call__(self, text_inputs: list[ChatType], **kwargs: Any) -> list[list[dict[str, ChatType]]]: ... + + def __call__(self, text_inputs, **kwargs): + """ + Complete the prompt(s) given as inputs. + + Args: + text_inputs (`str`, `list[str]`, list[dict[str, str]], or `list[list[dict[str, str]]]`): + One or several prompts (or one list of prompts) to complete. If strings or a list of string are + passed, this pipeline will continue each prompt. Alternatively, a "chat", in the form of a list + of dicts with "role" and "content" keys, can be passed, or a list of such chats. When chats are passed, + the model's chat template will be used to format them before passing them to the model. + return_tensors (`bool`, *optional*, defaults to `False`): + Returns the tensors of predictions (as token indices) in the outputs. If set to + `True`, the decoded text is not returned. + return_text (`bool`, *optional*): + Returns the decoded texts in the outputs. + return_full_text (`bool`, *optional*, defaults to `True`): + If set to `False` only added text is returned, otherwise the full text is returned. Cannot be + specified at the same time as `return_text`. + clean_up_tokenization_spaces (`bool`, *optional*, defaults to `True`): + Whether or not to clean up the potential extra spaces in the text output. + continue_final_message( `bool`, *optional*): This indicates that you want the model to continue the + last message in the input chat rather than starting a new one, allowing you to "prefill" its response. + By default this is `True` when the final message in the input chat has the `assistant` role and + `False` otherwise, but you can manually override that behaviour by setting this flag. + prefix (`str`, *optional*): + Prefix added to prompt. + handle_long_generation (`str`, *optional*): + By default, this pipelines does not handle long generation (ones that exceed in one form or the other + the model maximum length). There is no perfect way to address this (more info + :https://github.com/huggingface/transformers/issues/14033#issuecomment-948385227). This provides common + strategies to work around that problem depending on your use case. + + - `None` : default strategy where nothing in particular happens + - `"hole"`: Truncates left of input, and leaves a gap wide enough to let generation happen (might + truncate a lot of the prompt and not suitable when generation exceed the model capacity) + tokenizer_encode_kwargs (`dict`, *optional*): + Additional keyword arguments to pass along to the encoding step of the tokenizer. If the text input is + a chat, it is passed to `apply_chat_template`. Otherwise, it is passed to `__call__`. + generate_kwargs (`dict`, *optional*): + Additional keyword arguments to pass along to the generate method of the model (see the generate method + corresponding to your framework [here](./text_generation)). + + Return: + A list or a list of lists of `dict`: Returns one of the following dictionaries (cannot return a combination + of both `generated_text` and `generated_token_ids`): + + - **generated_text** (`str`, present when `return_text=True`) -- The generated text. + - **generated_token_ids** (`torch.Tensor` or `tf.Tensor`, present when `return_tensors=True`) -- The token + ids of the generated text. + """ + if isinstance( + text_inputs, + (list, tuple, types.GeneratorType, KeyDataset) + if is_torch_available() + else (list, tuple, types.GeneratorType), + ): + if isinstance(text_inputs, types.GeneratorType): + text_inputs, _ = itertools.tee(text_inputs) + text_inputs, first_item = (x for x in text_inputs), next(_) + else: + first_item = text_inputs[0] + if isinstance(first_item, (list, tuple, dict)): + # We have one or more prompts in list-of-dicts format, so this is chat mode + if isinstance(first_item, dict): + return super().__call__(Chat(text_inputs), **kwargs) + else: + chats = (Chat(chat) for chat in text_inputs) # 🐈 🐈 🐈 + if isinstance(text_inputs, types.GeneratorType): + return super().__call__(chats, **kwargs) + else: + return super().__call__(list(chats), **kwargs) + return super().__call__(text_inputs, **kwargs) + + def preprocess( + self, + prompt_text, + prefix="", + handle_long_generation=None, + add_special_tokens=None, + truncation=None, + padding=None, + max_length=None, + continue_final_message=None, + tokenizer_encode_kwargs=None, + **generate_kwargs, + ): + # Only set non-None tokenizer kwargs, so as to rely on the tokenizer's defaults + tokenizer_kwargs = { + "add_special_tokens": add_special_tokens, + "truncation": truncation, + "padding": padding, + "max_length": max_length, # NOTE: `max_length` is also a `generate` arg. Use `tokenizer_encode_kwargs` to avoid a name clash + } + tokenizer_kwargs = {key: value for key, value in tokenizer_kwargs.items() if value is not None} + tokenizer_kwargs.update(tokenizer_encode_kwargs or {}) + + if isinstance(prompt_text, Chat): + tokenizer_kwargs.pop("add_special_tokens", None) # ignore add_special_tokens on chats + # If the user passes a chat that ends in an assistant message, we treat it as a prefill by default + # because very few models support multiple separate, consecutive assistant messages + if continue_final_message is None: + continue_final_message = prompt_text.messages[-1]["role"] == "assistant" + inputs = self.tokenizer.apply_chat_template( + prompt_text.messages, + add_generation_prompt=not continue_final_message, + continue_final_message=continue_final_message, + return_dict=True, + return_tensors=self.framework, + **tokenizer_kwargs, + ) + else: + inputs = self.tokenizer(prefix + prompt_text, return_tensors=self.framework, **tokenizer_kwargs) + + inputs["prompt_text"] = prompt_text + + if handle_long_generation == "hole": + cur_len = inputs["input_ids"].shape[-1] + if "max_new_tokens" in generate_kwargs: + new_tokens = generate_kwargs["max_new_tokens"] + else: + new_tokens = generate_kwargs.get("max_length", self.generation_config.max_length) - cur_len + if new_tokens < 0: + raise ValueError("We cannot infer how many new tokens are expected") + if cur_len + new_tokens > self.tokenizer.model_max_length: + keep_length = self.tokenizer.model_max_length - new_tokens + if keep_length <= 0: + raise ValueError( + "We cannot use `hole` to handle this generation the number of desired tokens exceeds the" + " models max length" + ) + + inputs["input_ids"] = inputs["input_ids"][:, -keep_length:] + if "attention_mask" in inputs: + inputs["attention_mask"] = inputs["attention_mask"][:, -keep_length:] + + return inputs + + def _forward(self, model_inputs, **generate_kwargs): + input_ids = model_inputs["input_ids"] + attention_mask = model_inputs.get("attention_mask", None) + # Allow empty prompts + if input_ids.shape[1] == 0: + input_ids = None + attention_mask = None + in_b = 1 + else: + in_b = input_ids.shape[0] + prompt_text = model_inputs.pop("prompt_text") + + # If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying + # generate_kwargs, as some of the parameterization may come from the initialization of the pipeline. + prefix_length = generate_kwargs.pop("prefix_length", 0) + if prefix_length > 0: + has_max_new_tokens = "max_new_tokens" in generate_kwargs or ( + "generation_config" in generate_kwargs + and generate_kwargs["generation_config"].max_new_tokens is not None + ) + if not has_max_new_tokens: + generate_kwargs["max_length"] = generate_kwargs.get("max_length") or self.generation_config.max_length + generate_kwargs["max_length"] += prefix_length + has_min_new_tokens = "min_new_tokens" in generate_kwargs or ( + "generation_config" in generate_kwargs + and generate_kwargs["generation_config"].min_new_tokens is not None + ) + if not has_min_new_tokens and "min_length" in generate_kwargs: + generate_kwargs["min_length"] += prefix_length + + # User-defined `generation_config` passed to the pipeline call take precedence + if "generation_config" not in generate_kwargs: + generate_kwargs["generation_config"] = self.generation_config + + output = self.model.generate(input_ids=input_ids, attention_mask=attention_mask, **generate_kwargs) + + if isinstance(output, ModelOutput): + generated_sequence = output.sequences + other_outputs = {k: v for k, v in output.items() if k not in {"sequences", "past_key_values"}} + out_b = generated_sequence.shape[0] + + if self.framework == "pt": + for key, value in other_outputs.items(): + if isinstance(value, torch.Tensor) and value.shape[0] == out_b: + other_outputs[key] = value.reshape(in_b, out_b // in_b, *value.shape[1:]) + if isinstance(value, tuple) and len(value[0]) == out_b: + value = torch.stack(value).swapaxes(0, 1) + other_outputs[key] = value + elif self.framework == "tf": + for key, value in other_outputs.items(): + if isinstance(value, tf.Tensor) and value.shape[0] == out_b: + other_outputs[key] = tf.reshape(value, (in_b, out_b // in_b, *value.shape[1:])) + if isinstance(value, tuple) and len(value[0]) == out_b: + value = tf.stack(value).swapaxes(0, 1) + other_outputs[key] = value + else: + generated_sequence = output + other_outputs = {} + + out_b = generated_sequence.shape[0] + if self.framework == "pt": + generated_sequence = generated_sequence.reshape(in_b, out_b // in_b, *generated_sequence.shape[1:]) + elif self.framework == "tf": + generated_sequence = tf.reshape(generated_sequence, (in_b, out_b // in_b, *generated_sequence.shape[1:])) + + model_outputs = { + "generated_sequence": generated_sequence, + "input_ids": input_ids, + "prompt_text": prompt_text, + } + if other_outputs: + model_outputs.update({"additional_outputs": other_outputs}) + return model_outputs + + def postprocess( + self, + model_outputs, + return_type=ReturnType.FULL_TEXT, + clean_up_tokenization_spaces=True, + continue_final_message=None, + skip_special_tokens=None, + ): + generated_sequence = model_outputs["generated_sequence"][0] + input_ids = model_outputs["input_ids"] + prompt_text = model_outputs["prompt_text"] + generated_sequence = generated_sequence.numpy().tolist() + records = [] + other_outputs = model_outputs.get("additional_outputs", {}) + splitted_keys = {} + if other_outputs: + if self.framework == "pt": + for k, v in other_outputs.items(): + if isinstance(v, torch.Tensor) and v.shape[0] == len(generated_sequence): + splitted_keys[k] = v.numpy().tolist() + elif self.framework == "tf": + for k, v in other_outputs.items(): + if isinstance(v, tf.Tensor) and v.shape[0] == len(generated_sequence): + splitted_keys[k] = v.numpy().tolist() + + skip_special_tokens = skip_special_tokens if skip_special_tokens is not None else True + for idx, sequence in enumerate(generated_sequence): + if return_type == ReturnType.TENSORS: + record = {"generated_token_ids": sequence} + elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}: + # Decode text + text = self.tokenizer.decode( + sequence, + skip_special_tokens=skip_special_tokens, + clean_up_tokenization_spaces=clean_up_tokenization_spaces, + ) + + # Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used + if input_ids is None: + prompt_length = 0 + else: + prompt_length = len( + self.tokenizer.decode( + input_ids[0], + skip_special_tokens=skip_special_tokens, + clean_up_tokenization_spaces=clean_up_tokenization_spaces, + ) + ) + + all_text = text[prompt_length:] + if return_type == ReturnType.FULL_TEXT: + if isinstance(prompt_text, str): + all_text = prompt_text + all_text + elif isinstance(prompt_text, Chat): + if continue_final_message is None: + # If the user passes a chat ending in an assistant message, we treat it as a prefill by + # default because very few models support multiple separate, consecutive assistant messages + continue_final_message = prompt_text.messages[-1]["role"] == "assistant" + if continue_final_message: + # With assistant prefill, concat onto the end of the last message + all_text = list(prompt_text.messages)[:-1] + [ + { + "role": prompt_text.messages[-1]["role"], + "content": prompt_text.messages[-1]["content"] + all_text, + } + ] + else: + # When we're not starting from a prefill, the output is a new assistant message + all_text = list(prompt_text.messages) + [{"role": "assistant", "content": all_text}] + record = {"generated_text": all_text} + for key, values in splitted_keys.items(): + record[key] = values[idx] + records.append(record) + + return records diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/text_to_audio.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/text_to_audio.py new file mode 100644 index 0000000000000000000000000000000000000000..a4ef097038d4a84bc26ed9e77292030277319a81 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/text_to_audio.py @@ -0,0 +1,265 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License.from typing import List, Union +from typing import Any, Union, overload + +from ..generation import GenerationConfig +from ..utils import is_torch_available +from .base import Pipeline + + +if is_torch_available(): + import torch + + from ..models.auto.modeling_auto import MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING + from ..models.speecht5.modeling_speecht5 import SpeechT5HifiGan + +DEFAULT_VOCODER_ID = "microsoft/speecht5_hifigan" + + +class TextToAudioPipeline(Pipeline): + """ + Text-to-audio generation pipeline using any `AutoModelForTextToWaveform` or `AutoModelForTextToSpectrogram`. This + pipeline generates an audio file from an input text and optional other conditional inputs. + + Unless the model you're using explicitly sets these generation parameters in its configuration files + (`generation_config.json`), the following default values will be used: + - max_new_tokens: 256 + + Example: + + ```python + >>> from transformers import pipeline + + >>> pipe = pipeline(model="suno/bark-small") + >>> output = pipe("Hey it's HuggingFace on the phone!") + + >>> audio = output["audio"] + >>> sampling_rate = output["sampling_rate"] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + + + You can specify parameters passed to the model by using [`TextToAudioPipeline.__call__.forward_params`] or + [`TextToAudioPipeline.__call__.generate_kwargs`]. + + Example: + + ```python + >>> from transformers import pipeline + + >>> music_generator = pipeline(task="text-to-audio", model="facebook/musicgen-small", framework="pt") + + >>> # diversify the music generation by adding randomness with a high temperature and set a maximum music length + >>> generate_kwargs = { + ... "do_sample": True, + ... "temperature": 0.7, + ... "max_new_tokens": 35, + ... } + + >>> outputs = music_generator("Techno music with high melodic riffs", generate_kwargs=generate_kwargs) + ``` + + + + This pipeline can currently be loaded from [`pipeline`] using the following task identifiers: `"text-to-speech"` or + `"text-to-audio"`. + + See the list of available models on [huggingface.co/models](https://huggingface.co/models?filter=text-to-speech). + """ + + # Introducing the processor at load time for new behaviour + _load_processor = True + + _pipeline_calls_generate = True + _load_processor = False + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = True + + # Make sure the docstring is updated when the default generation config is changed + _default_generation_config = GenerationConfig( + max_new_tokens=256, + ) + + def __init__(self, *args, vocoder=None, sampling_rate=None, no_processor=True, **kwargs): + super().__init__(*args, **kwargs) + + # Legacy behaviour just uses the tokenizer while new models use the processor as a whole at any given time + self.no_processor = no_processor + + if self.framework == "tf": + raise ValueError("The TextToAudioPipeline is only available in PyTorch.") + + self.vocoder = None + if self.model.__class__ in MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING.values(): + self.vocoder = ( + SpeechT5HifiGan.from_pretrained(DEFAULT_VOCODER_ID).to(self.model.device) + if vocoder is None + else vocoder + ) + + self.sampling_rate = sampling_rate + if self.vocoder is not None: + self.sampling_rate = self.vocoder.config.sampling_rate + + if self.sampling_rate is None: + # get sampling_rate from config and generation config + + config = self.model.config + gen_config = self.model.__dict__.get("generation_config", None) + if gen_config is not None: + config.update(gen_config.to_dict()) + + for sampling_rate_name in ["sample_rate", "sampling_rate"]: + sampling_rate = getattr(config, sampling_rate_name, None) + if sampling_rate is not None: + self.sampling_rate = sampling_rate + + # last fallback to get the sampling rate based on processor + if self.sampling_rate is None and not self.no_processor and hasattr(self.processor, "feature_extractor"): + self.sampling_rate = self.processor.feature_extractor.sampling_rate + + def preprocess(self, text, **kwargs): + if isinstance(text, str): + text = [text] + + if self.model.config.model_type == "bark": + # bark Tokenizer is called with BarkProcessor which uses those kwargs + new_kwargs = { + "max_length": self.generation_config.semantic_config.get("max_input_semantic_length", 256), + "add_special_tokens": False, + "return_attention_mask": True, + "return_token_type_ids": False, + "padding": "max_length", + } + + # priority is given to kwargs + new_kwargs.update(kwargs) + + kwargs = new_kwargs + + preprocessor = self.tokenizer if self.no_processor else self.processor + output = preprocessor(text, **kwargs, return_tensors="pt") + + return output + + def _forward(self, model_inputs, **kwargs): + # we expect some kwargs to be additional tensors which need to be on the right device + kwargs = self._ensure_tensor_on_device(kwargs, device=self.device) + forward_params = kwargs["forward_params"] + generate_kwargs = kwargs["generate_kwargs"] + + if self.model.can_generate(): + # we expect some kwargs to be additional tensors which need to be on the right device + generate_kwargs = self._ensure_tensor_on_device(generate_kwargs, device=self.device) + + # User-defined `generation_config` passed to the pipeline call take precedence + if "generation_config" not in generate_kwargs: + generate_kwargs["generation_config"] = self.generation_config + + # generate_kwargs get priority over forward_params + forward_params.update(generate_kwargs) + + output = self.model.generate(**model_inputs, **forward_params) + else: + if len(generate_kwargs): + raise ValueError( + "You're using the `TextToAudioPipeline` with a forward-only model, but `generate_kwargs` is non " + "empty. For forward-only TTA models, please use `forward_params` instead of `generate_kwargs`. " + f"For reference, the `generate_kwargs` used here are: {generate_kwargs.keys()}" + ) + output = self.model(**model_inputs, **forward_params)[0] + + if self.vocoder is not None: + # in that case, the output is a spectrogram that needs to be converted into a waveform + output = self.vocoder(output) + + return output + + @overload + def __call__(self, text_inputs: str, **forward_params: Any) -> dict[str, Any]: ... + + @overload + def __call__(self, text_inputs: list[str], **forward_params: Any) -> list[dict[str, Any]]: ... + + def __call__( + self, text_inputs: Union[str, list[str]], **forward_params + ) -> Union[dict[str, Any], list[dict[str, Any]]]: + """ + Generates speech/audio from the inputs. See the [`TextToAudioPipeline`] documentation for more information. + + Args: + text_inputs (`str` or `list[str]`): + The text(s) to generate. + forward_params (`dict`, *optional*): + Parameters passed to the model generation/forward method. `forward_params` are always passed to the + underlying model. + generate_kwargs (`dict`, *optional*): + The dictionary of ad-hoc parametrization of `generate_config` to be used for the generation call. For a + complete overview of generate, check the [following + guide](https://huggingface.co/docs/transformers/en/main_classes/text_generation). `generate_kwargs` are + only passed to the underlying model if the latter is a generative model. + + Return: + A `dict` or a list of `dict`: The dictionaries have two keys: + + - **audio** (`np.ndarray` of shape `(nb_channels, audio_length)`) -- The generated audio waveform. + - **sampling_rate** (`int`) -- The sampling rate of the generated audio waveform. + """ + return super().__call__(text_inputs, **forward_params) + + def _sanitize_parameters( + self, + preprocess_params=None, + forward_params=None, + generate_kwargs=None, + ): + if getattr(self, "assistant_model", None) is not None: + generate_kwargs["assistant_model"] = self.assistant_model + if getattr(self, "assistant_tokenizer", None) is not None: + generate_kwargs["tokenizer"] = self.tokenizer + generate_kwargs["assistant_tokenizer"] = self.assistant_tokenizer + + params = { + "forward_params": forward_params if forward_params else {}, + "generate_kwargs": generate_kwargs if generate_kwargs else {}, + } + + if preprocess_params is None: + preprocess_params = {} + postprocess_params = {} + + return preprocess_params, params, postprocess_params + + def postprocess(self, audio): + output_dict = {} + + # We directly get the waveform + if self.no_processor: + if isinstance(audio, dict): + waveform = audio["waveform"] + elif isinstance(audio, tuple): + waveform = audio[0] + else: + waveform = audio + # Or we need to postprocess to get the waveform + else: + waveform = self.processor.decode(audio) + + output_dict["audio"] = waveform.to(device="cpu", dtype=torch.float).numpy() + output_dict["sampling_rate"] = self.sampling_rate + + return output_dict diff --git a/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/token_classification.py b/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/token_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..efa70ca1851f775e9add37d74a135a69b58990db --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/transformers/pipelines/token_classification.py @@ -0,0 +1,668 @@ +import types +import warnings +from typing import Any, Optional, Union, overload + +import numpy as np + +from ..models.bert.tokenization_bert import BasicTokenizer +from ..utils import ( + ExplicitEnum, + add_end_docstrings, + is_tf_available, + is_torch_available, +) +from .base import ArgumentHandler, ChunkPipeline, Dataset, build_pipeline_init_args + + +if is_tf_available(): + import tensorflow as tf + + from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES +if is_torch_available(): + import torch + + from ..models.auto.modeling_auto import MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES + + +class TokenClassificationArgumentHandler(ArgumentHandler): + """ + Handles arguments for token classification. + """ + + def __call__(self, inputs: Union[str, list[str]], **kwargs): + is_split_into_words = kwargs.get("is_split_into_words", False) + delimiter = kwargs.get("delimiter") + + if inputs is not None and isinstance(inputs, (list, tuple)) and len(inputs) > 0: + inputs = list(inputs) + batch_size = len(inputs) + elif isinstance(inputs, str): + inputs = [inputs] + batch_size = 1 + elif Dataset is not None and isinstance(inputs, Dataset) or isinstance(inputs, types.GeneratorType): + return inputs, is_split_into_words, None, delimiter + else: + raise ValueError("At least one input is required.") + + offset_mapping = kwargs.get("offset_mapping") + if offset_mapping: + if isinstance(offset_mapping, list) and isinstance(offset_mapping[0], tuple): + offset_mapping = [offset_mapping] + if len(offset_mapping) != batch_size: + raise ValueError("offset_mapping should have the same batch size as the input") + return inputs, is_split_into_words, offset_mapping, delimiter + + +class AggregationStrategy(ExplicitEnum): + """All the valid aggregation strategies for TokenClassificationPipeline""" + + NONE = "none" + SIMPLE = "simple" + FIRST = "first" + AVERAGE = "average" + MAX = "max" + + +@add_end_docstrings( + build_pipeline_init_args(has_tokenizer=True), + r""" + ignore_labels (`list[str]`, defaults to `["O"]`): + A list of labels to ignore. + grouped_entities (`bool`, *optional*, defaults to `False`): + DEPRECATED, use `aggregation_strategy` instead. Whether or not to group the tokens corresponding to the + same entity together in the predictions or not. + stride (`int`, *optional*): + If stride is provided, the pipeline is applied on all the text. The text is split into chunks of size + model_max_length. Works only with fast tokenizers and `aggregation_strategy` different from `NONE`. The + value of this argument defines the number of overlapping tokens between chunks. In other words, the model + will shift forward by `tokenizer.model_max_length - stride` tokens each step. + aggregation_strategy (`str`, *optional*, defaults to `"none"`): + The strategy to fuse (or not) tokens based on the model prediction. + + - "none" : Will simply not do any aggregation and simply return raw results from the model + - "simple" : Will attempt to group entities following the default schema. (A, B-TAG), (B, I-TAG), (C, + I-TAG), (D, B-TAG2) (E, B-TAG2) will end up being [{"word": ABC, "entity": "TAG"}, {"word": "D", + "entity": "TAG2"}, {"word": "E", "entity": "TAG2"}] Notice that two consecutive B tags will end up as + different entities. On word based languages, we might end up splitting words undesirably : Imagine + Microsoft being tagged as [{"word": "Micro", "entity": "ENTERPRISE"}, {"word": "soft", "entity": + "NAME"}]. Look for FIRST, MAX, AVERAGE for ways to mitigate that and disambiguate words (on languages + that support that meaning, which is basically tokens separated by a space). These mitigations will + only work on real words, "New york" might still be tagged with two different entities. + - "first" : (works only on word based models) Will use the `SIMPLE` strategy except that words, cannot + end up with different tags. Words will simply use the tag of the first token of the word when there + is ambiguity. + - "average" : (works only on word based models) Will use the `SIMPLE` strategy except that words, + cannot end up with different tags. scores will be averaged first across tokens, and then the maximum + label is applied. + - "max" : (works only on word based models) Will use the `SIMPLE` strategy except that words, cannot + end up with different tags. Word entity will simply be the token with the maximum score.""", +) +class TokenClassificationPipeline(ChunkPipeline): + """ + Named Entity Recognition pipeline using any `ModelForTokenClassification`. See the [named entity recognition + examples](../task_summary#named-entity-recognition) for more information. + + Example: + + ```python + >>> from transformers import pipeline + + >>> token_classifier = pipeline(model="Jean-Baptiste/camembert-ner", aggregation_strategy="simple") + >>> sentence = "Je m'appelle jean-baptiste et je vis à montréal" + >>> tokens = token_classifier(sentence) + >>> tokens + [{'entity_group': 'PER', 'score': 0.9931, 'word': 'jean-baptiste', 'start': 12, 'end': 26}, {'entity_group': 'LOC', 'score': 0.998, 'word': 'montréal', 'start': 38, 'end': 47}] + + >>> token = tokens[0] + >>> # Start and end provide an easy way to highlight words in the original text. + >>> sentence[token["start"] : token["end"]] + ' jean-baptiste' + + >>> # Some models use the same idea to do part of speech. + >>> syntaxer = pipeline(model="vblagoje/bert-english-uncased-finetuned-pos", aggregation_strategy="simple") + >>> syntaxer("My name is Sarah and I live in London") + [{'entity_group': 'PRON', 'score': 0.999, 'word': 'my', 'start': 0, 'end': 2}, {'entity_group': 'NOUN', 'score': 0.997, 'word': 'name', 'start': 3, 'end': 7}, {'entity_group': 'AUX', 'score': 0.994, 'word': 'is', 'start': 8, 'end': 10}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'sarah', 'start': 11, 'end': 16}, {'entity_group': 'CCONJ', 'score': 0.999, 'word': 'and', 'start': 17, 'end': 20}, {'entity_group': 'PRON', 'score': 0.999, 'word': 'i', 'start': 21, 'end': 22}, {'entity_group': 'VERB', 'score': 0.998, 'word': 'live', 'start': 23, 'end': 27}, {'entity_group': 'ADP', 'score': 0.999, 'word': 'in', 'start': 28, 'end': 30}, {'entity_group': 'PROPN', 'score': 0.999, 'word': 'london', 'start': 31, 'end': 37}] + ``` + + Learn more about the basics of using a pipeline in the [pipeline tutorial](../pipeline_tutorial) + + This token recognition pipeline can currently be loaded from [`pipeline`] using the following task identifier: + `"ner"` (for predicting the classes of tokens in a sequence: person, organisation, location or miscellaneous). + + The models that this pipeline can use are models that have been fine-tuned on a token classification task. See the + up-to-date list of available models on + [huggingface.co/models](https://huggingface.co/models?filter=token-classification). + """ + + default_input_names = "sequences" + + _load_processor = False + _load_image_processor = False + _load_feature_extractor = False + _load_tokenizer = True + + def __init__(self, args_parser=TokenClassificationArgumentHandler(), *args, **kwargs): + super().__init__(*args, **kwargs) + + self.check_model_type( + TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES + if self.framework == "tf" + else MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES + ) + + self._basic_tokenizer = BasicTokenizer(do_lower_case=False) + self._args_parser = args_parser + + def _sanitize_parameters( + self, + ignore_labels=None, + grouped_entities: Optional[bool] = None, + ignore_subwords: Optional[bool] = None, + aggregation_strategy: Optional[AggregationStrategy] = None, + offset_mapping: Optional[list[tuple[int, int]]] = None, + is_split_into_words: Optional[bool] = False, + stride: Optional[int] = None, + delimiter: Optional[str] = None, + ): + preprocess_params = {} + preprocess_params["is_split_into_words"] = is_split_into_words + + if is_split_into_words: + preprocess_params["delimiter"] = " " if delimiter is None else delimiter + + if offset_mapping is not None: + preprocess_params["offset_mapping"] = offset_mapping + + postprocess_params = {} + if grouped_entities is not None or ignore_subwords is not None: + if grouped_entities and ignore_subwords: + aggregation_strategy = AggregationStrategy.FIRST + elif grouped_entities and not ignore_subwords: + aggregation_strategy = AggregationStrategy.SIMPLE + else: + aggregation_strategy = AggregationStrategy.NONE + + if grouped_entities is not None: + warnings.warn( + "`grouped_entities` is deprecated and will be removed in version v5.0.0, defaulted to" + f' `aggregation_strategy="{aggregation_strategy}"` instead.' + ) + if ignore_subwords is not None: + warnings.warn( + "`ignore_subwords` is deprecated and will be removed in version v5.0.0, defaulted to" + f' `aggregation_strategy="{aggregation_strategy}"` instead.' + ) + + if aggregation_strategy is not None: + if isinstance(aggregation_strategy, str): + aggregation_strategy = AggregationStrategy[aggregation_strategy.upper()] + if ( + aggregation_strategy + in {AggregationStrategy.FIRST, AggregationStrategy.MAX, AggregationStrategy.AVERAGE} + and not self.tokenizer.is_fast + ): + raise ValueError( + "Slow tokenizers cannot handle subwords. Please set the `aggregation_strategy` option" + ' to `"simple"` or use a fast tokenizer.' + ) + postprocess_params["aggregation_strategy"] = aggregation_strategy + if ignore_labels is not None: + postprocess_params["ignore_labels"] = ignore_labels + if stride is not None: + if stride >= self.tokenizer.model_max_length: + raise ValueError( + "`stride` must be less than `tokenizer.model_max_length` (or even lower if the tokenizer adds special tokens)" + ) + if aggregation_strategy == AggregationStrategy.NONE: + raise ValueError( + "`stride` was provided to process all the text but `aggregation_strategy=" + f'"{aggregation_strategy}"`, please select another one instead.' + ) + else: + if self.tokenizer.is_fast: + tokenizer_params = { + "return_overflowing_tokens": True, + "padding": True, + "stride": stride, + } + preprocess_params["tokenizer_params"] = tokenizer_params + else: + raise ValueError( + "`stride` was provided to process all the text but you're using a slow tokenizer." + " Please use a fast tokenizer." + ) + return preprocess_params, {}, postprocess_params + + @overload + def __call__(self, inputs: str, **kwargs: Any) -> list[dict[str, str]]: ... + + @overload + def __call__(self, inputs: list[str], **kwargs: Any) -> list[list[dict[str, str]]]: ... + + def __call__( + self, inputs: Union[str, list[str]], **kwargs: Any + ) -> Union[list[dict[str, str]], list[list[dict[str, str]]]]: + """ + Classify each token of the text(s) given as inputs. + + Args: + inputs (`str` or `List[str]`): + One or several texts (or one list of texts) for token classification. Can be pre-tokenized when + `is_split_into_words=True`. + + Return: + A list or a list of list of `dict`: Each result comes as a list of dictionaries (one for each token in the + corresponding input, or each entity if this pipeline was instantiated with an aggregation_strategy) with + the following keys: + + - **word** (`str`) -- The token/word classified. This is obtained by decoding the selected tokens. If you + want to have the exact string in the original sentence, use `start` and `end`. + - **score** (`float`) -- The corresponding probability for `entity`. + - **entity** (`str`) -- The entity predicted for that token/word (it is named *entity_group* when + *aggregation_strategy* is not `"none"`. + - **index** (`int`, only present when `aggregation_strategy="none"`) -- The index of the corresponding + token in the sentence. + - **start** (`int`, *optional*) -- The index of the start of the corresponding entity in the sentence. Only + exists if the offsets are available within the tokenizer + - **end** (`int`, *optional*) -- The index of the end of the corresponding entity in the sentence. Only + exists if the offsets are available within the tokenizer + """ + + _inputs, is_split_into_words, offset_mapping, delimiter = self._args_parser(inputs, **kwargs) + kwargs["is_split_into_words"] = is_split_into_words + kwargs["delimiter"] = delimiter + if is_split_into_words and not all(isinstance(input, list) for input in inputs): + return super().__call__([inputs], **kwargs) + if offset_mapping: + kwargs["offset_mapping"] = offset_mapping + + return super().__call__(inputs, **kwargs) + + def preprocess(self, sentence, offset_mapping=None, **preprocess_params): + tokenizer_params = preprocess_params.pop("tokenizer_params", {}) + truncation = self.tokenizer.model_max_length and self.tokenizer.model_max_length > 0 + + word_to_chars_map = None + is_split_into_words = preprocess_params["is_split_into_words"] + if is_split_into_words: + delimiter = preprocess_params["delimiter"] + if not isinstance(sentence, list): + raise ValueError("When `is_split_into_words=True`, `sentence` must be a list of tokens.") + words = sentence + sentence = delimiter.join(words) # Recreate the sentence string for later display and slicing + # This map will allows to convert back word => char indices + word_to_chars_map = [] + delimiter_len = len(delimiter) + char_offset = 0 + for word in words: + word_to_chars_map.append((char_offset, char_offset + len(word))) + char_offset += len(word) + delimiter_len + + # We use `words` as the actual input for the tokenizer + text_to_tokenize = words + tokenizer_params["is_split_into_words"] = True + else: + if not isinstance(sentence, str): + raise ValueError("When `is_split_into_words=False`, `sentence` must be an untokenized string.") + text_to_tokenize = sentence + + inputs = self.tokenizer( + text_to_tokenize, + return_tensors=self.framework, + truncation=truncation, + return_special_tokens_mask=True, + return_offsets_mapping=self.tokenizer.is_fast, + **tokenizer_params, + ) + + if is_split_into_words and not self.tokenizer.is_fast: + raise ValueError("is_split_into_words=True is only supported with fast tokenizers.") + + inputs.pop("overflow_to_sample_mapping", None) + num_chunks = len(inputs["input_ids"]) + + for i in range(num_chunks): + if self.framework == "tf": + model_inputs = {k: tf.expand_dims(v[i], 0) for k, v in inputs.items()} + else: + model_inputs = {k: v[i].unsqueeze(0) for k, v in inputs.items()} + if offset_mapping is not None: + model_inputs["offset_mapping"] = offset_mapping + + model_inputs["sentence"] = sentence if i == 0 else None + model_inputs["is_last"] = i == num_chunks - 1 + if word_to_chars_map is not None: + model_inputs["word_ids"] = inputs.word_ids(i) + model_inputs["word_to_chars_map"] = word_to_chars_map + + yield model_inputs + + def _forward(self, model_inputs): + # Forward + special_tokens_mask = model_inputs.pop("special_tokens_mask") + offset_mapping = model_inputs.pop("offset_mapping", None) + sentence = model_inputs.pop("sentence") + is_last = model_inputs.pop("is_last") + word_ids = model_inputs.pop("word_ids", None) + word_to_chars_map = model_inputs.pop("word_to_chars_map", None) + + if self.framework == "tf": + logits = self.model(**model_inputs)[0] + else: + output = self.model(**model_inputs) + logits = output["logits"] if isinstance(output, dict) else output[0] + + return { + "logits": logits, + "special_tokens_mask": special_tokens_mask, + "offset_mapping": offset_mapping, + "sentence": sentence, + "is_last": is_last, + "word_ids": word_ids, + "word_to_chars_map": word_to_chars_map, + **model_inputs, + } + + def postprocess(self, all_outputs, aggregation_strategy=AggregationStrategy.NONE, ignore_labels=None): + if ignore_labels is None: + ignore_labels = ["O"] + all_entities = [] + + # Get map from the first output, it's the same for all chunks + word_to_chars_map = all_outputs[0].get("word_to_chars_map") + + for model_outputs in all_outputs: + if self.framework == "pt" and model_outputs["logits"][0].dtype in (torch.bfloat16, torch.float16): + logits = model_outputs["logits"][0].to(torch.float32).numpy() + else: + logits = model_outputs["logits"][0].numpy() + + sentence = all_outputs[0]["sentence"] + input_ids = model_outputs["input_ids"][0] + offset_mapping = ( + model_outputs["offset_mapping"][0] if model_outputs["offset_mapping"] is not None else None + ) + special_tokens_mask = model_outputs["special_tokens_mask"][0].numpy() + word_ids = model_outputs.get("word_ids") + + maxes = np.max(logits, axis=-1, keepdims=True) + shifted_exp = np.exp(logits - maxes) + scores = shifted_exp / shifted_exp.sum(axis=-1, keepdims=True) + + if self.framework == "tf": + input_ids = input_ids.numpy() + offset_mapping = offset_mapping.numpy() if offset_mapping is not None else None + + pre_entities = self.gather_pre_entities( + sentence, + input_ids, + scores, + offset_mapping, + special_tokens_mask, + aggregation_strategy, + word_ids=word_ids, + word_to_chars_map=word_to_chars_map, + ) + grouped_entities = self.aggregate(pre_entities, aggregation_strategy) + # Filter anything that is in self.ignore_labels + entities = [ + entity + for entity in grouped_entities + if entity.get("entity", None) not in ignore_labels + and entity.get("entity_group", None) not in ignore_labels + ] + all_entities.extend(entities) + num_chunks = len(all_outputs) + if num_chunks > 1: + all_entities = self.aggregate_overlapping_entities(all_entities) + return all_entities + + def aggregate_overlapping_entities(self, entities): + if len(entities) == 0: + return entities + entities = sorted(entities, key=lambda x: x["start"]) + aggregated_entities = [] + previous_entity = entities[0] + for entity in entities: + if previous_entity["start"] <= entity["start"] < previous_entity["end"]: + current_length = entity["end"] - entity["start"] + previous_length = previous_entity["end"] - previous_entity["start"] + if ( + current_length > previous_length + or current_length == previous_length + and entity["score"] > previous_entity["score"] + ): + previous_entity = entity + else: + aggregated_entities.append(previous_entity) + previous_entity = entity + aggregated_entities.append(previous_entity) + return aggregated_entities + + def gather_pre_entities( + self, + sentence: str, + input_ids: np.ndarray, + scores: np.ndarray, + offset_mapping: Optional[list[tuple[int, int]]], + special_tokens_mask: np.ndarray, + aggregation_strategy: AggregationStrategy, + word_ids: Optional[list[Optional[int]]] = None, + word_to_chars_map: Optional[list[tuple[int, int]]] = None, + ) -> list[dict]: + """Fuse various numpy arrays into dicts with all the information needed for aggregation""" + pre_entities = [] + for idx, token_scores in enumerate(scores): + # Filter special_tokens + if special_tokens_mask[idx]: + continue + + word = self.tokenizer.convert_ids_to_tokens(int(input_ids[idx])) + if offset_mapping is not None: + start_ind, end_ind = offset_mapping[idx] + + # If the input is pre-tokenized, we need to rescale the offsets to the absolute sentence. + if word_ids is not None and word_to_chars_map is not None: + word_index = word_ids[idx] + if word_index is not None: + start_char, _ = word_to_chars_map[word_index] + start_ind += start_char + end_ind += start_char + + if not isinstance(start_ind, int): + if self.framework == "pt": + start_ind = start_ind.item() + end_ind = end_ind.item() + word_ref = sentence[start_ind:end_ind] + if getattr(self.tokenizer, "_tokenizer", None) and getattr( + self.tokenizer._tokenizer.model, "continuing_subword_prefix", None + ): + # This is a BPE, word aware tokenizer, there is a correct way + # to fuse tokens + is_subword = len(word) != len(word_ref) + else: + # This is a fallback heuristic. This will fail most likely on any kind of text + punctuation mixtures that will be considered "words". Non word aware models cannot do better than this unfortunately. + if aggregation_strategy in { + AggregationStrategy.FIRST, + AggregationStrategy.AVERAGE, + AggregationStrategy.MAX, + }: + warnings.warn( + "Tokenizer does not support real words, using fallback heuristic", + UserWarning, + ) + is_subword = start_ind > 0 and " " not in sentence[start_ind - 1 : start_ind + 1] + + if int(input_ids[idx]) == self.tokenizer.unk_token_id: + word = word_ref + is_subword = False + else: + start_ind = None + end_ind = None + is_subword = False + + pre_entity = { + "word": word, + "scores": token_scores, + "start": start_ind, + "end": end_ind, + "index": idx, + "is_subword": is_subword, + } + pre_entities.append(pre_entity) + return pre_entities + + def aggregate(self, pre_entities: list[dict], aggregation_strategy: AggregationStrategy) -> list[dict]: + if aggregation_strategy in {AggregationStrategy.NONE, AggregationStrategy.SIMPLE}: + entities = [] + for pre_entity in pre_entities: + entity_idx = pre_entity["scores"].argmax() + score = pre_entity["scores"][entity_idx] + entity = { + "entity": self.model.config.id2label[entity_idx], + "score": score, + "index": pre_entity["index"], + "word": pre_entity["word"], + "start": pre_entity["start"], + "end": pre_entity["end"], + } + entities.append(entity) + else: + entities = self.aggregate_words(pre_entities, aggregation_strategy) + + if aggregation_strategy == AggregationStrategy.NONE: + return entities + return self.group_entities(entities) + + def aggregate_word(self, entities: list[dict], aggregation_strategy: AggregationStrategy) -> dict: + word = self.tokenizer.convert_tokens_to_string([entity["word"] for entity in entities]) + if aggregation_strategy == AggregationStrategy.FIRST: + scores = entities[0]["scores"] + idx = scores.argmax() + score = scores[idx] + entity = self.model.config.id2label[idx] + elif aggregation_strategy == AggregationStrategy.MAX: + max_entity = max(entities, key=lambda entity: entity["scores"].max()) + scores = max_entity["scores"] + idx = scores.argmax() + score = scores[idx] + entity = self.model.config.id2label[idx] + elif aggregation_strategy == AggregationStrategy.AVERAGE: + scores = np.stack([entity["scores"] for entity in entities]) + average_scores = np.nanmean(scores, axis=0) + entity_idx = average_scores.argmax() + entity = self.model.config.id2label[entity_idx] + score = average_scores[entity_idx] + else: + raise ValueError("Invalid aggregation_strategy") + new_entity = { + "entity": entity, + "score": score, + "word": word, + "start": entities[0]["start"], + "end": entities[-1]["end"], + } + return new_entity + + def aggregate_words(self, entities: list[dict], aggregation_strategy: AggregationStrategy) -> list[dict]: + """ + Override tokens from a given word that disagree to force agreement on word boundaries. + + Example: micro|soft| com|pany| B-ENT I-NAME I-ENT I-ENT will be rewritten with first strategy as microsoft| + company| B-ENT I-ENT + """ + if aggregation_strategy in { + AggregationStrategy.NONE, + AggregationStrategy.SIMPLE, + }: + raise ValueError("NONE and SIMPLE strategies are invalid for word aggregation") + + word_entities = [] + word_group = None + for entity in entities: + if word_group is None: + word_group = [entity] + elif entity["is_subword"]: + word_group.append(entity) + else: + word_entities.append(self.aggregate_word(word_group, aggregation_strategy)) + word_group = [entity] + # Last item + if word_group is not None: + word_entities.append(self.aggregate_word(word_group, aggregation_strategy)) + return word_entities + + def group_sub_entities(self, entities: list[dict]) -> dict: + """ + Group together the adjacent tokens with the same entity predicted. + + Args: + entities (`dict`): The entities predicted by the pipeline. + """ + # Get the first entity in the entity group + entity = entities[0]["entity"].split("-", 1)[-1] + scores = np.nanmean([entity["score"] for entity in entities]) + tokens = [entity["word"] for entity in entities] + + entity_group = { + "entity_group": entity, + "score": np.mean(scores), + "word": self.tokenizer.convert_tokens_to_string(tokens), + "start": entities[0]["start"], + "end": entities[-1]["end"], + } + return entity_group + + def get_tag(self, entity_name: str) -> tuple[str, str]: + if entity_name.startswith("B-"): + bi = "B" + tag = entity_name[2:] + elif entity_name.startswith("I-"): + bi = "I" + tag = entity_name[2:] + else: + # It's not in B-, I- format + # Default to I- for continuation. + bi = "I" + tag = entity_name + return bi, tag + + def group_entities(self, entities: list[dict]) -> list[dict]: + """ + Find and group together the adjacent tokens with the same entity predicted. + + Args: + entities (`dict`): The entities predicted by the pipeline. + """ + + entity_groups = [] + entity_group_disagg = [] + + for entity in entities: + if not entity_group_disagg: + entity_group_disagg.append(entity) + continue + + # If the current entity is similar and adjacent to the previous entity, + # append it to the disaggregated entity group + # The split is meant to account for the "B" and "I" prefixes + # Shouldn't merge if both entities are B-type + bi, tag = self.get_tag(entity["entity"]) + last_bi, last_tag = self.get_tag(entity_group_disagg[-1]["entity"]) + + if tag == last_tag and bi != "B": + # Modify subword type to be previous_type + entity_group_disagg.append(entity) + else: + # If the current entity is different from the previous entity + # aggregate the disaggregated entity group + entity_groups.append(self.group_sub_entities(entity_group_disagg)) + entity_group_disagg = [entity] + if entity_group_disagg: + # it's the last entity, add it to the entity groups + entity_groups.append(self.group_sub_entities(entity_group_disagg)) + + return entity_groups + + +NerPipeline = TokenClassificationPipeline diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4284dd29f59a43833750354d41e4c47ce72a9361 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/_cpp_lib.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/_cpp_lib.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54802576273dac8ce71e8d957537c3c7cfdecad3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/_cpp_lib.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/_deprecation_warning.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/_deprecation_warning.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e3ed58887f52915f224ea9bcd2467d24ad5a13b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/_deprecation_warning.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/attn_bias_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/attn_bias_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..15d83952d5a90bd7885cb3813420d2fcb2769605 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/attn_bias_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/checkpoint.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/checkpoint.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dcc110e90c9b7211b72a84ff5b9295911eb4bd34 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/checkpoint.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/info.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/info.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56b231a4e0c8c338b9febc9e9e4cf8aaa51e082f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/info.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/test.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/test.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..275b6d9afa595d9c30b1082365c5257569467331 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/test.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a9646c21332dff49cf7b6a8533c369cfff8fe03 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/version.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f91cc122d27c8f5132e2ce0d1181a15ddecd993 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/__pycache__/version.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9ef52f504bbbf973aac473894afb4fd2a2967b95 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__init__.py @@ -0,0 +1,11 @@ +__version__ = "2.8.0.post2" + +from flash_attn.flash_attn_interface import ( + flash_attn_func, + flash_attn_kvpacked_func, + flash_attn_qkvpacked_func, + flash_attn_varlen_func, + flash_attn_varlen_kvpacked_func, + flash_attn_varlen_qkvpacked_func, + flash_attn_with_kvcache, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20fdd4ece9fe2662ed6799a883786fca7b181301 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/bert_padding.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/bert_padding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf59cb9abe45432e1ada404afb131356f17f0c85 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/bert_padding.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/flash_attn_interface.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/flash_attn_interface.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d55141b954bdb6db70f1e18834bc2dc2839ed35 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/flash_attn_interface.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/flash_attn_triton.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/flash_attn_triton.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99a20ecbb213ed988766d90166b13ecdc373a164 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/flash_attn_triton.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/flash_attn_triton_og.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/flash_attn_triton_og.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ea20bfe653bf72bff76cb95ff7133f03e510be5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/flash_attn_triton_og.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/flash_blocksparse_attention.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/flash_blocksparse_attention.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..217edd51bba5ec3cd47f6640aa2e0dae4a04920d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/flash_blocksparse_attention.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/flash_blocksparse_attn_interface.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/flash_blocksparse_attn_interface.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..44087e395ca36f2021bf7e0222eab153ac32fe76 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/flash_blocksparse_attn_interface.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/fused_softmax.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/fused_softmax.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..081842dcc3410781356b3ea9cfa63ea87bb77790 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/__pycache__/fused_softmax.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/bert_padding.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/bert_padding.py new file mode 100644 index 0000000000000000000000000000000000000000..3c2d35159a014a9d03aabead9e52e009168696ea --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/bert_padding.py @@ -0,0 +1,218 @@ +# Adapted from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/padding.py + +import torch +import torch.nn.functional as F +from einops import rearrange, repeat + + +class IndexFirstAxis(torch.autograd.Function): + @staticmethod + def forward(ctx, input, indices): + ctx.save_for_backward(indices) + assert input.ndim >= 2 + ctx.first_axis_dim, other_shape = input.shape[0], input.shape[1:] + second_dim = other_shape.numel() + # TD [2022-03-04] For some reason torch.gather is a bit faster than indexing. + # return input[indices] + return torch.gather( + rearrange(input, "b ... -> b (...)"), 0, repeat(indices, "z -> z d", d=second_dim) + ).reshape(-1, *other_shape) + + @staticmethod + def backward(ctx, grad_output): + (indices,) = ctx.saved_tensors + assert grad_output.ndim >= 2 + other_shape = grad_output.shape[1:] + grad_output = rearrange(grad_output, "b ... -> b (...)") + grad_input = torch.zeros( + [ctx.first_axis_dim, grad_output.shape[1]], + device=grad_output.device, + dtype=grad_output.dtype, + ) + # TD [2022-03-04] For some reason torch.scatter is a bit faster than indexing. + # grad_input[indices] = grad_output + grad_input.scatter_(0, repeat(indices, "z -> z d", d=grad_output.shape[1]), grad_output) + return grad_input.reshape(ctx.first_axis_dim, *other_shape), None + + +index_first_axis = IndexFirstAxis.apply + + +class IndexPutFirstAxis(torch.autograd.Function): + @staticmethod + def forward(ctx, values, indices, first_axis_dim): + ctx.save_for_backward(indices) + assert indices.ndim == 1 + assert values.ndim >= 2 + output = torch.zeros( + first_axis_dim, *values.shape[1:], device=values.device, dtype=values.dtype + ) + # TD [2022-03-04] For some reason torch.scatter is a bit faster than indexing. + output[indices] = values + # output.scatter_(0, repeat(indices, 'z -> z d', d=values.shape[1]), values) + return output + + @staticmethod + def backward(ctx, grad_output): + (indices,) = ctx.saved_tensors + # TD [2022-03-04] For some reason torch.gather is a bit faster than indexing. + grad_values = grad_output[indices] + # grad_values = torch.gather(grad_output, 0, repeat(indices, 'z -> z d', d=grad_output.shape[1])) + return grad_values, None, None + + +index_put_first_axis = IndexPutFirstAxis.apply + + +class IndexFirstAxisResidual(torch.autograd.Function): + @staticmethod + def forward(ctx, input, indices): + ctx.save_for_backward(indices) + assert input.ndim >= 2 + ctx.first_axis_dim, other_shape = input.shape[0], input.shape[1:] + second_dim = other_shape.numel() + # TD [2022-03-04] For some reason torch.gather is a bit faster than indexing. + output = input[indices] + # We don't want to reshape input (b ... -> b (...)) since it could change the channel_last + # memory format to channel_first. In other words, input might not be contiguous. + # If we don't detach, Pytorch complains about output being a view and is being modified inplace + return output, input.detach() + + @staticmethod + def backward(ctx, grad_output, grad_residual): + (indices,) = ctx.saved_tensors + assert grad_output.ndim >= 2 + other_shape = grad_output.shape[1:] + assert grad_residual.shape[1:] == other_shape + grad_input = grad_residual + # grad_input[indices] += grad_output + indices = indices.reshape(indices.shape[0], *((1,) * (grad_output.ndim - 1))) + indices = indices.expand_as(grad_output) + grad_input.scatter_add_(0, indices, grad_output) + return grad_input.reshape(ctx.first_axis_dim, *other_shape), None + + +index_first_axis_residual = IndexFirstAxisResidual.apply + + +def unpad_input(hidden_states, attention_mask, unused_mask=None): + """ + Arguments: + hidden_states: (batch, seqlen, ...) + attention_mask: (batch, seqlen), bool / int, 1 means valid and 0 means not valid. + unused_mask: (batch, seqlen), bool / int, 1 means the element is allocated but unused. + Return: + hidden_states: (total_nnz, ...), where total_nnz = number of tokens selected in attention_mask + unused_mask. + indices: (total_nnz), the indices of masked tokens from the flattened input sequence. + cu_seqlens: (batch + 1), the cumulative sequence lengths, used to index into hidden_states. + max_seqlen_in_batch: int + seqused: (batch), returns the number of tokens selected in attention_mask + unused_mask. + """ + all_masks = (attention_mask + unused_mask) if unused_mask is not None else attention_mask + seqlens_in_batch = all_masks.sum(dim=-1, dtype=torch.int32) + used_seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) + indices = torch.nonzero(all_masks.flatten(), as_tuple=False).flatten() + max_seqlen_in_batch = seqlens_in_batch.max().item() + cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0)) + # TD [2022-03-04] We don't want to index with a bool mask, because Pytorch will expand the + # bool mask, then call nonzero to get the indices, then index with those. The indices is @dim + # times larger than it needs to be, wasting memory. It's faster and more memory-efficient to + # index with integer indices. Moreover, torch's index is a bit slower than it needs to be, + # so we write custom forward and backward to make it a bit faster. + return ( + index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices), + indices, + cu_seqlens, + max_seqlen_in_batch, + used_seqlens_in_batch, + ) + + +def unpad_input_for_concatenated_sequences(hidden_states, attention_mask_in_length): + """ + Supports concatenating short samples in one sequence. The attention_mask_in_length is utilized to mask other short samples. It helps efficient training of variant lengths-based samples (e.g., the supervised fine-tuning task in large language model). + The motivation for this function is explained [here](https://github.com/Dao-AILab/flash-attention/issues/432#issuecomment-1668822286). + + For example, if batch = 3 and seqlen = 6, the attention_mask_in_length is: + ``` + [ + [2, 3, 0, 0, 0, 0], + [3, 2, 0, 0, 0, 0], + [6, 0, 0, 0, 0, 0] + ] + ``` + , which refers to the 3D-attention mask: + ``` + [ + [ + [1, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [0, 0, 1, 0, 0, 0], + [0, 0, 1, 1, 0, 0], + [0, 0, 1, 1, 1, 0], + [0, 0, 0, 0, 0, 1] + ], + [ + [1, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0], + [0, 0, 0, 1, 0, 0], + [0, 0, 0, 1, 1, 0], + [0, 0, 0, 0, 0, 1] + ], + [ + [1, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0], + [1, 1, 1, 1, 0, 0], + [1, 1, 1, 1, 1, 0], + [1, 1, 1, 1, 1, 1] + ] + ] + ```. + + Arguments: + hidden_states: (batch, seqlen, ...) + attention_mask_in_length: (batch, seqlen), int, a nonzero number (e.g., 1, 2, 3, etc.) means length of concatenated sequence in b-th batch, and 0 means none. + Return: + hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask. + indices: (total_nnz), the indices of non-masked tokens from the flattened input sequence. + cu_seqlens: (batch + 1), the cumulative sequence lengths, used to index into hidden_states. + max_seqlen_in_batch: int + """ + length = attention_mask_in_length.sum(dim=-1) + seqlen = attention_mask_in_length.size(-1) + attention_mask_2d = torch.arange(seqlen, device=length.device, dtype=length.dtype).expand(len(length), seqlen) < length.unsqueeze(1) + real_indices_idx = torch.nonzero(attention_mask_in_length.flatten(), as_tuple=False).flatten() + seqlens_in_batch = attention_mask_in_length.flatten()[real_indices_idx] + indices = torch.nonzero(attention_mask_2d.flatten(), as_tuple=False).flatten() + max_seqlen_in_batch = seqlens_in_batch.max().item() + cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0)) + # TD [2022-03-04] We don't want to index with a bool mask, because Pytorch will expand the + # bool mask, then call nonzero to get the indices, then index with those. The indices is @dim + # times larger than it needs to be, wasting memory. It's faster and more memory-efficient to + # index with integer indices. Moreover, torch's index is a bit slower than it needs to be, + # so we write custom forward and backward to make it a bit faster. + return ( + index_first_axis(rearrange(hidden_states, "b s ... -> (b s) ..."), indices), + indices, + cu_seqlens, + max_seqlen_in_batch, + ) + + +def pad_input(hidden_states, indices, batch, seqlen): + """ + Arguments: + hidden_states: (total_nnz, ...), where total_nnz = number of tokens in selected in attention_mask. + indices: (total_nnz), the indices that represent the non-masked tokens of the original padded input sequence. + batch: int, batch size for the padded sequence. + seqlen: int, maximum sequence length for the padded sequence. + Return: + hidden_states: (batch, seqlen, ...) + """ + dim = hidden_states.shape[-1] + # output = torch.zeros((batch * seqlen), dim, device=hidden_states.device, dtype=hidden_states.dtype) + # output[indices] = hidden_states + output = index_put_first_axis(hidden_states, indices, batch * seqlen) + return rearrange(output, "(b s) ... -> b s ...", b=batch) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_interface.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..1e041e4538d8488d739bf874e5224b533be7d4fa --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_interface.py @@ -0,0 +1,1606 @@ +# Copyright (c) 2023, Tri Dao. + +from typing import Optional, Sequence, Tuple, Union + +import torch +import torch.nn as nn +import os + +# isort: off +# We need to import the CUDA kernels after importing torch +USE_TRITON_ROCM = os.getenv("FLASH_ATTENTION_TRITON_AMD_ENABLE", "FALSE") == "TRUE" +if USE_TRITON_ROCM: + from .flash_attn_triton_amd import interface_fa as flash_attn_gpu +else: + import flash_attn_2_cuda as flash_attn_gpu + +# isort: on + +def maybe_contiguous(x): + return x.contiguous() if x is not None and x.stride(-1) != 1 else x + + +def _get_block_size_n(device, head_dim, is_dropout, is_causal): + # This should match the block sizes in the CUDA kernel + assert head_dim <= 256 + major, minor = torch.cuda.get_device_capability(device) + is_sm8x = major == 8 and minor > 0 # Only include sm86 and sm89, exclude sm80 (A100) + is_sm80 = major == 8 and minor == 0 + is_sm90 = major == 9 and minor == 0 + if head_dim <= 32: + return 128 + if head_dim <= 64: + return 128 if not is_dropout else 64 + elif head_dim <= 96: + return 64 + elif head_dim <= 128: + if is_sm8x: + return 64 if (not is_dropout and is_causal) else 32 + else: + return 64 if not is_dropout else 32 + elif head_dim <= 192: + return 64 + elif head_dim <= 224: + return 64 + elif head_dim <= 256: + return 64 + + +def round_multiple(x, m): + return (x + m - 1) // m * m + + +# torch.compile() support is only enabled for pytorch >= 2.4 +# The reason for this is that we are using the new custom_op and register_fake +# APIs, which support inplace modification of inputs in the function itself +if torch.__version__ >= "2.4.0": + _torch_custom_op_wrapper = torch.library.custom_op + _torch_register_fake_wrapper = torch.library.register_fake +else: + def noop_custom_op_wrapper(name, fn=None, /, *, mutates_args, device_types=None, schema=None): + def wrap(func): + return func + if fn is None: + return wrap + return fn + def noop_register_fake_wrapper(op, fn=None, /, *, lib=None, _stacklevel=1): + def wrap(func): + return func + if fn is None: + return wrap + return fn + _torch_custom_op_wrapper = noop_custom_op_wrapper + _torch_register_fake_wrapper = noop_register_fake_wrapper + + +@_torch_custom_op_wrapper("flash_attn::_flash_attn_forward", mutates_args=(), device_types="cuda") +def _flash_attn_forward( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int, + window_size_right: int, + softcap: float, + alibi_slopes: Optional[torch.Tensor], + return_softmax: bool +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + q, k, v = [maybe_contiguous(x) for x in (q, k, v)] + out, softmax_lse, S_dmask, rng_state = flash_attn_gpu.fwd( + q, + k, + v, + None, + alibi_slopes, + dropout_p, + softmax_scale, + causal, + window_size_left, + window_size_right, + softcap, + return_softmax, + None, + ) + return out, softmax_lse, S_dmask, rng_state + + +@_torch_register_fake_wrapper("flash_attn::_flash_attn_forward") +def _flash_attn_forward_fake( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int, + window_size_right: int, + softcap: float, + alibi_slopes: Optional[torch.Tensor], + return_softmax: bool +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + q, k, v = [maybe_contiguous(x) for x in (q, k, v)] + batch_size, seqlen_q, num_heads, head_size = q.shape + seqlen_k = k.shape[1] + out = torch.empty_like(q) + softmax_lse = torch.empty((batch_size, num_heads, seqlen_q), dtype=torch.float32, device=q.device, layout=q.layout) + p = torch.empty((0,), dtype=q.dtype, device=q.device, layout=q.layout) + if return_softmax: + p = torch.empty((batch_size, num_heads, round_multiple(seqlen_q, 128), round_multiple(seqlen_k, 128)), dtype=q.dtype, device=q.device, layout=q.layout) + rng_state = torch.empty((2,), dtype=torch.int64, device=q.device) + + return out, softmax_lse, p, rng_state + + +if torch.__version__ >= "2.4.0": + _wrapped_flash_attn_forward = torch.ops.flash_attn._flash_attn_forward +else: + _wrapped_flash_attn_forward = _flash_attn_forward + + +@_torch_custom_op_wrapper("flash_attn::_flash_attn_varlen_forward", mutates_args=(), device_types="cuda") +def _flash_attn_varlen_forward( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + cu_seqlens_q: torch.Tensor, + cu_seqlens_k: torch.Tensor, + max_seqlen_q: int, + max_seqlen_k: int, + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int = -1, + window_size_right: int = -1, + softcap: float = 0.0, + alibi_slopes: Optional[torch.Tensor] = None, + return_softmax: bool = False, + block_table: Optional[torch.Tensor] = None, + leftpad_k: Optional[torch.Tensor] = None, + seqused_k: Optional[torch.Tensor] = None, + zero_tensors: bool = False, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + q, k, v = [maybe_contiguous(x) for x in (q, k, v)] + out, softmax_lse, S_dmask, rng_state = flash_attn_gpu.varlen_fwd( + q, + k, + v, + None, + cu_seqlens_q, + cu_seqlens_k, + seqused_k, + leftpad_k, + block_table, + alibi_slopes, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + zero_tensors, + causal, + window_size_left, + window_size_right, + softcap, + return_softmax, + None, + ) + # if out.isnan().any() or softmax_lse.isnan().any(): + # breakpoint() + return out, softmax_lse, S_dmask, rng_state + + +@_torch_register_fake_wrapper("flash_attn::_flash_attn_varlen_forward") +def _flash_attn_varlen_forward_fake( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + cu_seqlens_q: torch.Tensor, + cu_seqlens_k: torch.Tensor, + max_seqlen_q: int, + max_seqlen_k: int, + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int = -1, + window_size_right: int = -1, + softcap: float = 0.0, + alibi_slopes: Optional[torch.Tensor] = None, + return_softmax: bool = False, + block_table: Optional[torch.Tensor] = None, + leftpad_k: Optional[torch.Tensor] = None, + seqused_k: Optional[torch.Tensor] = None, + zero_tensors: bool = False, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + q, k, v = [maybe_contiguous(x) for x in (q, k, v)] + paged_kv = block_table is not None + batch_size = cu_seqlens_q.numel() - 1 + total_q, num_heads, _ = q.shape + + out = torch.empty_like(q) + softmax_lse = torch.empty((num_heads, total_q), dtype=torch.float32, device=q.device, layout=q.layout) + p = torch.empty((0,), dtype=q.dtype, device=q.device, layout=q.layout) + seqlen_q_rounded = round_multiple(max_seqlen_q, 128) + seqlen_k_rounded = round_multiple(max_seqlen_k, 128) + if return_softmax: + p = torch.empty((batch_size, num_heads, seqlen_q_rounded, seqlen_k_rounded), dtype=q.dtype, device=q.device, layout=q.layout) + rng_state = torch.empty((2,), dtype=torch.int64, device=q.device) + return out, softmax_lse, p, rng_state + + +if torch.__version__ >= "2.4.0": + _wrapped_flash_attn_varlen_forward = torch.ops.flash_attn._flash_attn_varlen_forward +else: + _wrapped_flash_attn_varlen_forward = _flash_attn_varlen_forward + + +@_torch_custom_op_wrapper("flash_attn::_flash_attn_backward", mutates_args=("dq", "dk", "dv"), device_types="cuda") +def _flash_attn_backward( + dout: torch.Tensor, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + out: torch.Tensor, + softmax_lse: torch.Tensor, + dq: Optional[torch.Tensor], + dk: Optional[torch.Tensor], + dv: Optional[torch.Tensor], + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int, + window_size_right: int, + softcap: float, + alibi_slopes: Optional[torch.Tensor], + deterministic: bool, + rng_state: Optional[torch.Tensor] = None, +) -> torch.Tensor: + # dq, dk, dv are allocated by us so they should already be contiguous + dout, q, k, v, out = [maybe_contiguous(x) for x in (dout, q, k, v, out)] + ( + dq, + dk, + dv, + softmax_d, + ) = flash_attn_gpu.bwd( + dout, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + alibi_slopes, + dropout_p, + softmax_scale, + causal, + window_size_left, + window_size_right, + softcap, + deterministic, + None, + rng_state, + ) + return softmax_d + + +@_torch_register_fake_wrapper("flash_attn::_flash_attn_backward") +def _flash_attn_backward_fake( + dout: torch.Tensor, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + out: torch.Tensor, + softmax_lse: torch.Tensor, + dq: Optional[torch.Tensor], + dk: Optional[torch.Tensor], + dv: Optional[torch.Tensor], + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int, + window_size_right: int, + softcap: float, + alibi_slopes: Optional[torch.Tensor], + deterministic: bool, + rng_state: Optional[torch.Tensor] = None, +) -> torch.Tensor: + dout, q, k, v, out = [maybe_contiguous(x) for x in (dout, q, k, v, out)] + if dq is None: + dq = torch.empty_like(q) + if dk is None: + dk = torch.empty_like(k) + if dv is None: + dv = torch.empty_like(v) + batch_size, seqlen_q, num_heads, _ = q.shape + softmax_d = torch.empty((batch_size, num_heads, round_multiple(seqlen_q, 128)), device=q.device, dtype=torch.float32) + + return softmax_d + + +if torch.__version__ >= "2.4.0": + _wrapped_flash_attn_backward = torch.ops.flash_attn._flash_attn_backward +else: + _wrapped_flash_attn_backward = _flash_attn_backward + + +@_torch_custom_op_wrapper("flash_attn::_flash_attn_varlen_backward", mutates_args=("dq", "dk", "dv"), device_types="cuda") +def _flash_attn_varlen_backward( + dout: torch.Tensor, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + out: torch.Tensor, + softmax_lse: torch.Tensor, + dq: Optional[torch.Tensor], + dk: Optional[torch.Tensor], + dv: Optional[torch.Tensor], + cu_seqlens_q: torch.Tensor, + cu_seqlens_k: torch.Tensor, + max_seqlen_q: int, + max_seqlen_k: int, + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int, + window_size_right: int, + softcap: float, + alibi_slopes: Optional[torch.Tensor], + deterministic: bool, + rng_state: Optional[torch.Tensor] = None, + zero_tensors: bool = False, +) -> torch.Tensor: + # dq, dk, dv are allocated by us so they should already be contiguous + dout, q, k, v, out = [maybe_contiguous(x) for x in (dout, q, k, v, out)] + ( + dq, + dk, + dv, + softmax_d, + ) = flash_attn_gpu.varlen_bwd( + dout, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + cu_seqlens_q, + cu_seqlens_k, + alibi_slopes, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + zero_tensors, + causal, + window_size_left, + window_size_right, + softcap, + deterministic, + None, + rng_state, + ) + # if dk.isnan().any() or dk.isnan().any() or dv.isnan().any() or softmax_d.isnan().any(): + # breakpoint() + return softmax_d + + +@_torch_register_fake_wrapper("flash_attn::_flash_attn_varlen_backward") +def _flash_attn_varlen_backward_fake( + dout: torch.Tensor, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + out: torch.Tensor, + softmax_lse: torch.Tensor, + dq: Optional[torch.Tensor], + dk: Optional[torch.Tensor], + dv: Optional[torch.Tensor], + cu_seqlens_q: torch.Tensor, + cu_seqlens_k: torch.Tensor, + max_seqlen_q: int, + max_seqlen_k: int, + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int, + window_size_right: int, + softcap: float, + alibi_slopes: Optional[torch.Tensor], + deterministic: bool, + rng_state: Optional[torch.Tensor] = None, + zero_tensors: bool = False, +) -> torch.Tensor: + dout, q, k, v, out = [maybe_contiguous(x) for x in (dout, q, k, v, out)] + batch_size = cu_seqlens_q.numel() - 1 + total_q, num_heads, _ = q.shape + + if dq is None: + dq = torch.empty_like(q) + if dk is None: + dk = torch.empty_like(k) + if dv is None: + dv = torch.empty_like(v) + softmax_d = torch.empty((num_heads, total_q + 128 * batch_size), device=q.device, dtype=torch.float32) + + return softmax_d + + +if torch.__version__ >= "2.4.0": + _wrapped_flash_attn_varlen_backward = torch.ops.flash_attn._flash_attn_varlen_backward +else: + _wrapped_flash_attn_varlen_backward = _flash_attn_varlen_backward + + +class FlashAttnQKVPackedFunc(torch.autograd.Function): + @staticmethod + def forward( + ctx, + qkv, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_softmax, + is_grad_enabled, + ): + is_grad = is_grad_enabled and qkv.requires_grad + if softmax_scale is None: + softmax_scale = qkv.shape[-1] ** (-0.5) + q, k, v = qkv[:, :, 0].detach(), qkv[:, :, 1].detach(), qkv[:, :, 2].detach() + head_size_og = q.size(3) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_forward( + q, + k, + v, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + softcap=softcap, + alibi_slopes=alibi_slopes, + return_softmax=return_softmax and dropout_p > 0, + ) + if is_grad: + ctx.save_for_backward(q, k, v, out_padded, softmax_lse, rng_state) + ctx.dropout_p = dropout_p + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.softcap = softcap + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + out = out_padded[..., :head_size_og] + return out if not return_softmax else (out, softmax_lse, S_dmask) + + @staticmethod + def backward(ctx, dout, *args): + q, k, v, out, softmax_lse, rng_state = ctx.saved_tensors + qkv_shape = q.shape[:-2] + (3, *q.shape[-2:]) + dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device) + head_size_og = dout.size(3) + dout_padded = dout + if head_size_og % 8 != 0: + dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8]) + _wrapped_flash_attn_backward( + dout_padded, + q, + k, + v, + out, + softmax_lse, + dqkv[:, :, 0], + dqkv[:, :, 1], + dqkv[:, :, 2], + ctx.dropout_p, + ctx.softmax_scale, + ctx.causal, + ctx.window_size[0], + ctx.window_size[1], + ctx.softcap, + ctx.alibi_slopes, + ctx.deterministic, + rng_state=rng_state, + ) + dqkv = dqkv[..., : dout.shape[-1]] # We could have padded the head dimension + return dqkv, None, None, None, None, None, None, None, None, None + + +class FlashAttnVarlenQKVPackedFunc(torch.autograd.Function): + @staticmethod + def forward( + ctx, + qkv, + cu_seqlens, + max_seqlen, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_softmax, + is_grad_enabled, + ): + is_grad = is_grad_enabled and qkv.requires_grad + if softmax_scale is None: + softmax_scale = qkv.shape[-1] ** (-0.5) + q, k, v = qkv[:, 0].detach(), qkv[:, 1].detach(), qkv[:, 2].detach() + head_size_og = q.size(2) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_varlen_forward( + q, + k, + v, + cu_seqlens, + cu_seqlens, + max_seqlen, + max_seqlen, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + softcap=softcap, + alibi_slopes=alibi_slopes, + return_softmax=return_softmax and dropout_p > 0, + block_table=None, + ) + if is_grad: + ctx.save_for_backward(q, k, v, out_padded, softmax_lse, cu_seqlens, rng_state) + ctx.dropout_p = dropout_p + ctx.max_seqlen = max_seqlen + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.softcap = softcap + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + out = out_padded[..., :head_size_og] + return out if not return_softmax else (out, softmax_lse, S_dmask) + + @staticmethod + def backward(ctx, dout, *args): + q, k, v, out, softmax_lse, cu_seqlens, rng_state = ctx.saved_tensors + qkv_shape = q.shape[:-2] + (3, *q.shape[-2:]) + dqkv = torch.empty(qkv_shape, dtype=q.dtype, device=q.device) + head_size_og = dout.size(2) + dout_padded = dout + if head_size_og % 8 != 0: + dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8]) + _wrapped_flash_attn_varlen_backward( + dout_padded, + q, + k, + v, + out, + softmax_lse, + dqkv[:, 0], + dqkv[:, 1], + dqkv[:, 2], + cu_seqlens, + cu_seqlens, + ctx.max_seqlen, + ctx.max_seqlen, + ctx.dropout_p, + ctx.softmax_scale, + ctx.causal, + ctx.window_size[0], + ctx.window_size[1], + ctx.softcap, + ctx.alibi_slopes, + ctx.deterministic, + rng_state=rng_state, + ) + dqkv = dqkv[..., : dout.shape[-1]] # We could have padded the head dimension + return dqkv, None, None, None, None, None, None, None, None, None, None, None + + +class FlashAttnKVPackedFunc(torch.autograd.Function): + @staticmethod + def forward( + ctx, + q, + kv, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_softmax, + is_grad_enabled, + ): + is_grad = is_grad_enabled and any( + x.requires_grad for x in [q, kv] + ) + if softmax_scale is None: + softmax_scale = q.shape[-1] ** (-0.5) + k, v = kv[:, :, 0].detach(), kv[:, :, 1].detach() + head_size_og = q.size(3) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_forward( + q, + k, + v, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + softcap=softcap, + alibi_slopes=alibi_slopes, + return_softmax=return_softmax and dropout_p > 0, + ) + if is_grad: + ctx.save_for_backward(q, k, v, out_padded, softmax_lse, rng_state) + ctx.dropout_p = dropout_p + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.softcap = softcap + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + out = out_padded[..., :head_size_og] + return out if not return_softmax else (out, softmax_lse, S_dmask) + + @staticmethod + def backward(ctx, dout, *args): + q, k, v, out, softmax_lse, rng_state = ctx.saved_tensors + dq = torch.empty_like(q) + kv_shape = k.shape[:-2] + (2, *k.shape[-2:]) + dkv = torch.empty(kv_shape, dtype=k.dtype, device=k.device) + head_size_og = dout.size(3) + dout_padded = dout + if head_size_og % 8 != 0: + dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8]) + _wrapped_flash_attn_backward( + dout_padded, + q, + k, + v, + out, + softmax_lse, + dq, + dkv[:, :, 0], + dkv[:, :, 1], + ctx.dropout_p, + ctx.softmax_scale, + ctx.causal, + ctx.window_size[0], + ctx.window_size[1], + ctx.softcap, + ctx.alibi_slopes, + ctx.deterministic, + rng_state=rng_state, + ) + dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension + dkv = dkv[..., : dout.shape[-1]] + return dq, dkv, None, None, None, None, None, None, None, None, None + + +class FlashAttnVarlenKVPackedFunc(torch.autograd.Function): + @staticmethod + def forward( + ctx, + q, + kv, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_softmax, + is_grad_enabled, + ): + is_grad = is_grad_enabled and any( + x.requires_grad for x in [q, kv] + ) + if softmax_scale is None: + softmax_scale = q.shape[-1] ** (-0.5) + k, v = kv[:, 0].detach(), kv[:, 1].detach() + head_size_og = q.size(2) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_varlen_forward( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + softcap=softcap, + alibi_slopes=alibi_slopes, + return_softmax=return_softmax and dropout_p > 0, + block_table=None, + ) + if is_grad: + ctx.save_for_backward( + q, k, v, out_padded, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state + ) + ctx.dropout_p = dropout_p + ctx.max_seqlen_q = max_seqlen_q + ctx.max_seqlen_k = max_seqlen_k + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.softcap = softcap + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + out = out_padded[..., :head_size_og] + return out if not return_softmax else (out, softmax_lse, S_dmask) + + @staticmethod + def backward(ctx, dout, *args): + q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = ctx.saved_tensors + dq = torch.empty_like(q) + kv_shape = k.shape[:-2] + (2, *k.shape[-2:]) + dkv = torch.empty(kv_shape, dtype=k.dtype, device=k.device) + head_size_og = dout.size(2) + dout_padded = dout + if head_size_og % 8 != 0: + dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8]) + _wrapped_flash_attn_varlen_backward( + dout_padded, + q, + k, + v, + out, + softmax_lse, + dq, + dkv[:, 0], + dkv[:, 1], + cu_seqlens_q, + cu_seqlens_k, + ctx.max_seqlen_q, + ctx.max_seqlen_k, + ctx.dropout_p, + ctx.softmax_scale, + ctx.causal, + ctx.window_size[0], + ctx.window_size[1], + ctx.softcap, + ctx.alibi_slopes, + ctx.deterministic, + rng_state=rng_state, + ) + dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension + dkv = dkv[..., : dout.shape[-1]] + return dq, dkv, None, None, None, None, None, None, None, None, None, None, None, None, None + + +class FlashAttnFunc(torch.autograd.Function): + @staticmethod + def forward( + ctx, + q, + k, + v, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_softmax, + is_grad_enabled, + ): + is_grad = is_grad_enabled and any( + x.requires_grad for x in [q, k, v] + ) + if softmax_scale is None: + softmax_scale = q.shape[-1] ** (-0.5) + head_size_og = q.size(3) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_forward( + q, + k, + v, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + softcap=softcap, + alibi_slopes=alibi_slopes, + return_softmax=return_softmax and dropout_p > 0, + ) + if is_grad: + ctx.save_for_backward(q, k, v, out_padded, softmax_lse, rng_state) + ctx.dropout_p = dropout_p + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.softcap = softcap + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + out = out_padded[..., :head_size_og] + return out if not return_softmax else (out, softmax_lse, S_dmask) + + @staticmethod + def backward(ctx, dout, *args): + q, k, v, out, softmax_lse, rng_state = ctx.saved_tensors + dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v) + head_size_og = dout.size(3) + dout_padded = dout + if head_size_og % 8 != 0: + dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8]) + _wrapped_flash_attn_backward( + dout_padded, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + ctx.dropout_p, + ctx.softmax_scale, + ctx.causal, + ctx.window_size[0], + ctx.window_size[1], + ctx.softcap, + ctx.alibi_slopes, + ctx.deterministic, + rng_state=rng_state, + ) + dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension + dk = dk[..., : dout.shape[-1]] + dv = dv[..., : dout.shape[-1]] + return dq, dk, dv, None, None, None, None, None, None, None, None, None + + +class FlashAttnVarlenFunc(torch.autograd.Function): + @staticmethod + def forward( + ctx, + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_softmax, + block_table, + is_grad_enabled, + ): + is_grad = is_grad_enabled and any( + x.requires_grad for x in [q, k, v] + ) + if softmax_scale is None: + softmax_scale = q.shape[-1] ** (-0.5) + head_size_og = q.size(2) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + out_padded, softmax_lse, S_dmask, rng_state = _wrapped_flash_attn_varlen_forward( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + softcap=softcap, + alibi_slopes=alibi_slopes, + return_softmax=return_softmax and dropout_p > 0, + block_table=block_table, + ) + if is_grad: + ctx.save_for_backward( + q, k, v, out_padded, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state + ) + ctx.dropout_p = dropout_p + ctx.max_seqlen_q = max_seqlen_q + ctx.max_seqlen_k = max_seqlen_k + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.softcap = softcap + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + + out = out_padded[..., :head_size_og] + return out if not return_softmax else (out, softmax_lse, S_dmask) + + @staticmethod + def backward(ctx, dout, *args): + q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state = ctx.saved_tensors + dq, dk, dv = torch.empty_like(q), torch.empty_like(k), torch.empty_like(v) + head_size_og = dout.size(2) + dout_padded = dout + if head_size_og % 8 != 0: + dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8]) + _wrapped_flash_attn_varlen_backward( + dout_padded, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + cu_seqlens_q, + cu_seqlens_k, + ctx.max_seqlen_q, + ctx.max_seqlen_k, + ctx.dropout_p, + ctx.softmax_scale, + ctx.causal, + ctx.window_size[0], + ctx.window_size[1], + ctx.softcap, + ctx.alibi_slopes, + ctx.deterministic, + rng_state=rng_state, + ) + dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension + dk = dk[..., : dout.shape[-1]] + dv = dv[..., : dout.shape[-1]] + return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None + + +def flash_attn_qkvpacked_func( + qkv, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # <=0.0 means deactivate + alibi_slopes=None, + deterministic=False, + return_attn_probs=False, +): + """dropout_p should be set to 0.0 during evaluation + If Q, K, V are already stacked into 1 tensor, this function will be faster than + calling flash_attn_func on Q, K, V since the backward pass avoids explicit concatenation + of the gradients of Q, K, V. + For multi-query and grouped-query attention (MQA/GQA), please see + flash_attn_kvpacked_func and flash_attn_func. + + If window_size != (-1, -1), implements sliding window local attention. Query at position i + will only attend to keys between [i - window_size[0], i + window_size[1]] inclusive. + + Arguments: + qkv: (batch_size, seqlen, 3, nheads, headdim) + dropout_p: float. Dropout probability. + softmax_scale: float. The scaling of QK^T before applying softmax. + Default to 1 / sqrt(headdim). + causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling). + window_size: (left, right). If not (-1, -1), implements sliding window local attention. + softcap: float. Anything > 0 activates softcapping attention. + alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of (-alibi_slope * |i - j|) is added to + the attention score of query i and key j. + deterministic: bool. Whether to use the deterministic implementation of the backward pass, + which is slightly slower and uses more memory. The forward pass is always deterministic. + return_attn_probs: bool. Whether to return the attention probabilities. This option is for + testing only. The returned probabilities are not guaranteed to be correct + (they might not have the right scaling). + Return: + out: (batch_size, seqlen, nheads, headdim). + softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The + logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax + normalization factor). + S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen). + The output of softmax (possibly with different scaling). It also encodes the dropout + pattern (negative means that location was dropped, nonnegative means it was kept). + """ + return FlashAttnQKVPackedFunc.apply( + qkv, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_attn_probs, + torch.is_grad_enabled(), + ) + + +def flash_attn_kvpacked_func( + q, + kv, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # 0.0 means deactivated + alibi_slopes=None, + deterministic=False, + return_attn_probs=False, +): + """dropout_p should be set to 0.0 during evaluation + If K, V are already stacked into 1 tensor, this function will be faster than + calling flash_attn_func on Q, K, V since the backward pass avoids explicit concatenation + of the gradients of K, V. + Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads + than Q. Note that the number of heads in Q must be divisible by the number of heads in KV. + For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head + 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V. + + If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix. + For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is: + 1 1 1 1 0 + 1 1 1 1 1 + If seqlen_q = 5 and seqlen_k = 2, the causal mask is: + 0 0 + 0 0 + 0 0 + 1 0 + 1 1 + If the row of the mask is all zero, the output will be zero. + + If window_size != (-1, -1), implements sliding window local attention. Query at position i + will only attend to keys between + [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive. + + Arguments: + q: (batch_size, seqlen, nheads, headdim) + kv: (batch_size, seqlen, 2, nheads_k, headdim) + dropout_p: float. Dropout probability. + softmax_scale: float. The scaling of QK^T before applying softmax. + Default to 1 / sqrt(headdim). + causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling). + window_size: (left, right). If not (-1, -1), implements sliding window local attention. + softcap: float. Anything > 0 activates softcapping attention. + alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of + (-alibi_slope * |i + seqlen_k - seqlen_q - j|) + is added to the attention score of query i and key j. + deterministic: bool. Whether to use the deterministic implementation of the backward pass, + which is slightly slower and uses more memory. The forward pass is always deterministic. + return_attn_probs: bool. Whether to return the attention probabilities. This option is for + testing only. The returned probabilities are not guaranteed to be correct + (they might not have the right scaling). + Return: + out: (batch_size, seqlen, nheads, headdim). + softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The + logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax + normalization factor). + S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen). + The output of softmax (possibly with different scaling). It also encodes the dropout + pattern (negative means that location was dropped, nonnegative means it was kept). + """ + return FlashAttnKVPackedFunc.apply( + q, + kv, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_attn_probs, + torch.is_grad_enabled(), + ) + + +def flash_attn_func( + q, + k, + v, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # 0.0 means deactivated + alibi_slopes=None, + deterministic=False, + return_attn_probs=False, +): + """dropout_p should be set to 0.0 during evaluation + Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads + than Q. Note that the number of heads in Q must be divisible by the number of heads in KV. + For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head + 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V. + + If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix. + For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is: + 1 1 1 1 0 + 1 1 1 1 1 + If seqlen_q = 5 and seqlen_k = 2, the causal mask is: + 0 0 + 0 0 + 0 0 + 1 0 + 1 1 + If the row of the mask is all zero, the output will be zero. + + If window_size != (-1, -1), implements sliding window local attention. Query at position i + will only attend to keys between + [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive. + + Arguments: + q: (batch_size, seqlen, nheads, headdim) + k: (batch_size, seqlen, nheads_k, headdim) + v: (batch_size, seqlen, nheads_k, headdim) + dropout_p: float. Dropout probability. + softmax_scale: float. The scaling of QK^T before applying softmax. + Default to 1 / sqrt(headdim). + causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling). + window_size: (left, right). If not (-1, -1), implements sliding window local attention. + alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of + (-alibi_slope * |i + seqlen_k - seqlen_q - j|) + is added to the attention score of query i and key j. + deterministic: bool. Whether to use the deterministic implementation of the backward pass, + which is slightly slower and uses more memory. The forward pass is always deterministic. + return_attn_probs: bool. Whether to return the attention probabilities. This option is for + testing only. The returned probabilities are not guaranteed to be correct + (they might not have the right scaling). + Return: + out: (batch_size, seqlen, nheads, headdim). + softmax_lse [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen). The + logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax + normalization factor). + S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen). + The output of softmax (possibly with different scaling). It also encodes the dropout + pattern (negative means that location was dropped, nonnegative means it was kept). + """ + return FlashAttnFunc.apply( + q, + k, + v, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_attn_probs, + torch.is_grad_enabled(), + ) + + +def flash_attn_varlen_qkvpacked_func( + qkv, + cu_seqlens, + max_seqlen, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # 0.0 means deactivated + alibi_slopes=None, + deterministic=False, + return_attn_probs=False, +): + """dropout_p should be set to 0.0 during evaluation + If Q, K, V are already stacked into 1 tensor, this function will be faster than + calling flash_attn_varlen_func on Q, K, V since the backward pass avoids explicit concatenation + of the gradients of Q, K, V. + For multi-query and grouped-query attention (MQA/GQA), please see + flash_attn_varlen_kvpacked_func and flash_attn_varlen_func. + + If window_size != (-1, -1), implements sliding window local attention. Query at position i + will only attend to keys between [i - window_size[0], i + window_size[1]] inclusive. + + Arguments: + qkv: (total, 3, nheads, headdim), where total = total number of tokens in the batch. + cu_seqlens: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into qkv. + max_seqlen: int. Maximum sequence length in the batch. + dropout_p: float. Dropout probability. + softmax_scale: float. The scaling of QK^T before applying softmax. + Default to 1 / sqrt(headdim). + causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling). + window_size: (left, right). If not (-1, -1), implements sliding window local attention. + softcap: float. Anything > 0 activates softcapping attention. + alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of (-alibi_slope * |i - j|) + is added to the attention score of query i and key j. + deterministic: bool. Whether to use the deterministic implementation of the backward pass, + which is slightly slower and uses more memory. The forward pass is always deterministic. + return_attn_probs: bool. Whether to return the attention probabilities. This option is for + testing only. The returned probabilities are not guaranteed to be correct + (they might not have the right scaling). + Return: + out: (total, nheads, headdim). + softmax_lse [optional, if return_attn_probs=True]: (nheads, total_q_seqlen). The + logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax + normalization factor). + S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen). + The output of softmax (possibly with different scaling). It also encodes the dropout + pattern (negative means that location was dropped, nonnegative means it was kept). + """ + return FlashAttnVarlenQKVPackedFunc.apply( + qkv, + cu_seqlens, + max_seqlen, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_attn_probs, + torch.is_grad_enabled(), + ) + + +def flash_attn_varlen_kvpacked_func( + q, + kv, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # 0.0 means deactivated + alibi_slopes=None, + deterministic=False, + return_attn_probs=False, +): + """dropout_p should be set to 0.0 during evaluation + If K, V are already stacked into 1 tensor, this function will be faster than + calling flash_attn_func on Q, K, V since the backward pass avoids explicit concatenation + of the gradients of K, V. + Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads + than Q. Note that the number of heads in Q must be divisible by the number of heads in KV. + For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head + 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V. + + If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix. + For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is: + 1 1 1 1 0 + 1 1 1 1 1 + If seqlen_q = 5 and seqlen_k = 2, the causal mask is: + 0 0 + 0 0 + 0 0 + 1 0 + 1 1 + If the row of the mask is all zero, the output will be zero. + + If window_size != (-1, -1), implements sliding window local attention. Query at position i + will only attend to keys between + [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive. + + Arguments: + q: (total_q, nheads, headdim), where total_q = total number of query tokens in the batch. + kv: (total_k, 2, nheads_k, headdim), where total_k = total number of key tokens in the batch. + cu_seqlens_q: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into q. + cu_seqlens_k: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into kv. + max_seqlen_q: int. Maximum query sequence length in the batch. + max_seqlen_k: int. Maximum key sequence length in the batch. + dropout_p: float. Dropout probability. + softmax_scale: float. The scaling of QK^T before applying softmax. + Default to 1 / sqrt(headdim). + causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling). + window_size: (left, right). If not (-1, -1), implements sliding window local attention. + softcap: float. Anything > 0 activates softcapping attention. + alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of + (-alibi_slope * |i + seqlen_k - seqlen_q - j|) + is added to the attention score of query i and key j. + deterministic: bool. Whether to use the deterministic implementation of the backward pass, + which is slightly slower and uses more memory. The forward pass is always deterministic. + return_attn_probs: bool. Whether to return the attention probabilities. This option is for + testing only. The returned probabilities are not guaranteed to be correct + (they might not have the right scaling). + Return: + out: (total, nheads, headdim). + softmax_lse [optional, if return_attn_probs=True]: (nheads, total_q_seqlen). The + logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax + normalization factor). + S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen). + The output of softmax (possibly with different scaling). It also encodes the dropout + pattern (negative means that location was dropped, nonnegative means it was kept). + """ + return FlashAttnVarlenKVPackedFunc.apply( + q, + kv, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_attn_probs, + torch.is_grad_enabled(), + ) + + +def flash_attn_varlen_func( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # 0.0 means deactivated + alibi_slopes=None, + deterministic=False, + return_attn_probs=False, + block_table=None, +): + """dropout_p should be set to 0.0 during evaluation + Supports multi-query and grouped-query attention (MQA/GQA) by passing in K, V with fewer heads + than Q. Note that the number of heads in Q must be divisible by the number of heads in KV. + For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head + 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V. + + If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix. + For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is: + 1 1 1 1 0 + 1 1 1 1 1 + If seqlen_q = 5 and seqlen_k = 2, the causal mask is: + 0 0 + 0 0 + 0 0 + 1 0 + 1 1 + If the row of the mask is all zero, the output will be zero. + + If window_size != (-1, -1), implements sliding window local attention. Query at position i + will only attend to keys between + [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive. + + Arguments: + q: (total_q, nheads, headdim), where total_q = total number of query tokens in the batch. + k: (total_k, nheads_k, headdim), where total_k = total number of key tokens in the batch. + v: (total_k, nheads_k, headdim), where total_k = total number of key tokens in the batch. + cu_seqlens_q: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into q. + cu_seqlens_k: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into kv. + max_seqlen_q: int. Maximum query sequence length in the batch. + max_seqlen_k: int. Maximum key sequence length in the batch. + dropout_p: float. Dropout probability. + softmax_scale: float. The scaling of QK^T before applying softmax. + Default to 1 / sqrt(headdim). + causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling). + window_size: (left, right). If not (-1, -1), implements sliding window local attention. + softcap: float. Anything > 0 activates softcapping attention. + alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of + (-alibi_slope * |i + seqlen_k - seqlen_q - j|) + is added to the attention score of query i and key j. + deterministic: bool. Whether to use the deterministic implementation of the backward pass, + which is slightly slower and uses more memory. The forward pass is always deterministic. + return_attn_probs: bool. Whether to return the attention probabilities. This option is for + testing only. The returned probabilities are not guaranteed to be correct + (they might not have the right scaling). + Return: + out: (total, nheads, headdim). + softmax_lse [optional, if return_attn_probs=True]: (nheads, total_q_seqlen). The + logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax + normalization factor). + S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen). + The output of softmax (possibly with different scaling). It also encodes the dropout + pattern (negative means that location was dropped, nonnegative means it was kept). + """ + return FlashAttnVarlenFunc.apply( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_attn_probs, + block_table, + torch.is_grad_enabled(), + ) + + +def flash_attn_with_kvcache( + q, + k_cache, + v_cache, + k=None, + v=None, + rotary_cos=None, + rotary_sin=None, + cache_seqlens: Optional[Union[(int, torch.Tensor)]] = None, + cache_batch_idx: Optional[torch.Tensor] = None, + cache_leftpad: Optional[torch.Tensor] = None, + block_table: Optional[torch.Tensor] = None, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # 0.0 means deactivated + rotary_interleaved=True, + alibi_slopes=None, + num_splits=0, + return_softmax_lse=False, +): + """ + If k and v are not None, k_cache and v_cache will be updated *inplace* with the new values from + k and v. This is useful for incremental decoding: you can pass in the cached keys/values from + the previous step, and update them with the new keys/values from the current step, and do + attention with the updated cache, all in 1 kernel. + + If you pass in k / v, you must make sure that the cache is large enough to hold the new values. + For example, the KV cache could be pre-allocated with the max sequence length, and you can use + cache_seqlens to keep track of the current sequence lengths of each sequence in the batch. + + Also apply rotary embedding if rotary_cos and rotary_sin are passed in. The key @k will be + rotated by rotary_cos and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc. + If causal or local (i.e., window_size != (-1, -1)), the query @q will be rotated by rotary_cos + and rotary_sin at indices cache_seqlens, cache_seqlens + 1, etc. + If not causal and not local, the query @q will be rotated by rotary_cos and rotary_sin at + indices cache_seqlens only (i.e. we consider all tokens in @q to be at position cache_seqlens). + + See tests/test_flash_attn.py::test_flash_attn_kvcache for examples of how to use this function. + + Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads + than Q. Note that the number of heads in Q must be divisible by the number of heads in KV. + For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head + 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V. + + If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix. + For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is: + 1 1 1 1 0 + 1 1 1 1 1 + If seqlen_q = 5 and seqlen_k = 2, the causal mask is: + 0 0 + 0 0 + 0 0 + 1 0 + 1 1 + If the row of the mask is all zero, the output will be zero. + + If window_size != (-1, -1), implements sliding window local attention. Query at position i + will only attend to keys between + [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive. + + Note: Does not support backward pass. + + Arguments: + q: (batch_size, seqlen, nheads, headdim) + k_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim) if there's no block_table, + or (num_blocks, page_block_size, nheads_k, headdim) if there's a block_table (i.e. paged KV cache) + page_block_size must be a multiple of 256. + v_cache: (batch_size_cache, seqlen_cache, nheads_k, headdim) if there's no block_table, + or (num_blocks, page_block_size, nheads_k, headdim) if there's a block_table (i.e. paged KV cache) + k [optional]: (batch_size, seqlen_new, nheads_k, headdim). If not None, we concatenate + k with k_cache, starting at the indices specified by cache_seqlens. + v [optional]: (batch_size, seqlen_new, nheads_k, headdim). Similar to k. + rotary_cos [optional]: (seqlen_ro, rotary_dim / 2). If not None, we apply rotary embedding + to k and q. Only applicable if k and v are passed in. rotary_dim must be divisible by 16. + rotary_sin [optional]: (seqlen_ro, rotary_dim / 2). Similar to rotary_cos. + cache_seqlens: int, or (batch_size,), dtype torch.int32. The sequence lengths of the + KV cache. + cache_batch_idx: (batch_size,), dtype torch.int32. The indices used to index into the KV cache. + If None, we assume that the batch indices are [0, 1, 2, ..., batch_size - 1]. + If the indices are not distinct, and k and v are provided, the values updated in the cache + might come from any of the duplicate indices. + cache_leftpad: (batch_size,), dtype torch.int32. The index that the KV cache starts. If None, assume 0. + block_table [optional]: (batch_size, max_num_blocks_per_seq), dtype torch.int32. + softmax_scale: float. The scaling of QK^T before applying softmax. + Default to 1 / sqrt(headdim). + causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling). + window_size: (left, right). If not (-1, -1), implements sliding window local attention. + softcap: float. Anything > 0 activates softcapping attention. + rotary_interleaved: bool. Only applicable if rotary_cos and rotary_sin are passed in. + If True, rotary embedding will combine dimensions 0 & 1, 2 & 3, etc. If False, + rotary embedding will combine dimensions 0 & rotary_dim / 2, 1 & rotary_dim / 2 + 1 + (i.e. GPT-NeoX style). + alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of + (-alibi_slope * |i + seqlen_k - seqlen_q - j|) + is added to the attention score of query i and key j. + num_splits: int. If > 1, split the key/value into this many chunks along the sequence. + If num_splits == 1, we don't split the key/value. If num_splits == 0, we use a heuristic + to automatically determine the number of splits. + Don't change this unless you know what you are doing. + return_softmax_lse: bool. Whether to return the logsumexp of the attention scores. + + Return: + out: (batch_size, seqlen, nheads, headdim). + softmax_lse [optional, if return_softmax_lse=True]: (batch_size, nheads, seqlen). The + logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax + normalization factor). + """ + assert k_cache.stride(-1) == 1, "k_cache must have contiguous last dimension" + assert v_cache.stride(-1) == 1, "v_cache must have contiguous last dimension" + q, k, v = [maybe_contiguous(x) for x in (q, k, v)] + if softmax_scale is None: + softmax_scale = q.shape[-1] ** (-0.5) + if cache_seqlens is not None and isinstance(cache_seqlens, int): + cache_seqlens = torch.full( + (k_cache.shape[0],), cache_seqlens, dtype=torch.int32, device=k_cache.device + ) + cache_seqlens = maybe_contiguous(cache_seqlens) + cache_batch_idx = maybe_contiguous(cache_batch_idx) + block_table = maybe_contiguous(block_table) + out, softmax_lse = flash_attn_gpu.fwd_kvcache( + q, + k_cache, + v_cache, + k, + v, + cache_seqlens, + rotary_cos, + rotary_sin, + cache_batch_idx, + cache_leftpad, + block_table, + alibi_slopes, + None, + softmax_scale, + causal, + window_size[0], + window_size[1], + softcap, + rotary_interleaved, + num_splits, + ) + return (out, softmax_lse) if return_softmax_lse else out diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton.py new file mode 100644 index 0000000000000000000000000000000000000000..30420c057adf1916e16403d3f0d02d0e26c8b7a3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton.py @@ -0,0 +1,1160 @@ +""" +*Experimental* implementation of FlashAttention in Triton. +Tested with triton==2.0.0.dev20221202. +Triton 2.0 has a new backend (MLIR) but seems like it doesn't yet work for head dimensions +other than 64: +https://github.com/openai/triton/blob/d376020f90002757eea3ea9475d4f7cfc2ec5ead/python/triton/ops/flash_attention.py#L207 +We'll update this implementation with the new Triton backend once this is fixed. + +We use the FlashAttention implementation from Phil Tillet a starting point. +https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py + +Changes: +- Implement both causal and non-causal attention. +- Implement both self-attention and cross-attention. +- Support arbitrary seqlens (not just multiples of 128), for both forward and backward. +- Support all head dimensions up to 128 (not just 16, 32, 64, 128), for both forward and backward. +- Support attention bias. +- Speed up the forward pass a bit, and only store the LSE instead of m and l. +- Make the backward for d=128 much faster by reducing register spilling. +- Optionally parallelize the backward pass across seqlen_k, to deal with the case of +small batch size * nheads. + +Caution: +- This is an *experimental* implementation. The forward pass should be quite robust but +I'm not 100% sure that the backward pass doesn't have race conditions (due to the Triton compiler). +- This implementation has only been tested on A100. +- If you plan to use headdim other than 64 and 128, you should test for race conditions +(due to the Triton compiler), as done in tests/test_flash_attn.py +"test_flash_attn_triton_race_condition". I've tested and fixed many race conditions +for different head dimensions (40, 48, 64, 128, 80, 88, 96), but I'm still not 100% confident +that there are none left for other head dimensions. + +Differences between this Triton version and the CUDA version: +- Triton version doesn't support dropout. +- Triton forward is generally faster than CUDA forward, while Triton backward is +generally slower than CUDA backward. Overall Triton forward + backward is slightly slower +than CUDA forward + backward. +- Triton version doesn't support different sequence lengths in a batch (i.e., RaggedTensor/NestedTensor). +- Triton version supports attention bias, while CUDA version doesn't. +""" + +import math + +import torch +import triton +import triton.language as tl + + +# Disabling autotune for now, set num_warps=4 if headdim=64 and num_warps=8 if headdim=128 +# @triton.autotune( +# configs=[ +# triton.Config({"BLOCK_M": 128, "BLOCK_N": 128}, num_warps=4, num_stages=1), +# # This config has a race condition when EVEN_M == False, disabling it for now. +# # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64}, num_warps=4, num_stages=1), +# ], +# key=['CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL', 'BLOCK_HEADDIM'] +# ) +@triton.heuristics( + { + "EVEN_M": lambda args: args["seqlen_q"] % args["BLOCK_M"] == 0, + "EVEN_N": lambda args: args["seqlen_k"] % args["BLOCK_N"] == 0, + "EVEN_HEADDIM": lambda args: args["headdim"] == args["BLOCK_HEADDIM"], + } +) +@triton.jit +def _fwd_kernel( + Q, + K, + V, + Bias, + Out, + Lse, + TMP, # NOTE: TMP is a scratchpad buffer to workaround a compiler bug + softmax_scale, + stride_qb, + stride_qh, + stride_qm, + stride_kb, + stride_kh, + stride_kn, + stride_vb, + stride_vh, + stride_vn, + stride_bb, + stride_bh, + stride_bm, + stride_ob, + stride_oh, + stride_om, + nheads, + seqlen_q, + seqlen_k, + seqlen_q_rounded, + headdim, + CACHE_KEY_SEQLEN_Q, + CACHE_KEY_SEQLEN_K, + BIAS_TYPE: tl.constexpr, + IS_CAUSAL: tl.constexpr, + BLOCK_HEADDIM: tl.constexpr, + EVEN_M: tl.constexpr, + EVEN_N: tl.constexpr, + EVEN_HEADDIM: tl.constexpr, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, +): + start_m = tl.program_id(0) + off_hb = tl.program_id(1) + off_b = off_hb // nheads + off_h = off_hb % nheads + # off_b = tl.program_id(1) + # off_h = tl.program_id(2) + # off_hb = off_b * nheads + off_h + # initialize offsets + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + offs_n = tl.arange(0, BLOCK_N) + offs_d = tl.arange(0, BLOCK_HEADDIM) + # Initialize pointers to Q, K, V + # Adding parenthesis around indexing might use int32 math instead of int64 math? + # https://github.com/openai/triton/issues/741 + # I'm seeing a tiny bit of difference (5-7us) + q_ptrs = ( + Q + off_b * stride_qb + off_h * stride_qh + (offs_m[:, None] * stride_qm + offs_d[None, :]) + ) + k_ptrs = ( + K + off_b * stride_kb + off_h * stride_kh + (offs_n[:, None] * stride_kn + offs_d[None, :]) + ) + v_ptrs = ( + V + off_b * stride_vb + off_h * stride_vh + (offs_n[:, None] * stride_vn + offs_d[None, :]) + ) + if BIAS_TYPE == "vector": + b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n + elif BIAS_TYPE == "matrix": + b_ptrs = ( + Bias + + off_b * stride_bb + + off_h * stride_bh + + (offs_m[:, None] * stride_bm + offs_n[None, :]) + ) + # initialize pointer to m and l + t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m + lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf") + m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf") + acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32) + # load q: it will stay in SRAM throughout + # [2022-10-30] TD: Triton bug - in the case of EVEN_M=True and EVEN_N=False, if we just call + # tl.load(q_ptrs), we get the wrong output! + if EVEN_M & EVEN_N: + if EVEN_HEADDIM: + q = tl.load(q_ptrs) + else: + q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0) + else: + if EVEN_HEADDIM: + q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0) + else: + q = tl.load( + q_ptrs, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0 + ) + # loop over k, v and update accumulator + end_n = seqlen_k if not IS_CAUSAL else tl.minimum((start_m + 1) * BLOCK_M, seqlen_k) + for start_n in range(0, end_n, BLOCK_N): + start_n = tl.multiple_of(start_n, BLOCK_N) + # -- compute qk ---- + if EVEN_N & EVEN_M: # If we just do "if EVEN_N", there seems to be some race condition + if EVEN_HEADDIM: + k = tl.load(k_ptrs + start_n * stride_kn) + else: + k = tl.load(k_ptrs + start_n * stride_kn, mask=offs_d[None, :] < headdim, other=0.0) + else: + if EVEN_HEADDIM: + k = tl.load( + k_ptrs + start_n * stride_kn, + mask=(start_n + offs_n)[:, None] < seqlen_k, + other=0.0, + ) + else: + k = tl.load( + k_ptrs + start_n * stride_kn, + mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), + other=0.0, + ) + qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) + qk += tl.dot(q, k, trans_b=True) + # Trying to combine the two masks seem to make the result wrong + if not EVEN_N: # Need to mask out otherwise the softmax is wrong + qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0, float("-inf")) + if IS_CAUSAL: + qk += tl.where(offs_m[:, None] >= (start_n + offs_n)[None, :], 0, float("-inf")) + if BIAS_TYPE != "none": + if BIAS_TYPE == "vector": + if EVEN_N: + bias = tl.load(b_ptrs + start_n).to(tl.float32) + else: + bias = tl.load( + b_ptrs + start_n, mask=(start_n + offs_n) < seqlen_k, other=0.0 + ).to(tl.float32) + bias = bias[None, :] + elif BIAS_TYPE == "matrix": + if EVEN_M & EVEN_N: + bias = tl.load(b_ptrs + start_n).to(tl.float32) + else: + bias = tl.load( + b_ptrs + start_n, + mask=(offs_m[:, None] < seqlen_q) + & ((start_n + offs_n)[None, :] < seqlen_k), + other=0.0, + ).to(tl.float32) + # Slightly faster to multiply the softmax_scale in the tl.exp below since the compiler + # can then fuse the mult and add into an fma instruction. But if we have bias we need to + # to multiply with softmax_scale here. + qk = qk * softmax_scale + bias + m_ij = tl.maximum(tl.max(qk, 1), lse_i) + p = tl.exp(qk - m_ij[:, None]) + else: + m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i) + p = tl.exp(qk * softmax_scale - m_ij[:, None]) + l_ij = tl.sum(p, 1) + + # scale acc_o + acc_o_scale = tl.exp(m_i - m_ij) + + # # -- update output accumulator -- + # BUG: have to store and immediately load + tl.store(t_ptrs, acc_o_scale) + acc_o_scale = tl.load(t_ptrs) + acc_o = acc_o * acc_o_scale[:, None] + # update acc_o + if EVEN_N & EVEN_M: # If we just do "if EVEN_N", there seems to be some race condition + if EVEN_HEADDIM: + v = tl.load(v_ptrs + start_n * stride_vn) + else: + v = tl.load(v_ptrs + start_n * stride_vn, mask=offs_d[None, :] < headdim, other=0.0) + else: + if EVEN_HEADDIM: + v = tl.load( + v_ptrs + start_n * stride_vn, + mask=(start_n + offs_n)[:, None] < seqlen_k, + other=0.0, + ) + else: + v = tl.load( + v_ptrs + start_n * stride_vn, + mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), + other=0.0, + ) + p = p.to(v.dtype) + acc_o += tl.dot(p, v) + + # -- update statistics + m_i = m_ij + l_i_new = tl.exp(lse_i - m_ij) + l_ij + lse_i = m_ij + tl.log(l_i_new) + + o_scale = tl.exp(m_i - lse_i) + # BUG: have to store and immediately load + tl.store(t_ptrs, o_scale) + o_scale = tl.load(t_ptrs) + acc_o = acc_o * o_scale[:, None] + # rematerialize offsets to save registers + start_m = tl.program_id(0) + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + # write back l and m + lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m + tl.store(lse_ptrs, lse_i) + # initialize pointers to output + offs_d = tl.arange(0, BLOCK_HEADDIM) + out_ptrs = ( + Out + + off_b * stride_ob + + off_h * stride_oh + + (offs_m[:, None] * stride_om + offs_d[None, :]) + ) + if EVEN_M: + if EVEN_HEADDIM: + tl.store(out_ptrs, acc_o) + else: + tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim) + else: + if EVEN_HEADDIM: + tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q) + else: + tl.store( + out_ptrs, acc_o, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim) + ) + + +@triton.jit +def _bwd_preprocess_do_o_dot( + Out, + DO, + Delta, + stride_ob, + stride_oh, + stride_om, + stride_dob, + stride_doh, + stride_dom, + nheads, + seqlen_q, + seqlen_q_rounded, + headdim, + BLOCK_M: tl.constexpr, + BLOCK_HEADDIM: tl.constexpr, +): + start_m = tl.program_id(0) + off_hb = tl.program_id(1) + off_b = off_hb // nheads + off_h = off_hb % nheads + # initialize offsets + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + offs_d = tl.arange(0, BLOCK_HEADDIM) + # load + o = tl.load( + Out + off_b * stride_ob + off_h * stride_oh + offs_m[:, None] * stride_om + offs_d[None, :], + mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), + other=0.0, + ).to(tl.float32) + do = tl.load( + DO + + off_b * stride_dob + + off_h * stride_doh + + offs_m[:, None] * stride_dom + + offs_d[None, :], + mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), + other=0.0, + ).to(tl.float32) + delta = tl.sum(o * do, axis=1) + # write-back + tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta) + + +@triton.jit +def _bwd_store_dk_dv( + dk_ptrs, + dv_ptrs, + dk, + dv, + offs_n, + offs_d, + seqlen_k, + headdim, + EVEN_M: tl.constexpr, + EVEN_N: tl.constexpr, + EVEN_HEADDIM: tl.constexpr, +): + # [2022-11-01] TD: Same bug. In the case of EVEN_N=True and EVEN_M=False, + # if we just call tl.store(dv_ptrs), there's a race condition + if EVEN_N & EVEN_M: + if EVEN_HEADDIM: + tl.store(dv_ptrs, dv) + tl.store(dk_ptrs, dk) + else: + tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim) + tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim) + else: + if EVEN_HEADDIM: + tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k) + tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k) + else: + tl.store(dv_ptrs, dv, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim)) + tl.store(dk_ptrs, dk, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim)) + + +@triton.jit +def _bwd_kernel_one_col_block( + start_n, + Q, + K, + V, + Bias, + DO, + DQ, + DK, + DV, + LSE, + D, + softmax_scale, + stride_qm, + stride_kn, + stride_vn, + stride_bm, + stride_dom, + stride_dqm, + stride_dkn, + stride_dvn, + seqlen_q, + seqlen_k, + headdim, + ATOMIC_ADD: tl.constexpr, + BIAS_TYPE: tl.constexpr, + IS_CAUSAL: tl.constexpr, + BLOCK_HEADDIM: tl.constexpr, + EVEN_M: tl.constexpr, + EVEN_N: tl.constexpr, + EVEN_HEADDIM: tl.constexpr, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, +): + # We need to make sure begin_m is a multiple of BLOCK_M (not BLOCK_N) + begin_m = 0 if not IS_CAUSAL else ((start_n * BLOCK_N) // BLOCK_M) * BLOCK_M + # initialize row/col offsets + offs_qm = begin_m + tl.arange(0, BLOCK_M) + offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N) + offs_m = tl.arange(0, BLOCK_M) + offs_d = tl.arange(0, BLOCK_HEADDIM) + # initialize pointers to value-like data + q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :]) + k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :]) + v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :]) + do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :]) + dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :]) + if BIAS_TYPE == "vector": + b_ptrs = Bias + offs_n + elif BIAS_TYPE == "matrix": + b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :]) + # initialize dv and dk + dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32) + dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32) + # There seems to be some problem with Triton pipelining that makes results wrong for + # headdim=64, seqlen=(113, 255), bias_type='matrix'. In this case the for loop + # may have zero step, and pipelining with the bias matrix could screw it up. + # So we just exit early. + if begin_m >= seqlen_q: + dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :]) + dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :]) + _bwd_store_dk_dv( + dk_ptrs, + dv_ptrs, + dk, + dv, + offs_n, + offs_d, + seqlen_k, + headdim, + EVEN_M=EVEN_M, + EVEN_N=EVEN_N, + EVEN_HEADDIM=EVEN_HEADDIM, + ) + return + # k and v stay in SRAM throughout + # [2022-10-30] TD: Same bug as the fwd. In the case of EVEN_N=True and EVEN_M=False, + # if we just call tl.load(k_ptrs), we get the wrong output! + if EVEN_N & EVEN_M: + if EVEN_HEADDIM: + k = tl.load(k_ptrs) + v = tl.load(v_ptrs) + else: + k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0) + v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0) + else: + if EVEN_HEADDIM: + k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0) + v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0) + else: + k = tl.load( + k_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0 + ) + v = tl.load( + v_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0 + ) + # loop over rows + num_block_m = tl.cdiv(seqlen_q, BLOCK_M) + for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M): + start_m = tl.multiple_of(start_m, BLOCK_M) + offs_m_curr = start_m + offs_m + # load q, k, v, do on-chip + # Same bug as below. Otherwise gives wrong result for headdim=40, seqlen=(128, 117) + if EVEN_M & EVEN_HEADDIM: + q = tl.load(q_ptrs) + else: + if EVEN_HEADDIM: + q = tl.load(q_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0) + else: + q = tl.load( + q_ptrs, + mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), + other=0.0, + ) + # recompute p = softmax(qk, dim=-1).T + qk = tl.dot(q, k, trans_b=True) + # Trying to combine the two masks seem to make the result wrong + if not EVEN_N: # Need to mask out otherwise the softmax is wrong + qk = tl.where(offs_n[None, :] < seqlen_k, qk, float("-inf")) + if IS_CAUSAL: + qk = tl.where(offs_m_curr[:, None] >= (offs_n[None, :]), qk, float("-inf")) + if BIAS_TYPE != "none": + tl.debug_barrier() # Race condition otherwise + if BIAS_TYPE == "vector": + if EVEN_N: + bias = tl.load(b_ptrs).to(tl.float32) + else: + bias = tl.load(b_ptrs, mask=offs_n < seqlen_k, other=0.0).to(tl.float32) + bias = bias[None, :] + elif BIAS_TYPE == "matrix": + if EVEN_M & EVEN_N: + bias = tl.load(b_ptrs).to(tl.float32) + else: + bias = tl.load( + b_ptrs, + mask=(offs_m_curr[:, None] < seqlen_q) & (offs_n[None, :] < seqlen_k), + other=0.0, + ).to(tl.float32) + qk = qk * softmax_scale + bias + # There seems to be a race condition when headdim=48/96, and dq, dk, dv are wrong. + # Also wrong for headdim=64. + if not (EVEN_M & EVEN_HEADDIM): + tl.debug_barrier() + lse_i = tl.load(LSE + offs_m_curr) + if BIAS_TYPE == "none": + p = tl.exp(qk * softmax_scale - lse_i[:, None]) + else: + p = tl.exp(qk - lse_i[:, None]) + # compute dv + # [2022-10-30] TD: A Triton bug: if EVEN_M=True and EVEN_HEADDIM=False, if we call + # do = tl.load(do_ptrs, mask=offs_d[None, :] < headdim, other=0.0), we get wrong outputs + # in the case of headdim=48/96, seqlen_q & seqlen_k >= 512. If headdim=40 or seqlen < 512, + # the output is correct. + if EVEN_M & EVEN_HEADDIM: + do = tl.load(do_ptrs) + else: + # [2022-11-01] TD: Triton bug, there's a race condition if we just use m_mask and not d_mask. + do = tl.load( + do_ptrs, + mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), + other=0.0, + ) + # if EVEN_M: + # if EVEN_HEADDIM: + # do = tl.load(do_ptrs) + # else: + # do = tl.load(do_ptrs, mask=offs_d[None, :] < headdim, other=0.0) + # else: + # if EVEN_HEADDIM: + # do = tl.load(do_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0) + # else: + # do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) + # & (offs_d[None, :] < headdim), other=0.0) + dv += tl.dot(p.to(do.dtype), do, trans_a=True) + # compute dp = dot(v, do) + # There seems to be a race condition when headdim=48/96, and dq, dk are wrong. + # Also wrong for headdim=128, seqlen=(108, 256), and ATOMIC_ADD=True + # Also wrong for headdim=64, seqlen=(1023, 1024), and ATOMIC_ADD=False + if not (EVEN_M & EVEN_HEADDIM): + tl.debug_barrier() + dp = tl.dot(do, v, trans_b=True) + # There's a race condition for headdim=48 + if not EVEN_HEADDIM: + tl.debug_barrier() + # compute ds = p * (dp - delta[:, None]) + # Putting the subtraction after the dp matmul (instead of before) is slightly faster + Di = tl.load(D + offs_m_curr) + # Converting ds to q.dtype here reduces register pressure and makes it much faster + # for BLOCK_HEADDIM=128 + ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype) + # compute dk = dot(ds.T, q) + dk += tl.dot(ds, q, trans_a=True) + # compute dq + if not ( + EVEN_M & EVEN_HEADDIM + ): # Otherewise there's a race condition when BIAS_TYPE='matrix' + tl.debug_barrier() + if not ATOMIC_ADD: + if EVEN_M & EVEN_HEADDIM: # Race condition if we just do EVEN_M + dq = tl.load(dq_ptrs, eviction_policy="evict_last") + dq += tl.dot(ds, k) + tl.store(dq_ptrs, dq, eviction_policy="evict_last") + else: + if EVEN_HEADDIM: + dq = tl.load( + dq_ptrs, + mask=offs_m_curr[:, None] < seqlen_q, + other=0.0, + eviction_policy="evict_last", + ) + dq += tl.dot(ds, k) + tl.store( + dq_ptrs, + dq, + mask=offs_m_curr[:, None] < seqlen_q, + eviction_policy="evict_last", + ) + else: + dq = tl.load( + dq_ptrs, + mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), + other=0.0, + eviction_policy="evict_last", + ) + dq += tl.dot(ds, k) + tl.store( + dq_ptrs, + dq, + mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), + eviction_policy="evict_last", + ) + else: # If we're parallelizing across the seqlen_k dimension + dq = tl.dot(ds, k) + if EVEN_M & EVEN_HEADDIM: # Race condition if we just do EVEN_M + tl.atomic_add(dq_ptrs, dq) + else: + if EVEN_HEADDIM: + tl.atomic_add(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q) + else: + tl.atomic_add( + dq_ptrs, + dq, + mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), + ) + # increment pointers + dq_ptrs += BLOCK_M * stride_dqm + q_ptrs += BLOCK_M * stride_qm + do_ptrs += BLOCK_M * stride_dom + if BIAS_TYPE == "matrix": + b_ptrs += BLOCK_M * stride_bm + # write-back + dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :]) + dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :]) + _bwd_store_dk_dv( + dk_ptrs, + dv_ptrs, + dk, + dv, + offs_n, + offs_d, + seqlen_k, + headdim, + EVEN_M=EVEN_M, + EVEN_N=EVEN_N, + EVEN_HEADDIM=EVEN_HEADDIM, + ) + + +def init_to_zero(name): + return lambda nargs: nargs[name].zero_() + + +@triton.autotune( + configs=[ + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 128, "SEQUENCE_PARALLEL": False}, + num_warps=8, + num_stages=1, + pre_hook=init_to_zero("DQ"), + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 128, "SEQUENCE_PARALLEL": True}, + num_warps=8, + num_stages=1, + pre_hook=init_to_zero("DQ"), + ), + # Other configs seem to give wrong results when seqlen_q % 128 != 0, disabling them for now + # # Kernel is buggy (give wrong result) if we set BLOCK_m=128, BLOCK_n=64, num_warps=*4* + # triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "SEQUENCE_PARALLEL": False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')), + # triton.Config({"BLOCK_M": 128, "BLOCK_N": 64, "SEQUENCE_PARALLEL": True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')), + # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "SEQUENCE_PARALLEL": False}, num_warps=4, num_stages=1, pre_hook=init_to_zero('DQ')), + # triton.Config({"BLOCK_M": 64, "BLOCK_N": 64, "SEQUENCE_PARALLEL": True}, num_warps=4, num_stages=1, pre_hook=init_to_zero('DQ')), + ], + key=["CACHE_KEY_SEQLEN_Q", "CACHE_KEY_SEQLEN_K", "BIAS_TYPE", "IS_CAUSAL", "BLOCK_HEADDIM"], +) +@triton.heuristics( + { + "EVEN_M": lambda args: args["seqlen_q"] % args["BLOCK_M"] == 0, + "EVEN_N": lambda args: args["seqlen_k"] % args["BLOCK_N"] == 0, + "EVEN_HEADDIM": lambda args: args["headdim"] == args["BLOCK_HEADDIM"], + } +) +@triton.jit +def _bwd_kernel( + Q, + K, + V, + Bias, + DO, + DQ, + DK, + DV, + LSE, + D, + softmax_scale, + stride_qb, + stride_qh, + stride_qm, + stride_kb, + stride_kh, + stride_kn, + stride_vb, + stride_vh, + stride_vn, + stride_bb, + stride_bh, + stride_bm, + stride_dob, + stride_doh, + stride_dom, + stride_dqb, + stride_dqh, + stride_dqm, + stride_dkb, + stride_dkh, + stride_dkn, + stride_dvb, + stride_dvh, + stride_dvn, + nheads, + seqlen_q, + seqlen_k, + seqlen_q_rounded, + headdim, + CACHE_KEY_SEQLEN_Q, + CACHE_KEY_SEQLEN_K, + BIAS_TYPE: tl.constexpr, + IS_CAUSAL: tl.constexpr, + BLOCK_HEADDIM: tl.constexpr, + SEQUENCE_PARALLEL: tl.constexpr, + EVEN_M: tl.constexpr, + EVEN_N: tl.constexpr, + EVEN_HEADDIM: tl.constexpr, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, +): + off_hb = tl.program_id(1) + off_b = off_hb // nheads + off_h = off_hb % nheads + # offset pointers for batch/head + Q += off_b * stride_qb + off_h * stride_qh + K += off_b * stride_kb + off_h * stride_kh + V += off_b * stride_vb + off_h * stride_vh + DO += off_b * stride_dob + off_h * stride_doh + DQ += off_b * stride_dqb + off_h * stride_dqh + DK += off_b * stride_dkb + off_h * stride_dkh + DV += off_b * stride_dvb + off_h * stride_dvh + if BIAS_TYPE != "none": + Bias += off_b * stride_bb + off_h * stride_bh + # pointer to row-wise quantities in value-like data + D += off_hb * seqlen_q_rounded + LSE += off_hb * seqlen_q_rounded + if not SEQUENCE_PARALLEL: + num_block_n = tl.cdiv(seqlen_k, BLOCK_N) + for start_n in range(0, num_block_n): + _bwd_kernel_one_col_block( + start_n, + Q, + K, + V, + Bias, + DO, + DQ, + DK, + DV, + LSE, + D, + softmax_scale, + stride_qm, + stride_kn, + stride_vn, + stride_bm, + stride_dom, + stride_dqm, + stride_dkn, + stride_dvn, + seqlen_q, + seqlen_k, + headdim, + ATOMIC_ADD=False, + BIAS_TYPE=BIAS_TYPE, + IS_CAUSAL=IS_CAUSAL, + BLOCK_HEADDIM=BLOCK_HEADDIM, + EVEN_M=EVEN_M, + EVEN_N=EVEN_N, + EVEN_HEADDIM=EVEN_HEADDIM, + BLOCK_M=BLOCK_M, + BLOCK_N=BLOCK_N, + ) + else: + start_n = tl.program_id(0) + _bwd_kernel_one_col_block( + start_n, + Q, + K, + V, + Bias, + DO, + DQ, + DK, + DV, + LSE, + D, + softmax_scale, + stride_qm, + stride_kn, + stride_vn, + stride_bm, + stride_dom, + stride_dqm, + stride_dkn, + stride_dvn, + seqlen_q, + seqlen_k, + headdim, + ATOMIC_ADD=True, + BIAS_TYPE=BIAS_TYPE, + IS_CAUSAL=IS_CAUSAL, + BLOCK_HEADDIM=BLOCK_HEADDIM, + EVEN_M=EVEN_M, + EVEN_N=EVEN_N, + EVEN_HEADDIM=EVEN_HEADDIM, + BLOCK_M=BLOCK_M, + BLOCK_N=BLOCK_N, + ) + + +def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None): + # shape constraints + batch, seqlen_q, nheads, d = q.shape + _, seqlen_k, _, _ = k.shape + assert k.shape == (batch, seqlen_k, nheads, d) + assert v.shape == (batch, seqlen_k, nheads, d) + assert d <= 128, "FlashAttention only support head dimensions up to 128" + assert q.dtype == k.dtype == v.dtype, "All tensors must have the same type" + assert q.dtype in [torch.float16, torch.bfloat16], "Only support fp16 and bf16" + assert q.is_cuda and k.is_cuda and v.is_cuda + softmax_scale = softmax_scale or 1.0 / math.sqrt(d) + + has_bias = bias is not None + bias_type = "none" + if has_bias: + assert bias.dtype in [q.dtype, torch.float] + assert bias.is_cuda + assert bias.dim() == 4 + if bias.stride(-1) != 1: + bias = bias.contiguous() + if bias.shape[2:] == (1, seqlen_k): + bias_type = "vector" + elif bias.shape[2:] == (seqlen_q, seqlen_k): + bias_type = "matrix" + else: + raise RuntimeError( + "Last 2 dimensions of bias must be (1, seqlen_k)" " or (seqlen_q, seqlen_k)" + ) + bias = bias.expand(batch, nheads, seqlen_q, seqlen_k) + bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0) + + seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128 + lse = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32) + tmp = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32) + o = torch.empty_like(q) + + BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16) + BLOCK = 128 + num_warps = 4 if d <= 64 else 8 + grid = lambda META: (triton.cdiv(seqlen_q, META["BLOCK_M"]), batch * nheads) + _fwd_kernel[grid]( + q, + k, + v, + bias, + o, + lse, + tmp, + softmax_scale, + q.stride(0), + q.stride(2), + q.stride(1), + k.stride(0), + k.stride(2), + k.stride(1), + v.stride(0), + v.stride(2), + v.stride(1), + *bias_strides, + o.stride(0), + o.stride(2), + o.stride(1), + nheads, + seqlen_q, + seqlen_k, + seqlen_q_rounded, + d, + seqlen_q // 32, + seqlen_k // 32, # key for triton cache (limit number of compilations) + # Can't use kwargs here because triton autotune expects key to be args, not kwargs + # IS_CAUSAL=causal, BLOCK_HEADDIM=d, + bias_type, + causal, + BLOCK_HEADDIM, + BLOCK_M=BLOCK, + BLOCK_N=BLOCK, + num_warps=num_warps, + num_stages=1, + ) + return o, lse, softmax_scale # softmax_scale could have been updated + + +def _flash_attn_backward( + do, q, k, v, o, lse, dq, dk, dv, bias=None, causal=False, softmax_scale=None +): + # Make sure that the last dimension is contiguous + if do.stride(-1) != 1: + do = do.contiguous() + batch, seqlen_q, nheads, d = q.shape + _, seqlen_k, _, _ = k.shape + # assert d in {16, 32, 64, 128} + assert d <= 128 + seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128 + assert lse.shape == (batch, nheads, seqlen_q_rounded) + assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1 + assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1 + softmax_scale = softmax_scale or 1.0 / math.sqrt(d) + # dq_accum = torch.zeros_like(q, dtype=torch.float32) + dq_accum = torch.empty_like(q, dtype=torch.float32) + delta = torch.empty_like(lse) + # delta = torch.zeros_like(lse) + + BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16) + grid = lambda META: (triton.cdiv(seqlen_q, META["BLOCK_M"]), batch * nheads) + _bwd_preprocess_do_o_dot[grid]( + o, + do, + delta, + o.stride(0), + o.stride(2), + o.stride(1), + do.stride(0), + do.stride(2), + do.stride(1), + nheads, + seqlen_q, + seqlen_q_rounded, + d, + BLOCK_M=128, + BLOCK_HEADDIM=BLOCK_HEADDIM, + ) + + has_bias = bias is not None + bias_type = "none" + if has_bias: + assert bias.dtype in [q.dtype, torch.float] + assert bias.is_cuda + assert bias.dim() == 4 + assert bias.stride(-1) == 1 + if bias.shape[2:] == (1, seqlen_k): + bias_type = "vector" + elif bias.shape[2:] == (seqlen_q, seqlen_k): + bias_type = "matrix" + else: + raise RuntimeError( + "Last 2 dimensions of bias must be (1, seqlen_k)" " or (seqlen_q, seqlen_k)" + ) + bias = bias.expand(batch, nheads, seqlen_q, seqlen_k) + bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0) + + # BLOCK_M = 128 + # BLOCK_N = 64 + # num_warps = 4 + grid = lambda META: ( + triton.cdiv(seqlen_k, META["BLOCK_N"]) if META["SEQUENCE_PARALLEL"] else 1, + batch * nheads, + ) + _bwd_kernel[grid]( + q, + k, + v, + bias, + do, + dq_accum, + dk, + dv, + lse, + delta, + softmax_scale, + q.stride(0), + q.stride(2), + q.stride(1), + k.stride(0), + k.stride(2), + k.stride(1), + v.stride(0), + v.stride(2), + v.stride(1), + *bias_strides, + do.stride(0), + do.stride(2), + do.stride(1), + dq_accum.stride(0), + dq_accum.stride(2), + dq_accum.stride(1), + dk.stride(0), + dk.stride(2), + dk.stride(1), + dv.stride(0), + dv.stride(2), + dv.stride(1), + nheads, + seqlen_q, + seqlen_k, + seqlen_q_rounded, + d, + seqlen_q // 32, + seqlen_k // 32, # key for triton cache (limit number of compilations) + # Can't use kwargs here because triton autotune expects key to be args, not kwargs + # IS_CAUSAL=causal, BLOCK_HEADDIM=d, + bias_type, + causal, + BLOCK_HEADDIM, + # SEQUENCE_PARALLEL=False, + # BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N, + # num_warps=num_warps, + # num_stages=1, + ) + dq.copy_(dq_accum) + + +class FlashAttnQKVPackedFunc(torch.autograd.Function): + @staticmethod + def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None): + """ + qkv: (batch, seqlen, 3, nheads, headdim) + bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen). + For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen). + ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen) + """ + # Make sure that the last dimension is contiguous + if qkv.stride(-1) != 1: + qkv = qkv.contiguous() + o, lse, ctx.softmax_scale = _flash_attn_forward( + qkv[:, :, 0], + qkv[:, :, 1], + qkv[:, :, 2], + bias=bias, + causal=causal, + softmax_scale=softmax_scale, + ) + ctx.save_for_backward(qkv, o, lse, bias) + ctx.causal = causal + return o + + @staticmethod + def backward(ctx, do): + qkv, o, lse, bias = ctx.saved_tensors + assert not ctx.needs_input_grad[1], "FlashAttention does not support bias gradient yet" + # Triton's autotune causes the Tensor._version to change, and so Pytorch autograd + # does a memcpy. To avoid this we run in inference_mode, which doesn't track the version. + with torch.inference_mode(): + dqkv = torch.empty_like(qkv) + _flash_attn_backward( + do, + qkv[:, :, 0], + qkv[:, :, 1], + qkv[:, :, 2], + o, + lse, + dqkv[:, :, 0], + dqkv[:, :, 1], + dqkv[:, :, 2], + bias=bias, + causal=ctx.causal, + softmax_scale=ctx.softmax_scale, + ) + return dqkv, None, None, None + + +flash_attn_qkvpacked_func = FlashAttnQKVPackedFunc.apply + + +class FlashAttnKVPackedFunc(torch.autograd.Function): + @staticmethod + def forward(ctx, q, kv, bias=None, causal=False, softmax_scale=None): + """ + q: (batch, seqlen_q, nheads, headdim) + kv: (batch, seqlen_k, 2, nheads, headdim) + bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k). + For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k). + ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k) + """ + # Make sure that the last dimension is contiguous + q, kv = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, kv]] + o, lse, ctx.softmax_scale = _flash_attn_forward( + q, kv[:, :, 0], kv[:, :, 1], bias=bias, causal=causal, softmax_scale=softmax_scale + ) + ctx.save_for_backward(q, kv, o, lse, bias) + ctx.causal = causal + return o + + @staticmethod + def backward(ctx, do): + q, kv, o, lse, bias = ctx.saved_tensors + if len(ctx.needs_input_grad) >= 3: + assert not ctx.needs_input_grad[2], "FlashAttention does not support bias gradient yet" + # Triton's autotune causes the Tensor._version to change, and so Pytorch autograd + # does a memcpy. To avoid this we run in inference_mode, which doesn't track the version. + with torch.inference_mode(): + dq = torch.empty_like(q) + dkv = torch.empty_like(kv) + _flash_attn_backward( + do, + q, + kv[:, :, 0], + kv[:, :, 1], + o, + lse, + dq, + dkv[:, :, 0], + dkv[:, :, 1], + bias=bias, + causal=ctx.causal, + softmax_scale=ctx.softmax_scale, + ) + return dq, dkv, None, None, None + + +flash_attn_kvpacked_func = FlashAttnKVPackedFunc.apply + + +class FlashAttnFunc(torch.autograd.Function): + @staticmethod + def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None): + """ + q: (batch_size, seqlen_q, nheads, headdim) + k, v: (batch_size, seqlen_k, nheads, headdim) + bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k). + For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k). + ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k) + """ + # Make sure that the last dimension is contiguous + q, k, v = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]] + o, lse, ctx.softmax_scale = _flash_attn_forward( + q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale + ) + ctx.save_for_backward(q, k, v, o, lse, bias) + ctx.causal = causal + return o + + @staticmethod + def backward(ctx, do): + q, k, v, o, lse, bias = ctx.saved_tensors + assert not ctx.needs_input_grad[3], "FlashAttention does not support bias gradient yet" + # Triton's autotune causes the Tensor._version to change, and so Pytorch autograd + # does a memcpy. To avoid this we run in inference_mode, which doesn't track the version. + with torch.inference_mode(): + dq = torch.empty_like(q) + dk = torch.empty_like(k) + dv = torch.empty_like(v) + _flash_attn_backward( + do, + q, + k, + v, + o, + lse, + dq, + dk, + dv, + bias=bias, + causal=ctx.causal, + softmax_scale=ctx.softmax_scale, + ) + return dq, dk, dv, None, None, None + + +flash_attn_func = FlashAttnFunc.apply diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..744644e13409f62d7f82f94ac5ec94eed4257101 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bench.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bench.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67b4b71a3dc94317edcfa1689f5c255df177ef9f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bench.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bwd_prefill.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bwd_prefill.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5feea67ad3ffff69a5142bc9d0f2b11a939bfea Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bwd_prefill.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bwd_prefill_fused.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bwd_prefill_fused.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e0b4ede14c44dfa06b6bac42bfa0c192cd26064 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bwd_prefill_fused.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c337470b196dce12b8bce6599cdcb741226ecf75c4c2ab4936f400fc95d376b1 +size 110341 diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bwd_prefill_onekernel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bwd_prefill_onekernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..79ec006031c3387c56cc5153baba9b9a7314a09e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bwd_prefill_onekernel.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bwd_prefill_split.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bwd_prefill_split.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f13bfd418f9c70cee31641eed889af4b2cd93236 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bwd_prefill_split.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bwd_ref.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bwd_ref.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddc92b82ad3a3a0cf48a26014585baa15d59a859 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/bwd_ref.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/fp8.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/fp8.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e70de427a99e7d2945ccd5146ce7fb4a35f576dc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/fp8.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/fwd_decode.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/fwd_decode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a502b2e1138b8ca31cb8a976e11f1ac083b6404d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/fwd_decode.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/fwd_prefill.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/fwd_prefill.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1269a963c41b44093f20675b9be482a1bb90539 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/fwd_prefill.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/fwd_ref.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/fwd_ref.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba69e5bd0420da7ff5e7df00c32143521f297e31 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/fwd_ref.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/interface_fa.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/interface_fa.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f267d28b60b04eb7087738c878ffd10a100565fe Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/interface_fa.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/test.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/test.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6acb638223b0d21e1f5bd0c407aaadae77ca861 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/test.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/train.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/train.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ac92f20ca8277355b59ceea9c07ba23445de149 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/train.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e8147a0cfc15c3fe5fb44a295b23c31f0b21556 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bench.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bench.py new file mode 100644 index 0000000000000000000000000000000000000000..05e64c349be1ab248f881b4ae7185bd5584ab490 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bench.py @@ -0,0 +1,1223 @@ +import os +import sys +import torch +import triton +import time +import argparse +import itertools +import pandas as pd +from logging import warning +from typing import Dict, List, Literal, Optional, Tuple +from dataclasses import dataclass +from functools import lru_cache +from utils import get_arch, input_helper + +DEBUG = False + +ENV_FLAGS = ["FLASH_ATTENTION_TRITON_AMD_ENABLE", "FLASH_ATTENTION_TRITON_AMD_AUTOTUNE", "FLASH_ATTENTION_TRITON_AMD_DEBUG"] + +FUNCTIONS = [ + "flash_attn_func", + "flash_attn_fp8_func", + "flash_attn_kvpacked_func", + "flash_attn_qkvpacked_func", + "flash_attn_qkvpacked_fp8_func", + "flash_attn_varlen_func", + "flash_attn_varlen_fp8_func", + "flash_attn_varlen_kvpacked_func", + "flash_attn_varlen_qkvpacked_func", + "flash_attn_varlen_qkvpacked_fp8_func", + "flash_attn_with_kvcache", +] + +SUPPORTED_DTYPES = { + "flash_attn_func": [torch.float16], + "flash_attn_fp8_func": [torch.float8_e4m3fnuz], + "flash_attn_kvpacked_func": [torch.float16], + "flash_attn_qkvpacked_func": [torch.float16], + "flash_attn_qkvpacked_fp8_func": [torch.float16], + "flash_attn_varlen_func": [torch.float16], + "flash_attn_varlen_fp8_func": [torch.float8_e4m3fnuz], + "flash_attn_varlen_kvpacked_func": [torch.float16], + "flash_attn_varlen_qkvpacked_func": [torch.float16], + "flash_attn_varlen_qkvpacked_fp8_func": [torch.float16], + "flash_attn_with_kvcache": [torch.float16], +} + +SUPPORTED_BACKENDS = { + "flash_attn_func": ["ck", "triton"], + "flash_attn_fp8_func": ["triton"], + "flash_attn_kvpacked_func": ["ck", "triton"], + "flash_attn_qkvpacked_func": ["ck", "triton"], + "flash_attn_qkvpacked_fp8_func": ["triton"], + "flash_attn_varlen_func": ["ck", "triton"], + "flash_attn_varlen_fp8_func": ["triton"], + "flash_attn_varlen_kvpacked_func": ["ck", "triton"], + "flash_attn_varlen_qkvpacked_func": ["ck", "triton"], + "flash_attn_varlen_qkvpacked_fp8_func": ["triton"], + "flash_attn_with_kvcache": ["ck", "triton"], +} + +VALID_MODES = ['fwd', 'bwd', 'full'] +SUPPORTED_MODES = { + "flash_attn_func": ["fwd", "bwd", "full"], + "flash_attn_fp8_func": ["fwd", "bwd", "full"], + "flash_attn_kvpacked_func": ["fwd", "bwd", "full"], + "flash_attn_qkvpacked_func": ["fwd", "bwd", "full"], + "flash_attn_qkvpacked_fp8_func": ["fwd", "bwd", "full"], + "flash_attn_varlen_func": ["fwd", "bwd", "full"], + "flash_attn_varlen_fp8_func": ["fwd", "bwd", "full"], + "flash_attn_varlen_kvpacked_func": ["fwd", "bwd", "full"], + "flash_attn_varlen_qkvpacked_func": ["fwd", "bwd", "full"], + "flash_attn_varlen_qkvpacked_fp8_func": ["fwd", "bwd", "full"], + "flash_attn_with_kvcache": ["fwd"], +} + +@dataclass +class EnvVariableConfig: + key: str + values: List[str] + backend: Optional[Literal["triton", "ck"]] = None + +ENV_VARIABLE_CONFIGS : List[EnvVariableConfig] = [ + EnvVariableConfig(key="BWD_MODE", values=["split", "fused", "jingning"], backend="triton"), +] + +class FunctionConfig: + def __init__(self, fn_name: str, mode: Literal["fwd", "bwd", "full"], dtype, backend: Literal["triton", "ck"], env_config: Dict): + self.fn_name = fn_name + self.mode: Literal["fwd", "bwd", "full"] = mode + self.dtype = dtype + self.backend: Literal["triton", "ck"] = backend + self.arch = get_arch() + self.env_configs = env_config + + def __str__(self): + # extract base dtype name if it's a torch dtype + dtype_str = str(self.dtype) + if "torch." in dtype_str: + dtype_str = dtype_str.split(".")[-1] + + if len(self.env_configs) > 0: + env_str = "" + for env_key, env_value in self.env_configs.items(): + env_str += f"{env_key}={env_value}" + return f"{self.fn_name}_{self.mode}_{dtype_str}_{self.backend}_{self.arch}_{env_str}" + else: + return f"{self.fn_name}_{self.mode}_{dtype_str}_{self.backend}_{self.arch}" + + def column_name(self): + return f"{self}_ms" + + +@lru_cache() +def available_backends(): + available = [] + + # try to load each backend + for backend in ["triton", "ck"]: + try: + # try loading the module with this backend + flash_attn = load_flash_attn_module(backend) + + # if we got here, the backend loaded successfully + available.append(backend) + except Exception as e: + # backend not available, just continue + print(f"Backend {backend} not available. Error: {e}") + + # if no backends available, default to triton + if not available: + raise ValueError("No Backends available") + + return available + +@lru_cache() +def get_fn_params(fn_name): + # get params for fn + packing = get_packing_type(fn_name) + is_varlen = True if "varlen" in fn_name else False + is_fp8 = True if "fp8" in fn_name else False + supported_dtypes = SUPPORTED_DTYPES.get(fn_name, [torch.float16]) # default to float16 if not found + supported_backends = [backend for backend in SUPPORTED_BACKENDS.get(fn_name, ["triton"]) if backend in available_backends()] # default to triton backend + supports_backward = False if fn_name in ["flash_attn_with_kvcache"] else True + supported_modes = SUPPORTED_MODES.get(fn_name, ["fwd"]) + device = "cuda" + + # get supported env configs for each backend + supported_env_configs = {} + for backend in supported_backends: + supported_env_configs[backend] = get_env_value_combinations(backend) + + # check backward pass support + if not supports_backward: + warning(f"{fn_name} does not have a backward pass so benching forward pass only.") + + return is_varlen, is_fp8, packing, supported_dtypes, supported_backends, supported_modes, supported_env_configs, device + +def generate_fn_inputs( + fn_name: str, + BATCH: int, + HQ: int, + HK: int, + N_CTX_Q: int, + N_CTX_K: int, + D_HEAD: int, + CAUSAL: bool, + DROPOUT_P: float, + dtype: torch.dtype, + device: Literal["cpu", "cuda"] + ): + if fn_name == "flash_attn_func": + return input_helper(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, CAUSAL, DROPOUT_P, dtype, layout="bshd", device=device) + elif fn_name == "flash_attn_kvpacked_func": + return input_helper(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, CAUSAL, DROPOUT_P, dtype, layout="bshd", packing="kv", device=device) + elif fn_name == "flash_attn_qkvpacked_func": + return input_helper(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, CAUSAL, DROPOUT_P, dtype, layout="bshd", packing="qkv", device=device) + elif fn_name == "flash_attn_varlen_func": + return input_helper(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, CAUSAL, DROPOUT_P, dtype, layout="thd", device=device) + elif fn_name == "flash_attn_varlen_kvpacked_func": + return input_helper(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, CAUSAL, DROPOUT_P, dtype, layout="thd", packing="kv", device=device) + elif fn_name == "flash_attn_varlen_qkvpacked_func": + return input_helper(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, CAUSAL, DROPOUT_P, dtype, layout="thd", packing="qkv", device=device) + elif fn_name == "flash_attn_with_kvcache": + return input_helper(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, CAUSAL, DROPOUT_P, dtype, layout="bshd", device=device) + elif fn_name == "flash_attn_fp8_func": + return input_helper(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, CAUSAL, DROPOUT_P, dtype, layout="bshd", device=device) + elif fn_name == "flash_attn_qkvpacked_fp8_func": + return input_helper(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, CAUSAL, DROPOUT_P, dtype, layout="bshd", packing="qkv", device=device) + elif fn_name == "flash_attn_varlen_fp8_func": + return input_helper(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, CAUSAL, DROPOUT_P, dtype, layout="thd", device=device) + elif fn_name == "flash_attn_varlen_qkvpacked_fp8_func": + return input_helper(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, CAUSAL, DROPOUT_P, dtype, layout="thd", packing="qkv", device=device) + else: + valid_fn_names = ", ".join(FUNCTIONS) + raise ValueError(f"{fn_name} should be one of the following functions. {valid_fn_names}") + +def estimate_memory(config): + batch, hq, hk, sq, sk, d_head, causal, dropout = config + memory_estimate = batch * (hq * sq + hk * sk) * d_head * 4 # bytes + return memory_estimate + +def generate_benchmark_configs(is_varlen: bool, packing: Optional[Literal["kv", "qkv"]]): + """ + generates a small number of configs that cover the parameter space well + """ + + # define all parameter options as lists + batch_sizes = [1, 64] + if packing == "qkv": + hq_values = hk_values = [2, 8] + sq_values = sk_values = [256, 8192] + else: + if is_varlen: # make sure the seqlen is greater than the batchsize so that subsequences are greater than 0 + hq_values = [16, 32] # test mqa/gqa + hk_values = [8, 16] + sq_values = [128, 512] + sk_values = [512, 2024] + else: + hq_values = [64, 128] # test mqa/gqa + hk_values = [16, 64] + sq_values = [4, 4096] + sk_values = [4096, 16384] # test large k values for inference perf + d_head_values = [64, 128] + causal_values = [True, False] # most models usual causal True + dropout_values = [0.0, 0.1] + + # generate all fn_configs without inputs + input_configs = [] + + # one big loop to generate configs + for batch in batch_sizes: + for hq in hq_values: + for hk in hk_values: + for sq in sq_values: + for sk in sk_values: + for d_head in d_head_values: + for causal in causal_values: + for dropout in dropout_values: + # filter configs + input_config = (batch, hq, hk, sq, sk, d_head, causal, dropout) + + # skip if memory usage would be too high + if estimate_memory(input_config) > 8 * 1024 * 1024 * 1024: # 8 GB limit + continue + + # we need hq to be a multiple of hk + if hq % hk != 0: + continue + + # for qkvpacked functions, q and k must have same dimensions + if packing == "qkv" and (sq != sk or hq != hk): + continue + + input_configs.append(input_config) + + return input_configs + +def create_benchmark_fn( + flash_attn, + fn_name, + fn_input, + mode: Literal["fwd", "bwd", "full"] +): + if DEBUG: + print("create_benchmark_fn") + print("flash_attn:", flash_attn) + print("fn_name:", fn_name) + print("fn_input:", len(fn_input)) + print("mode:", mode) + + if fn_name == "flash_attn_func": + q, k, v, do, metadata = fn_input + if mode == "fwd": + def flash_attn_bench_fn(): + out, lse, S_dmask = flash_attn.flash_attn_func( + q, + k, + v, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0, + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + return out + elif mode == "bwd": + out, lse, S_dmask = flash_attn.flash_attn_func( + q, + k, + v, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0, + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + def flash_attn_bench_fn(): + dq, dk, dv = torch.autograd.grad(out, (q, k, v), do, retain_graph=True) + return dq, dk, dv + elif mode == "full": + def flash_attn_bench_fn(): + out, lse, S_dmask = flash_attn.flash_attn_func( + q, + k, + v, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0, + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + dq, dk, dv = torch.autograd.grad(out, (q, k, v), do, retain_graph=True) + return dq, dk, dv + else: + raise ValueError(f"Unsupported benchmarking mode: {mode}") + + return flash_attn_bench_fn + + elif fn_name == "flash_attn_kvpacked_func": + q, kv, do, metadata = fn_input + if mode == "fwd": + def flash_attn_kvpacked_bench_fn(): + out, lse, S_dmask = flash_attn.flash_attn_kvpacked_func( + q, + kv, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0, + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + return out + elif mode == "bwd": + out, lse, S_dmask = flash_attn.flash_attn_kvpacked_func( + q, + kv, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0, + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + def flash_attn_kvpacked_bench_fn(): + dq, dkv = torch.autograd.grad(out, (q, kv), do, retain_graph=True) + return dq, dkv + elif mode == "full": + def flash_attn_kvpacked_bench_fn(): + out, lse, S_dmask = flash_attn.flash_attn_kvpacked_func( + q, + kv, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0, + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + dq, dkv = torch.autograd.grad(out, (q, kv), do, retain_graph=True) + return dq, dkv + else: + raise ValueError(f"Unsupported benchmarking mode: {mode}") + + return flash_attn_kvpacked_bench_fn + elif fn_name == "flash_attn_qkvpacked_func": + qkv, do, metadata = fn_input + if mode == "fwd": + def flash_attn_qkvpacked_bench_fn(): + out, lse, S_dmask = flash_attn.flash_attn_qkvpacked_func( + qkv, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0, + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + return out + elif mode == "bwd": + out, lse, S_dmask = flash_attn.flash_attn_qkvpacked_func( + qkv, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0, + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + def flash_attn_qkvpacked_bench_fn(): + dqkv = torch.autograd.grad(out, (qkv), do, retain_graph=True) + return dqkv + elif mode == "full": + def flash_attn_qkvpacked_bench_fn(): + out, lse, S_dmask = flash_attn.flash_attn_qkvpacked_func( + qkv, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0, + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + dqkv = torch.autograd.grad(out, (qkv), do, retain_graph=True) + return dqkv + else: + raise ValueError(f"Unsupported benchmarking mode: {mode}") + + return flash_attn_qkvpacked_bench_fn + elif fn_name == "flash_attn_varlen_func": + q_unpad, k_unpad, v_unpad, do_unpad, metadata = fn_input + if mode == "fwd": + def flash_attn_varlen_bench_fn(): + out_unpad, lse, S_dmask = flash_attn.flash_attn_varlen_func( + q_unpad, + k_unpad, + v_unpad, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0 , + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + return out_unpad + elif mode == "bwd": + out_unpad, lse, S_dmask = flash_attn.flash_attn_varlen_func( + q_unpad, + k_unpad, + v_unpad, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0 , + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + def flash_attn_varlen_bench_fn(): + dq_unpad, dk_unpad, dv_unpad = torch.autograd.grad(out_unpad, (q_unpad, k_unpad, v_unpad), do_unpad, retain_graph=True) + return dq_unpad, dk_unpad, dv_unpad + elif mode == "full": + def flash_attn_varlen_bench_fn(): + out_unpad, lse, S_dmask = flash_attn.flash_attn_varlen_func( + q_unpad, + k_unpad, + v_unpad, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0 , + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + dq_unpad, dk_unpad, dv_unpad = torch.autograd.grad(out_unpad, (q_unpad, k_unpad, v_unpad), do_unpad, retain_graph=True) + return dq_unpad, dk_unpad, dv_unpad + else: + raise ValueError(f"Unsupported benchmarking mode: {mode}") + + return flash_attn_varlen_bench_fn + elif fn_name == "flash_attn_varlen_kvpacked_func": + q_unpad, kv_unpad, do_unpad, metadata = fn_input + if mode == "fwd": + def flash_attn_varlen_kvpacked_bench_fn(): + out_unpad, lse, S_dmask = flash_attn.flash_attn_varlen_kvpacked_func( + q_unpad, + kv_unpad, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0 , + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + return out_unpad + elif mode == "bwd": + out_unpad, lse, S_dmask = flash_attn.flash_attn_varlen_kvpacked_func( + q_unpad, + kv_unpad, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0 , + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + def flash_attn_varlen_kvpacked_bench_fn(): + dq_unpad, dkv_unpad = torch.autograd.grad(out_unpad, (q_unpad, kv_unpad), do_unpad, retain_graph=True) + return dq_unpad, dkv_unpad + elif mode == "full": + def flash_attn_varlen_kvpacked_bench_fn(): + out_unpad, lse, S_dmask = flash_attn.flash_attn_varlen_kvpacked_func( + q_unpad, + kv_unpad, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0 , + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + dq_unpad, dkv_unpad = torch.autograd.grad(out_unpad, (q_unpad, kv_unpad), do_unpad, retain_graph=True) + return dq_unpad, dkv_unpad + else: + raise ValueError(f"Unsupported benchmarking mode: {mode}") + + return flash_attn_varlen_kvpacked_bench_fn + elif fn_name == "flash_attn_varlen_qkvpacked_func": + qkv_unpad, do_unpad, metadata = fn_input + if mode == "fwd": + def flash_attn_varlen_qkvpacked_bench_fn(): + out_unpad, lse, S_dmask = flash_attn.flash_attn_varlen_qkvpacked_func( + qkv_unpad, + metadata.cu_seqlens_q, + metadata.max_seqlens_q, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0 , + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + return out_unpad + elif mode == "bwd": + out_unpad, lse, S_dmask = flash_attn.flash_attn_varlen_qkvpacked_func( + qkv_unpad, + metadata.cu_seqlens_q, + metadata.max_seqlens_q, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0 , + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + def flash_attn_varlen_qkvpacked_bench_fn(): + dqkv_unpad = torch.autograd.grad(out_unpad, (qkv_unpad), do_unpad, retain_graph=True) + return dqkv_unpad + elif mode == "full": + def flash_attn_varlen_qkvpacked_bench_fn(): + out_unpad, lse, S_dmask = flash_attn.flash_attn_varlen_qkvpacked_func( + qkv_unpad, + metadata.cu_seqlens_q, + metadata.max_seqlens_q, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0 , + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + dqkv_unpad = torch.autograd.grad(out_unpad, (qkv_unpad), do_unpad, retain_graph=True) + return dqkv_unpad + else: + raise ValueError(f"Unsupported benchmarking mode: {mode}") + + return flash_attn_varlen_qkvpacked_bench_fn + elif fn_name == "flash_attn_with_kvcache": + q, k_cache, v_cache, _, metadata = fn_input + if mode == "fwd": + def flash_attn_with_kvcache_bench_fn(): + out = flash_attn.flash_attn_with_kvcache( + q, + k_cache, + v_cache, + None, + None, + rotary_cos=None, + rotary_sin=None, + cache_seqlens=None, + cache_batch_idx=None, + cache_leftpad=None, + block_table=None, + causal=metadata.causal, + window_size=(-1, -1), + rotary_interleaved=False, + alibi_slopes=None, + num_splits=0, + ) + return out + else: + raise ValueError(f"Unsupported benchmarking mode: {mode}") + + return flash_attn_with_kvcache_bench_fn + elif fn_name == "flash_attn_fp8_func": + (q, descale_q), (k, descale_k), (v, descale_v), (do, descale_do), metadata = fn_input + if mode == "fwd": + def flash_attn_f8_bench_fn(): + out, lse, S_dmask = flash_attn.flash_attn_fp8_func( + q, + k, + v, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0, + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + return out + elif mode == "bwd": + out, lse, S_dmask = flash_attn.flash_attn_fp8_func( + q, + k, + v, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0, + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + def flash_attn_f8_bench_fn(): + dq, dk, dv = torch.autograd.grad(out, (q, k, v), do, retain_graph=True) + return dq, dk, dv + elif mode == "full": + def flash_attn_f8_bench_fn(): + out, lse, S_dmask = flash_attn.flash_attn_fp8_func( + q, + k, + v, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0, + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + dq, dk, dv = torch.autograd.grad(out, (q, k, v), do, retain_graph=True) + return dq, dk, dv + else: + raise ValueError(f"Unsupported benchmarking mode: {mode}") + + return flash_attn_f8_bench_fn + elif fn_name == "flash_attn_qkvpacked_fp8_func": + qkv, do, metadata = fn_input + if mode == "fwd": + def flash_attn_qkvpacked_fp8_bench_fn(): + out, lse, S_dmask = flash_attn.flash_attn_qkvpacked_fp8_func( + qkv, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0, + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + return out + elif mode == "bwd": + out, lse, S_dmask = flash_attn.flash_attn_qkvpacked_fp8_func( + qkv, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0, + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + def flash_attn_qkvpacked_fp8_bench_fn(): + dqkv = torch.autograd.grad(out, (qkv), do, retain_graph=True) + return dqkv + elif mode == "full": + def flash_attn_qkvpacked_fp8_bench_fn(): + out, lse, S_dmask = flash_attn.flash_attn_qkvpacked_fp8_func( + qkv, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0, + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + dqkv = torch.autograd.grad(out, (qkv), do, retain_graph=True) + return dqkv + else: + raise ValueError(f"Unsupported benchmarking mode: {mode}") + + return flash_attn_qkvpacked_fp8_bench_fn + elif fn_name == "flash_attn_varlen_fp8_func": + (q_unpad, descale_q), (k_unpad, descale_k), (v_unpad, descale_v), (do_unpad, descale_do), metadata = fn_input + if mode == "fwd": + def flash_attn_varlen_fp8_bench_fn(): + out_unpad, lse, S_dmask = flash_attn.flash_attn_varlen_fp8_func( + q_unpad, + k_unpad, + v_unpad, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0 , + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + return out_unpad + elif mode == "bwd": + out_unpad, lse, S_dmask = flash_attn.flash_attn_varlen_fp8_func( + q_unpad, + k_unpad, + v_unpad, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0 , + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + def flash_attn_varlen_fp8_bench_fn(): + dq_unpad, dk_unpad, dv_unpad = torch.autograd.grad(out_unpad, (q_unpad, k_unpad, v_unpad), do_unpad, retain_graph=True) + return dq_unpad, dk_unpad, dv_unpad + elif mode == "full": + def flash_attn_varlen_fp8_bench_fn(): + out_unpad, lse, S_dmask = flash_attn.flash_attn_varlen_fp8_func( + q_unpad, + k_unpad, + v_unpad, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0 , + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + dq_unpad, dk_unpad, dv_unpad = torch.autograd.grad(out_unpad, (q_unpad, k_unpad, v_unpad), do_unpad, retain_graph=True) + return dq_unpad, dk_unpad, dv_unpad + else: + raise ValueError(f"Unsupported benchmarking mode: {mode}") + + return flash_attn_varlen_fp8_bench_fn + elif fn_name == "flash_attn_varlen_qkvpacked_fp8_func": + qkv_unpad, do_unpad, metadata = fn_input + if mode == "fwd": + def flash_attn_varlen_qkvpacked_fp8_bench_fn(): + out_unpad, lse, S_dmask = flash_attn.flash_attn_varlen_qkvpacked_fp8_func( + qkv_unpad, + metadata.cu_seqlens_q, + metadata.max_seqlens_q, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0 , + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + return out_unpad + elif mode == "bwd": + out_unpad, lse, S_dmask = flash_attn.flash_attn_varlen_qkvpacked_fp8_func( + qkv_unpad, + metadata.cu_seqlens_q, + metadata.max_seqlens_q, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0 , + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + def flash_attn_varlen_qkvpacked_fp8_bench_fn(): + dqkv_unpad = torch.autograd.grad(out_unpad, (qkv_unpad), do_unpad, retain_graph=True) + return dqkv_unpad + elif mode == "full": + def flash_attn_varlen_qkvpacked_fp8_bench_fn(): + out_unpad, lse, S_dmask = flash_attn.flash_attn_varlen_qkvpacked_fp8_func( + qkv_unpad, + metadata.cu_seqlens_q, + metadata.max_seqlens_q, + metadata.dropout_p, + causal=metadata.causal, + window_size=(-1, -1), + softcap=0.0 , + alibi_slopes=None, + deterministic=False, + return_attn_probs=True, + ) + dqkv_unpad = torch.autograd.grad(out_unpad, (qkv_unpad), do_unpad, retain_graph=True) + return dqkv_unpad + else: + raise ValueError(f"Unsupported benchmarking mode: {mode}") + + return flash_attn_varlen_qkvpacked_fp8_bench_fn + else: + valid_fn_names = ", ".join(FUNCTIONS) + raise ValueError(f"{fn_name} should be one of the following functions. {valid_fn_names}") + +def get_packing_type(fn_name: str) -> Optional[Literal["kv", "qkv"]]: + if "_kvpacked" in fn_name: + packing = "kv" + elif "_qkvpacked" in fn_name: + packing = "qkv" + else: + packing = None + + return packing + +def load_flash_attn_module(backend: Literal["triton", "ck"], env_configs: Dict = {}, verbose = False): + """ + Load the flash_attn module with the specified backend configuration + """ + + # remove any existing env variables first + for key in ENV_FLAGS: + if key in os.environ: + del os.environ[key] + + # set environment variable for the desired backend + if backend == "triton": + os.environ["FLASH_ATTENTION_TRITON_AMD_ENABLE"] = "TRUE" + os.environ["FLASH_ATTENTION_TRITON_AMD_AUTOTUNE"] = "0" + os.environ["FLASH_ATTENTION_TRITON_AMD_DEBUG"] = "0" + elif backend == "ck": + os.environ["FLASH_ATTENTION_TRITON_AMD_ENABLE"] = "FALSE" + else: + raise ValueError(f"Unknown backend {backend}") + + # add custom env configs + add_env_configs(env_configs) + + if verbose: + print(f"Loading flash_attn module with {backend} backend.") + + # Remove any existing flash_attn modules from sys.modules + for module_name in list(sys.modules.keys()): + if module_name.startswith('flash_attn'): + del sys.modules[module_name] + + # Clear CUDA cache + torch.cuda.empty_cache() + + # Import and return the module + import flash_attn + + return flash_attn + +def add_env_configs(env_config: Dict): + for env_key, env_value in env_config.items(): + if env_key in os.environ: + del os.environ[env_key] # remove previous version so that env key is the latest key added + os.environ[env_key] = env_value + +def run_benchmark(func_config: FunctionConfig, input_configs): + """ + Runs the benchmark for the provided function configuration with the given input configurations. + """ + # print new line to seperate benchmark runs + print() + if DEBUG: + print("func_config:", func_config) + + # extract function configuration parameters + fn_name = func_config.fn_name + mode = func_config.mode + dtype = func_config.dtype + backend = func_config.backend + + # load flash attention module + flash_attn_module = load_flash_attn_module(backend, func_config.env_configs, verbose=True) + + # start timing the benchmark + start_time = time.time() + + # print bench fn + print(f"Benchmarking {func_config} ...") + + # Setup benchmark configurations + bench_configs = [ + triton.testing.Benchmark( + x_names=["BATCH", "HQ", "HK", "N_CTX_Q", "N_CTX_K", "D_HEAD", "CAUSAL", "DROPOUT"], + x_vals=list(input_configs.keys()), + line_arg="provider", + line_vals=["triton"], + line_names=["Time (ms)"], + styles=[("red", "-")], + ylabel="ms", + plot_name=f"benchmark-{func_config}", + args={ + }, + ) + ] + + @triton.testing.perf_report(bench_configs) + def bench_function( + BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, CAUSAL, DROPOUT, provider, device="cuda" + ): + if DEBUG: + print("BATCH:", BATCH) + print("HQ:", HQ) + print("HK:", HK) + print("N_CTX_Q:", N_CTX_Q) + print("N_CTX_Q:", N_CTX_Q) + print("D_HEAD:", D_HEAD) + print("CAUSAL:", CAUSAL) + print("DROPOUT:", DROPOUT) + print("mode:", mode) + print("provider:", provider) + print("device:", device) + fn_input = input_configs[(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, CAUSAL, DROPOUT)] + benchmark_fn = create_benchmark_fn(flash_attn_module, fn_name, fn_input, mode) + + # run the benchmark + ms = triton.testing.do_bench(benchmark_fn, warmup=25, rep=100) + return ms + + df = bench_function.run(save_path=".", print_data=True, return_df=True)[0] + + # set the column name to reflect the function configuration + df = df.rename(columns={"Time (ms)": func_config.column_name()}) + + # calculate and print elapsed time + elapsed_time = time.time() - start_time + print(f"Total time for benchmarking {fn_name} in {mode} mode with {dtype}: {elapsed_time:.2f} seconds") + + return df + +def filter_modes(requested_modes, fn_name, supported_modes_for_fn): + modes_to_run = [] + if requested_modes: + for mode in requested_modes: + if mode in supported_modes_for_fn: + modes_to_run.append(mode) + else: + warning(f"Mode '{mode}' requested but not supported by function '{fn_name}'. Skipping this mode for this function.") + else: + modes_to_run = ["full" if "full" in supported_modes_for_fn else "fwd"] + return modes_to_run + +def get_env_value_combinations(current_backend: Optional[Literal["triton", "ck"]]) -> List[Dict[str, str]]: + # filter environment variations applicable to the current backend + applicable_variations = [ + var_config for var_config in ENV_VARIABLE_CONFIGS + if var_config.backend is None or var_config.backend == current_backend + ] + + if not applicable_variations: + # no applicable variations, return list with empty dict + return [{}] + + # prepare keys and value lists + variation_keys = [v.key for v in applicable_variations] + variation_value_lists = [v.values for v in applicable_variations] + + # generate all combinations as dictionaries directly + env_configs = [] + for value_combination in itertools.product(*variation_value_lists): + env_configs.append(dict(zip(variation_keys, value_combination))) + + return env_configs + +def get_input_config_set(config_type): + if config_type == "llama": + # batch, hq, hk, sq, sk, d_head, causal, dropout + input_configs = [ + # LLaMA 3 8B + (1, 32, 8, 8192, 8192, 128, True, 0.0), + # LLaMA 3 70B + (1, 64, 8, 8192, 8192, 128, True, 0.0), + ] + else: + raise ValueError(f"Unknown input config: {config_type}") + + return input_configs + + +def process_args(): + """ + Parses command-line arguments and returns function configs and input configs. + """ + # create parser + parser = argparse.ArgumentParser( + prog="Benchmark FlashAttention", + allow_abbrev=False, + ) + # functions + parser.add_argument( + "-benchmark_fn", + type=str, + nargs="*", + choices=FUNCTIONS, + required=True, + help=f"Function(s) to benchmark", + ) + parser.add_argument( + "--mode", + type=str, + nargs='*', + choices=VALID_MODES, + default=None, + help=f"Benchmarking mode(s) to run. If omitted, runs all supported modes for each function.", + ) + # config + parser.add_argument("-b", type=int, default=None, help="Batch size") + parser.add_argument("-hq", type=int, default=None, help="Q Number of heads") + parser.add_argument("-hk", type=int, default=None, help="K and V Number of heads") + parser.add_argument("-sq", type=int, default=None, help="Q Sequence Length") + parser.add_argument("-sk", type=int, default=None, help="K and V Sequence Length") + parser.add_argument("-d", type=int, default=None, help="Head Dimension") + parser.add_argument("-causal", action="store_true", default=None, help="Causal") + parser.add_argument("-dropout", type=float, default=None, help="Dropout") + + # parse args + args = parser.parse_args() + + # parse function args + benchmark_fns = args.benchmark_fn + requested_modes = args.mode + + # fenerate function configurations and input configurations separately + all_function_configs = [] + all_input_configs = {} # Maps function config -> input configs + for fn_name in benchmark_fns: + is_varlen, is_fp8, packing, supported_dtypes, supported_backends, supported_modes_for_fn, supported_env_configs, device = get_fn_params(fn_name) + + # Generate or use custom input configurations + if args.b or args.hq or args.hk or args.sq or args.sk or args.d: + assert args.b and args.hq and args.sq and args.d, ( + "if custom config is specified, please provide at least batch, number of Q heads, Q sequence length, and head size." + ) + + batch = args.b + hq = args.hq + hk = args.hk if args.hk is not None else args.hq + sq = args.sq + sk = args.sk if args.sk is not None else args.sq + d_head = args.d + causal = args.causal if args.causal is not None else False + dropout = args.dropout if args.dropout is not None else 0.0 + input_configs = [(batch, hq, hk, sq, sk, d_head, causal, dropout)] + else: + if True: + input_configs = get_input_config_set("llama") + else: + input_configs = generate_benchmark_configs(is_varlen, packing) + + # filter by mode + modes_to_run = filter_modes(requested_modes, fn_name, supported_modes_for_fn) + if not modes_to_run: + warning(f"No valid modes to run for function '{fn_name}' based on request and function support. Skipping this function.") + continue + + # create a function config for each backend and dtype combination + for backend in supported_backends: + for dtype in supported_dtypes: + for mode in modes_to_run: + for env_config in supported_env_configs[backend]: + func_config = FunctionConfig(fn_name, mode, dtype, backend, env_config) + all_function_configs.append(func_config) + + # Generate inputs for this function configuration + fn_inputs = {} + for input_config in input_configs: + fn_inputs[input_config] = generate_fn_inputs(fn_name, *input_config, dtype, device) + + all_input_configs[func_config] = fn_inputs + + return all_function_configs, all_input_configs + +def check_environment_variables(): + for key in ENV_FLAGS: + if key in os.environ: + raise ValueError(f"Running with {key} environment variable is not recommended for the benching script. Use --help to see how to use the benching script.") + +def main(): + """ + Main function to run benchmarks. + """ + # check environment variables + check_environment_variables() + + # start timing the entire benchmarking process + total_start_time = time.time() + + # process args to get function configs and input configs + function_configs, all_input_configs = process_args() + + # Check if we have multiple function configurations + has_multiple_func_configs = len(function_configs) > 1 + combined_df = None + + # run benchmarks for each function configuration + for func_config in function_configs: + # run benchmark with the input configs for this function config + input_configs = all_input_configs[func_config] + df = run_benchmark(func_config, input_configs) + + # Define the columns that represent input configurations + input_config_cols = ["BATCH", "HQ", "HK", "N_CTX_Q", "N_CTX_K", "D_HEAD", "CAUSAL", "DROPOUT"] + + # merge into one final dataframe + if combined_df is None: + combined_df = df + else: + # Ensure we're joining on input configuration columns + combined_df = combined_df.merge(df, on=input_config_cols, how="outer") + + + # print new line to seperate the combined data information from the benchmark specific information + print() + + # print total time for all benchmarks + total_elapsed_time = time.time() - total_start_time + print(f"Total time for all benchmarks: {total_elapsed_time:.2f} seconds") + + # save combined data and make comparisons if we have multiple function configs + if has_multiple_func_configs: + if len(function_configs) == 2: + func1 = function_configs[0] + func2 = function_configs[1] + + # construct column names for the timing results + col1 = func1.column_name() + col2 = func2.column_name() + + # Check if we're comparing triton vs ck (in either order) + is_triton_vs_ck = ( + (func1.backend == "triton" and func2.backend == "ck") or + (func1.backend == "ck" and func2.backend == "triton") + ) + + # For triton vs ck comparisons + if is_triton_vs_ck: + # For triton vs ck comparisons, always make triton the baseline + if func1.backend == "triton" and func2.backend == "ck": + triton_col = col1 + ck_col = col2 + ratio_col = f"ck_to_triton_ratio" + else: + triton_col = col2 + ck_col = col1 + ratio_col = f"ck_to_triton_ratio" + + # Calculate ratio: ck_time / triton_time (values > 1 mean triton is faster) + combined_df[ratio_col] = combined_df[ck_col] / combined_df[triton_col] + + # print explanation + print(f"Comparison Results (triton vs ck):") + print(f"Ratio values: values > 1 mean triton is faster (by that factor), values < 1 mean ck is faster") + elif False: + # For other comparisons, use the standard approach + ratio_col = f"{func1}_to_{func2}_ratio" + + # Calculate the ratio + combined_df[ratio_col] = combined_df[col2] / combined_df[col1] + + # print explanation + print(f"Comparison Results ({func1} vs {func2}):") + print(f"Ratio values: values > 1 mean {func1} is faster than {func2} (by that factor), values < 1 mean slower") + + print(f"Combined data:") + print(combined_df) + + # save csv & markdown + combined_filename = f"benchmark_combined" + combined_df.to_csv(f"{combined_filename}.csv", index=False) + with open(f"{combined_filename}.md", 'w') as f: + f.write(combined_df.to_markdown(index=False, floatfmt=".2f")) + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bwd_prefill.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bwd_prefill.py new file mode 100644 index 0000000000000000000000000000000000000000..44e2c294b0dbf6af0f3257edccb78af0e0addc22 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bwd_prefill.py @@ -0,0 +1,814 @@ +from typing import Literal, Optional +import torch +import triton +import triton.language as tl +from .utils import DEBUG, DROPOUT_USE_PYTORCH, DROPOUT_DUMP, compute_fp8_scaling_factors, get_shapes_from_layout, get_strides_from_layout, is_fp8, write_dropout_mask, create_dropout_mask + +# TODO: move this into utils.py so it's shared among kernels +# NOTE: triton fails to import tl.constexprs so create them here for the file +tl_DROPOUT_USE_PYTORCH: tl.constexpr = triton.language.constexpr(DROPOUT_USE_PYTORCH) +tl_DROPOUT_DUMP: tl.constexpr = triton.language.constexpr(DROPOUT_DUMP) + +@triton.jit +def _bwd_preprocess( + Out, + DO, + Delta, + stride_oz, stride_oh, stride_om, stride_ok, + stride_doz, stride_doh, stride_dom, stride_dok, + stride_deltaz, stride_deltah, stride_deltam, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + DESCALE_do, + BLOCK_M: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + ACTUAL_BLOCK_DMODEL: tl.constexpr, + N_CTX_Q: tl.constexpr, + Z: tl.constexpr, + H: tl.constexpr, + IS_VARLEN: tl.constexpr, + IS_FP8: tl.constexpr, +): + pid_bh = tl.program_id(0) + pid_m = tl.program_id(1) + + # Compute batch and head indices + off_z = pid_bh // H + off_h = pid_bh % H + + if IS_VARLEN: + # Compute sequence lengths for the current batch + q_start = tl.load(cu_seqlens_q + off_z) + q_end = tl.load(cu_seqlens_q + off_z + 1) + k_start = tl.load(cu_seqlens_k + off_z) + k_end = tl.load(cu_seqlens_k + off_z + 1) + + # Compute actual sequence lengths + N_CTX_Q = q_end - q_start + N_CTX_K = k_end - k_start + else: + q_start = 0 + k_start = 0 + N_CTX_Q = max_seqlen_q + N_CTX_K = max_seqlen_k + + off_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + off_d = tl.arange(0, BLOCK_DMODEL) + + # create masks + mask_m = off_m < N_CTX_Q + mask_d = off_d < ACTUAL_BLOCK_DMODEL + + # compute offsets + o_offset = Out + off_z * stride_oz + off_h * stride_oh + q_start * stride_om + do_offset = DO + off_z * stride_oz + off_h * stride_oh + q_start * stride_om + + # compute pointers + out_ptrs = o_offset + off_m[:, None] * stride_om + off_d[None, :] * stride_ok + do_ptrs = do_offset + off_m[:, None] * stride_dom + off_d[None, :] * stride_dok + + # load + o = tl.load(out_ptrs, mask=mask_m[:, None] & mask_d[None, :], other=0.0) + do = tl.load(do_ptrs, mask=mask_m[:, None] & mask_d[None, :], other=0.0) + + # compute delta + if IS_FP8: + stride_descale_q_z = H + descale_do = tl.load(DESCALE_do + off_z * stride_descale_q_z + off_h) + + # NOTE: do is scaled into the fp8 range and o is in fp8 but should be in the same scale as fp32 + delta = tl.sum(o.to(tl.float32) * (do.to(tl.float32) * descale_do), axis=1) + else: + delta = tl.sum(o.to(tl.float32) * do.to(tl.float32), axis=1) + + # write-back delta + delta_offset = Delta + off_z * stride_deltaz + off_h * stride_deltah + q_start * stride_deltam + delta_ptrs = delta_offset + off_m * stride_deltam + tl.store(delta_ptrs, delta, mask=mask_m) + + +@triton.jit +def _bwd_kernel_one_col_block( + Q, + K, + V, + sm_scale, + Out, + DO, + DQ, + DK, + DV, + L, + D, + q_offset, + k_offset, + v_offset, + do_offset, + dq_offset, + dk_offset, + dv_offset, + l_offset, + delta_offset, + dropout_offset, + stride_dq_all, + stride_qz, + stride_qh, + stride_qm, + stride_qk, + stride_kz, + stride_kh, + stride_kn, + stride_kk, + stride_vz, + stride_vh, + stride_vn, + stride_vk, + stride_deltaz, + stride_deltah, + stride_deltam, + stride_dropoutz, stride_dropouth, stride_dropoutm, stride_dropoutn, + N_CTX_Q, + N_CTX_K, + start_n, + num_block_m, + num_block_n, + dropout_p, + philox_seed, + batch_philox_offset, + descale_q, + descale_k, + descale_v, + descale_do, + BLOCK_M: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + ACTUAL_BLOCK_DMODEL: tl.constexpr, + BLOCK_N: tl.constexpr, + SEQUENCE_PARALLEL: tl.constexpr, + CAUSAL: tl.constexpr, + DROPOUT: tl.constexpr, + USE_EXP2: tl.constexpr, + GROUP_SIZE: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, +): + if CAUSAL: + # TODO: Causal can skip more blocks with something like lo = start_m * BLOCK_M + lo = 0 + else: + lo = 0 + + # initialize col and head offsets + offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N) + offs_d = tl.arange(0, BLOCK_DMODEL) + + # masks + mask_n = offs_n < N_CTX_K + mask_d = offs_d < ACTUAL_BLOCK_DMODEL + kv_mask = mask_n[:, None] & mask_d[None, :] + + + # initialize grad accumulators + dv = tl.zeros([BLOCK_N, BLOCK_DMODEL], dtype=tl.float32) + dk = tl.zeros([BLOCK_N, BLOCK_DMODEL], dtype=tl.float32) + + # load k and v once per column block + k_ptrs = k_offset + offs_n[:, None] * stride_kn + offs_d[None, :] * stride_kk + v_ptrs = v_offset + offs_n[:, None] * stride_vn + offs_d[None, :] * stride_vk + k = tl.load(k_ptrs, mask=kv_mask, other=0.0) + kT = tl.trans(k) + vT = tl.trans(tl.load(v_ptrs, mask=kv_mask, other=0.0)) + + # loop over rows + for start_m in range(lo, num_block_m): + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + q_ptrs = q_offset + offs_m[:, None] * stride_qm + offs_d[None, :] * stride_qk + dq_ptrs = dq_offset + offs_m[:, None] * stride_qm + offs_d[None, :] * stride_qk + do_ptrs = do_offset + offs_m[:, None] * stride_qm + offs_d[None, :] * stride_qk + + # update mask as row block changes + mask_m = offs_m < N_CTX_Q + q_mask = mask_m[:, None] & mask_d[None, :] + + # load q, k, v, do on-chip + q = tl.load(q_ptrs, mask=q_mask, other=0.0) + do = tl.load(do_ptrs, mask=q_mask, other=0.0) + + # recompute p = softmax(qk, dim=-1).T + qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) + if IS_FP8: + qk += (tl.dot(q, kT) * descale_q * descale_k) + else: + qk += tl.dot(q, kT) + + if CAUSAL: + col_offset = N_CTX_Q - N_CTX_K + causal_mask = offs_m[:, None] >= (col_offset + offs_n[None, :]) + qk = tl.where(causal_mask, qk, float("-inf")) + + l_ptrs = l_offset + offs_m * stride_deltam + l_i = tl.load(l_ptrs, mask=mask_m) + + # compute p + if USE_EXP2: + RCP_LN2: tl.constexpr = 1.4426950408889634 + qk *= sm_scale * RCP_LN2 + l_i *= RCP_LN2 + p = tl.math.exp2(qk - l_i[:, None]) + else: + qk *= sm_scale + p = tl.math.exp(qk - l_i[:, None]) + + # mask block in the cases where the data is smaller the block size + p_mask = mask_m[:, None] & mask_n[None, :] + p = tl.where(p_mask, p, 0.0) + + if DROPOUT: + # NOTE: must create a new var p_drop to prevent p (which is used later to compute ds) from changing + philox_offset = batch_philox_offset + offs_m[:, None] * stride_dropoutm + offs_n[None, :] * stride_dropoutn + # print("philox_seed:", philox_seed) + # print("philox_offset:", philox_offset) + if tl_DROPOUT_USE_PYTORCH: + dropout_ptrs = dropout_offset + offs_m[:, None] * stride_dropoutm + offs_n[None, :] * stride_dropoutn + dropout_mask = tl.load(dropout_ptrs, mask=p_mask) + else: + rand_vals = tl.rand(philox_seed, philox_offset) + dropout_mask = rand_vals > dropout_p + dropout_scale = 1/ (1 - dropout_p) + + if tl_DROPOUT_DUMP: + dropout_ptrs = dropout_offset + offs_m[:, None] * stride_dropoutm + offs_n[None, :] * stride_dropoutn + tl.store(dropout_ptrs, dropout_mask, mask=p_mask) + + # apply dropout mask + p_drop = tl.where(dropout_mask, p, 0.0) + p_drop_scaled = p_drop * dropout_scale + + # compute dv + if IS_FP8: + scale_p_dropout, descale_p_dropout = compute_fp8_scaling_factors(p_drop_scaled, FP8_MAX) + dv += (tl.dot(tl.trans(p_drop_scaled * scale_p_dropout).to(do.type.element_ty), do) * descale_p_dropout * descale_do) + else: + dv += tl.dot(tl.trans(p_drop_scaled).to(do.type.element_ty), do) + + # compute dp + if IS_FP8: + dp_drop_scaled = (tl.dot(do, vT) * descale_do * descale_v) + else: + dp_drop_scaled = tl.dot(do, vT) + dp = tl.where(dropout_mask, dp_drop_scaled, 0.0) * dropout_scale + else: + + # compute dv + if IS_FP8: + scale_p, descale_p = compute_fp8_scaling_factors(p, FP8_MAX) + dv += (tl.dot(tl.trans(p * scale_p).to(do.type.element_ty), do) * descale_p * descale_do) + else: + dv += tl.dot(tl.trans(p).to(do.type.element_ty), do) + + # compute dp + if IS_FP8: + dp = (tl.dot(do, vT) * descale_do * descale_v) + else: + dp = tl.dot(do, vT) + + + # load delta + delta_ptrs = delta_offset + offs_m * stride_deltam + delta_i = tl.load(delta_ptrs, mask=mask_m) + + # compute ds + dscores_scaled = (p * (dp - delta_i[:, None])) + ds = dscores_scaled * sm_scale + ds = tl.where(p_mask, ds, 0.0) + + # compute descale_ds + if IS_FP8: + scale_ds, descale_ds = compute_fp8_scaling_factors(ds, FP8_MAX) + else: + scale_ds, descale_ds = 1.0, 1.0 + + # compute dk + if IS_FP8: + dk += (tl.dot(tl.trans(ds * scale_ds).to(q.type.element_ty), q) * descale_ds * descale_q) + else: + dk += tl.dot(tl.trans(ds).to(q.type.element_ty), q) + + # compute dq + if SEQUENCE_PARALLEL: + if IS_FP8: + dq = (tl.dot((ds * scale_ds).to(k.type.element_ty), k) * descale_ds * descale_k) + else: + dq = tl.dot(ds.to(k.type.element_ty), k) + else: + dq = tl.load(dq_ptrs, mask=q_mask, other=0.0) + if IS_FP8: + dq += (tl.dot((ds * scale_ds).to(k.type.element_ty), k) * descale_ds * descale_k) + else: + dq += tl.dot(ds.to(k.type.element_ty), k) + tl.store(dq_ptrs, dq.to(Q.dtype.element_ty), mask=q_mask) + + # write-back dv and dk + dk_ptrs = dk_offset + offs_n[:, None] * stride_kn + offs_d[None, :] * stride_kk + dv_ptrs = dv_offset + offs_n[:, None] * stride_vn + offs_d[None, :] * stride_vk + + # write-back + if GROUP_SIZE != 1: + # use atomic_add to properly accumulate gradients from multiple query heads + tl.atomic_add(dk_ptrs, dk.to(K.dtype.element_ty), mask=kv_mask) + tl.atomic_add(dv_ptrs, dv.to(V.dtype.element_ty), mask=kv_mask) + else: + tl.store(dk_ptrs, dk.to(K.dtype.element_ty), mask=kv_mask) + tl.store(dv_ptrs, dv.to(V.dtype.element_ty), mask=kv_mask) + +@triton.jit +def _bwd_kernel( + Q, + K, + V, + sm_scale, + Out, + DO, + DQ, + DK, + DV, + L, + Delta, + Dropout_mask, + DESCALE_q, + DESCALE_k, + DESCALE_v, + DESCALE_do, + stride_dq_all, + stride_qz, + stride_qh, + stride_qm, + stride_qk, + stride_kz, + stride_kh, + stride_kn, + stride_kk, + stride_vz, + stride_vh, + stride_vn, + stride_vk, + stride_deltaz, + stride_deltah, + stride_deltam, + stride_dropoutz, stride_dropouth, stride_dropoutm, stride_dropoutn, + Z, + HQ, + HK, + num_block_m, + num_block_n, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + philox_seed, + philox_offset_base, + BLOCK_M: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + ACTUAL_BLOCK_DMODEL: tl.constexpr, + BLOCK_N: tl.constexpr, + SEQUENCE_PARALLEL: tl.constexpr, + CAUSAL: tl.constexpr, + DROPOUT: tl.constexpr, + USE_EXP2: tl.constexpr, + IS_VARLEN: tl.constexpr, + GROUP_SIZE: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, +): + # program ids + off_zh = tl.program_id(0) + if SEQUENCE_PARALLEL: + start_n = tl.program_id(1) + off_z = off_zh // HQ + off_hq = off_zh % HQ + + # check if GQA/MQA + if GROUP_SIZE != 1: + off_hk = off_hq // GROUP_SIZE + else: + off_hk = off_hq + + if IS_VARLEN: + # Compute sequence lengths for the current batch + q_start = tl.load(cu_seqlens_q + off_z) + q_end = tl.load(cu_seqlens_q + off_z + 1) + k_start = tl.load(cu_seqlens_k + off_z) + k_end = tl.load(cu_seqlens_k + off_z + 1) + + # Compute actual sequence lengths + N_CTX_Q = q_end - q_start + N_CTX_K = k_end - k_start + else: + q_start = 0 + k_start = 0 + N_CTX_Q = max_seqlen_q + N_CTX_K = max_seqlen_k + + # input tensor offsets + q_offset = Q + off_z * stride_qz + off_hq * stride_qh + q_start * stride_qm + k_offset = K + off_z * stride_kz + off_hk * stride_kh + k_start * stride_kn + v_offset = V + off_z * stride_vz + off_hk * stride_vh + k_start * stride_vn + do_offset = DO + off_z * stride_qz + off_hq * stride_qh + q_start * stride_qm + l_offset = L + off_z * stride_deltaz + off_hq * stride_deltah + q_start * stride_deltam + delta_offset = Delta + off_z * stride_deltaz + off_hq * stride_deltah + q_start * stride_deltam + + if DROPOUT: + batch_philox_offset = philox_offset_base + off_z * stride_dropoutz + off_hq * stride_dropouth #+ q_start * stride_dropoutm + dropout_offset = Dropout_mask + off_z * stride_dropoutz + off_hq * stride_dropouth #+ q_start * stride_dropoutm + else: + batch_philox_offset = 0 + dropout_offset = 0 + + if IS_FP8: + stride_descale_q_z = HQ + stride_descale_kv_z = HK + + descale_q = tl.load(DESCALE_q + off_z * stride_descale_q_z + off_hq) + descale_k = tl.load(DESCALE_k + off_z * stride_descale_kv_z + off_hk) + descale_v = tl.load(DESCALE_v + off_z * stride_descale_kv_z + off_hk) + descale_do = tl.load(DESCALE_do + off_z * stride_descale_q_z + off_hq) + else: + descale_q, descale_k, descale_v, descale_do = 1.0, 1.0, 1.0, 1.0 + + # output tensor offsets + dk_offset = DK + off_z * stride_kz + off_hk * stride_kh + k_start * stride_kn + dv_offset = DV + off_z * stride_vz + off_hk * stride_vh + k_start * stride_vn + if SEQUENCE_PARALLEL: + dq_offset = DQ + start_n * stride_dq_all + off_z * stride_qz + off_hq * stride_qh + q_start * stride_qm + else: + dq_offset = DQ + off_z * stride_qz + off_hq * stride_qh + q_start * stride_qm + + # inner loop + if SEQUENCE_PARALLEL: + _bwd_kernel_one_col_block( + Q, + K, + V, + sm_scale, + Out, + DO, + DQ, + DK, + DV, + L, + Delta, + q_offset, + k_offset, + v_offset, + do_offset, + dq_offset, + dk_offset, + dv_offset, + l_offset, + delta_offset, + dropout_offset, + stride_dq_all, + stride_qz, + stride_qh, + stride_qm, + stride_qk, + stride_kz, + stride_kh, + stride_kn, + stride_kk, + stride_vz, + stride_vh, + stride_vn, + stride_vk, + stride_deltaz, + stride_deltah, + stride_deltam, + stride_dropoutz, stride_dropouth, stride_dropoutm, stride_dropoutn, + N_CTX_Q, + N_CTX_K, + start_n, + num_block_m, + num_block_n, + dropout_p, + philox_seed, + batch_philox_offset, + descale_q, + descale_k, + descale_v, + descale_do, + BLOCK_M=BLOCK_M, + BLOCK_DMODEL=BLOCK_DMODEL, + ACTUAL_BLOCK_DMODEL=ACTUAL_BLOCK_DMODEL, + BLOCK_N=BLOCK_N, + SEQUENCE_PARALLEL=SEQUENCE_PARALLEL, + CAUSAL=CAUSAL, + DROPOUT=DROPOUT, + USE_EXP2=USE_EXP2, + GROUP_SIZE=GROUP_SIZE, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX + ) + else: + for start_n in range(0, num_block_n): + _bwd_kernel_one_col_block( + Q, + K, + V, + sm_scale, + Out, + DO, + DQ, + DK, + DV, + L, + Delta, + q_offset, + k_offset, + v_offset, + do_offset, + dq_offset, + dk_offset, + dv_offset, + l_offset, + delta_offset, + dropout_offset, + stride_dq_all, + stride_qz, + stride_qh, + stride_qm, + stride_qk, + stride_kz, + stride_kh, + stride_kn, + stride_kk, + stride_vz, + stride_vh, + stride_vn, + stride_vk, + stride_deltaz, + stride_deltah, + stride_deltam, + stride_dropoutz, stride_dropouth, stride_dropoutm, stride_dropoutn, + N_CTX_Q, + N_CTX_K, + start_n, + num_block_m, + num_block_n, + dropout_p, + philox_seed, + batch_philox_offset, + descale_q, + descale_k, + descale_v, + descale_do, + BLOCK_M=BLOCK_M, + BLOCK_DMODEL=BLOCK_DMODEL, + ACTUAL_BLOCK_DMODEL=ACTUAL_BLOCK_DMODEL, + BLOCK_N=BLOCK_N, + SEQUENCE_PARALLEL=SEQUENCE_PARALLEL, + CAUSAL=CAUSAL, + DROPOUT=DROPOUT, + USE_EXP2=USE_EXP2, + GROUP_SIZE=GROUP_SIZE, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX + ) + + +# NOTE: smaller blocks have lower accuracy. more accumulation error probably 128 * 128 seems good but leads to oom. 64 * 64 has accumulation errors but no oom. +def attention_prefill_backward_triton_impl( + do: torch.Tensor, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + o: torch.Tensor, + softmax_lse: torch.Tensor, + dq: torch.Tensor, + dk: torch.Tensor, + dv: torch.Tensor, + sm_scale: float, + alibi_slopes: Optional[torch.Tensor], + causal: bool, + layout: Literal["bshd", "bhsd", "thd"], + cu_seqlens_q: Optional[torch.Tensor], + cu_seqlens_k: Optional[torch.Tensor], + max_seqlen_q: int, + max_seqlen_k: int, + dropout_p: float, + philox_seed: Optional[int], + philox_offset: Optional[int], + use_exp2: bool, + sequence_parallel: bool = True, + # fp8 + descale_q: Optional[torch.Tensor] = None, + descale_k: Optional[torch.Tensor] = None, + descale_v: Optional[torch.Tensor] = None, + descale_do: Optional[torch.Tensor] = None, +): + if DEBUG: + print() + print("attention_prefill_backward_triton_impl") + print("do:", do, do.shape) + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("o:", o, o.shape) + print("softmax_lse:", softmax_lse, softmax_lse.shape) + print("dq:", dq, dq.shape if dq is not None else None) + print("dk:", dk, dk.shape if dk is not None else None) + print("dv:", dv, dv.shape if dv is not None else None) + print("sm_scale:", sm_scale) + print("alibi_slopes:", alibi_slopes) + print("causal:", causal) + print("layout:", layout) + print("cu_seqlens_q:", cu_seqlens_q) + print("cu_seqlens_k:", cu_seqlens_k) + print("max_seqlen_q:", max_seqlen_q) + print("max_seqlen_k:", max_seqlen_k) + print("dropout_p:", dropout_p) + print("philox_seed:", philox_seed) + print("philox_offset:", philox_offset) + print("use_exp2:", use_exp2) + print("sequence_parallel:", sequence_parallel) + print("descale_q:", descale_q) + print("descale_k:", descale_k) + print("descale_v:", descale_v) + print("descale_do:", descale_do) + + IS_FP8 = is_fp8(q) + if IS_FP8: + FP8_MAX=torch.finfo(q.dtype).max + else: + FP8_MAX=None + + # make contiguous + q = q.contiguous() + k = k.contiguous() + v = v.contiguous() + softmax_lse = softmax_lse.contiguous() + + # get strides and shape + batch, nheads_q, nheads_k, head_size, max_seqlen_q, max_seqlen_k = get_shapes_from_layout(q, k, layout, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k) + q_strides, k_strides, v_strides, o_strides = get_strides_from_layout(q, k, v, o, layout) + stride_qz, stride_qh, stride_qm, stride_qk = q_strides + stride_kz, stride_kh, stride_kn, stride_kk = k_strides + stride_vz, stride_vh, stride_vn, stride_vk = v_strides + stride_oz, stride_oh, stride_om, stride_ok = o_strides + is_varlen = layout == "thd" + group_size = nheads_q // nheads_k + use_dropout = (dropout_p > 0.0) + + # FIXME: some configs lead to oom for some reason when using 64 x 64 blocks + if max_seqlen_q <= 32 or max_seqlen_k <= 32: + BLOCK_M = 32 + BLOCK_N = 32 + else: + BLOCK_M = 64 + BLOCK_N = 64 + + if DEBUG: + print("BLOCK_M:", BLOCK_M) + print("BLOCK_N:", BLOCK_N) + + num_warps = 4 # NOTE: original is 8. changing it to 1 caused issues be careful + num_stages = 1 + waves_per_eu = 1 + + # divide up the problem + num_blocks_m = triton.cdiv(max_seqlen_q, BLOCK_M) + num_blocks_n = triton.cdiv(max_seqlen_k, BLOCK_N) + + # get closest power of 2 over or equal to 32. + padded_d_model = 1 << (head_size - 1).bit_length() + padded_d_model = max(padded_d_model, 16) + BLOCK_DMODEL = padded_d_model + ACTUAL_BLOCK_DMODEL = head_size + + do = do.contiguous() + + # deal with dq + if sequence_parallel: + dq = dq.unsqueeze(0).repeat(num_blocks_n, *([1] * len(q.shape))) # we do repeat instead of expand because we need to write data so views are not enough + stride_dq_all = dq.stride()[0] + + # assert contiguous + assert do.is_contiguous() + assert q.is_contiguous() + assert k.is_contiguous() + assert v.is_contiguous() + assert o.is_contiguous() + assert softmax_lse.is_contiguous() + + # init delta + delta = torch.zeros_like(softmax_lse) + if is_varlen: + stride_deltam, stride_deltah = delta.stride() + stride_deltaz = 0 + else: + stride_deltaz, stride_deltah, stride_deltam = delta.stride() + + # dropout mask tensor for debugging. We dump the dropout mask created in the kernel for testing + if use_dropout: + if DROPOUT_USE_PYTORCH: + dropout_mask = create_dropout_mask(dropout_p, (batch, nheads_q, max_seqlen_q, max_seqlen_k), seed = philox_seed) + else: + dropout_mask = torch.zeros((batch, nheads_q, max_seqlen_q, max_seqlen_k), device=q.device, + dtype=torch.float32) + stride_dropoutz, stride_dropouth, stride_dropoutm, stride_dropoutn = (dropout_mask.stride(0), dropout_mask.stride(1), dropout_mask.stride(2), dropout_mask.stride(3)) + else: + dropout_mask = None + stride_dropoutz, stride_dropouth, stride_dropoutm, stride_dropoutn = (0, 0 , 0 , 0) + + + _bwd_preprocess[(batch * nheads_q, num_blocks_m)]( + o, + do, + delta, + stride_oz, stride_oh, stride_om, stride_ok, + stride_oz, stride_oh, stride_om, stride_ok, # FIXME: don't share strides with derivatives this was causing a lot of issues + stride_deltaz, stride_deltah, stride_deltam, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + descale_do, + BLOCK_M=BLOCK_M, + BLOCK_DMODEL=BLOCK_DMODEL, + ACTUAL_BLOCK_DMODEL=ACTUAL_BLOCK_DMODEL, + N_CTX_Q=max_seqlen_q, + Z=batch, + H=nheads_q, + IS_VARLEN=is_varlen, + IS_FP8=IS_FP8 + ) + + if DEBUG: + print("delta:", delta, delta.shape) + print("group_size:", group_size) + + _bwd_kernel[(batch * nheads_q, num_blocks_n if sequence_parallel else 1)]( + q, + k, + v, + sm_scale, + o, + do, + dq, + dk, + dv, + softmax_lse, + delta, + dropout_mask, + descale_q, + descale_k, + descale_v, + descale_do, + stride_dq_all, + stride_qz, stride_qh, stride_qm, stride_qk, # FIXME: don't share strides with derivatives this was causing a lot of issues + stride_kz, stride_kh, stride_kn, stride_kk, + stride_vz, stride_vh, stride_vn, stride_vk, + stride_deltaz, stride_deltah, stride_deltam, + stride_dropoutz, stride_dropouth, stride_dropoutm, stride_dropoutn, + batch, + nheads_q, + nheads_k, + num_blocks_m, + num_blocks_n, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, philox_seed, philox_offset, + BLOCK_M=BLOCK_M, + BLOCK_N=BLOCK_N, + BLOCK_DMODEL=BLOCK_DMODEL, + ACTUAL_BLOCK_DMODEL=ACTUAL_BLOCK_DMODEL, + SEQUENCE_PARALLEL=sequence_parallel, + CAUSAL=causal, + DROPOUT=use_dropout, + USE_EXP2=use_exp2, + num_warps=num_warps, + num_stages=num_stages, + waves_per_eu = waves_per_eu, + IS_VARLEN=is_varlen, + GROUP_SIZE=group_size, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX + ) + + if sequence_parallel: + dq = dq.sum(dim=0) + + if DEBUG: + print("attention_prefill_backward_triton_impl outputs") + print("dv:", dv, dv.shape) + print("dk:", dk, dk.shape) + print("dq:", dq, dq.shape) + if use_dropout: + print("dropout_mask:", dropout_mask, dropout_mask.shape if dropout_mask is not None else None) + print("dropout_fraction bwd:", 1.0 - (dropout_mask.sum()/ dropout_mask.numel()).item()) + write_dropout_mask(dropout_mask, "dropout_mask_bwd") + + return delta diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bwd_prefill_fused.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bwd_prefill_fused.py new file mode 100644 index 0000000000000000000000000000000000000000..3c018be4fa08352cc6736b21742d2174e706160b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bwd_prefill_fused.py @@ -0,0 +1,3266 @@ +import torch +import triton +import triton.language as tl + +from typing import Optional, Tuple + +@triton.jit +def cdiv_fn(x, y): + return (x + y - 1) // y + +@triton.jit +def compute_fp8_scaling_factors(x, fp8_max: tl.constexpr): + # compute fp8 scaling and descaling factor for a block + x_amax = tl.max(tl.abs(x)) # NOTE: abs deals with negative values + x_amax = tl.where(x_amax <= 1e-9, 1e-9, x_amax) + scale_x = fp8_max / x_amax + descale_x = x_amax / fp8_max + return scale_x, descale_x + +def is_fp8(x): + if x.dtype in {torch.float8_e4m3fnuz, torch.float8_e4m3fn, torch.float8_e5m2, torch.float8_e5m2fnuz}: + if arch_supports_fp8(): + return True + else: + raise RuntimeError("This device does not support fp8") + else: + return False + + +def cast_to_fp8( + x: torch.Tensor, + fp8_dtype, + layout, + clamp_val=1e-9, +): + if len(x.shape) != 4: + raise ValueError(f"'bshd' tensor should have shape [batch, seqlen, heads, dim], got {x.shape}") + reduce_dims = (1, 3) # seq_len and dim dimensions + + # Compute the absolute max along reduce_dims, clamped to avoid 0-scale + x_abs_max = x.abs().amax(dim=reduce_dims) + x_abs_max = torch.maximum(x_abs_max, x.new_tensor(clamp_val)) + + # Unsqueeze back to a shape suitable for broadcast + unsqueeze_dims = sorted(reduce_dims) + for d in unsqueeze_dims: + x_abs_max = x_abs_max.unsqueeze(d) + + # compute scale and descale + fp8_max = torch.finfo(fp8_dtype).max + scale = fp8_max / x_abs_max + descale_factor = x_abs_max / fp8_max + + # cast to FP8, optionally setting requires_grad + x_fp8 = (x * scale).to(fp8_dtype) + + return x_fp8, descale_factor + + +def cast_varlen_to_fp8( + x: torch.Tensor, + fp8_dtype: torch.dtype, + cu_seqlens, + clamp_val: float = 1e-9, +) -> tuple[torch.Tensor, torch.Tensor]: + # validate tensor shape + if len(x.shape) != 3: + raise ValueError(f"tensor should have shape [total_seqlen, heads, dim], got {x.shape}") + num_heads = x.shape[1] + + # Get batch size from cu_seqlens + batch = cu_seqlens.shape[0] - 1 + fp8_max = torch.finfo(fp8_dtype).max + + # Compute scale and descale factors per sequence + x_fp8 = torch.zeros_like(x, dtype=fp8_dtype) + descale_factors = torch.zeros((batch, num_heads), device=x.device, dtype=torch.float32) + + for i in range(batch): + start = cu_seqlens[i] + end = cu_seqlens[i + 1] + x_slice = x[start:end] # Slice for current sequence + + # Standard tensor (0: seq_len, 2: head_dim) + x_abs_max = x_slice.abs().amax(dim=(0, 2)) # [heads] + + # apply minimum clamping + x_abs_max = torch.maximum(x_abs_max, x.new_tensor(clamp_val)) + + # compute scale and descale factors + scale_i = fp8_max / x_abs_max + descale_i = x_abs_max / fp8_max + + # store descale factors + descale_factors[i, :] = descale_i + + scale_reshape = scale_i.reshape(1, num_heads, 1) + + # scale and cast to FP8 + x_fp8[start:end] = (x_slice * scale_reshape).to(fp8_dtype) + + return x_fp8, descale_factors + + +#TODO Move this to a common folder. Will need to add future arch list +def get_arch(): + return triton.runtime.driver.active.get_current_target().arch + +def is_hip(): + return triton.runtime.driver.active.get_current_target().backend == "hip" + +def arch_supports_fp8(): + return is_hip() and get_arch() in ('gfx942') + +@triton.jit +def load_fn(ptrs, offset_first, offset_second, boundary_first, boundary_second): + if offset_first is not None and offset_second is not None: + mask = (offset_first[:, None] < boundary_first) & \ + (offset_second[None, :] < boundary_second) + tensor = tl.load(ptrs, mask=mask, other=0.0) + elif offset_first is not None: + mask = offset_first[:, None] < boundary_first + tensor = tl.load(ptrs, mask=mask, other=0.0) + elif offset_second is not None: + mask = offset_second[None, :] < boundary_second + tensor = tl.load(ptrs, mask=mask, other=0.0) + else: + tensor = tl.load(ptrs) + return tensor + +@triton.jit +def compute_alibi_block(alibi_slope, seqlen_q, seqlen_k, offs_m, offs_n, transpose=False): + # when seqlen_k and seqlen_q are different we want the diagonal to stick to the bottom right of the attention matrix + # for casual mask we want something like this where (1 is kept and 0 is masked) + # seqlen_q = 2 and seqlen_k = 5 + # 1 1 1 1 0 + # 1 1 1 1 1 + # seqlen_q = 5 and seqlen_k = 2 + # 0 0 + # 0 0 + # 0 0 + # 1 0 + # 1 1 + # for alibi the diagonal is 0 indicating no penalty for attending to that spot and increasing penalty for attending further from the diagonal + # e.g. alibi_slope = 1, seqlen_q = 2, seqlen_k = 5, offs_m = [0, 1, 2, 3], offs_n = [0, 1, 2, 3, 4], transpose = False + # 1. offs_m[:,None] = [[0], + # [1], + # 2. offs_m[:,None] + seqlen_k = [[5], + # [6], + # 3. offs_m[:,None] + seqlen_k - seqlen_q = [[3], + # [4], + # 4. offs_m[:,None] + seqlen_k - seqlen_q - offs_n[None,:] = [[3], - [[0, 1, 2, 3, 4]] = [[ 3, 2, 1, 0,-1], + # [4], [ 4, 3, 2, 1, 0]] + # 5. -1 * alibi_slope * tl.abs(relative_pos_block) = [[ -3, -2, -1, 0,-1], + # [ -4, -3, -2, -1, 0]], + relative_pos_block = offs_m[:, None] + seqlen_k - seqlen_q - offs_n[None, :] + alibi_block = -1 * alibi_slope * tl.abs(relative_pos_block) + if transpose: + return alibi_block.T + else: + return alibi_block + +@triton.jit +def _attn_fwd_inner( + acc, + l_i, + m_i, + q, + k_ptrs, + v_ptrs, + stride_kn, + stride_vk, + stride_sn, + start_m, + seqlen_k, + seqlen_q, + dropout_p, + sd_mask_ptrs, + dropout_mask_ptrs, + philox_seed, + philox_ptrs, + block_min, + block_max, + offs_n_causal, + masked_blocks, + n_extra_tokens, + alibi_slope, + descale_q, + descale_k, + descale_v, + OFFS_M: tl.constexpr, + OFFS_N: tl.constexpr, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + BLOCK_DMODEL_POW2: tl.constexpr, + SM_SCALE: tl.constexpr, + IS_CAUSAL: tl.constexpr, + MASK_STEPS: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + RETURN_SCORES: tl.constexpr, + PADDED_HEAD: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, +): + RCP_LN2: tl.constexpr = 1.4426950408889634 + + # loop over k, v, and update accumulator + + for start_n in range(block_min, block_max, BLOCK_N): + # For padded blocks, we will overrun the tensor size if + # we load all BLOCK_N. For others, the blocks are all within range. + if MASK_STEPS: + k_offs_n = start_n + tl.arange(0, BLOCK_N) + else: + k_offs_n = None + k_offs_k = None if not PADDED_HEAD else tl.arange(0, BLOCK_DMODEL_POW2) + k = load_fn(k_ptrs, k_offs_k, k_offs_n, BLOCK_DMODEL, seqlen_k) + + qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) + # We start from end of seqlen_k so only the first iteration would need + # to be checked for padding if it is not a multiple of block_n + # TODO: This can be optimized to only be true for the padded block. + if MASK_STEPS: + # If this is the last block / iteration, we want to + # mask if the sequence length is not a multiple of block size + # a solution is to always do BLOCK_M // BLOCK_N + 1 steps if not is_modulo_mn. + # last step might get wasted but that is okay. check if this masking works For + # that case. + if (start_n + BLOCK_N == block_max) and (n_extra_tokens != 0): + boundary_m = tl.full([BLOCK_M], seqlen_k, dtype=tl.int32) + size_n = start_n + OFFS_N[None, :] + mask = size_n < boundary_m[:, None] + qk = tl.where(mask, qk, float("-inf")) + + # compute masks + q_mask = (OFFS_M[:, None] < seqlen_q) + k_mask = ((start_n + tl.arange(0, BLOCK_N))[None, :] < seqlen_k) + p_mask = q_mask & k_mask + + # -- compute qk ---- + if IS_FP8: + qk += (tl.dot(q, k) * descale_q * descale_k) + else: + qk += tl.dot(q, k) + qk_scaled = qk * SM_SCALE + if IS_CAUSAL: + causal_boundary = start_n + offs_n_causal + causal_mask = OFFS_M[:, None] >= causal_boundary[None, :] + qk_scaled = tl.where(causal_mask, qk_scaled, float("-inf")) + + if alibi_slope is not None: + # Compute the global position of each token within the sequence + global_m_positions = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + global_n_positions = start_n + tl.arange(0, BLOCK_N) + alibi_block = compute_alibi_block(alibi_slope, seqlen_q, seqlen_k, global_m_positions, + global_n_positions) + qk_scaled += alibi_block + # get max scores so far + m_ij = tl.maximum(m_i, tl.max(qk_scaled, 1)) + + # scale and subtract max + q_shifted = qk_scaled - m_ij[:, None] + + # Compute scaled QK and softmax probabilities + p = tl.math.exp2(q_shifted * RCP_LN2) + + # CAVEAT: Must update l_ij before applying dropout + l_ij = tl.sum(p, 1) + if ENABLE_DROPOUT: + rng_output = tl.rand(philox_seed, philox_ptrs) # TODO: use tl.randint for better performance + dropout_mask = rng_output > dropout_p + tl.store(dropout_mask_ptrs, dropout_mask, mask=p_mask) + + # return scores with negative values for dropped vals + sd_mask = tl.where(dropout_mask, p, -p) + tl.store(sd_mask_ptrs, sd_mask, mask=p_mask) + + # apply dropout mask in place + p = tl.where(dropout_mask, p, 0.0) + elif RETURN_SCORES: + # NOTE: the returned score is not the same as the reference because we need to adjust as we find new maxes per block. We are not doing that + tl.store(sd_mask_ptrs, p, mask=p_mask) + + # -- update output accumulator -- + # alpha is an adjustment factor for acc and li as we loop and find new maxes + # store the diff in maxes to adjust acc and li as we discover new maxes + m_diff = m_i - m_ij + alpha = tl.math.exp2(m_diff * RCP_LN2) + acc = acc * alpha[:, None] + v = load_fn(v_ptrs, k_offs_n, k_offs_k, seqlen_k, BLOCK_DMODEL) + # -- update m_i and l_i + l_i = l_i * alpha + l_ij + # update m_i and l_i + m_i = m_ij + + if IS_FP8: + scale_p, descale_p = compute_fp8_scaling_factors(p, FP8_MAX) + acc += (tl.dot((p * scale_p).to(v.type.element_ty), v) * descale_p * descale_v) + else: + acc += tl.dot(p.to(v.type.element_ty), v) + + k_ptrs += BLOCK_N * stride_kn + v_ptrs += BLOCK_N * stride_vk + if RETURN_SCORES: + sd_mask_ptrs += BLOCK_N * stride_sn + + if ENABLE_DROPOUT: + dropout_mask_ptrs += BLOCK_N * stride_sn + philox_ptrs += BLOCK_N * stride_sn + + return acc, l_i, m_i + + +@triton.jit +def _attn_fwd(q_ptr: torch.Tensor, + k_ptr: torch.Tensor, + v_ptr: torch.Tensor, + descale_q_ptr: torch.Tensor, + descale_k_ptr: torch.Tensor, + descale_v_ptr: torch.Tensor, + out_ptr: torch.Tensor, + alibi_slopes_ptr: torch.Tensor, + s_dmask_ptr: torch.Tensor, + dropout_mask_ptr: torch.Tensor, + softmax_lse_ptr: torch.Tensor, + stride_qz, stride_qh, stride_qm, stride_qk, + stride_kz, stride_kh, stride_kn, stride_kk, + stride_vz, stride_vh, stride_vn, stride_vk, + stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, + stride_oz, stride_oh, stride_om, stride_on, + stride_alibi_z, stride_alibi_h, + stride_sd_z, stride_sd_h, stride_sd_m, stride_sd_n, + stride_lse_z, stride_lse_h, stride_lse_m, + sm_scale, + cu_seqlens_q, + cu_seqlens_k, + dropout_p, + philox_seed, + philox_offset, + SEQLEN_Q: tl.constexpr, + SEQLEN_K: tl.constexpr, + IS_CAUSAL: tl.constexpr, + NUM_Q_HEADS: tl.constexpr, + NUM_K_HEADS: tl.constexpr, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + BLOCK_DMODEL_POW2: tl.constexpr, + RETURN_SCORES: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, + VARLEN: tl.constexpr, +): + #calculate offsets + start_m = tl.program_id(0) #seqlen_q + off_q_head = tl.program_id(1) #num_q_heads + off_z = tl.program_id(2) #batch + + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + offs_n = tl.arange(0, BLOCK_N) + offs_d = tl.arange(0, BLOCK_DMODEL_POW2) + + if VARLEN: + cu_seqlens_q_start = tl.load(cu_seqlens_q + off_z) + cu_seqlens_q_end = tl.load(cu_seqlens_q + off_z + 1) + + seqlen_q = cu_seqlens_q_end - cu_seqlens_q_start + # We have a one-size-fits-all grid in id(0). Some seqlens might be too + # small for all start_m so for those we return early. + if start_m * BLOCK_M > seqlen_q: + return + cu_seqlens_k_start = tl.load(cu_seqlens_k + off_z) + cu_seqlens_k_end = tl.load(cu_seqlens_k + off_z + 1) + seqlen_k = cu_seqlens_k_end - cu_seqlens_k_start + else: + cu_seqlens_q_start = 0 + cu_seqlens_k_start = 0 + seqlen_q = SEQLEN_Q + seqlen_k = SEQLEN_K + + n_blocks = cdiv_fn(seqlen_k, BLOCK_N) + + # Now we compute whether we need to exit early due to causal masking. + # This is because for seqlen_q > seqlen_k, M rows of the attn scores + # are completely masked, resulting in 0s written to the output, and + # inf written to LSE. We don't need to do any GEMMs in this case. + # This block of code determines what N is, and if this WG is operating + # on those M rows. + if (IS_CAUSAL): + # If seqlen_q == seqlen_k, the attn scores are a square matrix. + # If seqlen_q != seqlen_k, attn scores are rectangular which means + # the causal mask boundary is bottom right aligned, and ends at either + # the top edge (seqlen_q < seqlen_k) or left edge. + + # This captures the decrease in n_blocks if we have a rectangular attn matrix + n_blocks_seqlen = cdiv_fn((start_m + 1) * BLOCK_M + seqlen_k - seqlen_q, BLOCK_N) + + # This is what adjusts the block_max for the current WG, only + # if IS_CAUSAL. Otherwise we want to always iterate through all n_blocks + n_blocks = min(n_blocks, n_blocks_seqlen) + + # If we have no blocks after adjusting for seqlen deltas, this WG is part of + # the blocks that are all 0. We exit early. + if n_blocks <= 0: + offs_out = (off_z * stride_oz + + off_q_head * stride_oh + + cu_seqlens_q_start * stride_om + + offs_m[:, None] * stride_om + + offs_d[None, :] * stride_on) + acc = tl.zeros([BLOCK_M, BLOCK_DMODEL_POW2], dtype=out_ptr.type.element_ty) + out_mask = (offs_m[:, None] < seqlen_q) & (offs_d < BLOCK_DMODEL) + tl.store(out_ptr + offs_out, acc, mask=out_mask) + + if softmax_lse_ptr is not None: + offs_lse = (off_z * stride_lse_z + + off_q_head * stride_lse_h + + cu_seqlens_q_start * stride_lse_m + + offs_m*stride_lse_m + ) + lse_mask = offs_m < SEQLEN_Q + lse = tl.full([BLOCK_M], value=0.0, dtype=tl.float32) + tl.store(softmax_lse_ptr + offs_lse, lse, mask=lse_mask) + # TODO: Should dropout and return encoded softmax be handled here too? + + return + + grp_sz:tl.constexpr = NUM_Q_HEADS // NUM_K_HEADS + if grp_sz != 1: #Grouped Query Attention + off_k_head = off_q_head // grp_sz + else: + off_k_head = off_q_head + + #q,k,v offsets + q_offs = (off_z * stride_qz + + off_q_head * stride_qh + + cu_seqlens_q_start * stride_qm + + offs_m[:, None] * stride_qm + offs_d[None, :]*stride_qk + ) + q_ptrs = q_ptr + q_offs + + k_offs = (off_z * stride_kz + + off_k_head * stride_kh + + cu_seqlens_k_start * stride_kn + + offs_d[:, None] * stride_kk + offs_n[None, :]*stride_kn + ) + k_ptrs = k_ptr + k_offs + + v_offs = (off_z * stride_vz + + off_k_head * stride_vh + + cu_seqlens_k_start * stride_vn + + offs_n[:, None] * stride_vn + offs_d[None, :]*stride_vk + ) + v_ptrs = v_ptr + v_offs + + #alibi slopes + if alibi_slopes_ptr is not None: + alibi_offs = off_z * stride_alibi_z + off_q_head * stride_alibi_h + alibi_slope = tl.load(alibi_slopes + alibi_offs) + else: + alibi_slope = None + + #s_dmask (return_scores) + if s_dmask_ptr is not None: + s_dmask_offs = (off_z * stride_sd_z + + off_q_head * stride_sd_h + + offs_m[:, None] * stride_sd_m + + offs_n[None, :] * stride_sd_n + ) + s_dmask_ptrs = s_dmask_ptr + s_dmask_offs + else: + s_dmask_ptrs = None + + #dropout + if dropout_mask_ptr is not None: + dropout_mask_offs = (off_z * stride_sd_z + + off_q_head * stride_sd_h + + offs_m[:, None] * stride_sd_m + + offs_n[None, :] * stride_sd_n + ) + dropout_mask_ptrs = dropout_mask_ptr + dropout_mask_offs + philox_ptrs = (philox_offset + + off_z * stride_sd_z + + off_q_head * stride_sd_h + + offs_m[:, None] * stride_sd_m + + offs_n[None, :] * stride_sd_n + ) + else: + dropout_mask_ptrs = None + philox_ptrs = None + + m_i = tl.full([BLOCK_M], float("-inf"), dtype=tl.float32) + l_i = tl.full([BLOCK_M], 1.0, dtype=tl.float32) + acc = tl.zeros([BLOCK_M, BLOCK_DMODEL_POW2], dtype=tl.float32) + if (BLOCK_DMODEL == BLOCK_DMODEL_POW2): + q_mask = (offs_m[:, None] < seqlen_q) + else: + q_mask = (offs_m[:, None] < seqlen_q) & (offs_d[None, :] < BLOCK_DMODEL) + q = tl.load(q_ptrs, mask=q_mask, other=0.0) + if IS_FP8: + descale_q = tl.load(descale_q_ptr + off_z * stride_descale_q_z + off_q_head) + descale_k = tl.load(descale_k_ptr + off_z * stride_descale_k_z + off_k_head) + descale_v = tl.load(descale_v_ptr + off_z * stride_descale_v_z + off_k_head) + else: + descale_q, descale_k ,descale_v = 1.0, 1.0, 1.0 + + n_extra_tokens = 0 + if seqlen_k < BLOCK_N: + n_extra_tokens = BLOCK_N -seqlen_k + elif seqlen_k % BLOCK_N: + n_extra_tokens = seqlen_k % BLOCK_N + + #if CAUSAL, then determine masked_blocks and full blocks + # Here we compute how many full and masked blocks we have. + padded_block_k = n_extra_tokens != 0 + is_modulo_mn = not padded_block_k and (seqlen_q % BLOCK_M == 0) + if IS_CAUSAL: + # There are always at least BLOCK_M // BLOCK_N masked blocks. + # Additionally there might be one more due to dissimilar seqlens. + masked_blocks = BLOCK_M // BLOCK_N + (not is_modulo_mn) + else: + # Padding on Q does not need to be masked in the FA loop. + masked_blocks = padded_block_k + # if IS_CAUSAL, not is_modulo_mn does not always result in an additional block. + # In this case we might exceed n_blocks so pick the min. + masked_blocks = min(masked_blocks, n_blocks) + n_full_blocks = n_blocks - masked_blocks + block_min = 0 + block_max = n_blocks * BLOCK_N + # Compute for full blocks. Here we set causal to false regardless of its actual + # value because there is no masking. Similarly we do not need padding. + if n_full_blocks > 0: + block_max = (n_blocks - masked_blocks) * BLOCK_N + acc, l_i, m_i = _attn_fwd_inner(acc, + l_i, + m_i, + q, + k_ptrs, + v_ptrs, + stride_kn, + stride_vn, + stride_sd_n, + start_m, + seqlen_k, + seqlen_q, + dropout_p, + s_dmask_ptrs, dropout_mask_ptrs, philox_seed, philox_ptrs, + block_min, block_max, 0, 0, 0, alibi_slope, + descale_q, descale_k, descale_v, + offs_m, offs_n, BLOCK_M, BLOCK_N, BLOCK_DMODEL,BLOCK_DMODEL_POW2, + sm_scale, False, MASK_STEPS=False, ENABLE_DROPOUT=ENABLE_DROPOUT, + RETURN_SCORES=RETURN_SCORES, PADDED_HEAD=BLOCK_DMODEL!=BLOCK_DMODEL_POW2, + IS_FP8=IS_FP8, FP8_MAX=FP8_MAX + ) + block_min = block_max + block_max = n_blocks * BLOCK_N + + # Remaining blocks, if any, are full / not masked. + if (masked_blocks > 0): + if IS_CAUSAL: + offs_n_causal = offs_n + (seqlen_q - seqlen_k) + else: + offs_n_causal = 0 + k_ptrs += n_full_blocks * BLOCK_N * stride_kn + v_ptrs += n_full_blocks * BLOCK_N * stride_vn + if RETURN_SCORES: + s_dmask_ptrs += n_full_blocks * BLOCK_N * stride_sd_n + if ENABLE_DROPOUT: + dropout_mask_ptrs += n_full_blocks * BLOCK_N * stride_sd_n + acc, l_i, m_i = _attn_fwd_inner(acc, + l_i, + m_i, + q, + k_ptrs, + v_ptrs, + stride_kn, stride_vn, stride_sd_n, + start_m, seqlen_k, seqlen_q, + dropout_p, + s_dmask_ptrs, dropout_mask_ptrs, philox_seed, philox_ptrs, + block_min, block_max, offs_n_causal, masked_blocks, n_extra_tokens, alibi_slope, + descale_q, descale_k, descale_v, + offs_m, offs_n, BLOCK_M, BLOCK_N, BLOCK_DMODEL,BLOCK_DMODEL_POW2, + sm_scale, IS_CAUSAL, MASK_STEPS=True, ENABLE_DROPOUT=ENABLE_DROPOUT, + RETURN_SCORES=RETURN_SCORES, PADDED_HEAD=BLOCK_DMODEL!=BLOCK_DMODEL_POW2, + IS_FP8=IS_FP8, FP8_MAX=FP8_MAX + ) + # epilogue + # This helps the compiler do Newton Raphson on l_i vs on acc which is much larger. + l_recip = 1 / l_i[:, None] + acc = acc * l_recip + if ENABLE_DROPOUT: + dropout_scale = 1 / (1 - dropout_p) + acc = acc * dropout_scale + # If seqlen_q > seqlen_k but the delta is not a multiple of BLOCK_M, + # then we have one block with a row of all NaNs which come from computing + # softmax over a row of all -infs (-inf - inf = NaN). We check for that here + # and store 0s where there are NaNs as these rows should've been zeroed out. + end_m_idx = (start_m + 1) * BLOCK_M + start_m_idx = start_m * BLOCK_M + causal_start_idx = seqlen_q - seqlen_k + if IS_CAUSAL: + if causal_start_idx > start_m_idx and causal_start_idx < end_m_idx: + out_mask_boundary = tl.full((BLOCK_DMODEL_POW2, ), causal_start_idx, dtype=tl.int32) + mask_m_offsets = start_m_idx + tl.arange(0, BLOCK_M) + out_ptrs_mask = mask_m_offsets[:, None] >= out_mask_boundary[None, :] + z = 0.0 + acc = tl.where(out_ptrs_mask, acc, z.to(acc.type.element_ty)) + + # write back LSE(Log Sum Exponents), the log of the normalization constant + overflow_size = end_m_idx - seqlen_q + if softmax_lse_ptr is not None: + RCP_LN2: tl.constexpr = 1.4426950408889634 + LN2: tl.constexpr = 0.6931471824645996 + # compute log-sum-exp in base 2 units + mi_base2 = m_i * RCP_LN2 + softmax_lse = mi_base2 + tl.math.log2(l_i) + # convert back to natural units + softmax_lse *= LN2 + + if IS_CAUSAL: + # zero out nans caused by -infs when doing causal + lse_causal_mask = (start_m_idx + tl.arange(0, BLOCK_M)) < causal_start_idx + softmax_lse = tl.where(lse_causal_mask, 0.0, softmax_lse) + + # If seqlen_q not multiple of BLOCK_M, we need to mask out the last few rows. + # This is only true for the last M block. For others, overflow_size will be -ve + offs_lse = off_z * stride_lse_z + off_q_head * stride_lse_h + cu_seqlens_q_start * stride_lse_m + offs_m*stride_lse_m + if overflow_size > 0: + boundary = tl.full((BLOCK_M, ), BLOCK_M - overflow_size, dtype=tl.int32) + lse_mask = tl.arange(0, BLOCK_M) < boundary + tl.store(softmax_lse_ptr + offs_lse, softmax_lse, mask=lse_mask) # the log of the normalization constant + else: + tl.store(softmax_lse_ptr + offs_lse, softmax_lse) # the log of the normalization constant + + # write back O + offs_out = (off_z * stride_oz + + off_q_head * stride_oh + + cu_seqlens_q_start * stride_om + + offs_m[:, None] * stride_om + + offs_d[None, :] * stride_on) + out_mask = tl.full([BLOCK_M, BLOCK_DMODEL_POW2], 1, dtype=tl.int1) + if overflow_size > 0: + out_mask = out_mask & (offs_m[:, None] < seqlen_q) + if BLOCK_DMODEL != BLOCK_DMODEL_POW2: + out_mask = out_mask & (offs_d[None, :] < BLOCK_DMODEL) + op = acc.to(out_ptr.dtype.element_ty) + tl.store(out_ptr + offs_out, op, mask=out_mask) + +def _flash_attn_forward( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int, + window_size_right: int, + alibi_slopes: Optional[torch.Tensor], + return_lse: bool, + return_softmax: bool, + max_seqlen_q: int, + max_seqlen_k: int, + cu_seqlens_q: Optional[torch.Tensor] = None, + cu_seqlens_k: Optional[torch.Tensor] = None, + descale_q: Optional[torch.Tensor] = None, + descale_k: Optional[torch.Tensor] = None, + descale_v: Optional[torch.Tensor] = None, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + + #FP8 + IS_FP8 = is_fp8(q) + FP8_MAX: tl.constexpr=torch.finfo(q.dtype).max + is_varlen = True if cu_seqlens_q is not None else False + + if IS_FP8: + o = torch.zeros_like(q, dtype=torch.float32) + else: + o = torch.zeros_like(q) + if is_varlen: + #Layout for q,k,v is thd ie [total_tokens, num_head, head_dim] + batch, seqlen_q, num_q_heads, head_sz = len(cu_seqlens_q) - 1, max_seqlen_q, q.shape[1], q.shape[2] + seqlen_k, num_k_heads = max_seqlen_k, k.shape[1] + q_strides = (0, q.stride(1), q.stride(0), q.stride(2)) + k_strides = (0, k.stride(1), k.stride(0), k.stride(2)) + v_strides = (0, v.stride(1), v.stride(0), v.stride(2)) + o_strides = (0, o.stride(1), o.stride(0), o.stride(2)) + else: + #Layout for q,k,v is bshd ie [batch, seq_len, num_head, head_dim] + batch, seqlen_q, num_q_heads, head_sz = q.shape + seqlen_k = k.shape[1] + num_k_heads = k.shape[2] + q_strides = (q.stride(0), q.stride(2), q.stride(1), q.stride(3)) + k_strides = (k.stride(0), k.stride(2), k.stride(1), k.stride(3)) + v_strides = (v.stride(0), v.stride(2), v.stride(1), v.stride(3)) + o_strides = (o.stride(0), o.stride(2), o.stride(1), o.stride(3)) + + #padding for head_dim. Power of 2 or 16 + BLOCK_DMODEL_POW2 = triton.next_power_of_2(head_sz) + BLOCK_DMODEL_POW2 = max(BLOCK_DMODEL_POW2, 16) + + #softmax_lse [batch, num_q_heads, seqlen_q] + if return_lse: + if is_varlen: + softmax_lse = torch.zeros((q.shape[0], num_q_heads), device=q.device, dtype=torch.float32) + stride_lse_z, stride_lse_h, stride_lse_m = 0, softmax_lse.stride(1), softmax_lse.stride(0) + else: + softmax_lse = torch.zeros((batch, num_q_heads, max_seqlen_q), device=q.device, dtype=torch.float32) + stride_lse_z, stride_lse_h, stride_lse_m = softmax_lse.stride() + else: + softmax_lse = None + + #exp_scores [batch, num_q_heads, seqlen_q, seqlen_k] + enable_dropout = dropout_p > 0.0 + if enable_dropout: + philox_seed = torch.randint(0, 0xffffff, (1,))[0].item() #No specific reason to restrict range to 0xffffff + philox_offset = torch.randint(0, 0xffffff, (1,))[0].item() #Pass in an int, not Tensor + else: + philox_seed = 0 + philox_offset = 0 + if return_softmax or enable_dropout: + s_dmask = torch.zeros((batch, num_q_heads, max_seqlen_q, max_seqlen_k), device=q.device, dtype=torch.float32) + dropout_mask = torch.zeros((batch, num_q_heads, max_seqlen_q, max_seqlen_k), device=q.device, dtype=torch.float32) + else: + s_dmask = None + dropout_mask = None + + + # Best config from ROCm/triton/python/perf-kernels/flash_attention.py::attn_fwd autotuning is BLOCK_M: 128, BLOCK_N: 64, waves_per_eu: 2, num_warps: 4, num_ctas: 1, num_stages: 1 + # Tuned for MI300x + config = { + 'BLOCK_M': 128, + 'BLOCK_N': 32, # BLOCK_N: 64 spills for _attn_fwd + 'waves_per_eu': 2, + 'num_warps': 4, + 'num_ctas': 1, + 'num_stages': 1, + } + + grid = lambda META:(triton.cdiv(seqlen_q, META['BLOCK_M']), num_q_heads, batch) + _attn_fwd[grid](q, + k, + v, + descale_q, + descale_k, + descale_v, + o, + alibi_slopes, + s_dmask, + dropout_mask, + softmax_lse, + *q_strides, + *k_strides, + *v_strides, + descale_q.stride(0) if descale_q is not None else 0, + descale_k.stride(0) if descale_k is not None else 0, + descale_v.stride(0) if descale_v is not None else 0, + *o_strides, + alibi_slopes.stride(0) if alibi_slopes is not None else 0, + alibi_slopes.stride(1) if alibi_slopes is not None else 0, + s_dmask.stride(0) if s_dmask is not None else 0, + s_dmask.stride(1) if s_dmask is not None else 0, + s_dmask.stride(2) if s_dmask is not None else 0, + s_dmask.stride(3) if s_dmask is not None else 0, + stride_lse_z if softmax_lse is not None else 0, + stride_lse_h if softmax_lse is not None else 0, + stride_lse_m if softmax_lse is not None else 0, + softmax_scale, + cu_seqlens_q, + cu_seqlens_k, + dropout_p, + philox_seed, + philox_offset, + SEQLEN_Q=max_seqlen_q, + SEQLEN_K=max_seqlen_k, + IS_CAUSAL=causal, + NUM_Q_HEADS=num_q_heads, + NUM_K_HEADS=num_k_heads, + BLOCK_DMODEL=head_sz, + BLOCK_DMODEL_POW2=BLOCK_DMODEL_POW2, + RETURN_SCORES=return_softmax, + ENABLE_DROPOUT=enable_dropout, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + VARLEN=is_varlen, + **config + ) + + return o, softmax_lse, s_dmask, philox_seed, philox_offset + +# This function computes delta given output Out and gradient DO +# Here is the I/O shape: +# Out: (batch, nhead_q, max_seqlens_q, headDim) +# DO: (batch, nhead_q, max_seqlens_q, headDim) +# Delta: (batch, nheads_q, max_seqlens_q), same as softmax_lse defined at +@triton.jit +def _bwd_preprocess( + o_ptr, do_ptr, # noqa: E741 + delta_ptr, + stride_o_b, stride_o_h, stride_o_m, stride_o_k, + stride_delta_b, stride_delta_h, stride_delta_m, + stride_descale_do_z, + cu_seqlens_q, max_seqlen_q, + descale_do_ptr, + BLOCK_M: tl.constexpr, + BLOCK_D_MODEL: tl.constexpr, + BLOCK_D_MODEL_POW2: tl.constexpr, + IS_VARLEN: tl.constexpr, + IS_FP8: tl.constexpr +): + pid_m = tl.program_id(0) #seqlen + bid = tl.program_id(1) #batch + hid = tl.program_id(2) #head + + # Handle varlen + q_start = 0 + seqlen_q = max_seqlen_q + if IS_VARLEN: + q_start = tl.load(cu_seqlens_q + bid) + q_end = tl.load(cu_seqlens_q + bid + 1) + seqlen_q = q_end - q_start + else: + q_start = 0 + seqlen_q = max_seqlen_q + + # Compute offsets + offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + offs_k = tl.arange(0, BLOCK_D_MODEL_POW2) + + # Offset O/DO by batch, head and q_start + offs = (bid * stride_o_b + + hid * stride_o_h + + q_start * stride_o_m + offs_m[:, None] * stride_o_m + + offs_k[None, :] * stride_o_k) + + # create masks + mask_m = offs_m < seqlen_q + mask = mask_m[:, None] + PADDED_HEAD: tl.constexpr = (BLOCK_D_MODEL != BLOCK_D_MODEL_POW2) + if PADDED_HEAD: + mask &= offs_k[None, :] < BLOCK_D_MODEL + + # load [BLOCK_M, BLOCK_D_MODEL_POW2] + o = tl.load(o_ptr + offs, mask=mask, other=0.0) + do = tl.load(do_ptr + offs, mask=mask, other=0.0) + + # compute and write-back to delta + if IS_FP8: + descale_do = tl.load(descale_do_ptr + bid * stride_descale_do_z + hid) + + # NOTE: do is in the fp8 range and o is not in fp8 + delta = tl.sum(o.to(tl.float32) * (do.to(tl.float32) * descale_do), axis=1) + else: + delta = tl.sum(o.to(tl.float32) * do.to(tl.float32), axis=1) + + offs_delta = (bid * stride_delta_b + + hid * stride_delta_h + + q_start * stride_delta_m + offs_m * stride_delta_m) + tl.store(delta_ptr + offs_delta, delta, mask=mask_m) + +@triton.jit +def _bwd_dq_inner( + dq, + q, K, V, do, m, Delta, sm_scale, + stride_qm, stride_qk, stride_kn, stride_kk, stride_vn, stride_vk, + stride_dropout_m, stride_dropout_n, + stride_deltam, + seqlen_q, seqlen_k, + dropout_p, philox_seed, batch_philox_offset, dropout_offset, + start_m, start_n, end_n, num_steps, + descale_q, descale_k, descale_v, descale_do, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLOCK_D_MODEL: tl.constexpr, + BLOCK_D_MODEL_POW2: tl.constexpr, + MASK: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, +): + RCP_LN2: tl.constexpr = 1.4426950408889634 + + PADDED_HEAD: tl.constexpr = (BLOCK_D_MODEL != BLOCK_D_MODEL_POW2) + delta_qk = seqlen_q - seqlen_k + offs_m = start_m + tl.arange(0, BLOCK_M) + offs_n = start_n + tl.arange(0, BLOCK_N) + offs_k = tl.arange(0, BLOCK_D_MODEL_POW2) + + # mask to make sure not OOB of seqlen_q + mask_m = offs_m < seqlen_q + + kT_ptrs = K + offs_n[None, :] * stride_kn + offs_k[:, None] * stride_kk + vT_ptrs = V + offs_n[None, :] * stride_vn + offs_k[:, None] * stride_vk + + # D (= delta) is pre-divided by ds_scale. + Di = tl.load(Delta + offs_m * stride_deltam, mask=mask_m, other=0.0) + + curr_n = start_n + step_n = BLOCK_N + curr_philox_offset = batch_philox_offset + curr_dropout_offset = dropout_offset + for blk_idx in range(num_steps): + offs_n = curr_n + tl.arange(0, BLOCK_N) + # end_n is needed because the end of causal True might not be perfectly + # aligned with the end of the block + mask_n = offs_n < end_n + mask_kT = mask_n[None, :] + mask_mn = mask_m[:, None] & (offs_n[None, :] < end_n) + if PADDED_HEAD: + mask_kT &= offs_k[:, None] < BLOCK_D_MODEL + + kT = tl.load(kT_ptrs, mask=mask_kT, other=0.0) + vT = tl.load(vT_ptrs, mask=mask_kT, other=0.0) + + #dropout + if ENABLE_DROPOUT: + philox_offs = (curr_philox_offset + + offs_m[:, None] * stride_dropout_m + + offs_n[None, :] * stride_dropout_n) + rand_vals = tl.rand(philox_seed, philox_offs) + dropout_mask = rand_vals > dropout_p + dropout_scale = 1 / (1 - dropout_p) + + #qk + if IS_FP8: + qk = tl.dot(q, kT) * descale_q * descale_k + else: + qk = tl.dot(q, kT) + p = tl.math.exp2(qk * sm_scale * RCP_LN2 - m * RCP_LN2) + + if MASK: + causal_mask = (offs_m[:, None] - delta_qk) >= offs_n[None, :] + mask = causal_mask * mask_mn + p = tl.where(mask, p, 0.0) + + #dp + if IS_FP8: + dp = (tl.dot(do, vT) * descale_do * descale_v) + else: + dp = tl.dot(do, vT) + + if ENABLE_DROPOUT: + dp = tl.where(dropout_mask, dp, 0.0) * dropout_scale + + #ds + delta_i = Di[:, None] + ds = p * (dp - delta_i) + + #dq + # NOTE: We need to de-scale dq in the end, because kT was pre-scaled. + if IS_FP8: + scale_ds, descale_ds = compute_fp8_scaling_factors(ds, FP8_MAX) + dq += (tl.dot((ds*scale_ds).to(kT.type.element_ty), tl.trans(kT)) * descale_ds * descale_k) + else: + dq += tl.dot(ds.to(kT.type.element_ty), tl.trans(kT)) + + curr_n += step_n + kT_ptrs += step_n * stride_kn + vT_ptrs += step_n * stride_vn + return dq + + +@triton.jit +def _bwd_dkdv_inner( + dk, dv, + Q, k, v, DO, M, D, sm_scale, + stride_q_m, stride_q_k, + stride_do_m, stride_do_k, + stride_dropout_m, stride_dropout_n, + stride_deltam, + dropout_p, philox_seed, batch_philox_offset, dropout_offset, + seqlen_q, seqlen_k, + start_n, start_m, num_steps, + descale_q, descale_k, descale_v, descale_do, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLOCK_D_MODEL: tl.constexpr, + BLOCK_D_MODEL_POW2: tl.constexpr, + MASK: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, +): + PADDED_HEAD: tl.constexpr = (BLOCK_D_MODEL != BLOCK_D_MODEL_POW2) + delta_qk = seqlen_q - seqlen_k + offs_m = start_m + tl.arange(0, BLOCK_M) + offs_n = start_n + tl.arange(0, BLOCK_N) + offs_k = tl.arange(0, BLOCK_D_MODEL_POW2) + + # mask to make sure not OOB of seqlen_q + mask_n = offs_n < seqlen_k + qT_ptrs = Q + offs_m[None, :] * stride_q_m + offs_k[:, None] * stride_q_k #[BLOCK_D_MODEL_POW2, BLOCK_M] + do_ptrs = DO + offs_m[:, None] * stride_do_m + offs_k[None,: ] * stride_do_k + curr_m = start_m + step_m = BLOCK_M + curr_philox_offset = batch_philox_offset + curr_dropout_offset = dropout_offset + RCP_LN2: tl.constexpr = 1.4426950408889634 + + #Iterate over blocks(BLOCK_M size) of Q while calculating + #a fixed block(BLOCK_N) of dk and dv. Note, during backward + #pass P has to be recomputed. However, this kernel computes + #dV and dK, so we compute we need P^T and S^T. See backward pass + #equations + # + #From Flash Attention Paper: + #ForwardPass: S = QkT, P=softmax(S), O=PV + # + #BackwardPass equations + #dV = P^TdO + #dP = dOV^T + #dS = dsoftmax(dP) + #dQ = dSK + #dK = QdS^T + for blk_idx in range(num_steps): + offs_m = curr_m + tl.arange(0, BLOCK_M) + mask_m = offs_m < seqlen_q + mask_qT = mask_m[None, :] + mask_do = mask_m[:, None] + mask_nm = mask_n[:, None] & (offs_m[None, :] < seqlen_q) + if PADDED_HEAD: + mask_qT &= offs_k[:, None] < BLOCK_D_MODEL + mask_do &= offs_k[None, :] < BLOCK_D_MODEL + + #load qT + qT = tl.load(qT_ptrs, mask=mask_qT, other=0.0) + + #dropout + if ENABLE_DROPOUT: + # NOTE: dropout is transposed because it is used to mask pT + philox_offs = (curr_philox_offset + + offs_m[None, :] * stride_dropout_m + + offs_n[:, None] * stride_dropout_n) + rand_vals = tl.rand(philox_seed, philox_offs) + dropout_mask = rand_vals > dropout_p + dropout_scale = 1.0 / (1 - dropout_p) + + #Load M + m = tl.load(M + offs_m * stride_deltam, mask=mask_m, other=0.0) + + #Compute qkT + if IS_FP8: + qkT = (tl.dot(k, qT) * descale_q * descale_k) + else: + qkT = tl.dot(k, qT) + + #Compute pT(use m and also apply sm_scale) + pT = tl.math.exp(qkT * sm_scale - m[None, :]) + + if MASK: + causal_mask = (offs_m[None, :] - delta_qk) >= offs_n[:, None] + mask = causal_mask & mask_nm + pT = tl.where(mask, pT, 0.0) + + #load DO + do = tl.load(do_ptrs, mask=mask_do, other=0.0) + + #dV + if ENABLE_DROPOUT: + pT_dropout = tl.where(dropout_mask, pT, 0.0) * dropout_scale + if IS_FP8: + scale_p_dropout, descale_p_dropout = compute_fp8_scaling_factors(pT_dropout, FP8_MAX) + dv += (tl.dot((pT_dropout * scale_p_dropout).to(do.type.element_ty), do) * descale_p_dropout * descale_do) + else: + dv += tl.dot(pT_dropout.to(do.type.element_ty), do) + else: + if IS_FP8: + scale_pT, descale_pT = compute_fp8_scaling_factors(pT, FP8_MAX) + dv += (tl.dot((pT * scale_pT).to(do.type.element_ty), do) * descale_pT * descale_do) + else: + dv += tl.dot(pT.to(do.type.element_ty), do) + + #Load delta + Di = tl.load(D + offs_m * stride_deltam, mask=mask_m) + + #Compute dP and dS + if IS_FP8: + dpT = tl.dot(v, tl.trans(do)) * descale_v * descale_do + else: + dpT = tl.dot(v, tl.trans(do)) + + if ENABLE_DROPOUT: + dpT = tl.where(dropout_mask, dpT, 0.0) * dropout_scale + + delta_i = Di[None, :] + dsT = pT * (dpT - delta_i) + + #compute dk + if IS_FP8: + scale_dsT, descale_dsT = compute_fp8_scaling_factors(dsT, FP8_MAX) + dk += (tl.dot((dsT * scale_dsT).to(qT.type.element_ty), tl.trans(qT)) * descale_dsT * descale_q) + else: + dk += tl.dot(dsT.to(qT.type.element_ty), tl.trans(qT)) + + #increment pointers + curr_m += step_m + qT_ptrs += step_m * stride_q_m + do_ptrs += step_m * stride_do_m + + return dk, dv + + +@triton.jit +def _bwd_dkdvdq_inner( + dk, dv, + Q, k, v, DO, DQ, M, D, sm_scale, + stride_q_m, stride_q_k, + stride_do_m, stride_do_k, + stride_dropout_m, stride_dropout_n, + stride_deltam, + dropout_p, philox_seed, batch_philox_offset, dropout_offset, + seqlen_q, seqlen_k, + start_n, start_m, num_steps, + descale_q, descale_k, descale_v, descale_do, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLOCK_D_MODEL: tl.constexpr, + BLOCK_D_MODEL_POW2: tl.constexpr, + MASK: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, + workgroup_id: tl.int32, +): + PADDED_HEAD: tl.constexpr = (BLOCK_D_MODEL != BLOCK_D_MODEL_POW2) + delta_qk = seqlen_q - seqlen_k + offs_m = start_m + tl.arange(0, BLOCK_M) + offs_n = start_n + tl.arange(0, BLOCK_N) + offs_k = tl.arange(0, BLOCK_D_MODEL_POW2) + + # mask to make sure not OOB of seqlen_q + mask_n = offs_n < seqlen_k + + qT_ptrs_start = Q + offs_m[None, :] * stride_q_m + offs_k[:, None] * stride_q_k #[BLOCK_D_MODEL_POW2, BLOCK_M] + dq_ptrs_start = DQ + offs_m[:, None] * stride_q_m + offs_k[None,:] * stride_q_k #[BLOCK_M, BLOCK_D_MODEL_POW2] + + do_ptrs_start = DO + offs_m[:, None] * stride_do_m + offs_k[None,: ] * stride_do_k + curr_m = start_m + step_m = BLOCK_M + curr_philox_offset = batch_philox_offset + curr_dropout_offset = dropout_offset + RCP_LN2: tl.constexpr = 1.4426950408889634 + + #Iterate over blocks(BLOCK_M size) of Q while calculating + #a fixed block(BLOCK_N) of dk and dv. Note, during backward + #pass P has to be recomputed. However, this kernel computes + #dV and dK, so we compute we need P^T and S^T. See backward pass + #equations + # + #From Flash Attention Paper: + #ForwardPass: S = QkT, P=softmax(S), O=PV + # + #BackwardPass equations + #dV = P^TdO + #dP = dOV^T + #dS = dsoftmax(dP) + #dQ = dSK + #dK = QdS^T + + # Compute a starting index and step based on workgroup_id + # Use a simple hash-like function to spread out the starting points + start_idx = (workgroup_id * 17) % num_steps # 17 is an arbitrary prime to spread indices + # Ensure step is coprime with num_steps to visit all indices exactly once + step = 1 # 3 if num_steps > 1 or num_steps==3 else 1 # coprime with num_steps + + + for iter in range(num_steps): + # Compute the permuted block index + blk_idx = (start_idx + iter * step) % num_steps + + curr_m = start_m + blk_idx * step_m + qT_ptrs = qT_ptrs_start + blk_idx * step_m * stride_q_m + dq_ptrs = dq_ptrs_start + blk_idx * step_m * stride_q_m + do_ptrs = do_ptrs_start + blk_idx * step_m * stride_do_m + + offs_m = curr_m + tl.arange(0, BLOCK_M) + mask_m = offs_m < seqlen_q + mask_qT = mask_m[None, :] + mask_do = mask_m[:, None] + mask_nm = mask_n[:, None] & (offs_m[None, :] < seqlen_q) + + if PADDED_HEAD: + mask_qT &= offs_k[:, None] < BLOCK_D_MODEL + mask_do &= offs_k[None, :] < BLOCK_D_MODEL + + #load qT + qT = tl.load(qT_ptrs, mask=mask_qT, other=0.0) + + #dropout + if ENABLE_DROPOUT: + # NOTE: dropout is transposed because it is used to mask pT + philox_offs = (curr_philox_offset + + offs_m[None, :] * stride_dropout_m + + offs_n[:, None] * stride_dropout_n) + rand_vals = tl.rand(philox_seed, philox_offs) + dropout_mask = rand_vals > dropout_p + dropout_scale = 1.0 / (1 - dropout_p) + + #Load M + m = tl.load(M + offs_m * stride_deltam, mask=mask_m, other=0.0) + + #Compute qkT + if IS_FP8: + qkT = (tl.dot(k, qT) * descale_q * descale_k) + else: + qkT = tl.dot(k, qT) + + #Compute pT(use m and also apply sm_scale) + pT = tl.math.exp(qkT * sm_scale - m[None, :]) + + if MASK: + causal_mask = (offs_m[None, :] - delta_qk) >= (offs_n[:, None]) + mask = causal_mask & mask_nm + pT = tl.where(mask, pT, 0.0) + + #load DO + do = tl.load(do_ptrs, mask=mask_do, other=0.0) + + #dV + if ENABLE_DROPOUT: + pT_dropout = tl.where(dropout_mask, pT, 0.0) * dropout_scale + if IS_FP8: + scale_p_dropout, descale_p_dropout = compute_fp8_scaling_factors(pT_dropout, FP8_MAX) + dv += (tl.dot((pT_dropout * scale_p_dropout).to(do.type.element_ty), do) * descale_p_dropout * descale_do) + else: + dv += tl.dot(pT_dropout.to(do.type.element_ty), do) + else: + if IS_FP8: + scale_pT, descale_pT = compute_fp8_scaling_factors(pT, FP8_MAX) + dv += (tl.dot((pT * scale_pT).to(do.type.element_ty), do) * descale_pT * descale_do) + else: + dv += tl.dot(pT.to(do.type.element_ty), do) + + #Load delta + Di = tl.load(D + offs_m * stride_deltam, mask=mask_m) + + #Compute dP and dS + if IS_FP8: + dpT = tl.dot(v, tl.trans(do)) * descale_v * descale_do + else: + dpT = tl.dot(v, tl.trans(do)) + + if ENABLE_DROPOUT: + dpT = tl.where(dropout_mask, dpT, 0.0) * dropout_scale + + delta_i = Di[None, :] + dsT = pT * (dpT - delta_i) + + #compute dk + if IS_FP8: + scale_dsT, descale_dsT = compute_fp8_scaling_factors(dsT, FP8_MAX) + dk += (tl.dot((dsT * scale_dsT).to(qT.type.element_ty), tl.trans(qT)) * descale_dsT * descale_q) + else: + dk += tl.dot(dsT.to(qT.type.element_ty), tl.trans(qT)) + + + # We can compute the dq_partial here and do a atomic add to the correct memory location + # NOTE: Possible problems with the atomic add: contention, is inside a loop which has achieved bad perf before + # (BLOCK_M, BLOCK_N) x (BLOCK_N, D) + if IS_FP8: + dq_partial = tl.dot((dsT * scale_dsT).to(k.dtype).T, k) * descale_dsT * descale_k + else: + dq_partial = tl.dot(dsT.to(k.dtype).T, k) + tl.atomic_add( + dq_ptrs, + dq_partial * sm_scale, + mask=mask_m[:, None], + sem="relaxed", + ) + + return dk, dv + + +@triton.jit +def _bwd_kernel_dkdvdq_causal( + q_ptr, k_ptr, v_ptr, sm_scale, do_ptr, dk_ptr, dv_ptr, dq_ptr, + m_ptr, delta_ptr, + stride_q_b, stride_q_h, stride_q_m, stride_q_k, + stride_k_b, stride_k_h, stride_k_n, stride_k_k, + stride_v_b, stride_v_h, stride_v_n, stride_v_k, + stride_dk_b, stride_dk_h, stride_dk_n, stride_dk_k, + stride_delta_b, stride_delta_h, stride_delta_m, + stride_do_b, stride_do_h, stride_do_m, stride_do_k, + stride_dropout_b, stride_dropout_h, stride_dropout_m, stride_dropout_n, + stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_do_z, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, max_seqlen_k, + dropout_mask, dropout_p, philox_seed, philox_offset_base, + descale_q_ptr, descale_k_ptr, descale_v_ptr, descale_do_ptr, + NUM_Q_HEADS: tl.constexpr, + NUM_K_HEADS: tl.constexpr, + BATCH, + NUM_K_PIDS, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLK_SLICE_FACTOR: tl.constexpr, + BLOCK_D_MODEL: tl.constexpr, + BLOCK_D_MODEL_POW2: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + IS_VARLEN: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, +): + wid = tl.program_id(0) # workgoup id: 0, ..., NUM_K_PIDS * BATCH * NUM_K_HEADS - 1 + + # workgroups get launched first along batch dim, then in head_k dim, and then in seq k block dim + batch_idx = wid % BATCH + head_k_idx = wid // BATCH % NUM_K_HEADS + seq_k_blk_idx = wid // (BATCH * NUM_K_HEADS) % NUM_K_PIDS + + #Determine q and k start along with seqlen_q and seqlen_k + q_start = 0 + k_start = 0 + seqlen_q = max_seqlen_q + seqlen_k = max_seqlen_k + if IS_VARLEN: + q_start = tl.load(cu_seqlens_q + batch_idx) + q_end = tl.load(cu_seqlens_q + batch_idx + 1) + k_start = tl.load(cu_seqlens_k + batch_idx) + k_end = tl.load(cu_seqlens_k + batch_idx + 1) + seqlen_q = q_end - q_start + seqlen_k = k_end - k_start + + dk = tl.zeros([BLOCK_N, BLOCK_D_MODEL_POW2], dtype=tl.float32) + dv = tl.zeros([BLOCK_N, BLOCK_D_MODEL_POW2], dtype=tl.float32) + + # Figure out causal starting block since we have seqlen_q >=< seqlen_k. + # Unlike forward pass where we tile on M dim and iterate on N dim, so that + # we can skip some M blocks, in backward pass, we tile on the N dim for kv + # and iterate over the M. In this way, we cannot skip N blocks, but only to + # determine the starting M blocks to skip some initial blocks masked by + # causal. + delta_qk = seqlen_q - seqlen_k + + # q > k: diretcly skip all the way until the start of causal block + start_delta_q_gt_k = delta_qk + + # q < k: some blocks will have no Masked block, other needs to re-calc + # starting position + # delta_qk is negative so flip it, only multiple of BLOCK_N can skip the + # masked op + num_blocks_skip = -delta_qk // BLOCK_N + delta_aligned = (num_blocks_skip + 1) * BLOCK_N + delta_qk + start_delta_q_lt_k = delta_aligned // BLOCK_M * BLOCK_M + if delta_qk >= 0: + start_delta = delta_qk + else: + start_delta = start_delta_q_lt_k + + start_n = seq_k_blk_idx * BLOCK_N + + offs_k = tl.arange(0, BLOCK_D_MODEL_POW2) + offs_n = start_n + tl.arange(0, BLOCK_N) + # Mask for loading K and V + mask_kv = offs_n[:, None] < seqlen_k + PADDED_HEAD: tl.constexpr = (BLOCK_D_MODEL != BLOCK_D_MODEL_POW2) + if PADDED_HEAD: + mask_k = offs_k < BLOCK_D_MODEL + mask_kv &= mask_k[None, :] + + GROUP_SIZE = NUM_Q_HEADS // NUM_K_HEADS + adj_k = (batch_idx * stride_k_b + + head_k_idx * stride_k_h + + k_start * stride_k_n + offs_n[:, None] * stride_k_n + + offs_k[None, :] * stride_k_k) + adj_v = (batch_idx * stride_v_b + + head_k_idx * stride_v_h + + k_start * stride_v_n + offs_n[:, None] * stride_v_n + + offs_k[None, :] * stride_v_k) + # load K and V: they stay in SRAM throughout the inner loop. + k = tl.load(k_ptr + adj_k , mask=mask_kv, other=0.0) + v = tl.load(v_ptr + adj_v, mask=mask_kv, other=0.0) + + # If MQA / GQA, set the K and V head offsets appropriately. + for head_q_idx in range(head_k_idx * GROUP_SIZE, head_k_idx * GROUP_SIZE + GROUP_SIZE): + if delta_qk >= 0: + start_m = start_n + start_delta + len_m = BLOCK_N + else: + start_m = max(start_n + delta_qk, 0) + start_m = (start_m // BLOCK_M) * BLOCK_M + # because we might shift the masked blocks up, we are deeper into + # the masked out region, so we would potentially increase the total + # steps with masked operation to get out of it + residue_m = max(start_n + delta_qk - start_m, 0) + len_m = BLOCK_N + residue_m + + # offset input and output tensor by batch and Q/K heads + adj_q = batch_idx * stride_q_b + head_q_idx * stride_q_h + q_start * stride_q_m + + q_ptr_adj = q_ptr + adj_q + dq_ptr_adj = dq_ptr + adj_q + + adj_do = batch_idx * stride_do_b + head_q_idx * stride_do_h + q_start * stride_do_m + do_ptr_adj = do_ptr + adj_do + adj_delta = batch_idx * stride_delta_b + head_q_idx * stride_delta_h + q_start * stride_delta_m + m_ptr_adj = m_ptr + adj_delta + delta_ptr_adj = delta_ptr + adj_delta + + # batch_philox_offset is the ACTUALLY dropout offset + # dropout_offset is for debug purpose and will be removed later + batch_philox_offset = 0 + dropout_offset = 0 + if ENABLE_DROPOUT: + batch_philox_offset = (philox_offset_base + batch_idx * stride_dropout_b + + head_q_idx * stride_dropout_h) + dropout_offset = (dropout_mask + batch_idx * stride_dropout_b + + head_q_idx * stride_dropout_h) + + MASK_BLOCK_M: tl.constexpr = BLOCK_M // BLK_SLICE_FACTOR + # bound the masked operation to q len so it does not have to wast cycles + len_m = min(len_m, seqlen_q) + num_steps = tl.cdiv(len_m, MASK_BLOCK_M) + + + # when q < k, we may skip the initial masked op + # if seq_k_blk_idx < num_blocks_skip: + # num_steps = 0 + + if IS_FP8: + descale_q = tl.load(descale_q_ptr + batch_idx * stride_descale_q_z + head_q_idx) + descale_k = tl.load(descale_k_ptr + batch_idx * stride_descale_k_z + head_k_idx) + descale_v = tl.load(descale_v_ptr + batch_idx * stride_descale_v_z + head_k_idx) + descale_do = tl.load(descale_do_ptr + batch_idx * stride_descale_do_z + head_q_idx) + else: + descale_q, descale_k, descale_v, descale_do = 1.0, 1.0, 1.0, 1.0 + + # if start_m is negative, the current N-tile has no block on the + # diagonal of causal mask, so everything have no causal mask + dk, dv = _bwd_dkdvdq_inner( + dk, dv, # output tensors + q_ptr_adj, k, v, do_ptr_adj, dq_ptr_adj, m_ptr_adj, delta_ptr_adj, sm_scale, # input tensors + stride_q_m, stride_q_k, # strides for q + stride_do_m, stride_do_k, # strides for o + stride_dropout_m, stride_dropout_n, # strides for dropout + stride_delta_m, + dropout_p, philox_seed, batch_philox_offset, dropout_offset, # + seqlen_q, seqlen_k, # max sequence length for q and k + start_n, start_m, num_steps, # iteration numbers + descale_q, descale_k, descale_v, descale_do, # fp8 descale factors from user + MASK_BLOCK_M, BLOCK_N, # block dim + BLOCK_D_MODEL, BLOCK_D_MODEL_POW2, # head dim + MASK=True, # causal masking + ENABLE_DROPOUT=ENABLE_DROPOUT, # activate dropout + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + workgroup_id=seq_k_blk_idx, + ) + start_m += num_steps * MASK_BLOCK_M + num_steps = tl.cdiv(seqlen_q - start_m, BLOCK_M) + end_m = start_m + num_steps * BLOCK_M + + dk, dv = _bwd_dkdvdq_inner( + dk, dv, # output tensors + q_ptr_adj, k, v, do_ptr_adj, dq_ptr_adj, m_ptr_adj, delta_ptr_adj, sm_scale, # input tensors + stride_q_m, stride_q_k, # strides for q + stride_do_m, stride_do_k, # strides for o + stride_dropout_m, stride_dropout_n, # strides for dropout + stride_delta_m, + dropout_p, philox_seed, batch_philox_offset, dropout_offset, # + seqlen_q, seqlen_k, # max sequence length for q and k + start_n, start_m, num_steps, # iteration numbers + descale_q, descale_k, descale_v, descale_do, # fp8 descale factors from user + BLOCK_M, BLOCK_N, # block dim + BLOCK_D_MODEL, BLOCK_D_MODEL_POW2, # head dim + MASK=False, # causal masking + ENABLE_DROPOUT=ENABLE_DROPOUT, # activate dropout + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + workgroup_id=seq_k_blk_idx, + ) + + # Write back dV and dK. + offs_dkdv = (batch_idx * stride_dk_b + + head_k_idx * stride_dk_h + + k_start * stride_dk_n + offs_n[:, None] * stride_dk_n + + offs_k[None, :] * stride_dk_k) + tl.store(dv_ptr + offs_dkdv, dv, mask=mask_kv) + dk *= sm_scale + tl.store(dk_ptr + offs_dkdv, dk, mask=mask_kv) + + +@triton.jit +def _bwd_kernel_dkdv_causal( + q_ptr, k_ptr, v_ptr, sm_scale, do_ptr, dk_ptr, dv_ptr, + m_ptr, delta_ptr, + stride_q_b, stride_q_h, stride_q_m, stride_q_k, + stride_k_b, stride_k_h, stride_k_n, stride_k_k, + stride_v_b, stride_v_h, stride_v_n, stride_v_k, + stride_dk_b, stride_dk_h, stride_dk_n, stride_dk_k, + stride_delta_b, stride_delta_h, stride_delta_m, + stride_do_b, stride_do_h, stride_do_m, stride_do_k, + stride_dropout_b, stride_dropout_h, stride_dropout_m, stride_dropout_n, + stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_do_z, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, max_seqlen_k, + dropout_mask, dropout_p, philox_seed, philox_offset_base, + descale_q_ptr, descale_k_ptr, descale_v_ptr, descale_do_ptr, + NUM_Q_HEADS: tl.constexpr, + NUM_K_HEADS: tl.constexpr, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLK_SLICE_FACTOR: tl.constexpr, + BLOCK_D_MODEL: tl.constexpr, + BLOCK_D_MODEL_POW2: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + IS_VARLEN: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, +): + #seq block, batch, head_k + seq_k_blk_idx = tl.program_id(0) + batch_idx = tl.program_id(1) + head_k_idx = tl.program_id(2) + + #Determine q and k start along with seqlen_q and seqlen_k + q_start = 0 + k_start = 0 + seqlen_q = max_seqlen_q + seqlen_k = max_seqlen_k + if IS_VARLEN: + q_start = tl.load(cu_seqlens_q + batch_idx) + q_end = tl.load(cu_seqlens_q + batch_idx + 1) + k_start = tl.load(cu_seqlens_k + batch_idx) + k_end = tl.load(cu_seqlens_k + batch_idx + 1) + seqlen_q = q_end - q_start + seqlen_k = k_end - k_start + + dk = tl.zeros([BLOCK_N, BLOCK_D_MODEL_POW2], dtype=tl.float32) + dv = tl.zeros([BLOCK_N, BLOCK_D_MODEL_POW2], dtype=tl.float32) + + # Figure out causal starting block since we have seqlen_q >=< seqlen_k. + # Unlike forward pass where we tile on M dim and iterate on N dim, so that + # we can skip some M blocks, in backward pass, we tile on the N dim for kv + # and iterate over the M. In this way, we cannot skip N blocks, but only to + # determine the starting M blocks to skip some initial blocks masked by + # causal. + delta_qk = seqlen_q - seqlen_k + + # q > k: diretcly skip all the way until the start of causal block + start_delta_q_gt_k = delta_qk + + # q < k: some blocks will have no Masked block, other needs to re-calc + # starting position + # delta_qk is negative so flip it, only multiple of BLOCK_N can skip the + # masked op + num_blocks_skip = -delta_qk // BLOCK_N + delta_aligned = (num_blocks_skip + 1) * BLOCK_N + delta_qk + start_delta_q_lt_k = delta_aligned // BLOCK_M * BLOCK_M + if delta_qk >= 0: + start_delta = delta_qk + else: + start_delta = start_delta_q_lt_k + + start_n = seq_k_blk_idx *BLOCK_N + + offs_k = tl.arange(0, BLOCK_D_MODEL_POW2) + offs_n = start_n + tl.arange(0, BLOCK_N) + # Mask for loading K and V + mask_kv = offs_n[:, None] < seqlen_k + PADDED_HEAD: tl.constexpr = (BLOCK_D_MODEL != BLOCK_D_MODEL_POW2) + if PADDED_HEAD: + mask_k = offs_k < BLOCK_D_MODEL + mask_kv &= mask_k[None, :] + + GROUP_SIZE = NUM_Q_HEADS // NUM_K_HEADS + adj_k = (batch_idx * stride_k_b + + head_k_idx * stride_k_h + + k_start * stride_k_n + offs_n[:, None] * stride_k_n + + offs_k[None, :] * stride_k_k) + adj_v = (batch_idx * stride_v_b + + head_k_idx * stride_v_h + + k_start * stride_v_n + offs_n[:, None] * stride_v_n + + offs_k[None, :] * stride_v_k) + # load K and V: they stay in SRAM throughout the inner loop. + k = tl.load(k_ptr + adj_k , mask=mask_kv, other=0.0) + v = tl.load(v_ptr + adj_v, mask=mask_kv, other=0.0) + + # If MQA / GQA, set the K and V head offsets appropriately. + for head_q_idx in range(head_k_idx * GROUP_SIZE, head_k_idx * GROUP_SIZE + GROUP_SIZE): + if delta_qk >= 0: + start_m = start_n + start_delta + len_m = BLOCK_N + else: + start_m = max(start_n + delta_qk, 0) + start_m = start_m // BLOCK_M * BLOCK_M + # because we might shift the masked blocks up, we are deeper into + # the masked out region, so we would potentially increase the total + # steps with masked operation to get out of it + residue_m = max(start_n + delta_qk - start_m, 0) + len_m = BLOCK_N + residue_m + + # offset input and output tensor by batch and Q/K heads + adj_q = batch_idx * stride_q_b + head_q_idx * stride_q_h + q_start * stride_q_m + q_ptr_adj = q_ptr + adj_q + adj_do = batch_idx * stride_do_b + head_q_idx * stride_do_h + q_start * stride_do_m + do_ptr_adj = do_ptr + adj_do + adj_delta = batch_idx * stride_delta_b + head_q_idx * stride_delta_h + q_start * stride_delta_m + m_ptr_adj = m_ptr + adj_delta + delta_ptr_adj = delta_ptr + adj_delta + + # batch_philox_offset is the ACTUALLY dropout offset + # dropout_offset is for debug purpose and will be removed later + batch_philox_offset = 0 + dropout_offset = 0 + if ENABLE_DROPOUT: + batch_philox_offset = (philox_offset_base + batch_idx * stride_dropout_b + + head_q_idx * stride_dropout_h) + dropout_offset = (dropout_mask + batch_idx * stride_dropout_b + + head_q_idx * stride_dropout_h) + + MASK_BLOCK_M: tl.constexpr = BLOCK_M // BLK_SLICE_FACTOR + # bound the masked operation to q len so it does not have to wast cycles + len_m = min(len_m, seqlen_q) + num_steps = tl.cdiv(len_m, MASK_BLOCK_M) + # when q < k, we may skip the initial masked op + if seq_k_blk_idx < num_blocks_skip: + num_steps = 0 + + if IS_FP8: + descale_q = tl.load(descale_q_ptr + batch_idx * stride_descale_q_z + head_q_idx) + descale_k = tl.load(descale_k_ptr + batch_idx * stride_descale_k_z + head_k_idx) + descale_v = tl.load(descale_v_ptr + batch_idx * stride_descale_v_z + head_k_idx) + descale_do = tl.load(descale_do_ptr + batch_idx * stride_descale_do_z + head_q_idx) + else: + descale_q, descale_k, descale_v, descale_do = 1.0, 1.0, 1.0, 1.0 + + # if start_m is negative, the current N-tile has no block on the + # diagonal of causal mask, so everything have no causal mask + dk, dv = _bwd_dkdv_inner( + dk, dv, # output tensors + q_ptr_adj, k, v, do_ptr_adj, m_ptr_adj, delta_ptr_adj, sm_scale, # input tensors + stride_q_m, stride_q_k, # strides for q + stride_do_m, stride_do_k, # strides for o + stride_dropout_m, stride_dropout_n, # strides for dropout + stride_delta_m, + dropout_p, philox_seed, batch_philox_offset, dropout_offset, # + seqlen_q, seqlen_k, # max sequence length for q and k + start_n, start_m, num_steps, # iteration numbers + descale_q, descale_k, descale_v, descale_do, # fp8 descale factors from user + MASK_BLOCK_M, BLOCK_N, # block dim + BLOCK_D_MODEL, BLOCK_D_MODEL_POW2, # head dim + MASK=True, # causal masking + ENABLE_DROPOUT=ENABLE_DROPOUT, # activate dropout + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + ) + start_m += num_steps * MASK_BLOCK_M + num_steps = tl.cdiv(seqlen_q - start_m, BLOCK_M) + end_m = start_m + num_steps * BLOCK_M + + dk, dv = _bwd_dkdv_inner( + dk, dv, # output tensors + q_ptr_adj, k, v, do_ptr_adj, m_ptr_adj, delta_ptr_adj, sm_scale, # input tensors + stride_q_m, stride_q_k, # strides for q + stride_do_m, stride_do_k, # strides for o + stride_dropout_m, stride_dropout_n, # strides for dropout + stride_delta_m, + dropout_p, philox_seed, batch_philox_offset, dropout_offset, # + seqlen_q, seqlen_k, # max sequence length for q and k + start_n, start_m, num_steps, # iteration numbers + descale_q, descale_k, descale_v, descale_do, # fp8 descale factors from user + BLOCK_M, BLOCK_N, # block dim + BLOCK_D_MODEL, BLOCK_D_MODEL_POW2, # head dim + MASK=False, # causal masking + ENABLE_DROPOUT=ENABLE_DROPOUT, # activate dropout + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + ) + + # Write back dV and dK. + offs_dkdv = (batch_idx * stride_dk_b + + head_k_idx * stride_dk_h + + k_start * stride_dk_n + offs_n[:, None] * stride_dk_n + + offs_k[None, :] * stride_dk_k) + tl.store(dv_ptr + offs_dkdv, dv, mask=mask_kv) + dk *= sm_scale + tl.store(dk_ptr + offs_dkdv, dk, mask=mask_kv) + +@triton.jit +def _bwd_kernel_dq_causal( + q_ptr, k_ptr, v_ptr, sm_scale, do_ptr, dq_ptr, + m_ptr, delta_ptr, + stride_q_b, stride_q_h, stride_q_m, stride_q_k, + stride_k_b, stride_k_h, stride_k_n, stride_k_k, + stride_v_b, stride_v_h, stride_v_n, stride_v_k, + stride_dq_b, stride_dq_h, stride_dq_m, stride_dq_k, + stride_delta_b, stride_delta_h, stride_delta_m, + stride_do_b, stride_do_h, stride_do_m, stride_do_k, + stride_dropout_b, stride_dropout_h, stride_dropout_m, stride_dropout_n, + stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_do_z, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, max_seqlen_k, + dropout_mask, dropout_p, philox_seed, philox_offset_base, + descale_q_ptr, descale_k_ptr, descale_v_ptr, descale_do_ptr, + NUM_Q_HEADS: tl.constexpr, + NUM_K_HEADS: tl.constexpr, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLK_SLICE_FACTOR: tl.constexpr, + BLOCK_D_MODEL: tl.constexpr, + BLOCK_D_MODEL_POW2: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + IS_VARLEN: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, +): + seq_q_blk_idx = tl.program_id(0) + batch_idx = tl.program_id(1) + head_k_idx = tl.program_id(2) + + q_start = 0 + k_start = 0 + seqlen_q = max_seqlen_q + seqlen_k = max_seqlen_k + if IS_VARLEN: + q_start = tl.load(cu_seqlens_q + batch_idx) + q_end = tl.load(cu_seqlens_q + batch_idx + 1) + k_start = tl.load(cu_seqlens_k + batch_idx) + k_end = tl.load(cu_seqlens_k + batch_idx + 1) + seqlen_q = q_end - q_start + seqlen_k = k_end - k_start + + # Figure out causal starting block since we have seqlen_q <=> seqlen_k. + # Unlike forward pass where we tile on M dim and iterate on N dim, so that + # we can skip some M blocks, in backward pass, we tile on the N dim for kv + # and iterate over the M. In this way, we cannot skip N blocks, but only to + # determine the starting M blocks to skip some initial blocks masked by + # causal. + # DQ tiles on M dim and iterate on N dim, so we there could be some tiles we + # can simply skip and we need to adjust starting position. + start_m = seq_q_blk_idx * BLOCK_M + # seqlen_q > seqlen_k, no need to process these tile for dq + delta_qk = seqlen_q - seqlen_k + if start_m + BLOCK_M < delta_qk: + return + + offs_k = tl.arange(0, BLOCK_D_MODEL_POW2) + offs_m = start_m + tl.arange(0, BLOCK_M) + # Mask for loading K and V + mask_q = offs_m[:, None] < seqlen_q + PADDED_HEAD: tl.constexpr = (BLOCK_D_MODEL != BLOCK_D_MODEL_POW2) + if PADDED_HEAD: + mask_k = offs_k < BLOCK_D_MODEL + mask_q &= mask_k[None, :] + offs_q = offs_m[:, None] * stride_q_m + offs_k[None, :] * stride_q_k + offs_do = offs_m[:, None] * stride_do_m + offs_k[None, :] * stride_do_k + adj_k = batch_idx * stride_k_b + head_k_idx * stride_k_h + k_start * stride_k_n + adj_v = batch_idx * stride_v_b + head_k_idx * stride_v_h + k_start * stride_v_n + k_ptr_adj = k_ptr + v_ptr_adj = v_ptr + k_ptr_adj += adj_k + v_ptr_adj += adj_v + + # If MQA / GQA, set the K and V head offsets appropriately. + GROUP_SIZE = NUM_Q_HEADS // NUM_K_HEADS + for head_q_idx in range(head_k_idx * GROUP_SIZE, head_k_idx * GROUP_SIZE + GROUP_SIZE): + # seqlen_q < seqlen_k: delta_qk more kv tokens are added at the front + # for every M-tile + end_n = start_m + BLOCK_M - delta_qk + # clamp end_n at [0, seqlen_k] + end_n = max(min(end_n, seqlen_k), 0) + + # offset input and output tensor by batch and Q/K heads + adj_q = (batch_idx * stride_q_b + + head_q_idx * stride_q_h + + q_start * stride_q_m) + adj_do = (batch_idx * stride_do_b + + head_q_idx * stride_do_h + + q_start * stride_do_m) + adj_delta = (batch_idx * stride_delta_b + + head_q_idx * stride_delta_h + + q_start * stride_delta_m) + delta_ptr_adj = delta_ptr + adj_delta + + # batch_philox_offset is the ACTUALLY dropout offset + # dropout_offset is for debug purpose and will be removed later + batch_philox_offset = 0 + dropout_offset = 0 + if ENABLE_DROPOUT: + batch_philox_offset = (philox_offset_base + + batch_idx * stride_dropout_b + + head_q_idx * stride_dropout_h) + dropout_offset = (dropout_mask + + batch_idx * stride_dropout_b + + head_q_idx * stride_dropout_h) + + q = tl.load(q_ptr + adj_q + offs_q, mask=mask_q, other=0.0) + do = tl.load(do_ptr + adj_do + offs_do, mask=mask_q, other=0.0) + m = tl.load(m_ptr + adj_delta + offs_m * stride_delta_m, + mask=offs_m < seqlen_q) + m = m[:, None] + + MASK_BLOCK_N: tl.constexpr = BLOCK_N // BLK_SLICE_FACTOR + # start can only be 0 at minimum + start_n = max(end_n - BLOCK_M, 0) + num_steps = tl.cdiv(end_n - start_n, MASK_BLOCK_N) + + if IS_FP8: + descale_q = tl.load(descale_q_ptr + batch_idx * stride_descale_q_z + head_q_idx) + descale_k = tl.load(descale_k_ptr + batch_idx * stride_descale_k_z + head_k_idx) + descale_v = tl.load(descale_v_ptr + batch_idx * stride_descale_v_z + head_k_idx) + descale_do = tl.load(descale_do_ptr + batch_idx * stride_descale_do_z + head_q_idx) + else: + descale_q, descale_k, descale_v, descale_do = 1.0, 1.0, 1.0, 1.0 + + dq = tl.zeros([BLOCK_M, BLOCK_D_MODEL_POW2], dtype=tl.float32) + # Compute dQ for masked (diagonal) blocks. + # NOTE: This code scans each row of QK^T backward (from right to left, + # but inside each call to _bwd_dq_inner, from left to right), but that's + # not due to anything important. I just wanted to reuse the loop + # structure for dK & dV above as much as possible. + dq = _bwd_dq_inner( + dq, + q, k_ptr_adj, v_ptr_adj, do, m, delta_ptr_adj, sm_scale, + stride_q_m, stride_q_k, stride_k_n, stride_k_k, stride_v_n, stride_v_k, + stride_dropout_m, stride_dropout_n, + stride_delta_m, + seqlen_q, seqlen_k, + dropout_p, philox_seed, batch_philox_offset, dropout_offset, + start_m, start_n, end_n, num_steps, + descale_q, descale_k, descale_v, descale_do, + BLOCK_M, MASK_BLOCK_N, + BLOCK_D_MODEL, BLOCK_D_MODEL_POW2, + MASK=True, + ENABLE_DROPOUT=ENABLE_DROPOUT, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + ) + end_n -= num_steps * MASK_BLOCK_N + num_steps = tl.cdiv(end_n, BLOCK_N) + start_n = max(end_n - num_steps * BLOCK_N, 0) + dq = _bwd_dq_inner( + dq, + q, k_ptr_adj, v_ptr_adj, do, m, delta_ptr_adj, sm_scale, + stride_q_m, stride_q_k, stride_k_n, stride_k_k, stride_v_n, stride_v_k, + stride_dropout_m, stride_dropout_n, + stride_delta_m, + seqlen_q, seqlen_k, + dropout_p, philox_seed, batch_philox_offset, dropout_offset, + start_m, start_n, end_n, num_steps, + descale_q, descale_k, descale_v, descale_do, + BLOCK_M, BLOCK_N, + BLOCK_D_MODEL, BLOCK_D_MODEL_POW2, + MASK=False, + ENABLE_DROPOUT=ENABLE_DROPOUT, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + ) + # Write back dQ. + offs_dq = (batch_idx * stride_dq_b + + head_q_idx * stride_dq_h + + q_start * stride_dq_m + + offs_m[:, None] * stride_dq_m + + offs_k[None, :] * stride_dq_k) + dq *= sm_scale + tl.store(dq_ptr + offs_dq, dq, mask=mask_q) + + +@triton.jit +def _bwd_kernel_dkdvdq_noncausal( + Q, K, V, sm_scale, DO, DK, DV, DQ, + M, Delta, + stride_qb, stride_qh, stride_qm, stride_qk, + stride_kb, stride_kh, stride_kn, stride_kk, + stride_vb, stride_vh, stride_vn, stride_vk, + stride_dkb, stride_dkh, stride_dkn, stride_dkk, + stride_deltab, stride_deltah, stride_deltam, + stride_dob, stride_doh, stride_dom, stride_dok, + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn, + stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_do_z, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, max_seqlen_k, + dropout_mask, dropout_p, philox_seed, philox_offset, + descale_q_ptr, descale_k_ptr, descale_v_ptr, descale_do_ptr, + NUM_Q_HEADS: tl.constexpr, + NUM_K_HEADS: tl.constexpr, + BATCH, + NUM_K_PIDS, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLK_SLICE_FACTOR: tl.constexpr, + BLOCK_D_MODEL: tl.constexpr, + BLOCK_D_MODEL_POW2: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + IS_VARLEN: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, +): + # workgroup id + wid = tl.program_id(0) # 0, ..., NUM_K_PIDS * BATCH * NUM_K_HEADS - 1 + + # Workgroups get launched first along batch dim, then in head_k dim, and then in seq k block dim + # This is in order to avoid contention for the tl.atomic_add (inside _bwd_dkdvdq_inner) that happens between workgroups that share the same batch and head_k. + bid = wid % BATCH + hkid = wid // BATCH % NUM_K_HEADS + pid = wid // (BATCH * NUM_K_HEADS) % NUM_K_PIDS + + q_start = 0 + k_start = 0 + seqlen_q = max_seqlen_q + seqlen_k = max_seqlen_k + + if IS_VARLEN: + q_start = tl.load(cu_seqlens_q + bid) + q_end = tl.load(cu_seqlens_q + bid + 1) + k_start = tl.load(cu_seqlens_k + bid) + k_end = tl.load(cu_seqlens_k + bid + 1) + seqlen_q = q_end - q_start + seqlen_k = k_end - k_start + + + dk = tl.zeros([BLOCK_N, BLOCK_D_MODEL_POW2], dtype=tl.float32) + dv = tl.zeros([BLOCK_N, BLOCK_D_MODEL_POW2], dtype=tl.float32) + + start_n = pid * BLOCK_N + + offs_k = tl.arange(0, BLOCK_D_MODEL_POW2) + offs_n = start_n + tl.arange(0, BLOCK_N) + mask_kv = offs_n[:, None] < seqlen_k + PADDED_HEAD: tl.constexpr = (BLOCK_D_MODEL != BLOCK_D_MODEL_POW2) + if PADDED_HEAD: + mask_kv &= offs_k < BLOCK_D_MODEL + + GROUP_SIZE = NUM_Q_HEADS // NUM_K_HEADS + adj_k = (bid * stride_kb + + hkid * stride_kh + + k_start * stride_kn + + offs_n[:, None] * stride_kn + + offs_k[None, :] * stride_kk) + adj_v = (bid * stride_vb + + hkid * stride_vh + + k_start * stride_vn + + offs_n[:, None] * stride_vn + + offs_k[None, :] * stride_vk) + + k = tl.load(K + adj_k, mask=mask_kv, other=0.0) + v = tl.load(V + adj_v, mask=mask_kv, other=0.0) + + for hqid in range(hkid * GROUP_SIZE, hkid * GROUP_SIZE + GROUP_SIZE): + adj_q = (bid * stride_qb + hqid * stride_qh + q_start * stride_qm) + + Q_ptr = Q + adj_q + DQ_ptr = DQ + adj_q + + adj_do = (bid * stride_dob + hqid * stride_doh + q_start * stride_dom) + DO_ptr = DO + adj_do + adj_delta = (bid * stride_deltab + hqid * stride_deltah + q_start * stride_deltam) + M_ptr = M + adj_delta + Delta_ptr = Delta + adj_delta + + #dropout + batch_philox_offset = 0 + dropout_offset = 0 + if ENABLE_DROPOUT: + batch_philox_offset = philox_offset + bid * stride_dropoutb + \ + hqid * stride_dropouth + dropout_offset = dropout_mask + bid * stride_dropoutb + \ + hqid * stride_dropouth + + if IS_FP8: + descale_q = tl.load(descale_q_ptr + bid * stride_descale_q_z + hqid) + descale_k = tl.load(descale_k_ptr + bid * stride_descale_k_z + hkid) + descale_v = tl.load(descale_v_ptr + bid * stride_descale_v_z + hkid) + descale_do = tl.load(descale_do_ptr + bid * stride_descale_do_z + hqid) + else: + descale_q, descale_k, descale_v, descale_do = 1.0, 1.0, 1.0, 1.0 + + start_m = 0 + num_steps = tl.cdiv(seqlen_q, BLOCK_M) + + dk, dv = _bwd_dkdvdq_inner( + dk, dv, + Q_ptr, k, v, DO_ptr, DQ_ptr, M_ptr, Delta_ptr, sm_scale, + stride_qm, stride_qk, + stride_dom, stride_dok, + stride_dropoutm, stride_dropoutn, + stride_deltam, + dropout_p, philox_seed, batch_philox_offset, dropout_offset, + seqlen_q, seqlen_k, + start_n, start_m, num_steps, + descale_q, descale_k, descale_v, descale_do, + BLOCK_M, BLOCK_N, + BLOCK_D_MODEL, BLOCK_D_MODEL_POW2, + MASK=False, + ENABLE_DROPOUT=ENABLE_DROPOUT, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + workgroup_id=pid, + ) + + adj_dkdv = (bid * stride_dkb + + hkid * stride_dkh + + k_start * stride_dkn + offs_n[:, None] * stride_dkn + + offs_k[None, :] * stride_dkk) + tl.store(DV + adj_dkdv, dv, mask=mask_kv) + dk *= sm_scale + tl.store(DK + adj_dkdv, dk, mask=mask_kv) + + + +@triton.jit +def _bwd_kernel_dkdv_noncausal( + Q, K, V, sm_scale, DO, DK, DV, + M, Delta, + stride_qb, stride_qh, stride_qm, stride_qk, + stride_kb, stride_kh, stride_kn, stride_kk, + stride_vb, stride_vh, stride_vn, stride_vk, + stride_dkb, stride_dkh, stride_dkn, stride_dkk, + stride_deltab, stride_deltah, stride_deltam, + stride_dob, stride_doh, stride_dom, stride_dok, + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn, + stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_do_z, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, max_seqlen_k, + dropout_mask, dropout_p, philox_seed, philox_offset, + descale_q_ptr, descale_k_ptr, descale_v_ptr, descale_do_ptr, + NUM_Q_HEADS: tl.constexpr, + NUM_K_HEADS: tl.constexpr, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLK_SLICE_FACTOR: tl.constexpr, + BLOCK_D_MODEL: tl.constexpr, + BLOCK_D_MODEL_POW2: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + IS_VARLEN: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, +): + pid = tl.program_id(0) + bid = tl.program_id(1) + hkid = tl.program_id(2) + + q_start = 0 + k_start = 0 + seqlen_q = max_seqlen_q + seqlen_k = max_seqlen_k + + if IS_VARLEN: + q_start = tl.load(cu_seqlens_q + bid) + q_end = tl.load(cu_seqlens_q + bid + 1) + k_start = tl.load(cu_seqlens_k + bid) + k_end = tl.load(cu_seqlens_k + bid + 1) + seqlen_q = q_end - q_start + seqlen_k = k_end - k_start + + + dk = tl.zeros([BLOCK_N, BLOCK_D_MODEL_POW2], dtype=tl.float32) + dv = tl.zeros([BLOCK_N, BLOCK_D_MODEL_POW2], dtype=tl.float32) + + start_n = pid * BLOCK_N + + offs_k = tl.arange(0, BLOCK_D_MODEL_POW2) + offs_n = start_n + tl.arange(0, BLOCK_N) + mask_kv = offs_n[:, None] < seqlen_k + PADDED_HEAD: tl.constexpr = (BLOCK_D_MODEL != BLOCK_D_MODEL_POW2) + if PADDED_HEAD: + mask_kv &= offs_k < BLOCK_D_MODEL + + GROUP_SIZE = NUM_Q_HEADS // NUM_K_HEADS + adj_k = (bid * stride_kb + + hkid * stride_kh + + k_start * stride_kn + + offs_n[:, None] * stride_kn + + offs_k[None, :] * stride_kk) + adj_v = (bid * stride_vb + + hkid * stride_vh + + k_start * stride_vn + + offs_n[:, None] * stride_vn + + offs_k[None, :] * stride_vk) + + k = tl.load(K + adj_k, mask=mask_kv, other=0.0) + v = tl.load(V + adj_v, mask=mask_kv, other=0.0) + + for hqid in range(hkid * GROUP_SIZE, hkid * GROUP_SIZE + GROUP_SIZE): + adj_q = (bid * stride_qb + hqid * stride_qh + q_start * stride_qm) + Q_ptr = Q + adj_q + adj_do = (bid * stride_dob + hqid * stride_doh + q_start * stride_dom) + DO_ptr = DO + adj_do + adj_delta = (bid * stride_deltab + hqid * stride_deltah + q_start * stride_deltam) + M_ptr = M + adj_delta + Delta_ptr = Delta + adj_delta + + #dropout + batch_philox_offset = 0 + dropout_offset = 0 + if ENABLE_DROPOUT: + batch_philox_offset = philox_offset + bid * stride_dropoutb + \ + hqid * stride_dropouth + dropout_offset = dropout_mask + bid * stride_dropoutb + \ + hqid * stride_dropouth + + if IS_FP8: + descale_q = tl.load(descale_q_ptr + bid * stride_descale_q_z + hqid) + descale_k = tl.load(descale_k_ptr + bid * stride_descale_k_z + hkid) + descale_v = tl.load(descale_v_ptr + bid * stride_descale_v_z + hkid) + descale_do = tl.load(descale_do_ptr + bid * stride_descale_do_z + hqid) + else: + descale_q, descale_k, descale_v, descale_do = 1.0, 1.0, 1.0, 1.0 + + start_m = 0 + num_steps = tl.cdiv(seqlen_q, BLOCK_M) + dk, dv = _bwd_dkdv_inner( + dk, dv, + Q_ptr, k, v, DO_ptr, M_ptr, Delta_ptr, sm_scale, + stride_qm, stride_qk, + stride_dom, stride_dok, + stride_dropoutm, stride_dropoutn, + stride_deltam, + dropout_p, philox_seed, batch_philox_offset, dropout_offset, + seqlen_q, seqlen_k, + start_n, start_m, num_steps, + descale_q, descale_k, descale_v, descale_do, + BLOCK_M, BLOCK_N, + BLOCK_D_MODEL, BLOCK_D_MODEL_POW2, + MASK=False, + ENABLE_DROPOUT=ENABLE_DROPOUT, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + ) + + adj_dkdv = (bid * stride_dkb + + hkid * stride_dkh + + k_start * stride_dkn + offs_n[:, None] * stride_dkn + + offs_k[None, :] * stride_dkk) + tl.store(DV + adj_dkdv, dv, mask=mask_kv) + dk *= sm_scale + tl.store(DK + adj_dkdv, dk, mask=mask_kv) + + +@triton.jit +def _bwd_kernel_dq_noncausal( + Q, K, V, sm_scale, DO, DQ, + M, delta, + stride_qb, stride_qh, stride_qm, stride_qk, + stride_kb, stride_kh, stride_kn, stride_kk, + stride_vb, stride_vh, stride_vn, stride_vk, + stride_dqb, stride_dqh, stride_dqm, stride_dqk, + stride_deltab, stride_deltah, stride_deltam, + stride_dob, stride_doh, stride_dom, stride_dok, + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn, + stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_do_z, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, max_seqlen_k, + dropout_mask, dropout_p, philox_seed, philox_offset_base, + descale_q_ptr, descale_k_ptr, descale_v_ptr, descale_do_ptr, + NUM_Q_HEADS: tl.constexpr, + NUM_K_HEADS: tl.constexpr, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLK_SLICE_FACTOR: tl.constexpr, + BLOCK_D_MODEL: tl.constexpr, + BLOCK_D_MODEL_POW2: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + IS_VARLEN: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, +): + pid = tl.program_id(0) #seqlen + bid = tl.program_id(1) #batch + hkid = tl.program_id(2) #head_k + + q_start = 0 + k_start = 0 + seqlen_q = max_seqlen_q + seqlen_k = max_seqlen_k + + if IS_VARLEN: + # Compute actual sequence lengths + q_start = tl.load(cu_seqlens_q + bid) + q_end = tl.load(cu_seqlens_q + bid + 1) + k_start = tl.load(cu_seqlens_k + bid) + k_end = tl.load(cu_seqlens_k + bid + 1) + seqlen_q = q_end - q_start + seqlen_k = k_end - k_start + + start_m = pid * BLOCK_M + + offs_k = tl.arange(0, BLOCK_D_MODEL_POW2) + offs_m = start_m + tl.arange(0, BLOCK_M) + + #mask for loading K and V + mask_q = offs_m[:, None] < seqlen_q + PADDED_HEAD: tl.constexpr = (BLOCK_D_MODEL != BLOCK_D_MODEL_POW2) + if PADDED_HEAD: + mask_k = offs_k < BLOCK_D_MODEL + mask_q &= mask_k[None, :] + offs_q = offs_m[:, None] * stride_qm + offs_k[None, :] * stride_qk + offs_do = offs_m[:, None] * stride_dom + offs_k[None, :] * stride_dok + adj_k = bid * stride_kb + hkid * stride_kh + k_start * stride_kn + adj_v = bid * stride_vb + hkid * stride_vh + k_start * stride_vn + K += adj_k + V += adj_v + + GROUP_SIZE = NUM_Q_HEADS // NUM_K_HEADS + for hqid in range(hkid * GROUP_SIZE, hkid * GROUP_SIZE + GROUP_SIZE): + adj_q = bid * stride_qb + hqid * stride_qh + q_start * stride_qm + adj_do = bid * stride_dob + hqid * stride_doh + q_start * stride_dom + adj_delta = bid * stride_deltab + hqid * stride_deltah + q_start * stride_deltam + delta_ptr = delta + adj_delta + + batch_philox_offset = 0 + dropout_offset = 0 + if ENABLE_DROPOUT: + batch_philox_offset = (philox_offset_base + + bid * stride_dropoutb + + hqid * stride_dropouth) + dropout_offset = ( + dropout_mask + bid * stride_dropoutb + hqid * stride_dropouth) + + q = tl.load(Q + adj_q + offs_q, mask=mask_q, other=0.0) + do = tl.load(DO + adj_do + offs_do, mask=mask_q, other=0.0) + m = tl.load(M + adj_delta + offs_m * stride_deltam, mask=offs_m < seqlen_q) + m = m[:, None] + + #FP8 + if IS_FP8: + descale_q = tl.load(descale_q_ptr + bid * stride_descale_q_z + hqid) + descale_k = tl.load(descale_k_ptr + bid * stride_descale_k_z + hkid) + descale_v = tl.load(descale_v_ptr + bid * stride_descale_v_z + hkid) + descale_do = tl.load(descale_do_ptr + bid * stride_descale_do_z + hqid) + else: + descale_q, descale_k, descale_v, descale_do = 1.0, 1.0, 1.0, 1.0 + + start_n = 0 + end_n = seqlen_k + num_steps = tl.cdiv(seqlen_k, BLOCK_N) + dq = tl.zeros([BLOCK_M, BLOCK_D_MODEL_POW2], dtype=tl.float32) + dq = _bwd_dq_inner( + dq, + q, K, V, do, m, delta_ptr, sm_scale, + stride_qm, stride_qk, stride_kn, stride_kk, stride_vn, stride_vk, + stride_dropoutm, stride_dropoutn, + stride_deltam, + seqlen_q, seqlen_k, + dropout_p, philox_seed, batch_philox_offset, dropout_offset, + start_m, start_n, end_n, num_steps, + descale_q, descale_k, descale_v, descale_do, + BLOCK_M, BLOCK_N, + BLOCK_D_MODEL, BLOCK_D_MODEL_POW2, + MASK=False, + ENABLE_DROPOUT=ENABLE_DROPOUT, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + ) + + adj_dq = bid * stride_dqb + hqid * stride_dqh + q_start * stride_dqm + offs_dq = offs_m[:, None] * stride_dqm + offs_k[None, :] * stride_dqk + dq *= sm_scale + tl.store(DQ + adj_dq + offs_dq, dq, mask=mask_q) + +def _flash_attn_backward( + do: torch.Tensor, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + o: torch.Tensor, + softmax_lse: torch.Tensor, + dq: torch.Tensor, + dk: torch.Tensor, + dv: torch.Tensor, + sm_scale: float, + alibi_slopes: Optional[torch.Tensor], + causal: bool, + cu_seqlens_q: Optional[torch.Tensor], + cu_seqlens_k: Optional[torch.Tensor], + max_seqlen_q: int, + max_seqlen_k: int, + dropout_p: float, + philox_seed: Optional[int] = 0, + philox_offset: Optional[int] = 0, + descale_q: Optional[torch.Tensor] = None, + descale_k: Optional[torch.Tensor] = None, + descale_v: Optional[torch.Tensor] = None, + descale_do: Optional[torch.Tensor] = None, + fused: bool = False, +): + IS_FP8 = is_fp8(q) + if IS_FP8: + FP8_MAX = torch.finfo(q.dtype).max + descale_strides = (descale_q.stride(0),descale_k.stride(0),descale_v.stride(0),descale_do.stride(0) ) + else: + FP8_MAX = None + stride_descale_q_z = stride_descale_k_z = stride_descale_v_z = stride_descale_do_z = None + descale_strides = (stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_do_z) + + IS_VARLEN = True if cu_seqlens_q is not None else False + + #get strides and shape + if IS_VARLEN: + #Layout for q,k,v is thd ie [total tokens, num_head, head_dim] + batch, seqlen_q, num_q_heads, head_sz = len(cu_seqlens_q) - 1, max_seqlen_q, q.shape[1], q.shape[2] + seqlen_k, num_k_heads = max_seqlen_k, k.shape[1] + q_strides = (0, q.stride(1), q.stride(0), q.stride(2)) + q_strides = (0, q.stride(1), q.stride(0), q.stride(2)) + k_strides = (0, k.stride(1), k.stride(0), k.stride(2)) + v_strides = (0, v.stride(1), v.stride(0), v.stride(2)) + o_strides = (0, o.stride(1), o.stride(0), o.stride(2)) + dq_strides = (0, dq.stride(1), dq.stride(0), dq.stride(2)) + dk_strides = (0, dk.stride(1), dk.stride(0), dk.stride(2)) + dv_strides = (0, dv.stride(1), dv.stride(0), dv.stride(2)) + do_strides = (0, do.stride(1), do.stride(0), do.stride(2)) + else: + #Layout for q,k,v is bshd ie [batch, seq_len, num_head, head_dim] + batch, seqlen_q, num_q_heads, head_sz = q.shape + seqlen_k, num_k_heads = k.shape[1], k.shape[2] + q_strides = (q.stride(0), q.stride(2), q.stride(1), q.stride(3)) + k_strides = (k.stride(0), k.stride(2), k.stride(1), k.stride(3)) + v_strides = (v.stride(0), v.stride(2), v.stride(1), v.stride(3)) + o_strides = (o.stride(0), o.stride(2), o.stride(1), o.stride(3)) + dq_strides = (dq.stride(0), dq.stride(2), dq.stride(1), dq.stride(3)) + dk_strides = (dk.stride(0), dk.stride(2), dk.stride(1), dk.stride(3)) + dv_strides = (dv.stride(0), dv.stride(2), dv.stride(1), dv.stride(3)) + do_strides = (do.stride(0), do.stride(2), do.stride(1), do.stride(3)) + + #BLOCK_D_MODEL, BLOCK_D_MODEL_POW2 + #padding for head_dim. Power of 2 or 16 + BLOCK_D_MODEL_POW2 = triton.next_power_of_2(head_sz) + BLOCK_D_MODEL_POW2 = max(BLOCK_D_MODEL_POW2, 16) + + #Configs + #PRE_BLOCK, BLOCK_M1, BLOCK_N1, BLOCK_M2, BLOCK_N2 + #BLK_SLICE_FACTOR + NUM_WARPS, NUM_STAGES = 4, 1 + WAVES_PER_EU = 1 + PRE_BLOCK = 128 + #BLOCK_M1, BLOCK_N1, BLOCK_M2, BLOCK_N2 = 32, 128, 128, 32 + BLOCK_M1, BLOCK_N1, BLOCK_M2, BLOCK_N2 = 64, 64, 64, 16 + BLK_SLICE_FACTOR = 2 + + #init delta + delta = torch.zeros_like(softmax_lse) + if IS_VARLEN: + #[total_tokens, num_q_heads, seqlen_q] + delta_strides = (0, delta.stride(1), delta.stride(0)) + else: + #[batch, num_q_heads, seqlen_q] + delta_strides = delta.stride() + + #preprocess + #compute D(delta) = rowsum(dO*O). Note, multiplication is element-wise. + pre_grid = (triton.cdiv(max_seqlen_q, PRE_BLOCK), batch, num_q_heads) + _bwd_preprocess[pre_grid]( + o, do, + delta, + *o_strides, + *delta_strides, + descale_strides[3], + cu_seqlens_q, max_seqlen_q, + descale_do, + BLOCK_M=PRE_BLOCK, + BLOCK_D_MODEL=head_sz, + BLOCK_D_MODEL_POW2=BLOCK_D_MODEL_POW2, + IS_VARLEN=IS_VARLEN, + IS_FP8=IS_FP8 + ) + + #dropout_mask + use_dropout = (dropout_p > 0.0) + if use_dropout: + dropout_mask = torch.zeros( + (batch, num_q_heads, max_seqlen_q, max_seqlen_k), + device=q.device, + dtype=torch.float32) + dropout_strides = dropout_mask.stride() + else: + dropout_mask = None + dropout_strides = (0, 0, 0, 0) + + grid_dkdv = ((max_seqlen_k + BLOCK_N1 - 1) // BLOCK_N1, batch, num_k_heads) + grid_dq = ((max_seqlen_q + BLOCK_M2 - 1) // BLOCK_M2, batch, num_k_heads) + + if fused: # fuses dk, dv, dq computations into one kernel by computing the dq using atomic adds between workgroups + + BLOCK_N = 128 + config = { + "BLOCK_M": 32, + "BLOCK_N": BLOCK_N, + "num_warps": 4, + "num_stages": 1, + "waves_per_eu": 1, + "BLK_SLICE_FACTOR": 2, + } + + num_k_pids = (max_seqlen_k + BLOCK_N - 1) // BLOCK_N + grid_dkdvdq = (batch * num_k_heads * num_k_pids,) + + if causal: + _bwd_kernel_dkdvdq_causal[grid_dkdvdq]( + q, k, v, sm_scale, do, dk, dv, dq, + softmax_lse, delta, + *q_strides, + *k_strides, + *v_strides, + *dk_strides, + *delta_strides, + *do_strides, + *dropout_strides, + *descale_strides, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_mask,dropout_p, philox_seed, philox_offset, + descale_q, descale_k, descale_v, descale_do, + NUM_Q_HEADS=num_q_heads, + NUM_K_HEADS=num_k_heads, + BATCH=batch, + NUM_K_PIDS=num_k_pids, + BLOCK_D_MODEL=head_sz, + BLOCK_D_MODEL_POW2=BLOCK_D_MODEL_POW2, + ENABLE_DROPOUT=use_dropout, + IS_VARLEN=IS_VARLEN, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + **config, + ) + else: + _bwd_kernel_dkdvdq_noncausal[grid_dkdvdq]( + q, k, v, sm_scale, do, dk, dv, dq, + softmax_lse, delta, + *q_strides, + *k_strides, + *v_strides, + *dk_strides, + *delta_strides, + *do_strides, + *dropout_strides, + *descale_strides, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_mask,dropout_p, philox_seed, philox_offset, + descale_q, descale_k, descale_v, descale_do, + NUM_Q_HEADS=num_q_heads, + NUM_K_HEADS=num_k_heads, + BATCH=batch, + NUM_K_PIDS=num_k_pids, + BLOCK_D_MODEL=head_sz, + BLOCK_D_MODEL_POW2=BLOCK_D_MODEL_POW2, + ENABLE_DROPOUT=use_dropout, + IS_VARLEN=IS_VARLEN, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + **config, + ) + + return delta + + # split kernels solution: one kernel computes dk, dv and the other computes dq + + if causal: + _bwd_kernel_dkdv_causal[grid_dkdv]( + q, k, v, sm_scale, do, dk, dv, + softmax_lse, delta, + *q_strides, + *k_strides, + *v_strides, + *dk_strides, + *delta_strides, + *do_strides, + *dropout_strides, + *descale_strides, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_mask,dropout_p, philox_seed, philox_offset, + descale_q, descale_k, descale_v, descale_do, + NUM_Q_HEADS=num_q_heads, + NUM_K_HEADS=num_k_heads, + BLOCK_M=BLOCK_M1, + BLOCK_N=BLOCK_N1, + BLK_SLICE_FACTOR=BLK_SLICE_FACTOR, + BLOCK_D_MODEL=head_sz, + BLOCK_D_MODEL_POW2=BLOCK_D_MODEL_POW2, + ENABLE_DROPOUT=use_dropout, + IS_VARLEN=IS_VARLEN, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + num_warps=NUM_WARPS, + num_stages=NUM_STAGES, + waves_per_eu=WAVES_PER_EU, + ) + _bwd_kernel_dq_causal[grid_dq]( + q, k, v, sm_scale, do, dq, + softmax_lse, delta, + *q_strides, + *k_strides, + *v_strides, + *dq_strides, + *delta_strides, + *do_strides, + *dropout_strides, + *descale_strides, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, max_seqlen_k, + dropout_mask,dropout_p, philox_seed, philox_offset, + descale_q, descale_k, descale_v, descale_do, + NUM_Q_HEADS=num_q_heads, + NUM_K_HEADS=num_k_heads, + BLOCK_M=BLOCK_M2, + BLOCK_N=BLOCK_N2, + BLK_SLICE_FACTOR=BLK_SLICE_FACTOR, + BLOCK_D_MODEL=head_sz, + BLOCK_D_MODEL_POW2=BLOCK_D_MODEL_POW2, + ENABLE_DROPOUT=use_dropout, + IS_VARLEN=IS_VARLEN, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + num_warps=NUM_WARPS, + num_stages=NUM_STAGES, + waves_per_eu=WAVES_PER_EU, + ) + else: + _bwd_kernel_dkdv_noncausal[grid_dkdv]( + q, k, v, sm_scale, do, dk, dv, + softmax_lse, delta, + *q_strides, + *k_strides, + *v_strides, + *dk_strides, + *delta_strides, + *do_strides, + *dropout_strides, + *descale_strides, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_mask,dropout_p, philox_seed, philox_offset, + descale_q, descale_k, descale_v, descale_do, + NUM_Q_HEADS=num_q_heads, + NUM_K_HEADS=num_k_heads, + BLOCK_M=BLOCK_M1, + BLOCK_N=BLOCK_N1, + BLK_SLICE_FACTOR=BLK_SLICE_FACTOR, + BLOCK_D_MODEL=head_sz, + BLOCK_D_MODEL_POW2=BLOCK_D_MODEL_POW2, + ENABLE_DROPOUT=use_dropout, + IS_VARLEN=IS_VARLEN, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + num_warps=NUM_WARPS, + num_stages=NUM_STAGES, + waves_per_eu=WAVES_PER_EU, + ) + + _bwd_kernel_dq_noncausal[grid_dq]( + q, k, v, sm_scale, do, dq, + softmax_lse, delta, + *q_strides, + *k_strides, + *v_strides, + *dq_strides, + *delta_strides, + *do_strides, + *dropout_strides, + *descale_strides, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_mask,dropout_p, philox_seed, philox_offset, + descale_q, descale_k, descale_v, descale_do, + NUM_Q_HEADS=num_q_heads, + NUM_K_HEADS=num_k_heads, + BLOCK_M=BLOCK_M2, + BLOCK_N=BLOCK_N2, + BLK_SLICE_FACTOR=BLK_SLICE_FACTOR, + BLOCK_D_MODEL=head_sz, + BLOCK_D_MODEL_POW2=BLOCK_D_MODEL_POW2, + ENABLE_DROPOUT=use_dropout, + IS_VARLEN=IS_VARLEN, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + num_warps=NUM_WARPS, + num_stages=NUM_STAGES, + waves_per_eu=WAVES_PER_EU, + ) + + return delta + + +class FlashAttnFunc(torch.autograd.Function): + @staticmethod + def forward( + ctx, + q, + k, + v, + dropout_p, + softmax_scale, + causal, + window_size, + alibi_slopes, + deterministic, + return_lse, + return_softmax, + is_grad_enabled, + fused_backward, + ): + is_grad = is_grad_enabled and any( + x.requires_grad for x in [q,k,v] + ) + if softmax_scale is None: + softmax_scale = q.shape[-1] ** (-0.5) + + + head_size_og = q.size(3) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + out_padded, softmax_lse, S_dmask, philox_seed, philox_offset = _flash_attn_forward( + q, + k, + v, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + alibi_slopes=alibi_slopes, + return_lse=return_lse, + return_softmax=return_softmax and dropout_p > 0, + max_seqlen_q=q.shape[1], + max_seqlen_k=k.shape[1], + ) + + if is_grad: + ctx.save_for_backward(q, k, v, out_padded, softmax_lse) + ctx.philox_seed = philox_seed + ctx.philox_offset = philox_offset + ctx.dropout_p = dropout_p + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + ctx.fused_backward = fused_backward + + + out = out_padded[..., :head_size_og] + result = [out] + if return_lse: + result.append(softmax_lse) + if return_softmax: + result.append(S_dmask) + + return tuple(result) + + @staticmethod + def backward(ctx, do, *args): + q, k, v, out, softmax_lse = ctx.saved_tensors + dq, dk, dv = torch.zeros_like(q), torch.empty_like(k), torch.empty_like(v) + head_size_v_og = do.size(3) + do_padded = do + if head_size_v_og % 8 != 0: + do_padded = torch.nn.functional.pad(do, [0, 8 - head_size_v_og % 8]) + _flash_attn_backward( + do_padded, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + ctx.softmax_scale, + ctx.alibi_slopes, + ctx.causal, + None, + None, + max_seqlen_q=q.shape[1], + max_seqlen_k=k.shape[1], + dropout_p=ctx.dropout_p, + philox_seed=ctx.philox_seed, + philox_offset=ctx.philox_offset, + fused=ctx.fused_backward, + ) + dq = dq[..., : q.shape[-1]] # We could have padded the head dimension + dk = dk[..., : k.shape[-1]] + dv = dv[..., : v.shape[-1]] + return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None + +def flash_attn_func( + q, + k, + v, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1,-1), + alibi_slopes=None, + deterministic=True, + return_lse=False, + return_attn_probs=False, + fused_backward=False, +): + """dropout_p should be set to 0.0 during evaluation + Supports multi-query and grouped-query attention (MQA/GQA) by passing in KV with fewer heads + than Q. Note that the number of heads in Q must be divisible by the number of heads in KV. + For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head + 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V. + + If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix. + For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is: + 1 1 1 1 0 + 1 1 1 1 1 + If seqlen_q = 5 and seqlen_k = 2, the causal mask is: + 0 0 + 0 0 + 0 0 + 1 0 + 1 1 + If the row of the mask is all zero, the output will be zero. + + If window_size != (-1, -1), implements sliding window local attention. Query at position i + will only attend to keys between + [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive. + + Arguments: + q: (batch_size, seqlen, nheads, headdim) + k: (batch_size, seqlen, nheads_k, headdim) + v: (batch_size, seqlen, nheads_k, headdim) + dropout_p: float. Dropout probability. + softmax_scale: float. The scaling of QK^T before applying softmax. + Default to 1 / sqrt(headdim). + causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling). + window_size: (left, right). If not (-1, -1), implements sliding window local attention. + alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of + (-alibi_slope * |i + seqlen_k - seqlen_q - j|) + is added to the attention score of query i and key j. + deterministic: bool. Whether to use the deterministic implementation of the backward pass, + which is slightly slower and uses more memory. The forward pass is always deterministic. + return_attn_probs: bool. Whether to return the attention probabilities. This option is for + testing only. The returned probabilities are not guaranteed to be correct + (they might not have the right scaling). + Return: + out: (batch_size, seqlen, nheads, headdim). + softmax_lse [optional, if return_lse=True]: (batch_size, nheads, seqlen). The + logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax + normalization factor). + S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen). + The output of softmax (possibly with different scaling). It also encodes the dropout + pattern (negative means that location was dropped, nonnegative means it was kept). + """ + return FlashAttnFunc.apply( + q, + k, + v, + dropout_p, + softmax_scale, + causal, + window_size, + alibi_slopes, + deterministic, + return_lse, + return_attn_probs, + torch.is_grad_enabled(), + fused_backward, + ) + + +class FlashAttnFP8Func(torch.autograd.Function): + @staticmethod + def forward( + ctx, + q, + k, + v, + dropout_p, + softmax_scale, + causal, + window_size, + alibi_slopes, + deterministic, + return_lse, + return_softmax, + is_grad_enabled, + ): + is_grad = is_grad_enabled and any( + x.requires_grad for x in [q,k,v] + ) + if softmax_scale is None: + softmax_scale = q.shape[-1] ** (-0.5) + head_size_og = q.size(3) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + + # cast input to fp8 + fp8_dtype = torch.float8_e4m3fnuz + q_fp8, descale_q = cast_to_fp8(q, fp8_dtype, "bshd") + k_fp8, descale_k = cast_to_fp8(k, fp8_dtype, "bshd") + v_fp8, descale_v = cast_to_fp8(v, fp8_dtype, "bshd") + + out_padded, softmax_lse, S_dmask, philox_seed, philox_offset = _flash_attn_forward( + q, + k, + v, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + alibi_slopes=alibi_slopes, + return_lse=return_lse, + return_softmax=return_softmax and dropout_p > 0, + max_seqlen_q=q.shape[1], + max_seqlen_k=k.shape[1], + cu_seqlens_q=None, + cu_seqlens_k=None, + descale_q=descale_q, + descale_k=descale_k, + descale_v=descale_v + ) + + if is_grad: + ctx.save_for_backward(q_fp8, k_fp8, v_fp8, out_padded, softmax_lse, descale_q, descale_k, descale_v) + ctx.philox_seed = philox_seed + ctx.philox_offset = philox_offset + ctx.dropout_p = dropout_p + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.alibi_slopes = alibi_slopes + + out = out_padded[..., :head_size_og] + result = [out] + if return_lse: + result.append(softmax_lse) + if return_softmax: + result.append(S_dmask) + + return tuple(result) + + @staticmethod + def backward(ctx, do, *args): + q_fp8, k_fp8, v_fp8, out, softmax_lse, descale_q, descale_k, descale_v = ctx.saved_tensors + dq, dk, dv = torch.zeros_like(q_fp8, dtype=torch.float32), torch.zeros_like(k_fp8, dtype=torch.float32), torch.zeros_like(v_fp8, dtype=torch.float32) + head_size_v_og = do.size(3) + do_padded = do + if head_size_v_og % 8 != 0: + do_padded = torch.nn.functional.pad(do, [0, 8 - head_size_v_og % 8]) + + fp8_dtype = torch.float8_e4m3fnuz + do_padded_fp8, descale_do = cast_to_fp8(do_padded, fp8_dtype, "bshd") + _flash_attn_backward( + do_padded_fp8, + q_fp8, + k_fp8, + v_fp8, + out, + softmax_lse, + dq, + dk, + dv, + ctx.softmax_scale, + ctx.alibi_slopes, + ctx.causal, + None, + None, + max_seqlen_q=q_fp8.shape[1], + max_seqlen_k=k_fp8.shape[1], + dropout_p=ctx.dropout_p, + philox_seed=ctx.philox_seed, + philox_offset=ctx.philox_offset, + descale_q=descale_q, + descale_k=descale_k, + descale_v=descale_v, + descale_do=descale_do, + ) + #dq = dq[..., : q_fp8.shape[-1]] # We could have padded the head dimension + #dk = dk[..., : k_fp8.shape[-1]] + #dv = dv[..., : v_fp8.shape[-1]] + return dq, dk, dv, None, None, None, None, None, None, None, None, None + +def flash_attn_fp8_func( + q, + k, + v, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + alibi_slopes=None, + deterministic=False, + return_lse=False, + return_attn_probs=False +): + return FlashAttnFP8Func.apply( + q, + k, + v, + dropout_p, + softmax_scale, + causal, + window_size, + alibi_slopes, + deterministic, + return_lse, + return_attn_probs, + torch.is_grad_enabled() + ) + +class FlashAttnVarlenFunc(torch.autograd.Function): + @staticmethod + def forward( + ctx, + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal, + window_size, + alibi_slopes, + deterministic, + return_lse, + return_softmax, + block_table, + is_grad_enabled, + fused_backward, + ): + is_grad = is_grad_enabled and any( + x.requires_grad for x in [q, k, v] + ) + if softmax_scale is None: + softmax_scale = q.shape[-1] ** (-0.5) + head_size_og = q.size(2) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + out_padded, softmax_lse, S_dmask, philox_seed, philox_offset = _flash_attn_forward( + q, + k, + v, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + alibi_slopes=alibi_slopes, + return_lse=return_lse, + return_softmax=return_softmax and dropout_p > 0.0, + max_seqlen_q=max_seqlen_q, + max_seqlen_k=max_seqlen_k, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + ) + if is_grad: + ctx.save_for_backward(q, k, v, out_padded, softmax_lse, cu_seqlens_q, cu_seqlens_k) + ctx.max_seqlen_q = max_seqlen_q + ctx.max_seqlen_k = max_seqlen_k + ctx.philox_seed = philox_seed + ctx.philox_offset = philox_offset + ctx.dropout_p = dropout_p + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.alibi_slopes = alibi_slopes + ctx.fused_backward = fused_backward + out = out_padded[..., :head_size_og] + + result = [out] + if return_lse: + result.append(softmax_lse) + if return_softmax: + result.append(S_dmask) + + return tuple(result) + + @staticmethod + def backward(ctx, do, *args): + q, k, v, out, softmax_lse, cu_seqlens_q, cu_seqlens_k = ctx.saved_tensors + dq, dk, dv = torch.zeros_like(q), torch.empty_like(k), torch.empty_like(v) + head_size_og = do.size(2) + do_padded = do + if head_size_og % 8 != 0: + do_padded = torch.nn.functional.pad(do, [0, 8 - head_size_og % 8]) + _flash_attn_backward( + do_padded, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + ctx.softmax_scale, + ctx.alibi_slopes, + ctx.causal, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q=ctx.max_seqlen_q, + max_seqlen_k=ctx.max_seqlen_k, + dropout_p=ctx.dropout_p, + philox_seed=ctx.philox_seed, + philox_offset=ctx.philox_offset, + fused=ctx.fused_backward, + ) + dq = dq[..., : q.shape[-1]] # We could have padded the head dimension + dk = dk[..., : k.shape[-1]] + dv = dv[..., : v.shape[-1]] + return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None + + +def flash_attn_varlen_func( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1,-1), + alibi_slopes=None, + deterministic=False, + return_lse=False, + return_attn_probs=False, + block_table=None, + fused_backward=False, +): + """dropout_p should be set to 0.0 during evaluation + Supports multi-query and grouped-query attention (MQA/GQA) by passing in K, V with fewer heads + than Q. Note that the number of heads in Q must be divisible by the number of heads in KV. + For example, if Q has 6 heads and K, V have 2 heads, head 0, 1, 2 of Q will attention to head + 0 of K, V, and head 3, 4, 5 of Q will attention to head 1 of K, V. + + If causal=True, the causal mask is aligned to the bottom right corner of the attention matrix. + For example, if seqlen_q = 2 and seqlen_k = 5, the causal mask (1 = keep, 0 = masked out) is: + 1 1 1 1 0 + 1 1 1 1 1 + If seqlen_q = 5 and seqlen_k = 2, the causal mask is: + 0 0 + 0 0 + 0 0 + 1 0 + 1 1 + If the row of the mask is all zero, the output will be zero. + + If window_size != (-1, -1), implements sliding window local attention. Query at position i + will only attend to keys between + [i + seqlen_k - seqlen_q - window_size[0], i + seqlen_k - seqlen_q + window_size[1]] inclusive. + + Arguments: + q: (total_q, nheads, headdim), where total_q = total number of query tokens in the batch. + k: (total_k, nheads_k, headdim), where total_k = total number of key tokens in the batch. + v: (total_k, nheads_k, headdim), where total_k = total number of key tokens in the batch. + cu_seqlens_q: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into q. + cu_seqlens_k: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into kv. + max_seqlen_q: int. Maximum query sequence length in the batch. + max_seqlen_k: int. Maximum key sequence length in the batch. + dropout_p: float. Dropout probability. + softmax_scale: float. The scaling of QK^T before applying softmax. + Default to 1 / sqrt(headdim). + causal: bool. Whether to apply causal attention mask (e.g., for auto-regressive modeling). + window_size: (left, right). If not (-1, -1), implements sliding window local attention. + alibi_slopes: (nheads,) or (batch_size, nheads), fp32. A bias of + (-alibi_slope * |i + seqlen_k - seqlen_q - j|) + is added to the attention score of query i and key j. + deterministic: bool. Whether to use the deterministic implementation of the backward pass, + which is slightly slower and uses more memory. The forward pass is always deterministic. + return_attn_probs: bool. Whether to return the attention probabilities. This option is for + testing only. The returned probabilities are not guaranteed to be correct + (they might not have the right scaling). + Return: + out: (total, nheads, headdim). + softmax_lse [optional, if return_attn_probs=True]: (nheads, total_q_seqlen). The + logsumexp of each row of the matrix QK^T * scaling (e.g., log of the softmax + normalization factor). + S_dmask [optional, if return_attn_probs=True]: (batch_size, nheads, seqlen, seqlen). + The output of softmax (possibly with different scaling). It also encodes the dropout + pattern (negative means that location was dropped, nonnegative means it was kept). + """ + return FlashAttnVarlenFunc.apply( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal, + window_size, + alibi_slopes, + deterministic, + return_lse, + return_attn_probs, + block_table, + torch.is_grad_enabled(), + fused_backward, + ) + + +class FlashAttnVarlenFP8Func(torch.autograd.Function): + @staticmethod + def forward( + ctx, + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal, + window_size, + alibi_slopes, + deterministic, + return_lse, + return_softmax, + block_table, + is_grad_enabled, + ): + is_grad = is_grad_enabled and any( + x.requires_grad for x in [q, k, v] + ) + if softmax_scale is None: + softmax_scale = q.shape[-1] ** (-0.5) + head_size_og = q.size(2) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + + # cast input to fp8 + fp8_dtype = torch.float8_e4m3fnuz + q_fp8, descale_q = cast_varlen_to_fp8(q, fp8_dtype, cu_seqlens=cu_seqlens_q) + k_fp8, descale_k = cast_varlen_to_fp8(k, fp8_dtype, cu_seqlens=cu_seqlens_k) + v_fp8, descale_v = cast_varlen_to_fp8(v, fp8_dtype, cu_seqlens=cu_seqlens_k) + + out_padded, softmax_lse, S_dmask, philox_seed, philox_offset = _flash_attn_forward( + q_fp8, + k_fp8, + v_fp8, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + alibi_slopes=alibi_slopes, + return_lse=return_lse, + return_softmax=return_softmax and dropout_p > 0, + max_seqlen_q=max_seqlen_q, + max_seqlen_k=max_seqlen_k, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + descale_q=descale_q, + descale_k=descale_k, + descale_v=descale_v + ) + if is_grad: + ctx.save_for_backward(q_fp8, k_fp8, v_fp8, out_padded, softmax_lse, cu_seqlens_q, cu_seqlens_k, descale_q, descale_k, descale_v) + ctx.max_seqlen_q = max_seqlen_q + ctx.max_seqlen_k = max_seqlen_k + ctx.philox_seed = philox_seed + ctx.philox_offset = philox_offset + ctx.dropout_p = dropout_p + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.alibi_slopes = alibi_slopes + out = out_padded[..., :head_size_og] + result = [out] + if return_lse: + result.append(softmax_lse) + if return_softmax: + result.append(S_dmask) + + return tuple(result) + + @staticmethod + def backward(ctx, do, *args): + q_fp8, k_fp8, v_fp8, out, softmax_lse, cu_seqlens_q, cu_seqlens_q, descale_q, descale_k, descale_v = ctx.saved_tensors + dq, dk, dv = torch.zeros_like(q, dtype=torch.float32), torch.zeros_like(k, dtype=torch.float32), torch.zeros_like(v, dtype=torch.float32) + head_size_v_og = do.size(3) + do_padded = do + if head_size_v_og % 8 != 0: + do_padded = torch.nn.functional.pad(do, [0, 8 - head_size_v_og % 8]) + + fp8_dtype = torch.float8_e4m3fnuz + do_padded_fp8, descale_do = cast_varlen_to_fp8(dout_padded, fp8_dtype, "thd", cu_seqlens_q) + + _flash_attn_backward( + do_padded_fp8, + q_fp8, + k_fp8, + v_fp8, + out, + softmax_lse, + dq, + dk, + dv, + ctx.softmax_scale, + ctx.alibi_slopes, + ctx.causal, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q=max_seqlen_q, + max_seqlen_k=max_seqlen_k, + dropout_p=ctx.dropout_p, + philox_seed=ctx.philox_seed, + philox_offset=ctx.philox_offset, + descale_q=descale_q, + descale_k=descale_k, + descale_v=descale_v, + descale_do=descale_do + ) + dq = dq[..., : q.shape[-1]] # We could have padded the head dimension + dk = dk[..., : k.shape[-1]] + dv = dv[..., : v.shape[-1]] + return dq, dk, dv, None, None, None, None, None, None, None, None, None + +def flash_attn_varlen_fp8_func( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + alibi_slopes=None, + deterministic=False, + return_lse=False, + return_attn_probs=False, + block_table=None +): + return FlashAttnVarlenFP8Func.apply( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal, + window_size, + alibi_slopes, + deterministic, + return_lse, + return_attn_probs, + block_table, + torch.is_grad_enabled() + ) \ No newline at end of file diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bwd_prefill_onekernel.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bwd_prefill_onekernel.py new file mode 100644 index 0000000000000000000000000000000000000000..3f650d288db78e428d6d17a3b470a4c5c5c0fc55 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bwd_prefill_onekernel.py @@ -0,0 +1,1091 @@ +import torch +import triton # type: ignore +import triton.language as tl # type: ignore +from typing import Literal, Optional +from .utils import AUTOTUNE, DROPOUT_USE_PYTORCH, DROPOUT_DUMP, get_shapes_from_layout, compute_fp8_scaling_factors, \ + get_strides_from_layout, create_dropout_mask, create_dropout_mask_varlen, is_cdna, is_rdna + +# NOTE: triton fails to import tl.constexprs so create them here for the file +tl_DROPOUT_USE_PYTORCH: tl.constexpr = triton.language.constexpr(DROPOUT_USE_PYTORCH) +tl_DROPOUT_DUMP: tl.constexpr = triton.language.constexpr(DROPOUT_DUMP) + + +def get_autotune_configs(): + if False: + if is_cdna(): + # shared meta-parameters + NUM_STAGES = 1 + NUM_WARPS = 4 + WAVES_PER_EU = 2 + MATRIX_INSTR_NONKDIM = 16 + + preprocess_autotune_configs = [ + triton.Config({"PRE_BLOCK": 128, "waves_per_eu": WAVES_PER_EU, "matrix_instr_nonkdim": MATRIX_INSTR_NONKDIM}, num_stages=NUM_STAGES, num_warps=NUM_WARPS), # og config + triton.Config({"PRE_BLOCK": 64, "waves_per_eu": WAVES_PER_EU, "matrix_instr_nonkdim": MATRIX_INSTR_NONKDIM}, num_stages=NUM_STAGES, num_warps=NUM_WARPS), + triton.Config({"PRE_BLOCK": 32, "waves_per_eu": WAVES_PER_EU, "matrix_instr_nonkdim": MATRIX_INSTR_NONKDIM}, num_stages=NUM_STAGES, num_warps=NUM_WARPS), + triton.Config({"PRE_BLOCK": 16, "waves_per_eu": WAVES_PER_EU, "matrix_instr_nonkdim": MATRIX_INSTR_NONKDIM}, num_stages=NUM_STAGES, num_warps=NUM_WARPS), + ] + preprocess_autotune_keys = [ + "IS_CAUSAL", "dropout_p", "MAX_SEQLENS_Q", "MAX_SEQLENS_K", + "ACTUAL_HEAD_DIM", "IS_VARLEN", "HQ", "HK", + ] + causal_autotune_configs = [ + triton.Config({"BLOCK_M1": 32, "BLOCK_N1": 128, "BLOCK_M2": 128, "BLOCK_N2": 32, "BLK_SLICE_FACTOR": 2, "waves_per_eu": WAVES_PER_EU, "matrix_instr_nonkdim": MATRIX_INSTR_NONKDIM}, num_stages=NUM_STAGES, num_warps=NUM_WARPS), # og config + triton.Config({'BLOCK_M1': 16, 'BLOCK_N1': 128, 'BLOCK_M2': 128, 'BLOCK_N2': 16, 'BLK_SLICE_FACTOR': 2, "waves_per_eu": WAVES_PER_EU, "matrix_instr_nonkdim": MATRIX_INSTR_NONKDIM}, num_stages=NUM_STAGES, num_warps=NUM_WARPS), + triton.Config({'BLOCK_M1': 16, 'BLOCK_N1': 64, 'BLOCK_M2': 64, 'BLOCK_N2': 16, 'BLK_SLICE_FACTOR': 2, "waves_per_eu": WAVES_PER_EU, "matrix_instr_nonkdim": MATRIX_INSTR_NONKDIM}, num_stages=NUM_STAGES, num_warps=NUM_WARPS), + triton.Config({'BLOCK_M1': 32, 'BLOCK_N1': 64, 'BLOCK_M2': 64, 'BLOCK_N2': 32, 'BLK_SLICE_FACTOR': 2, "waves_per_eu": WAVES_PER_EU, "matrix_instr_nonkdim": MATRIX_INSTR_NONKDIM}, num_stages=NUM_STAGES, num_warps=NUM_WARPS), + ] + causal_autotune_keys = [ + "IS_CAUSAL", "dropout_p", "MAX_SEQLENS_Q", "MAX_SEQLENS_K", + "ACTUAL_HEAD_DIM", "IS_VARLEN", "HQ", "HK", + ] + noncausal_autotune_configs = [ + triton.Config({"BLOCK_M1": 32, "BLOCK_N1": 128, "BLOCK_M2": 128, "BLOCK_N2": 32, "BLK_SLICE_FACTOR": 2, "waves_per_eu": WAVES_PER_EU, "matrix_instr_nonkdim": MATRIX_INSTR_NONKDIM}, num_stages=NUM_STAGES, num_warps=NUM_WARPS), # og config + triton.Config({'BLOCK_M1': 16, 'BLOCK_N1': 128, 'BLOCK_M2': 128, 'BLOCK_N2': 16, 'BLK_SLICE_FACTOR': 2, "waves_per_eu": WAVES_PER_EU, "matrix_instr_nonkdim": MATRIX_INSTR_NONKDIM}, num_stages=NUM_STAGES, num_warps=NUM_WARPS), + triton.Config({'BLOCK_M1': 16, 'BLOCK_N1': 64, 'BLOCK_M2': 64, 'BLOCK_N2': 16, 'BLK_SLICE_FACTOR': 2, "waves_per_eu": WAVES_PER_EU, "matrix_instr_nonkdim": MATRIX_INSTR_NONKDIM}, num_stages=NUM_STAGES, num_warps=NUM_WARPS), + triton.Config({'BLOCK_M1': 32, 'BLOCK_N1': 64, 'BLOCK_M2': 64, 'BLOCK_N2': 32, 'BLK_SLICE_FACTOR': 2, "waves_per_eu": WAVES_PER_EU, "matrix_instr_nonkdim": MATRIX_INSTR_NONKDIM}, num_stages=NUM_STAGES, num_warps=NUM_WARPS), + ] + noncausal_autotune_keys = [ + "IS_CAUSAL", "dropout_p", "MAX_SEQLENS_Q", "MAX_SEQLENS_K", + "ACTUAL_HEAD_DIM", "IS_VARLEN", "HQ", "HK", + ] + + return (preprocess_autotune_configs, preprocess_autotune_keys), (causal_autotune_configs, causal_autotune_keys), (noncausal_autotune_configs, noncausal_autotune_keys) + else: + raise ValueError("Unknown Device Type") + else: + # meta-parameters + # TODO: fix num_stages later + NUM_WARPS, NUM_STAGES = 4, 1 + WAVES_PER_EU = 1 + PRE_BLOCK = 128 + BLOCK_M1, BLOCK_N1, BLOCK_M2, BLOCK_N2 = 32, 128, 128, 32 + BLK_SLICE_FACTOR = 2 + + assert BLOCK_N1 == BLOCK_M2 + + # configs for the kernels + preprocess_autotune_configs = [ + triton.Config({"PRE_BLOCK": PRE_BLOCK, "waves_per_eu": WAVES_PER_EU}, num_stages=NUM_STAGES, num_warps=NUM_WARPS), + ] + preprocess_autotune_keys = [ + "IS_CAUSAL", "dropout_p", "MAX_SEQLENS_Q", "MAX_SEQLENS_K", + "ACTUAL_HEAD_DIM", "IS_VARLEN", "HQ", "HK", + ] + causal_autotune_configs = [ + triton.Config({"BLOCK_M1": BLOCK_M1, "BLOCK_N1": BLOCK_N1, "BLOCK_M2": BLOCK_M2, "BLOCK_N2": BLOCK_N2, "BLK_SLICE_FACTOR": BLK_SLICE_FACTOR, "waves_per_eu": WAVES_PER_EU}, num_stages=NUM_STAGES, num_warps=NUM_WARPS), + ] + causal_autotune_keys = [ + "IS_CAUSAL", "dropout_p", "MAX_SEQLENS_Q", "MAX_SEQLENS_K", + "ACTUAL_HEAD_DIM", "IS_VARLEN", "HQ", "HK", + ] + noncausal_autotune_configs = [ + triton.Config({"BLOCK_M1": BLOCK_M1, "BLOCK_N1": BLOCK_N1, "BLOCK_M2": BLOCK_M2, "BLOCK_N2": BLOCK_N2, "BLK_SLICE_FACTOR": BLK_SLICE_FACTOR, "waves_per_eu": WAVES_PER_EU}, num_stages=NUM_STAGES, num_warps=NUM_WARPS), + ] + noncausal_autotune_keys = [ + "IS_CAUSAL", "dropout_p", "MAX_SEQLENS_Q", "MAX_SEQLENS_K", + "ACTUAL_HEAD_DIM", "IS_VARLEN", "HQ", "HK", + ] + return (preprocess_autotune_configs, preprocess_autotune_keys), (causal_autotune_configs, causal_autotune_keys), (noncausal_autotune_configs, noncausal_autotune_keys) + + + +(preprocess_autotune_configs, preprocess_autotune_keys), (causal_autotune_configs, causal_autotune_keys), (noncausal_autotune_configs, noncausal_autotune_keys) = get_autotune_configs() + + +# This function computes delta given output Out and gradient DO +# Here is the I/O shape: +# Out: (batch, nhead_q, max_seqlens_q, headDim) +# DO: (batch, nhead_q, max_seqlens_q, headDim) +# Delta: (batch, nheads_q, max_seqlens_q), same as softmax_lse defined at +# fwd_prefill.py line 607 +@triton.autotune( + configs=preprocess_autotune_configs, + key=preprocess_autotune_keys, + use_cuda_graph=True, +) +@triton.jit +def _bwd_preprocess( + O, DO, # noqa: E741 + Delta, + stride_ob, stride_oh, stride_om, stride_ok, + stride_deltab, stride_deltah, stride_deltam, + stride_descale_do_z, + cu_seqlens_q, max_seqlen_q, + Descale_do, + PRE_BLOCK: tl.constexpr, + HEAD_DIM: tl.constexpr, + ACTUAL_HEAD_DIM: tl.constexpr, + IS_VARLEN: tl.constexpr, + IS_FP8: tl.constexpr +): + pid_m = tl.program_id(0) + bid = tl.program_id(1) + hid = tl.program_id(2) + # Handle varlen + q_start = 0 + seqlen_q = max_seqlen_q + if IS_VARLEN: + q_start = tl.load(cu_seqlens_q + bid) + q_end = tl.load(cu_seqlens_q + bid + 1) + seqlen_q = q_end - q_start + else: + q_start = 0 + seqlen_q = max_seqlen_q + + # Compute offsets + offs_m = pid_m * PRE_BLOCK + tl.arange(0, PRE_BLOCK) + offs_k = tl.arange(0, HEAD_DIM) + # Offset O/DO by batch, head and q_start + O += bid * stride_ob + hid * stride_oh + q_start * stride_om # noqa: E741 + DO += bid * stride_ob + hid * stride_oh + q_start * stride_om + # create masks + mask_m = offs_m < seqlen_q + mask_md = mask_m[:, None] + PADDED_HEAD: tl.constexpr = (ACTUAL_HEAD_DIM != HEAD_DIM) + if PADDED_HEAD: + mask_md &= offs_k[None, :] < ACTUAL_HEAD_DIM + # compute pointers + offs_do = offs_m[:, None] * stride_om + offs_k[None, :] * stride_ok + out_ptrs = O + offs_do + do_ptrs = DO + offs_do + # load + o = tl.load(out_ptrs, mask=mask_md, other=0.0) + do = tl.load(do_ptrs, mask=mask_md, other=0.0) + # compute and write-back to delta + if IS_FP8: + descale_do = tl.load(Descale_do + bid * stride_descale_do_z + hid) + + # NOTE: do is in the fp8 range and o is not in fp8 + delta = tl.sum(o.to(tl.float32) * (do.to(tl.float32) * descale_do), axis=1) + else: + delta = tl.sum(o.to(tl.float32) * do.to(tl.float32), axis=1) + delta_offset = Delta + bid * stride_deltab + hid * stride_deltah + q_start * stride_deltam + tl.store(delta_offset + offs_m * stride_deltam, delta, mask=mask_m) + + +# The main inner-loop logic for computing dK and dV. +@triton.jit +def _bwd_dkdv_inner( + dk, dv, # output + Q, k, v, DO, M, D, sm_scale, # input tensor + stride_qm, stride_qk, + stride_dom, stride_dok, + stride_dropoutm, stride_dropoutn, # + stride_deltam, + BLOCK_M: tl.constexpr, # 16 + BLOCK_N: tl.constexpr, # 128 + HEAD_DIM: tl.constexpr, # + ACTUAL_HEAD_DIM: tl.constexpr, # + dropout_p, philox_seed, batch_philox_offset, dropout_offset, # + seqlen_q, seqlen_k, # max sequence length for q and k + # Filled in by the wrapper. + start_n, start_m, num_steps, # iteration numbers + descale_q, descale_k, descale_v, descale_do, # fp8 descale factors from user + MASK: tl.constexpr, # causal masking, only apply to tiles on mask diagonal + ENABLE_DROPOUT: tl.constexpr, # activate dropout + USE_EXP2: tl.constexpr, # activate exp2 + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, + DEBUG_TRITON: tl.constexpr, + DEBUG_TRITON_DETAIL: tl.constexpr, +): + # if HEAD_DIM is padded + PADDED_HEAD: tl.constexpr = (ACTUAL_HEAD_DIM != HEAD_DIM) + delta_qk = seqlen_q - seqlen_k + offs_m = start_m + tl.arange(0, BLOCK_M) # start_m + (0, 15) + offs_n = start_n + tl.arange(0, BLOCK_N) # start_m + (0, 127) + offs_k = tl.arange(0, HEAD_DIM) + # mask to make sure not OOB of seqlen_q + mask_n = offs_n < seqlen_k + # Q and DO are (seqlen_q, head_dim) + # qT_ptrs = (1, BLOCK_M) + (HEAD_DIM, 1), transpose of q + qT_ptrs = Q + offs_m[None, :] * stride_qm + offs_k[:, None] * stride_qk + # do_ptrs = (BLOCK_M, 1) + (1, HEAD_DIM), NOT transposed + do_ptrs = DO + offs_m[:, None] * stride_dom + offs_k[None, :] * stride_dok + # BLOCK_N must be a multiple of BLOCK_M, otherwise the code wouldn't work. + tl.static_assert(BLOCK_N % BLOCK_M == 0) + curr_m = start_m + step_m = BLOCK_M + curr_philox_offset = batch_philox_offset + curr_dropout_offset = dropout_offset + RCP_LN2: tl.constexpr = 1.4426950408889634 # = 1.0 / ln(2) + + for blk_idx in range(num_steps): + if DEBUG_TRITON: print(f"iter {blk_idx}: curr_m = {curr_m}") # noqa: E701 + offs_m = curr_m + tl.arange(0, BLOCK_M) + # update the mask because offs_m advanced + mask_m = offs_m < seqlen_q + mask_qT = mask_m[None, :] + mask_do = mask_m[:, None] + mask_nm = mask_n[:, None] & (offs_m[None, :] < seqlen_q) + if PADDED_HEAD: + mask_qT &= offs_k[:, None] < ACTUAL_HEAD_DIM + mask_do &= offs_k[None, :] < ACTUAL_HEAD_DIM + qT = tl.load(qT_ptrs, mask=mask_qT, other=0.0) + # generate dropout mask + if ENABLE_DROPOUT: + # NOTE: dropout is transposed because it is used to mask pT + philox_offs = curr_philox_offset + \ + offs_m[None, :] * stride_dropoutm + \ + offs_n[:, None] * stride_dropoutn + if tl_DROPOUT_USE_PYTORCH: + dropout_offs = offs_m[None, :] * stride_dropoutm + \ + offs_n[:, None] * stride_dropoutn + dropout_mask = tl.load( + curr_dropout_offset + dropout_offs, + mask=mask_nm + ) + else: + rand_vals = tl.rand(philox_seed, philox_offs) + dropout_mask = rand_vals > dropout_p + dropout_scale = 1.0 / (1 - dropout_p) + # Load m before computing qk to reduce pipeline stall. + m = tl.load(M + offs_m * stride_deltam, mask=mask_m, other=0.0) + if IS_FP8: + qkT = (tl.dot(k, qT) * descale_q * descale_k) + else: + qkT = tl.dot(k, qT) + if DEBUG_TRITON_DETAIL: + if start_n == 256: + print(f"qT: {qT.shape}\n", qT) + print(f"k: {k.shape}\n", k) + print(f"qkT scaled: {qkT.shape}\n", qkT * sm_scale) + # TODO: remove the scaling of m later when we removed re-scaling in fwd + if USE_EXP2: + pT = tl.math.exp2(qkT * sm_scale * RCP_LN2 - m[None, :] * RCP_LN2) + else: + pT = tl.math.exp(qkT * sm_scale - m[None, :]) + + # Autoregressive masking. + if MASK: + # offset offs_m with delta_qk since the causal mask starts at + # bottom right of the (seqlen_q, seqlen_k) matrix + causal_mask = (offs_m[None, :] - delta_qk) >= offs_n[:, None] + mask = causal_mask & mask_nm + if DEBUG_TRITON_DETAIL: + if start_n == 256: + print(f"causal_mask: {causal_mask.shape}\n", causal_mask) + print(f"qkT after causal: {qkT.shape}\n", tl.where(causal_mask, qkT * sm_scale, 0.0)) + pT = tl.where(mask, pT, 0.0) + do = tl.load(do_ptrs, mask=mask_do, other=0.0) + # Compute dV. + if ENABLE_DROPOUT: + pT_dropout = tl.where(dropout_mask, pT, 0.0) * dropout_scale + if IS_FP8: + scale_p_dropout, descale_p_dropout = compute_fp8_scaling_factors(pT_dropout, FP8_MAX) + dv += (tl.dot((pT_dropout * scale_p_dropout).to(do.type.element_ty), do)* descale_p_dropout * descale_do) + else: + dv += tl.dot(pT_dropout.to(do.type.element_ty), do) + else: + if IS_FP8: + scale_pT, descale_pT = compute_fp8_scaling_factors(pT, FP8_MAX) + dv += (tl.dot((pT * scale_pT).to(do.type.element_ty), do) * descale_pT * descale_do) + else: + dv += tl.dot(pT.to(do.type.element_ty), do) + + if DEBUG_TRITON_DETAIL: + if start_n == 256: + print(f"pT: {pT.shape}\n", pT) + # D (= delta) is pre-divided by ds_scale. + Di = tl.load(D + offs_m * stride_deltam, mask=mask_m) + # Compute dP and dS. + if IS_FP8: + dpT = (tl.dot(v, tl.trans(do)) * descale_v * descale_do) + else: + dpT = tl.dot(v, tl.trans(do)) + if ENABLE_DROPOUT: + dpT = tl.where(dropout_mask, dpT, 0.0) * dropout_scale + delta_i = Di[None, :] + dsT = pT * (dpT - delta_i) + if IS_FP8: + scale_dsT, descale_dsT = compute_fp8_scaling_factors(dsT, FP8_MAX) + dk += (tl.dot((dsT * scale_dsT).to(qT.type.element_ty), tl.trans(qT)) * descale_dsT * descale_q) + else: + dk += tl.dot(dsT.to(qT.type.element_ty), tl.trans(qT)) + # Increment pointers. + curr_m += step_m + qT_ptrs += step_m * stride_qm + do_ptrs += step_m * stride_dom + return dk, dv + +# the main inner-loop logic for computing dQ +@triton.jit +def _bwd_dq_inner( + dq, # output + q, K, V, do, m, Delta, sm_scale, # input + # shared by Q/K/V. + stride_qm, stride_qk, stride_kn, stride_kk, stride_vn, stride_vk, + stride_dropoutm, stride_dropoutn, # stride for dropout + stride_deltam, + seqlen_q, seqlen_k, # + BLOCK_M2: tl.constexpr, # + BLOCK_N2: tl.constexpr, # + HEAD_DIM: tl.constexpr, + ACTUAL_HEAD_DIM: tl.constexpr, # + dropout_p, philox_seed, batch_philox_offset, dropout_offset, # + # Filled in by the wrapper. + start_m, start_n, end_n, num_steps, # + descale_q, descale_k, descale_v, descale_do, # fp8 descale factors from user + MASK: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + USE_EXP2: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, + DEBUG_TRITON: tl.constexpr, + DEBUG_TRITON_DETAIL: tl.constexpr, +): + # if HEAD_DIM is padded + PADDED_HEAD: tl.constexpr = (ACTUAL_HEAD_DIM != HEAD_DIM) + delta_qk = seqlen_q - seqlen_k + offs_m = start_m + tl.arange(0, BLOCK_M2) + offs_n = start_n + tl.arange(0, BLOCK_N2) + offs_k = tl.arange(0, HEAD_DIM) + + # mask to make sure not OOB of seqlen_q + mask_m = offs_m < seqlen_q + + kT_ptrs = K + offs_n[None, :] * stride_kn + offs_k[:, None] * stride_kk + vT_ptrs = V + offs_n[None, :] * stride_vn + offs_k[:, None] * stride_vk + # D (= delta) is pre-divided by ds_scale. + Di = tl.load(Delta + offs_m * stride_deltam, mask=mask_m, other=0.0) + # BLOCK_M2 must be a multiple of BLOCK_N2, otherwise the code wouldn't work. + tl.static_assert(BLOCK_M2 % BLOCK_N2 == 0) + curr_n = start_n + step_n = BLOCK_N2 + curr_philox_offset = batch_philox_offset + curr_dropout_offset = dropout_offset + RCP_LN2: tl.constexpr = 1.4426950408889634 # = 1.0 / ln(2) + for blk_idx in range(num_steps): + if DEBUG_TRITON: print(f"iter {blk_idx}: curr_n = {curr_n}") # noqa: E701 + offs_n = curr_n + tl.arange(0, BLOCK_N2) + # end_n is needed because the end of causal True might not be perfectly + # aligned with the end of the block + mask_n = offs_n < end_n + if DEBUG_TRITON_DETAIL: print(f"start_n = {start_n}, end_n = {end_n}, offs_n: {offs_n.shape}\n{offs_n}") # noqa: E701 + if DEBUG_TRITON_DETAIL: print(f"mask_n: {mask_n.shape}\n{mask_n}") # noqa: E701 + mask_kT = mask_n[None, :] + mask_mn = mask_m[:, None] & (offs_n[None, :] < end_n) + if PADDED_HEAD: + mask_kT &= offs_k[:, None] < ACTUAL_HEAD_DIM + + kT = tl.load(kT_ptrs, mask=mask_kT, other=0.0) + vT = tl.load(vT_ptrs, mask=mask_kT, other=0.0) + + if ENABLE_DROPOUT: + # NOTE: dropout is transposed because it is used to mask pT + philox_offs = curr_philox_offset + \ + offs_m[:, None] * stride_dropoutm + \ + offs_n[None, :] * stride_dropoutn + if tl_DROPOUT_USE_PYTORCH: + dropout_offs = offs_m[:, None] * stride_dropoutm + \ + offs_n[None, :] * stride_dropoutn + dropout_mask = tl.load( + curr_dropout_offset + dropout_offs, + mask=mask_mn) + else: + rand_vals = tl.rand(philox_seed, philox_offs) + dropout_mask = rand_vals > dropout_p + dropout_scale = 1 / (1 - dropout_p) + + if IS_FP8: + qk = (tl.dot(q, kT) * descale_q * descale_k) + else: + qk = tl.dot(q, kT) + if DEBUG_TRITON_DETAIL: print(f"qk scaled: {qk.shape}\n", qk * sm_scale) # noqa: E701 + if USE_EXP2: + p = tl.math.exp2(qk * sm_scale * RCP_LN2 - m * RCP_LN2) + else: + p = tl.math.exp(qk * sm_scale - m) + + # Autoregressive masking. + if MASK: + causal_mask = (offs_m[:, None] - delta_qk) >= offs_n[None, :] + mask = causal_mask & mask_mn + p = tl.where(mask, p, 0.0) + # Compute dP and dS. + if IS_FP8: + dp = (tl.dot(do, vT) * descale_do * descale_v) + else: + dp = tl.dot(do, vT) + if ENABLE_DROPOUT: + dp = tl.where(dropout_mask, dp, 0.0) * dropout_scale + delta_i = Di[:, None] + ds = p * (dp -delta_i) + # Compute dQ. + # NOTE: We need to de-scale dq in the end, because kT was pre-scaled. + if IS_FP8: + scale_ds, descale_ds = compute_fp8_scaling_factors(ds, FP8_MAX) + dq += (tl.dot((ds * scale_ds).to(kT.type.element_ty), tl.trans(kT)) * descale_ds * descale_k) + else: + dq += tl.dot(ds.to(kT.type.element_ty), tl.trans(kT)) + # Increment pointers. + curr_n += step_n + kT_ptrs += step_n * stride_kn + vT_ptrs += step_n * stride_vn + return dq + +@triton.autotune( + configs=causal_autotune_configs, + key=causal_autotune_keys, + use_cuda_graph=True, +) +@triton.jit +def bwd_kernel_causal( # grid = (tl.cdiv(max_seqlen_q // BLOCK_M2), batch, nheads_q) + Q, K, V, sm_scale, DO, DQ, DK, DV, + M, Delta, + stride_qb, stride_qh, stride_qm, stride_qk, + stride_kb, stride_kh, stride_kn, stride_kk, + stride_vb, stride_vh, stride_vn, stride_vk, + stride_dqb, stride_dqh, stride_dqm, stride_dqk, + stride_dkb, stride_dkh, stride_dkn, stride_dkk, + stride_deltab, stride_deltah, stride_deltam, + stride_dob, stride_doh, stride_dom, stride_dok, + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn, + HQ, HK, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, max_seqlen_k, + dropout_mask, dropout_p, philox_seed, philox_offset_base, + BLOCK_M1: tl.constexpr, + BLOCK_N1: tl.constexpr, + BLOCK_M2: tl.constexpr, + BLOCK_N2: tl.constexpr, + BLK_SLICE_FACTOR: tl.constexpr, + HEAD_DIM: tl.constexpr, + ACTUAL_HEAD_DIM: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + IS_VARLEN: tl.constexpr, + USE_EXP2: tl.constexpr, + DEBUG_TRITON: tl.constexpr, + DEBUG_TRITON_DETAIL: tl.constexpr, +): + # program ids + pid = tl.program_id(0) + bid = tl.program_id(1) + hkid = tl.program_id(2) + if DEBUG_TRITON: print(f"\npid: {pid}, bid: {bid}, hkid: {hkid}") # noqa: E701 + # figure out varlen start and end + q_start = 0 + k_start = 0 + seqlen_q = max_seqlen_q + seqlen_k = max_seqlen_k + if IS_VARLEN: + # Compute actual sequence lengths + q_start = tl.load(cu_seqlens_q + bid) + q_end = tl.load(cu_seqlens_q + bid + 1) + k_start = tl.load(cu_seqlens_k + bid) + k_end = tl.load(cu_seqlens_k + bid + 1) + seqlen_q = q_end - q_start + seqlen_k = k_end - k_start + + delta_qk = seqlen_q - seqlen_k + if DEBUG_TRITON: print(f"delta_qk = {delta_qk}") # noqa: E701 + PADDED_HEAD: tl.constexpr = (ACTUAL_HEAD_DIM != HEAD_DIM) + offs_k = tl.arange(0, HEAD_DIM) + GROUP_SIZE: tl.constexpr = HQ // HK + + # align the delta_qk + start_n = pid * BLOCK_N1 + if start_n < seqlen_k: + # This section does dk and dv + dk = tl.zeros([BLOCK_N1, HEAD_DIM], dtype=tl.float32) + dv = tl.zeros([BLOCK_N1, HEAD_DIM], dtype=tl.float32) + + # q > k: diretcly skip all the way until the start of causal block + start_delta_q_gt_k = delta_qk + # q < k: some blocks will have no Masked block, other needs to re-calc + # starting position + # delta_qk is negative so flip it, only multiple of BLOCK_N can skip the + # masked op + num_blocks_skip = -delta_qk // BLOCK_N1 + delta_aligned = (num_blocks_skip + 1) * BLOCK_N1 + delta_qk + start_delta_q_lt_k = delta_aligned // BLOCK_M1 * BLOCK_M1 + if delta_qk >= 0: + start_delta = delta_qk + if DEBUG_TRITON: print(f"q >= k: start_delta = delta_qk aligned to BLOCK_M = {start_delta_q_gt_k}") # noqa: E701 + else: + start_delta = start_delta_q_lt_k + if DEBUG_TRITON: print(f"q < k: start_delta = residue btw multiple BLOCK_N and delta_qk = {delta_aligned} = aligned to BLOCK_M = {start_delta_q_lt_k}") # noqa: E701 + + offs_n = start_n + tl.arange(0, BLOCK_N1) + # Mask for loading K and V + mask_kv = offs_n[:, None] < seqlen_k + if PADDED_HEAD: + mask_k = offs_k < ACTUAL_HEAD_DIM + mask_kv &= mask_k[None, :] + offs_kv = offs_n[:, None] * stride_kn + offs_k[None, :] * stride_kk + + # K/V tensors not changed for the group + adj_kv = bid * stride_kb + hkid * stride_kh + k_start * stride_kn + # load K and V: they stay in SRAM throughout the inner loop. + k = tl.load(K + adj_kv + offs_kv, mask=mask_kv, other=0.0) + v = tl.load(V + adj_kv + offs_kv, mask=mask_kv, other=0.0) + # If MQA / GQA, set the K and V head offsets appropriately. + # hqid = hkid + for hqid in range(hkid * GROUP_SIZE, hkid * GROUP_SIZE + GROUP_SIZE): + if delta_qk >= 0: + start_m = start_n + start_delta + len_m = BLOCK_N1 + else: + start_m = max(start_n + delta_qk, 0) + start_m = start_m // BLOCK_M1 * BLOCK_M1 + # because we might shift the masked blocks up, we are deeper into + # the masked out region, so we would potentially increase the total + # steps with masked operation to get out of it + residue_m = max(start_n + delta_qk - start_m, 0) + len_m = BLOCK_N1 + residue_m + if DEBUG_TRITON: print(f"residue_m = {residue_m}") # noqa: E701 + + # offset input and output tensor by batch and Q/K heads + adj_q = bid * stride_qb + hqid * stride_qh + q_start * stride_qm + Q_ptr = Q + adj_q + adj_do = bid * stride_dob + hqid * stride_doh + q_start * stride_dom + DO_ptr = DO + adj_do + adj_delta = bid * stride_deltab + hqid * stride_deltah + \ + q_start * stride_deltam + M_ptr = M + adj_delta + Delta_ptr = Delta + adj_delta + + # batch_philox_offset is the ACTUALLY dropout offset + # dropout_offset is for debug purpose and will be removed later + batch_philox_offset = 0 + dropout_offset = 0 + if ENABLE_DROPOUT: + batch_philox_offset = philox_offset_base + bid * stride_dropoutb + \ + hqid * stride_dropouth + dropout_offset = dropout_mask + bid * stride_dropoutb + \ + hqid * stride_dropouth + + MASK_BLOCK_M1: tl.constexpr = BLOCK_M1 // BLK_SLICE_FACTOR + # bound the masked operation to q len so it does not have to wast cycles + len_m = min(len_m, seqlen_q) + num_steps = tl.cdiv(len_m, MASK_BLOCK_M1) + # when q < k, we may skip the initial masked op + if pid < num_blocks_skip: + num_steps = 0 + + # if start_m is negative, the current N-tile has no block on the + # diagonal of causal mask, so everything have no causal mask + if DEBUG_TRITON: print(f"Masked: start_n: {start_n}; start_m: {start_m}, num_steps: {num_steps}") # noqa: E701 + dk, dv = _bwd_dkdv_inner( + dk, dv, # output tensors + Q_ptr, k, v, DO_ptr, M_ptr, Delta_ptr, sm_scale, # input tensors + stride_qm, stride_qk, # strides for q + stride_dom, stride_dok, # strides for o + stride_dropoutm, stride_dropoutn, # strides for dropout + stride_deltam, + MASK_BLOCK_M1, BLOCK_N1, # block dim + HEAD_DIM, ACTUAL_HEAD_DIM, # head dim + dropout_p, philox_seed, batch_philox_offset, dropout_offset, # + seqlen_q, seqlen_k, # max sequence length for q and k + start_n, start_m, num_steps, # iteration numbers + None, None, None, None, + MASK=True, # causal masking + ENABLE_DROPOUT=ENABLE_DROPOUT, # activate dropout + USE_EXP2=USE_EXP2, + IS_FP8=False, + FP8_MAX=None, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + start_m += num_steps * MASK_BLOCK_M1 + num_steps = tl.cdiv(seqlen_q - start_m, BLOCK_M1) + end_m = start_m + num_steps * BLOCK_M1 + + if DEBUG_TRITON: print(f"start_m after Masked step: {start_m}; num_steps: {num_steps}") # noqa: E701 + if DEBUG_TRITON: print(f"unMasked: start_n: {start_n}, start_m: {start_m}, end_m: {end_m}, num_steps: {num_steps}") # noqa: E701 + if DEBUG_TRITON: print("unMasked") # noqa: E701 + dk, dv = _bwd_dkdv_inner( + dk, dv, # output tensors + Q_ptr, k, v, DO_ptr, M_ptr, Delta_ptr, sm_scale, # input tensors + stride_qm, stride_qk, # strides for q + stride_dom, stride_dok, # strides for o + stride_dropoutm, stride_dropoutn, # strides for dropout + stride_deltam, + BLOCK_M1, BLOCK_N1, # block dim + HEAD_DIM, ACTUAL_HEAD_DIM, # head dim + dropout_p, philox_seed, batch_philox_offset, dropout_offset, # + seqlen_q, seqlen_k, # max sequence length for q and k + start_n, start_m, num_steps, # iteration numbers + None, None, None, None, + MASK=False, # causal masking + ENABLE_DROPOUT=ENABLE_DROPOUT, # activate dropout + USE_EXP2=USE_EXP2, + IS_FP8=False, + FP8_MAX=None, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + # end of GQA/MQA of dkdv + # Write back dV and dK. + adj_dkdv = bid * stride_dkb + hkid * stride_kh + k_start * stride_dkn + offs_dkdv = offs_n[:, None] * stride_dkn + offs_k[None, :] * stride_dkk + tl.store(DV + adj_dkdv + offs_dkdv, dv, mask=mask_kv) + dk *= sm_scale + tl.store(DK + adj_dkdv + offs_dkdv, dk, mask=mask_kv) + + # This part does dq + start_m = pid * BLOCK_M2 + if start_m < seqlen_q: + # seqlen_q > seqlen_k, no need to process these tile for dq + if DEBUG_TRITON: print(f"end_n = start_m + BLOCK_M = {start_m} + {BLOCK_M2} = {start_m + BLOCK_M2}") # noqa: E701 + if start_m + BLOCK_M2 < delta_qk: + if DEBUG_TRITON: print(f"start_m + BLOCK_M2 = {start_m} + {BLOCK_M2} = {start_m + BLOCK_M2} < delta_qk of {delta_qk}") # noqa: E701 + return + + offs_m = start_m + tl.arange(0, BLOCK_M2) + # Mask for loading K and V + mask_q = offs_m[:, None] < seqlen_q + if PADDED_HEAD: + mask_k = offs_k < ACTUAL_HEAD_DIM + mask_q &= mask_k[None, :] + offs_q = offs_m[:, None] * stride_qm + offs_k[None, :] * stride_qk + offs_do = offs_m[:, None] * stride_dom + offs_k[None, :] * stride_dok + adj_kv = bid * stride_kb + hkid * stride_kh + k_start * stride_kn + K += adj_kv + V += adj_kv + # If MQA / GQA, set the K and V head offsets appropriately. + for hqid in range(hkid * GROUP_SIZE, hkid * GROUP_SIZE + GROUP_SIZE): + # seqlen_q < seqlen_k: delta_qk more kv tokens are added at the front + # for every M-tile + end_n = start_m + BLOCK_M2 - delta_qk + # clamp end_n at [0, seqlen_k] + end_n = max(min(end_n, seqlen_k), 0) + if DEBUG_TRITON: print(f"delta_qk: {delta_qk}; end_n: {end_n}") # noqa: E701 + # offset input and output tensor by batch and Q/K heads + adj_q = bid * stride_qb + hqid * stride_qh + q_start * stride_qm + adj_do = bid * stride_dob + hqid * stride_doh + q_start * stride_dom + adj_delta = \ + bid * stride_deltab + hqid * stride_deltah + q_start * stride_deltam + Delta_ptr = Delta + adj_delta + + # batch_philox_offset is the ACTUALLY dropout offset + # dropout_offset is for debug purpose and will be removed later + batch_philox_offset = 0 + dropout_offset = 0 + if ENABLE_DROPOUT: + batch_philox_offset = philox_offset_base + \ + bid * stride_dropoutb + \ + hqid * stride_dropouth + dropout_offset = \ + dropout_mask + bid * stride_dropoutb + hqid * stride_dropouth + + q = tl.load(Q + adj_q + offs_q, mask=mask_q, other=0.0) + do = tl.load(DO + adj_do + offs_do, mask=mask_q, other=0.0) + m = tl.load(M + adj_delta + offs_m * stride_deltam, + mask=offs_m < seqlen_q) + m = m[:, None] + + MASK_BLOCK_N2: tl.constexpr = BLOCK_N2 // BLK_SLICE_FACTOR + # start can only be 0 at minimum + start_n = max(end_n - BLOCK_M2, 0) + num_steps = tl.cdiv(end_n - start_n, MASK_BLOCK_N2) + dq = tl.zeros([BLOCK_M2, HEAD_DIM], dtype=tl.float32) + dq = _bwd_dq_inner( + dq, + q, K, V, do, m, Delta_ptr, sm_scale, # + stride_qm, stride_qk, stride_kn, stride_kk, stride_vn, stride_vk, + stride_dropoutm, stride_dropoutn, # + stride_deltam, + seqlen_q, seqlen_k, # + BLOCK_M2, MASK_BLOCK_N2, # + HEAD_DIM, ACTUAL_HEAD_DIM, # + dropout_p, philox_seed, batch_philox_offset, dropout_offset, # + start_m, start_n, end_n, num_steps, # + None, None, None, None, + MASK=True, # + ENABLE_DROPOUT=ENABLE_DROPOUT, + USE_EXP2=USE_EXP2, + IS_FP8=False, + FP8_MAX=None, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + end_n -= num_steps * MASK_BLOCK_N2 + num_steps = tl.cdiv(end_n, BLOCK_N2) + start_n = max(end_n - num_steps * BLOCK_N2, 0) + if DEBUG_TRITON: print(f"unMasked: start_m: {start_m}, start_n: {start_n}, end_n: {end_n}, num_steps: {num_steps}") # noqa: E701 + dq = _bwd_dq_inner( + dq, # + q, K, V, do, m, Delta_ptr, sm_scale, # + stride_qm, stride_qk, stride_kn, stride_kk, stride_vn, stride_vk, # + stride_dropoutm, stride_dropoutn, # + stride_deltam, + seqlen_q, seqlen_k, # + BLOCK_M2, BLOCK_N2, # + HEAD_DIM, ACTUAL_HEAD_DIM, # + dropout_p, philox_seed, batch_philox_offset, dropout_offset, # + start_m, start_n, end_n, num_steps, # + None, None, None, None, + MASK=False, # + ENABLE_DROPOUT=ENABLE_DROPOUT, + USE_EXP2=USE_EXP2, + IS_FP8=False, + FP8_MAX=None, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + # Write back dQ. + adj_dq = bid * stride_dqb + hqid * stride_dqh + q_start * stride_dqm + offs_dq = offs_m[:, None] * stride_dqm + offs_k[None, :] * stride_dqk + dq *= sm_scale + tl.store(DQ + adj_dq + offs_dq, dq, mask=mask_q) + # end of GQA/MQA of dq + +@triton.autotune( + configs=noncausal_autotune_configs, + key=noncausal_autotune_keys, + use_cuda_graph=True, +) +@triton.jit +def bwd_kernel_noncausal( + Q, K, V, sm_scale, DO, DQ, DK, DV, + M, Delta, + stride_qb, stride_qh, stride_qm, stride_qk, + stride_kb, stride_kh, stride_kn, stride_kk, + stride_vb, stride_vh, stride_vn, stride_vk, + stride_dqb, stride_dqh, stride_dqm, stride_dqk, + stride_dkb, stride_dkh, stride_dkn, stride_dkk, + stride_deltab, stride_deltah, stride_deltam, + stride_dob, stride_doh, stride_dom, stride_dok, + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn, + HQ, HK, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, max_seqlen_k, + dropout_mask, dropout_p, philox_seed, philox_offset_base, + BLOCK_M1: tl.constexpr, # 32 + BLOCK_N1: tl.constexpr, # 128 + BLOCK_M2: tl.constexpr, # 128 + BLOCK_N2: tl.constexpr, # 32 + BLK_SLICE_FACTOR: tl.constexpr, + HEAD_DIM: tl.constexpr, + ACTUAL_HEAD_DIM: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + IS_VARLEN: tl.constexpr, + USE_EXP2: tl.constexpr, + DEBUG_TRITON: tl.constexpr, + DEBUG_TRITON_DETAIL: tl.constexpr, +): + # program ids + pid = tl.program_id(0) + bid = tl.program_id(1) + hkid = tl.program_id(2) + if DEBUG_TRITON: print(f"\npid: {pid}, bid: {bid}, hkid: {hkid}") # noqa: E701 + # figure out varlen start and end + q_start = 0 + k_start = 0 + seqlen_q = max_seqlen_q + seqlen_k = max_seqlen_k + if IS_VARLEN: + # Compute actual sequence lengths + q_start = tl.load(cu_seqlens_q + bid) + q_end = tl.load(cu_seqlens_q + bid + 1) + k_start = tl.load(cu_seqlens_k + bid) + k_end = tl.load(cu_seqlens_k + bid + 1) + seqlen_q = q_end - q_start + seqlen_k = k_end - k_start + + PADDED_HEAD: tl.constexpr = (ACTUAL_HEAD_DIM != HEAD_DIM) + offs_k = tl.arange(0, HEAD_DIM) + GROUP_SIZE: tl.constexpr = HQ // HK + + start_n = pid * BLOCK_N1 + if start_n < seqlen_k: + dk = tl.zeros([BLOCK_N1, HEAD_DIM], dtype=tl.float32) + dv = tl.zeros([BLOCK_N1, HEAD_DIM], dtype=tl.float32) + + offs_n = start_n + tl.arange(0, BLOCK_N1) + # Mask for loading K and V + mask_kv = offs_n[:, None] < seqlen_k + if PADDED_HEAD: + mask_k = offs_k < ACTUAL_HEAD_DIM + mask_kv &= mask_k[None, :] + offs_kv = offs_n[:, None] * stride_kn + offs_k[None, :] * stride_kk + + # K/V tensors not changed for the group + adj_kv = bid * stride_kb + hkid * stride_kh + k_start * stride_kn + # load K and V: they stay in SRAM throughout the inner loop. + k = tl.load(K + adj_kv + offs_kv, mask=mask_kv, other=0.0) + v = tl.load(V + adj_kv + offs_kv, mask=mask_kv, other=0.0) + # If MQA / GQA, set the K and V head offsets appropriately. + for hqid in range(hkid * GROUP_SIZE, hkid * GROUP_SIZE + GROUP_SIZE): + # offset input and output tensor by batch and Q/K heads + adj_q = bid * stride_qb + hqid * stride_qh + q_start * stride_qm + Q_ptr = Q + adj_q + adj_do = bid * stride_dob + hqid * stride_doh + q_start * stride_dom + DO_ptr = DO + adj_do + adj_delta = bid * stride_deltab + hqid * stride_deltah + q_start * stride_deltam + M_ptr = M + adj_delta + Delta_ptr = Delta + adj_delta + + # batch_philox_offset is the ACTUALLY dropout offset + # dropout_offset is for debug purpose and will be removed later + batch_philox_offset = 0 + dropout_offset = 0 + if ENABLE_DROPOUT: + batch_philox_offset = philox_offset_base + bid * stride_dropoutb + \ + hqid * stride_dropouth + dropout_offset = dropout_mask + bid * stride_dropoutb + \ + hqid * stride_dropouth + + # because there is no causal, we always start from the beginning + start_m = 0 + num_steps = tl.cdiv(seqlen_q, BLOCK_M1) + dk, dv = _bwd_dkdv_inner( + dk, dv, # output tensors + Q_ptr, k, v, DO_ptr, M_ptr, Delta_ptr, sm_scale, # input tensors + stride_qm, stride_qk, # strides for q + stride_dom, stride_dok, # strides for o + stride_dropoutm, stride_dropoutn, # strides for dropout + stride_deltam, + BLOCK_M1, BLOCK_N1, # block dim + HEAD_DIM, ACTUAL_HEAD_DIM, # head dim + dropout_p, philox_seed, batch_philox_offset, dropout_offset, # + seqlen_q, seqlen_k, # max sequence length for q and k + start_n, start_m, num_steps, # iteration numbers + None, None, None, None, + MASK=False, # causal masking + ENABLE_DROPOUT=ENABLE_DROPOUT, # activate dropout + USE_EXP2=USE_EXP2, + IS_FP8=False, + FP8_MAX=None, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + + # Write back dV and dK. + adj_dkdv = bid * stride_dkb + hkid * stride_kh + k_start * stride_dkn + offs_dkdv = offs_n[:, None] * stride_dkn + offs_k[None, :] * stride_dkk + tl.store(DV + adj_dkdv + offs_dkdv, dv, mask=mask_kv) + dk *= sm_scale + tl.store(DK + adj_dkdv + offs_dkdv, dk, mask=mask_kv) + + # THIS PART DOES DQ + start_m = pid * BLOCK_M2 + if start_m < seqlen_q: + offs_m = start_m + tl.arange(0, BLOCK_M2) + # Mask for loading K and V + mask_q = offs_m[:, None] < seqlen_q + if PADDED_HEAD: + mask_k = offs_k < ACTUAL_HEAD_DIM + mask_q &= mask_k[None, :] + offs_q = offs_m[:, None] * stride_qm + offs_k[None, :] * stride_qk + offs_do = offs_m[:, None] * stride_dom + offs_k[None, :] * stride_dok + adj_kv = bid * stride_kb + hkid * stride_kh + k_start * stride_kn + K += adj_kv + V += adj_kv + # If MQA / GQA, set the K and V head offsets appropriately. + for hqid in range(hkid * GROUP_SIZE, hkid * GROUP_SIZE + GROUP_SIZE): + # offset input and output tensor by batch and Q/K heads + adj_q = bid * stride_qb + hqid * stride_qh + q_start * stride_qm + adj_do = bid * stride_dob + hqid * stride_doh + q_start * stride_dom + adj_delta = \ + bid * stride_deltab + hqid * stride_deltah + q_start * stride_deltam + Delta_ptr = Delta + adj_delta + + # batch_philox_offset is the ACTUALLY dropout offset + # dropout_offset is for debug purpose and will be removed later + batch_philox_offset = 0 + dropout_offset = 0 + if ENABLE_DROPOUT: + batch_philox_offset = philox_offset_base + \ + bid * stride_dropoutb + \ + hqid * stride_dropouth + dropout_offset = \ + dropout_mask + bid * stride_dropoutb + hqid * stride_dropouth + + q = tl.load(Q + adj_q + offs_q, mask=mask_q, other=0.0) + do = tl.load(DO + adj_do + offs_do, mask=mask_q, other=0.0) + m = tl.load(M + adj_delta + offs_m * stride_deltam, + mask=offs_m < seqlen_q) + m = m[:, None] + + # start can only be 0 at minimum + start_n = 0 + end_n = seqlen_k + num_steps = tl.cdiv(seqlen_k, BLOCK_N2) + + dq = tl.zeros([BLOCK_M2, HEAD_DIM], dtype=tl.float32) + dq = _bwd_dq_inner( + dq, # + q, K, V, do, m, Delta_ptr, sm_scale, # + stride_qm, stride_qk, stride_kn, stride_kk, stride_vn, stride_vk, # + stride_dropoutm, stride_dropoutn, # + stride_deltam, + seqlen_q, seqlen_k, # + BLOCK_M2, BLOCK_N2, # + HEAD_DIM, ACTUAL_HEAD_DIM, # + dropout_p, philox_seed, batch_philox_offset, dropout_offset, # + start_m, start_n, end_n, num_steps, # + None, None, None, None, + MASK=False, # + ENABLE_DROPOUT=ENABLE_DROPOUT, + USE_EXP2=USE_EXP2, + IS_FP8=False, + FP8_MAX=None, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + # Write back dQ. + adj_dq = bid * stride_dqb + hqid * stride_dqh + q_start * stride_dqm + offs_dq = offs_m[:, None] * stride_dqm + offs_k[None, :] * stride_dqk + dq *= sm_scale + tl.store(DQ + adj_dq + offs_dq, dq, mask=mask_q) + + +def attention_prefill_backward_triton_split_oneKernel_impl( + do: torch.Tensor, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + o: torch.Tensor, + softmax_lse: torch.Tensor, + dq: torch.Tensor, + dk: torch.Tensor, + dv: torch.Tensor, + sm_scale: float, + alibi_slopes: Optional[torch.Tensor], + causal: bool, + layout: Literal["bshd", "bhsd", "thd"], + cu_seqlens_q: Optional[torch.Tensor], + cu_seqlens_k: Optional[torch.Tensor], + max_seqlen_q: Optional[int], + max_seqlen_k: Optional[int], + dropout_p: float, + philox_seed: Optional[int], + philox_offset: Optional[int], + use_exp2: bool, +): + # debug + DEBUG_TRITON: bool = False + DEBUG_TRITON_DETAIL: bool = False + + # get strides and shape + batch, nheads_q, nheads_k, head_size, max_seqlen_q_final, max_seqlen_k_final = \ + get_shapes_from_layout( + q, k, layout, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, max_seqlen_k + ) + q_strides, k_strides, v_strides, o_strides = \ + get_strides_from_layout(q, k, v, o, layout) + stride_qb, stride_qh, stride_qm, stride_qk = q_strides + stride_kb, stride_kh, stride_kn, stride_kk = k_strides + stride_vb, stride_vh, stride_vn, stride_vk = v_strides + stride_ob, stride_oh, stride_om, stride_ok = o_strides + dq_strides, dk_strides, _, do_strides = \ + get_strides_from_layout(dq, dk, dv, do, layout) + stride_dqb, stride_dqh, stride_dqm, stride_dqk = dq_strides + stride_dkb, stride_dkh, stride_dkn, stride_dkk = dk_strides + stride_dob, stride_doh, stride_dom, stride_dok = do_strides + IS_VARLEN = layout == "thd" + use_dropout = (dropout_p > 0.0) + + # get closest power of 2 over or equal to 32. + padded_d_model = 1 << (head_size - 1).bit_length() + padded_d_model = max(padded_d_model, 16) + HEAD_DIM = padded_d_model + ACTUAL_HEAD_DIM = head_size + + # init delta + delta = torch.empty_like(softmax_lse) + if IS_VARLEN: + stride_deltab = 0 + stride_deltam, stride_deltah = delta.stride() + else: + stride_deltab, stride_deltah, stride_deltam = delta.stride() + pre_grid = lambda META: (triton.cdiv(max_seqlen_q_final, META['PRE_BLOCK']), batch, nheads_q) + _bwd_preprocess[pre_grid]( + o, do, + delta, + stride_ob, stride_oh, stride_om, stride_ok, + stride_deltab, stride_deltah, stride_deltam, + 0, + cu_seqlens_q, max_seqlen_q_final, + None, + HEAD_DIM=HEAD_DIM, + ACTUAL_HEAD_DIM=ACTUAL_HEAD_DIM, + IS_VARLEN=IS_VARLEN, + IS_FP8=False + ) + + # dropout mask tensor for debugging. We dump the dropout mask created in + # the kernel for testing + dropout_mask = None + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn = \ + (0, 0 , 0 , 0) + if use_dropout: + dropout_mask = torch.zeros( + (batch, nheads_q, max_seqlen_q_final, max_seqlen_k_final), + device=q.device, + dtype=torch.float32 + ) + + if DROPOUT_USE_PYTORCH: + if not IS_VARLEN: + dropout_mask = create_dropout_mask( + dropout_p, + (batch, nheads_q, max_seqlen_q_final, max_seqlen_k_final), + seed = philox_seed + ) + else: + dropout_mask = create_dropout_mask_varlen( + dropout_p, batch, nheads_q, + cu_seqlens_q, cu_seqlens_k, philox_seed + ) + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn = \ + dropout_mask.stride() + + seqlen = max(max_seqlen_q_final, max_seqlen_k_final) + grid = lambda META: ((seqlen + META['BLOCK_N1'] - 1) // META['BLOCK_N1'], batch, nheads_k) + if causal: + if DEBUG_TRITON: print(f"bwd_kernel: grid = {grid}" ) # noqa: E701 + bwd_kernel_causal[grid]( + q, k, v, sm_scale, do, dq, dk, dv, + softmax_lse, delta, + stride_qb, stride_qh, stride_qm, stride_qk, + stride_kb, stride_kh, stride_kn, stride_kk, + stride_vb, stride_vh, stride_vn, stride_vk, + stride_dqb, stride_dqh, stride_dqm, stride_dqk, + stride_dkb, stride_dkh, stride_dkn, stride_dkk, + stride_deltab, stride_deltah, stride_deltam, + stride_dob, stride_doh, stride_dom, stride_dok, + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn, + nheads_q, nheads_k, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q_final, max_seqlen_k_final, + dropout_mask, dropout_p, philox_seed, philox_offset, + HEAD_DIM=HEAD_DIM, + ACTUAL_HEAD_DIM=ACTUAL_HEAD_DIM, + ENABLE_DROPOUT=use_dropout, + IS_VARLEN=IS_VARLEN, + USE_EXP2=use_exp2, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + else: + bwd_kernel_noncausal[grid]( + q, k, v, sm_scale, do, dq, dk, dv, + softmax_lse, delta, + stride_qb, stride_qh, stride_qm, stride_qk, + stride_kb, stride_kh, stride_kn, stride_kk, + stride_vb, stride_vh, stride_vn, stride_vk, + stride_dqb, stride_dqh, stride_dqm, stride_dqk, + stride_dkb, stride_dkh, stride_dkn, stride_dkk, + stride_deltab, stride_deltah, stride_deltam, + stride_dob, stride_doh, stride_dom, stride_dok, + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn, + nheads_q, nheads_k, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q_final, max_seqlen_k_final, + dropout_mask, dropout_p, philox_seed, philox_offset, + HEAD_DIM=HEAD_DIM, + ACTUAL_HEAD_DIM=ACTUAL_HEAD_DIM, + ENABLE_DROPOUT=use_dropout, + IS_VARLEN=IS_VARLEN, + USE_EXP2=use_exp2, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + + return delta \ No newline at end of file diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bwd_prefill_split.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bwd_prefill_split.py new file mode 100644 index 0000000000000000000000000000000000000000..c1e2ff5985f07a758a0189d730dbbd8db9746726 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bwd_prefill_split.py @@ -0,0 +1,1354 @@ +import torch +import triton # type: ignore +import triton.language as tl # type: ignore +from typing import Literal, Optional +from .utils import DEBUG, DROPOUT_USE_PYTORCH, DROPOUT_DUMP, compute_fp8_scaling_factors, get_shapes_from_layout, \ + get_strides_from_layout, create_dropout_mask, create_dropout_mask_varlen, is_fp8 + +# NOTE: triton fails to import tl.constexprs so create them here for the file +tl_DROPOUT_USE_PYTORCH: tl.constexpr = triton.language.constexpr(DROPOUT_USE_PYTORCH) +tl_DROPOUT_DUMP: tl.constexpr = triton.language.constexpr(DROPOUT_DUMP) + +# This function computes delta given output Out and gradient DO +# Here is the I/O shape: +# Out: (batch, nhead_q, max_seqlens_q, headDim) +# DO: (batch, nhead_q, max_seqlens_q, headDim) +# Delta: (batch, nheads_q, max_seqlens_q), same as softmax_lse defined at +# fwd_prefill.py line 607 +@triton.jit +def _bwd_preprocess( + O, DO, # noqa: E741 + Delta, + stride_ob, stride_oh, stride_om, stride_ok, + stride_deltab, stride_deltah, stride_deltam, + stride_descale_do_z, + cu_seqlens_q, max_seqlen_q, + Descale_do, + BLOCK_M: tl.constexpr, + HEAD_DIM: tl.constexpr, + ACTUAL_HEAD_DIM: tl.constexpr, + IS_VARLEN: tl.constexpr, + IS_FP8: tl.constexpr +): + pid_m = tl.program_id(0) + bid = tl.program_id(1) + hid = tl.program_id(2) + # Handle varlen + q_start = 0 + seqlen_q = max_seqlen_q + if IS_VARLEN: + q_start = tl.load(cu_seqlens_q + bid) + q_end = tl.load(cu_seqlens_q + bid + 1) + seqlen_q = q_end - q_start + else: + q_start = 0 + seqlen_q = max_seqlen_q + + # Compute offsets + offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + offs_k = tl.arange(0, HEAD_DIM) + # Offset O/DO by batch, head and q_start + O += bid * stride_ob + hid * stride_oh + q_start * stride_om # noqa: E741 + DO += bid * stride_ob + hid * stride_oh + q_start * stride_om + # create masks + mask_m = offs_m < seqlen_q + mask_md = mask_m[:, None] + PADDED_HEAD: tl.constexpr = (ACTUAL_HEAD_DIM != HEAD_DIM) + if PADDED_HEAD: + mask_md &= offs_k[None, :] < ACTUAL_HEAD_DIM + # compute pointers + offs_do = offs_m[:, None] * stride_om + offs_k[None, :] * stride_ok + out_ptrs = O + offs_do + do_ptrs = DO + offs_do + # load + o = tl.load(out_ptrs, mask=mask_md, other=0.0) + do = tl.load(do_ptrs, mask=mask_md, other=0.0) + # compute and write-back to delta + if IS_FP8: + descale_do = tl.load(Descale_do + bid * stride_descale_do_z + hid) + + # NOTE: do is in the fp8 range and o is not in fp8 + delta = tl.sum(o.to(tl.float32) * (do.to(tl.float32) * descale_do), axis=1) + else: + delta = tl.sum(o.to(tl.float32) * do.to(tl.float32), axis=1) + delta_offset = Delta + bid * stride_deltab + hid * stride_deltah + q_start * stride_deltam + tl.store(delta_offset + offs_m * stride_deltam, delta, mask=mask_m) + + +# The main inner-loop logic for computing dK and dV. +@triton.jit +def _bwd_dkdv_inner( + dk, dv, # output + Q, k, v, DO, M, D, sm_scale, # input tensor + stride_qm, stride_qk, + stride_dom, stride_dok, + stride_dropoutm, stride_dropoutn, + stride_deltam, + BLOCK_M: tl.constexpr, # 16 + BLOCK_N: tl.constexpr, # 128 + HEAD_DIM: tl.constexpr, # + ACTUAL_HEAD_DIM: tl.constexpr, # + dropout_p, philox_seed, batch_philox_offset, dropout_offset, + alibi_slope, + seqlen_q, seqlen_k, # max sequence length for q and k + # Filled in by the wrapper. + start_n, start_m, num_steps, # iteration numbers + descale_q, descale_k, descale_v, descale_do, # fp8 descale factors from user + MASK: tl.constexpr, # causal masking, only apply to tiles on mask diagonal + ENABLE_DROPOUT: tl.constexpr, # activate dropout + USE_ALIBI: tl.constexpr, + USE_EXP2: tl.constexpr, # activate exp2 + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, + DEBUG_TRITON: tl.constexpr, + DEBUG_TRITON_DETAIL: tl.constexpr, +): + # if HEAD_DIM is padded + PADDED_HEAD: tl.constexpr = (ACTUAL_HEAD_DIM != HEAD_DIM) + delta_qk = seqlen_q - seqlen_k + offs_m = start_m + tl.arange(0, BLOCK_M) # start_m + (0, 15) + offs_n = start_n + tl.arange(0, BLOCK_N) # start_m + (0, 127) + offs_k = tl.arange(0, HEAD_DIM) + # mask to make sure not OOB of seqlen_q + mask_n = offs_n < seqlen_k + # Q and DO are (seqlen_q, head_dim) + # qT_ptrs = (1, BLOCK_M) + (HEAD_DIM, 1), transpose of q + qT_ptrs = Q + offs_m[None, :] * stride_qm + offs_k[:, None] * stride_qk + # do_ptrs = (BLOCK_M, 1) + (1, HEAD_DIM), NOT transposed + do_ptrs = DO + offs_m[:, None] * stride_dom + offs_k[None, :] * stride_dok + # BLOCK_N must be a multiple of BLOCK_M, otherwise the code wouldn't work. + tl.static_assert(BLOCK_N % BLOCK_M == 0) + curr_m = start_m + step_m = BLOCK_M + curr_philox_offset = batch_philox_offset + curr_dropout_offset = dropout_offset + RCP_LN2: tl.constexpr = 1.4426950408889634 # = 1.0 / ln(2) + + for blk_idx in range(num_steps): + if DEBUG_TRITON: print(f"iter {blk_idx}: curr_m = {curr_m}") # noqa: E701 + offs_m = curr_m + tl.arange(0, BLOCK_M) + # update the mask because offs_m advanced + mask_m = offs_m < seqlen_q + mask_qT = mask_m[None, :] + mask_do = mask_m[:, None] + mask_nm = mask_n[:, None] & (offs_m[None, :] < seqlen_q) + if PADDED_HEAD: + mask_qT &= offs_k[:, None] < ACTUAL_HEAD_DIM + mask_do &= offs_k[None, :] < ACTUAL_HEAD_DIM + qT = tl.load(qT_ptrs, mask=mask_qT, other=0.0) + # generate dropout mask + if ENABLE_DROPOUT: + # NOTE: dropout is transposed because it is used to mask pT + philox_offs = curr_philox_offset + \ + offs_m[None, :] * stride_dropoutm + \ + offs_n[:, None] * stride_dropoutn + if tl_DROPOUT_USE_PYTORCH: + dropout_offs = offs_m[None, :] * stride_dropoutm + \ + offs_n[:, None] * stride_dropoutn + dropout_mask = tl.load( + curr_dropout_offset + dropout_offs, + mask=mask_nm + ) + else: + rand_vals = tl.rand(philox_seed, philox_offs) + dropout_mask = rand_vals > dropout_p + dropout_scale = 1.0 / (1 - dropout_p) + # Load m before computing qk to reduce pipeline stall. + m = tl.load(M + offs_m * stride_deltam, mask=mask_m, other=0.0) + if IS_FP8: + qkT = (tl.dot(k, qT) * descale_q * descale_k) + else: + qkT = tl.dot(k, qT) + qkT_scaled = qkT * sm_scale + + if USE_ALIBI: + relative_pos_block = offs_n[:, None] + seqlen_q - seqlen_k - offs_m[None, :] + alibi_block = -1 * alibi_slope * tl.abs(relative_pos_block) + qkT_scaled += alibi_block + + if DEBUG_TRITON_DETAIL: + if start_n == 256: + print(f"qT: {qT.shape}\n", qT) + print(f"k: {k.shape}\n", k) + print(f"qkT scaled: {qkT.shape}\n", qkT_scaled) + # TODO: remove the scaling of m later when we removed re-scaling in fwd + if USE_EXP2: + pT = tl.math.exp2(qkT_scaled * RCP_LN2 - m[None, :] * RCP_LN2) + else: + pT = tl.math.exp(qkT_scaled - m[None, :]) + + # Autoregressive masking. + if MASK: + # offset offs_m with delta_qk since the causal mask starts at + # bottom right of the (seqlen_q, seqlen_k) matrix + causal_mask = (offs_m[None, :] - delta_qk) >= offs_n[:, None] + mask = causal_mask & mask_nm + if DEBUG_TRITON_DETAIL: + if start_n == 256: + print(f"causal_mask: {causal_mask.shape}\n", causal_mask) + print(f"qkT after causal: {qkT.shape}\n", tl.where(causal_mask, qkT * sm_scale, 0.0)) + pT = tl.where(mask, pT, 0.0) + do = tl.load(do_ptrs, mask=mask_do, other=0.0) + # Compute dV. + if ENABLE_DROPOUT: + pT_dropout = tl.where(dropout_mask, pT, 0.0) * dropout_scale + if IS_FP8: + scale_p_dropout, descale_p_dropout = compute_fp8_scaling_factors(pT_dropout, FP8_MAX) + dv += (tl.dot((pT_dropout * scale_p_dropout).to(do.type.element_ty), do)* descale_p_dropout * descale_do) + else: + dv += tl.dot(pT_dropout.to(do.type.element_ty), do) + else: + if IS_FP8: + scale_pT, descale_pT = compute_fp8_scaling_factors(pT, FP8_MAX) + dv += (tl.dot((pT * scale_pT).to(do.type.element_ty), do) * descale_pT * descale_do) + else: + dv += tl.dot(pT.to(do.type.element_ty), do) + + if DEBUG_TRITON_DETAIL: + if start_n == 256: + print(f"pT: {pT.shape}\n", pT) + # D (= delta) is pre-divided by ds_scale. + Di = tl.load(D + offs_m * stride_deltam, mask=mask_m) + # Compute dP and dS. + if IS_FP8: + dpT = (tl.dot(v, tl.trans(do)) * descale_v * descale_do) + else: + dpT = tl.dot(v, tl.trans(do)) + if ENABLE_DROPOUT: + dpT = tl.where(dropout_mask, dpT, 0.0) * dropout_scale + delta_i = Di[None, :] + dsT = pT * (dpT - delta_i) + if IS_FP8: + scale_dsT, descale_dsT = compute_fp8_scaling_factors(dsT, FP8_MAX) + dk += (tl.dot((dsT * scale_dsT).to(qT.type.element_ty), tl.trans(qT)) * descale_dsT * descale_q) + else: + dk += tl.dot(dsT.to(qT.type.element_ty), tl.trans(qT)) + # Increment pointers. + curr_m += step_m + qT_ptrs += step_m * stride_qm + do_ptrs += step_m * stride_dom + return dk, dv + + +# grid = (max_seqlen_k // BLOCK_N, batch, nheads_q) +@triton.jit +def _bwd_kernel_dkdv_causal( + Q, K, V, sm_scale, DO, DK, DV, + M, Delta, + stride_qb, stride_qh, stride_qm, stride_qk, + stride_kb, stride_kh, stride_kn, stride_kk, + stride_vb, stride_vh, stride_vn, stride_vk, + stride_dkb, stride_dkh, stride_dkn, stride_dkk, + stride_deltab, stride_deltah, stride_deltam, + stride_dob, stride_doh, stride_dom, stride_dok, + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn, + stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_do_z, + stride_az, stride_ah, + HQ, HK, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, max_seqlen_k, + Dropout_mask, dropout_p, philox_seed, philox_offset_base, + Alibi_slopes, + Descale_q, Descale_k, Descale_v, Descale_do, + BLOCK_M: tl.constexpr, # 32 + BLOCK_N: tl.constexpr, # 128 + BLK_SLICE_FACTOR: tl.constexpr, + HEAD_DIM: tl.constexpr, + ACTUAL_HEAD_DIM: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + IS_VARLEN: tl.constexpr, + USE_ALIBI: tl.constexpr, + USE_EXP2: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, + FP8_OUTPUT: tl.constexpr, + DEBUG_TRITON: tl.constexpr, + DEBUG_TRITON_DETAIL: tl.constexpr, +): + # program ids + pid = tl.program_id(0) + bid = tl.program_id(1) + hkid = tl.program_id(2) + # figure out varlen start and end + q_start = 0 + k_start = 0 + seqlen_q = max_seqlen_q + seqlen_k = max_seqlen_k + if IS_VARLEN: + # Compute actual sequence lengths + q_start = tl.load(cu_seqlens_q + bid) + q_end = tl.load(cu_seqlens_q + bid + 1) + k_start = tl.load(cu_seqlens_k + bid) + k_end = tl.load(cu_seqlens_k + bid + 1) + seqlen_q = q_end - q_start + seqlen_k = k_end - k_start + + dk = tl.zeros([BLOCK_N, HEAD_DIM], dtype=tl.float32) + dv = tl.zeros([BLOCK_N, HEAD_DIM], dtype=tl.float32) + # Figure out causal starting block since we have seqlen_q >=< seqlen_k. + # Unlike forward pass where we tile on M dim and iterate on N dim, so that + # we can skip some M blocks, in backward pass, we tile on the N dim for kv + # and iterate over the M. In this way, we cannot skip N blocks, but only to + # determine the starting M blocks to skip some initial blocks masked by + # causal. + delta_qk = seqlen_q - seqlen_k + if DEBUG_TRITON: print(f"\npid: {pid}, bid: {bid}, hkid: {hkid}") + if DEBUG_TRITON: print(f"delta_qk = {delta_qk}") + # q > k: diretcly skip all the way until the start of causal block + start_delta_q_gt_k = delta_qk + # q < k: some blocks will have no Masked block, other needs to re-calc + # starting position + # delta_qk is negative so flip it, only multiple of BLOCK_N can skip the + # masked op + num_blocks_skip = -delta_qk // BLOCK_N + delta_aligned = (num_blocks_skip + 1) * BLOCK_N + delta_qk + start_delta_q_lt_k = delta_aligned // BLOCK_M * BLOCK_M + if delta_qk >= 0: + start_delta = delta_qk + if DEBUG_TRITON: print(f"q >= k: start_delta = delta_qk aligned to BLOCK_M = {start_delta_q_gt_k}") + else: + start_delta = start_delta_q_lt_k + if DEBUG_TRITON: print(f"q < k: start_delta = residue btw multiple BLOCK_N and delta_qk = {delta_aligned} = aligned to BLOCK_M = {start_delta_q_lt_k}") + # align the delta_qk + start_n = pid * BLOCK_N + + offs_k = tl.arange(0, HEAD_DIM) + offs_n = start_n + tl.arange(0, BLOCK_N) + # Mask for loading K and V + mask_kv = offs_n[:, None] < seqlen_k + PADDED_HEAD: tl.constexpr = (ACTUAL_HEAD_DIM != HEAD_DIM) + if PADDED_HEAD: + mask_k = offs_k < ACTUAL_HEAD_DIM + mask_kv &= mask_k[None, :] + + GROUP_SIZE = HQ // HK + # K/V tensors not changed for the group + adj_k = bid * stride_kb + hkid * stride_kh + k_start * stride_kn + offs_n[:, None] * stride_kn + offs_k[None, :] * stride_kk + adj_v = bid * stride_vb + hkid * stride_vh + k_start * stride_vn + offs_n[:, None] * stride_vn + offs_k[None, :] * stride_vk + # load K and V: they stay in SRAM throughout the inner loop. + k = tl.load(K + adj_k , mask=mask_kv, other=0.0) + v = tl.load(V + adj_v, mask=mask_kv, other=0.0) + # If MQA / GQA, set the K and V head offsets appropriately. + for hqid in range(hkid * GROUP_SIZE, hkid * GROUP_SIZE + GROUP_SIZE): + if delta_qk >= 0: + start_m = start_n + start_delta + len_m = BLOCK_N + else: + start_m = max(start_n + delta_qk, 0) + start_m = start_m // BLOCK_M * BLOCK_M + # because we might shift the masked blocks up, we are deeper into + # the masked out region, so we would potentially increase the total + # steps with masked operation to get out of it + residue_m = max(start_n + delta_qk - start_m, 0) + len_m = BLOCK_N + residue_m + if DEBUG_TRITON: print(f"residue_m = {residue_m}") + + # offset input and output tensor by batch and Q/K heads + adj_q = bid * stride_qb + hqid * stride_qh + q_start * stride_qm + Q_ptr = Q + adj_q + adj_do = bid * stride_dob + hqid * stride_doh + q_start * stride_dom + DO_ptr = DO + adj_do + adj_delta = bid * stride_deltab + hqid * stride_deltah + q_start * stride_deltam + M_ptr = M + adj_delta + Delta_ptr = Delta + adj_delta + + if USE_ALIBI: + alibi_offset = bid * stride_az + hqid * stride_ah + alibi_slope = tl.load(Alibi_slopes + alibi_offset) + else: + alibi_slope = None + + # batch_philox_offset is the ACTUALLY dropout offset + # dropout_offset is for debug purpose and will be removed later + batch_philox_offset = 0 + dropout_offset = 0 + if ENABLE_DROPOUT: + batch_philox_offset = philox_offset_base + bid * stride_dropoutb + \ + hqid * stride_dropouth + dropout_offset = Dropout_mask + bid * stride_dropoutb + \ + hqid * stride_dropouth + + MASK_BLOCK_M: tl.constexpr = BLOCK_M // BLK_SLICE_FACTOR + # bound the masked operation to q len so it does not have to wast cycles + len_m = min(len_m, seqlen_q) + num_steps = tl.cdiv(len_m, MASK_BLOCK_M) + # when q < k, we may skip the initial masked op + if pid < num_blocks_skip: + num_steps = 0 + + if IS_FP8: + descale_q = tl.load(Descale_q + bid * stride_descale_q_z + hqid) + descale_k = tl.load(Descale_k + bid * stride_descale_k_z + hkid) + descale_v = tl.load(Descale_v + bid * stride_descale_v_z + hkid) + descale_do = tl.load(Descale_do + bid * stride_descale_do_z + hqid) + else: + descale_q, descale_k, descale_v, descale_do = 1.0, 1.0, 1.0, 1.0 + + # if start_m is negative, the current N-tile has no block on the + # diagonal of causal mask, so everything have no causal mask + if DEBUG_TRITON: print(f"Masked: start_n: {start_n}; start_m: {start_m}, num_steps: {num_steps}") + dk, dv = _bwd_dkdv_inner( + dk, dv, # output tensors + Q_ptr, k, v, DO_ptr, M_ptr, Delta_ptr, sm_scale, # input tensors + stride_qm, stride_qk, # strides for q + stride_dom, stride_dok, # strides for o + stride_dropoutm, stride_dropoutn, # strides for dropout + stride_deltam, + MASK_BLOCK_M, BLOCK_N, # block dim + HEAD_DIM, ACTUAL_HEAD_DIM, # head dim + dropout_p, philox_seed, batch_philox_offset, dropout_offset, # + alibi_slope, + seqlen_q, seqlen_k, # max sequence length for q and k + start_n, start_m, num_steps, # iteration numbers + descale_q, descale_k, descale_v, descale_do, # fp8 descale factors from user + MASK=True, # causal masking + ENABLE_DROPOUT=ENABLE_DROPOUT, # activate dropout + USE_ALIBI=USE_ALIBI, + USE_EXP2=USE_EXP2, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + start_m += num_steps * MASK_BLOCK_M + num_steps = tl.cdiv(seqlen_q - start_m, BLOCK_M) + end_m = start_m + num_steps * BLOCK_M + + if DEBUG_TRITON: print(f"start_m after Masked step: {start_m}; num_steps: {num_steps}") # noqa: E701 + if DEBUG_TRITON: print(f"unMasked: start_n: {start_n}, start_m: {start_m}, end_m: {end_m}, num_steps: {num_steps}") # noqa: E701 + if DEBUG_TRITON: print("unMasked") # noqa: E701 + dk, dv = _bwd_dkdv_inner( + dk, dv, # output tensors + Q_ptr, k, v, DO_ptr, M_ptr, Delta_ptr, sm_scale, # input tensors + stride_qm, stride_qk, # strides for q + stride_dom, stride_dok, # strides for o + stride_dropoutm, stride_dropoutn, # strides for dropout + stride_deltam, + BLOCK_M, BLOCK_N, # block dim + HEAD_DIM, ACTUAL_HEAD_DIM, # head dim + dropout_p, philox_seed, batch_philox_offset, dropout_offset, # + alibi_slope, + seqlen_q, seqlen_k, # max sequence length for q and k + start_n, start_m, num_steps, # iteration numbers + descale_q, descale_k, descale_v, descale_do, # fp8 descale factors from user + MASK=False, # causal masking + ENABLE_DROPOUT=ENABLE_DROPOUT, # activate dropout + USE_ALIBI=USE_ALIBI, + USE_EXP2=USE_EXP2, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + + # Write back dV and dK. + adj_dkdv = bid * stride_dkb + hkid * stride_kh + k_start * stride_dkn + offs_dkdv = offs_n[:, None] * stride_dkn + offs_k[None, :] * stride_dkk + tl.store(DV + adj_dkdv + offs_dkdv, dv, mask=mask_kv) + dk *= sm_scale + tl.store(DK + adj_dkdv + offs_dkdv, dk, mask=mask_kv) + + +# the main inner-loop logic for computing dQ +@triton.jit +def _bwd_dq_inner( + dq, # output + q, K, V, do, m, Delta, sm_scale, # input + # shared by Q/K/V. + stride_qm, stride_qk, stride_kn, stride_kk, stride_vn, stride_vk, + stride_dropoutm, stride_dropoutn, # stride for dropout + stride_deltam, + seqlen_q, seqlen_k, # + BLOCK_M2: tl.constexpr, # + BLOCK_N2: tl.constexpr, # + HEAD_DIM: tl.constexpr, + ACTUAL_HEAD_DIM: tl.constexpr, # + dropout_p, philox_seed, batch_philox_offset, dropout_offset, + alibi_slope, + # Filled in by the wrapper. + start_m, start_n, end_n, num_steps, # + descale_q, descale_k, descale_v, descale_do, # fp8 descale factors from user + MASK: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + USE_ALIBI: tl.constexpr, + USE_EXP2: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, + DEBUG_TRITON: tl.constexpr, + DEBUG_TRITON_DETAIL: tl.constexpr, +): + # if HEAD_DIM is padded + PADDED_HEAD: tl.constexpr = (ACTUAL_HEAD_DIM != HEAD_DIM) + delta_qk = seqlen_q - seqlen_k + offs_m = start_m + tl.arange(0, BLOCK_M2) + offs_n = start_n + tl.arange(0, BLOCK_N2) + offs_k = tl.arange(0, HEAD_DIM) + + # mask to make sure not OOB of seqlen_q + mask_m = offs_m < seqlen_q + + kT_ptrs = K + offs_n[None, :] * stride_kn + offs_k[:, None] * stride_kk + vT_ptrs = V + offs_n[None, :] * stride_vn + offs_k[:, None] * stride_vk + # D (= delta) is pre-divided by ds_scale. + Di = tl.load(Delta + offs_m * stride_deltam, mask=mask_m, other=0.0) + # BLOCK_M2 must be a multiple of BLOCK_N2, otherwise the code wouldn't work. + tl.static_assert(BLOCK_M2 % BLOCK_N2 == 0) + curr_n = start_n + step_n = BLOCK_N2 + curr_philox_offset = batch_philox_offset + curr_dropout_offset = dropout_offset + RCP_LN2: tl.constexpr = 1.4426950408889634 # = 1.0 / ln(2) + for blk_idx in range(num_steps): + if DEBUG_TRITON: print(f"iter {blk_idx}: curr_n = {curr_n}") # noqa: E701 + offs_n = curr_n + tl.arange(0, BLOCK_N2) + # end_n is needed because the end of causal True might not be perfectly + # aligned with the end of the block + mask_n = offs_n < end_n + if DEBUG_TRITON_DETAIL: print(f"start_n = {start_n}, end_n = {end_n}, offs_n: {offs_n.shape}\n{offs_n}") # noqa: E701 + if DEBUG_TRITON_DETAIL: print(f"mask_n: {mask_n.shape}\n{mask_n}") # noqa: E701 + mask_kT = mask_n[None, :] + mask_mn = mask_m[:, None] & (offs_n[None, :] < end_n) + if PADDED_HEAD: + mask_kT &= offs_k[:, None] < ACTUAL_HEAD_DIM + + kT = tl.load(kT_ptrs, mask=mask_kT, other=0.0) + vT = tl.load(vT_ptrs, mask=mask_kT, other=0.0) + + if ENABLE_DROPOUT: + # NOTE: dropout is transposed because it is used to mask pT + philox_offs = curr_philox_offset + \ + offs_m[:, None] * stride_dropoutm + \ + offs_n[None, :] * stride_dropoutn + if tl_DROPOUT_USE_PYTORCH: + dropout_offs = offs_m[:, None] * stride_dropoutm + \ + offs_n[None, :] * stride_dropoutn + dropout_mask = tl.load( + curr_dropout_offset + dropout_offs, + mask=mask_mn) + else: + rand_vals = tl.rand(philox_seed, philox_offs) + dropout_mask = rand_vals > dropout_p + dropout_scale = 1 / (1 - dropout_p) + + if IS_FP8: + qk = (tl.dot(q, kT) * descale_q * descale_k) + else: + qk = tl.dot(q, kT) + qk_scaled = qk * sm_scale + + if USE_ALIBI: + relative_pos_block = offs_m[:, None] + seqlen_k - seqlen_q - offs_n[None, :] + alibi_block = -1 * alibi_slope * tl.abs(relative_pos_block) + qk_scaled += alibi_block + + if DEBUG_TRITON_DETAIL: print(f"qk scaled: {qk.shape}\n", qk_scaled) # noqa: E701 + if USE_EXP2: + p = tl.math.exp2(qk_scaled * RCP_LN2 - m * RCP_LN2) + else: + p = tl.math.exp(qk_scaled - m) + + # Autoregressive masking. + if MASK: + causal_mask = (offs_m[:, None] - delta_qk) >= offs_n[None, :] + mask = causal_mask & mask_mn + p = tl.where(mask, p, 0.0) + # Compute dP and dS. + if IS_FP8: + dp = (tl.dot(do, vT) * descale_do * descale_v) + else: + dp = tl.dot(do, vT) + if ENABLE_DROPOUT: + dp = tl.where(dropout_mask, dp, 0.0) * dropout_scale + delta_i = Di[:, None] + ds = p * (dp -delta_i) + # Compute dQ. + # NOTE: We need to de-scale dq in the end, because kT was pre-scaled. + if IS_FP8: + scale_ds, descale_ds = compute_fp8_scaling_factors(ds, FP8_MAX) + dq += (tl.dot((ds * scale_ds).to(kT.type.element_ty), tl.trans(kT)) * descale_ds * descale_k) + else: + dq += tl.dot(ds.to(kT.type.element_ty), tl.trans(kT)) + # Increment pointers. + curr_n += step_n + kT_ptrs += step_n * stride_kn + vT_ptrs += step_n * stride_vn + return dq + + +# grid = (tl.cdiv(max_seqlen_q // BLOCK_M2), batch, nheads_q) +@triton.jit +def _bwd_kernel_dq_causal( + Q, K, V, sm_scale, DO, DQ, + M, Delta, + stride_qb, stride_qh, stride_qm, stride_qk, + stride_kb, stride_kh, stride_kn, stride_kk, + stride_vb, stride_vh, stride_vn, stride_vk, + stride_dqb, stride_dqh, stride_dqm, stride_dqk, + stride_deltab, stride_deltah, stride_deltam, + stride_dob, stride_doh, stride_dom, stride_dok, + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn, + stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_do_z, + stride_az, stride_ah, + HQ, HK, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, max_seqlen_k, + Dropout_mask, dropout_p, philox_seed, philox_offset_base, + Alibi_slopes, + Descale_q, Descale_k, Descale_v, Descale_do, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLK_SLICE_FACTOR: tl.constexpr, + HEAD_DIM: tl.constexpr, + ACTUAL_HEAD_DIM: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + IS_VARLEN: tl.constexpr, + USE_ALIBI: tl.constexpr, + USE_EXP2: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, + FP8_OUTPUT: tl.constexpr, + DEBUG_TRITON: tl.constexpr, + DEBUG_TRITON_DETAIL: tl.constexpr, +): + # program ids + pid = tl.program_id(0) + bid = tl.program_id(1) + hkid = tl.program_id(2) + # figure out varlen start and end + q_start = 0 + k_start = 0 + seqlen_q = max_seqlen_q + seqlen_k = max_seqlen_k + if IS_VARLEN: + # Compute actual sequence lengths + q_start = tl.load(cu_seqlens_q + bid) + q_end = tl.load(cu_seqlens_q + bid + 1) + k_start = tl.load(cu_seqlens_k + bid) + k_end = tl.load(cu_seqlens_k + bid + 1) + seqlen_q = q_end - q_start + seqlen_k = k_end - k_start + + # Figure out causal starting block since we have seqlen_q <=> seqlen_k. + # Unlike forward pass where we tile on M dim and iterate on N dim, so that + # we can skip some M blocks, in backward pass, we tile on the N dim for kv + # and iterate over the M. In this way, we cannot skip N blocks, but only to + # determine the starting M blocks to skip some initial blocks masked by + # causal. + # DQ tiles on M dim and iterate on N dim, so we there could be some tiles we + # can simply skip and we need to adjust starting position. + start_m = pid * BLOCK_M + # seqlen_q > seqlen_k, no need to process these tile for dq + delta_qk = seqlen_q - seqlen_k + if DEBUG_TRITON: print(f"end_n = start_m + BLOCK_M = {start_m} + {BLOCK_M} = {start_m + BLOCK_M}") # noqa: E701 + if start_m + BLOCK_M < delta_qk: + if DEBUG_TRITON: print(f"start_m + BLOCK_M = {start_m} + {BLOCK_M} = {start_m + BLOCK_M} < delta_qk of {delta_qk}") # noqa: E701 + return + + offs_k = tl.arange(0, HEAD_DIM) + offs_m = start_m + tl.arange(0, BLOCK_M) + # Mask for loading K and V + mask_q = offs_m[:, None] < seqlen_q + PADDED_HEAD: tl.constexpr = (ACTUAL_HEAD_DIM != HEAD_DIM) + if PADDED_HEAD: + mask_k = offs_k < ACTUAL_HEAD_DIM + mask_q &= mask_k[None, :] + offs_q = offs_m[:, None] * stride_qm + offs_k[None, :] * stride_qk + offs_do = offs_m[:, None] * stride_dom + offs_k[None, :] * stride_dok + adj_k = bid * stride_kb + hkid * stride_kh + k_start * stride_kn + adj_v = bid * stride_vb + hkid * stride_vh + k_start * stride_vn + K += adj_k + V += adj_v + # If MQA / GQA, set the K and V head offsets appropriately. + GROUP_SIZE = HQ // HK + for hqid in range(hkid * GROUP_SIZE, hkid * GROUP_SIZE + GROUP_SIZE): + # seqlen_q < seqlen_k: delta_qk more kv tokens are added at the front + # for every M-tile + end_n = start_m + BLOCK_M - delta_qk + # clamp end_n at [0, seqlen_k] + end_n = max(min(end_n, seqlen_k), 0) + if DEBUG_TRITON: print(f"delta_qk: {delta_qk}; end_n: {end_n}") # noqa: E701 + # offset input and output tensor by batch and Q/K heads + adj_q = bid * stride_qb + hqid * stride_qh + q_start * stride_qm + adj_do = bid * stride_dob + hqid * stride_doh + q_start * stride_dom + adj_delta = \ + bid * stride_deltab + hqid * stride_deltah + q_start * stride_deltam + Delta_ptr = Delta + adj_delta + + if USE_ALIBI: + alibi_offset = bid * stride_az + hqid * stride_ah + alibi_slope = tl.load(Alibi_slopes + alibi_offset) + else: + alibi_slope = None + + # batch_philox_offset is the ACTUALLY dropout offset + # dropout_offset is for debug purpose and will be removed later + batch_philox_offset = 0 + dropout_offset = 0 + if ENABLE_DROPOUT: + batch_philox_offset = philox_offset_base + \ + bid * stride_dropoutb + \ + hqid * stride_dropouth + dropout_offset = \ + Dropout_mask + bid * stride_dropoutb + hqid * stride_dropouth + + q = tl.load(Q + adj_q + offs_q, mask=mask_q, other=0.0) + do = tl.load(DO + adj_do + offs_do, mask=mask_q, other=0.0) + m = tl.load(M + adj_delta + offs_m * stride_deltam, + mask=offs_m < seqlen_q) + m = m[:, None] + + MASK_BLOCK_N: tl.constexpr = BLOCK_N // BLK_SLICE_FACTOR + # start can only be 0 at minimum + start_n = max(end_n - BLOCK_M, 0) + num_steps = tl.cdiv(end_n - start_n, MASK_BLOCK_N) + + if IS_FP8: + descale_q = tl.load(Descale_q + bid * stride_descale_q_z + hqid) + descale_k = tl.load(Descale_k + bid * stride_descale_k_z + hkid) + descale_v = tl.load(Descale_v + bid * stride_descale_v_z + hkid) + descale_do = tl.load(Descale_do + bid * stride_descale_do_z + hqid) + else: + descale_q, descale_k, descale_v, descale_do = 1.0, 1.0, 1.0, 1.0 + + dq = tl.zeros([BLOCK_M, HEAD_DIM], dtype=tl.float32) + if DEBUG_TRITON: print(f"pid: {pid}; end_n: {end_n}, start_m: {start_m}") # noqa: E701 + # Compute dQ for masked (diagonal) blocks. + # NOTE: This code scans each row of QK^T backward (from right to left, + # but inside each call to _bwd_dq_inner, from left to right), but that's + # not due to anything important. I just wanted to reuse the loop + # structure for dK & dV above as much as possible. + if DEBUG_TRITON: print(f"Masked: start_m: {start_m}, start_n: {start_n}, end_n: {end_n}, num_steps: {num_steps}") # noqa: E701 + dq = _bwd_dq_inner( + dq, + q, K, V, do, m, Delta_ptr, sm_scale, + stride_qm, stride_qk, stride_kn, stride_kk, stride_vn, stride_vk, + stride_dropoutm, stride_dropoutn, + stride_deltam, + seqlen_q, seqlen_k, + BLOCK_M, MASK_BLOCK_N, + HEAD_DIM, ACTUAL_HEAD_DIM, + dropout_p, philox_seed, batch_philox_offset, dropout_offset, + alibi_slope, + start_m, start_n, end_n, num_steps, + descale_q, descale_k, descale_v, descale_do, + MASK=True, + ENABLE_DROPOUT=ENABLE_DROPOUT, + USE_ALIBI=USE_ALIBI, + USE_EXP2=USE_EXP2, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + end_n -= num_steps * MASK_BLOCK_N + num_steps = tl.cdiv(end_n, BLOCK_N) + start_n = max(end_n - num_steps * BLOCK_N, 0) + if DEBUG_TRITON: print(f"unMasked: start_m: {start_m}, start_n: {start_n}, end_n: {end_n}, num_steps: {num_steps}") # noqa: E701 + dq = _bwd_dq_inner( + dq, + q, K, V, do, m, Delta_ptr, sm_scale, + stride_qm, stride_qk, stride_kn, stride_kk, stride_vn, stride_vk, + stride_dropoutm, stride_dropoutn, + stride_deltam, + seqlen_q, seqlen_k, + BLOCK_M, BLOCK_N, + HEAD_DIM, ACTUAL_HEAD_DIM, + dropout_p, philox_seed, batch_philox_offset, dropout_offset, + alibi_slope, + start_m, start_n, end_n, num_steps, + descale_q, descale_k, descale_v, descale_do, + MASK=False, + ENABLE_DROPOUT=ENABLE_DROPOUT, + USE_ALIBI=USE_ALIBI, + USE_EXP2=USE_EXP2, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + # Write back dQ. + adj_dq = bid * stride_dqb + hqid * stride_dqh + q_start * stride_dqm + offs_dq = offs_m[:, None] * stride_dqm + offs_k[None, :] * stride_dqk + dq *= sm_scale + tl.store(DQ + adj_dq + offs_dq, dq, mask=mask_q) + + +@triton.jit +def _bwd_kernel_dkdv_noncausal( + Q, K, V, sm_scale, DO, DK, DV, + M, Delta, + stride_qb, stride_qh, stride_qm, stride_qk, + stride_kb, stride_kh, stride_kn, stride_kk, + stride_vb, stride_vh, stride_vn, stride_vk, + stride_dkb, stride_dkh, stride_dkn, stride_dkk, + stride_deltab, stride_deltah, stride_deltam, + stride_dob, stride_doh, stride_dom, stride_dok, + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn, + stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_do_z, + stride_az, stride_ah, + HQ, HK, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, max_seqlen_k, + Dropout_mask, dropout_p, philox_seed, philox_offset_base, + Alibi_slopes, + Descale_q, Descale_k, Descale_v, Descale_do, + BLOCK_M: tl.constexpr, # 32 + BLOCK_N: tl.constexpr, # 128 + BLK_SLICE_FACTOR: tl.constexpr, + HEAD_DIM: tl.constexpr, + ACTUAL_HEAD_DIM: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + IS_VARLEN: tl.constexpr, + USE_ALIBI: tl.constexpr, + USE_EXP2: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, + FP8_OUTPUT: tl.constexpr, + DEBUG_TRITON: tl.constexpr, + DEBUG_TRITON_DETAIL: tl.constexpr, +): + # program ids + pid = tl.program_id(0) + bid = tl.program_id(1) + hkid = tl.program_id(2) + # figure out varlen start and end + q_start = 0 + k_start = 0 + seqlen_q = max_seqlen_q + seqlen_k = max_seqlen_k + if IS_VARLEN: + # Compute actual sequence lengths + q_start = tl.load(cu_seqlens_q + bid) + q_end = tl.load(cu_seqlens_q + bid + 1) + k_start = tl.load(cu_seqlens_k + bid) + k_end = tl.load(cu_seqlens_k + bid + 1) + seqlen_q = q_end - q_start + seqlen_k = k_end - k_start + + dk = tl.zeros([BLOCK_N, HEAD_DIM], dtype=tl.float32) + dv = tl.zeros([BLOCK_N, HEAD_DIM], dtype=tl.float32) + + start_n = pid * BLOCK_N + + offs_k = tl.arange(0, HEAD_DIM) + offs_n = start_n + tl.arange(0, BLOCK_N) + # Mask for loading K and V + mask_kv = offs_n[:, None] < seqlen_k + PADDED_HEAD: tl.constexpr = (ACTUAL_HEAD_DIM != HEAD_DIM) + if PADDED_HEAD: + mask_k = offs_k < ACTUAL_HEAD_DIM + mask_kv &= mask_k[None, :] + + GROUP_SIZE = HQ // HK + # K/V tensors not changed for the group + adj_k = bid * stride_kb + hkid * stride_kh + k_start * stride_kn + offs_n[:, None] * stride_kn + offs_k[None, :] * stride_kk + adj_v = bid * stride_vb + hkid * stride_vh + k_start * stride_vn + offs_n[:, None] * stride_vn + offs_k[None, :] * stride_vk + # load K and V: they stay in SRAM throughout the inner loop. + k = tl.load(K + adj_k, mask=mask_kv, other=0.0) + v = tl.load(V + adj_v, mask=mask_kv, other=0.0) + # If MQA / GQA, set the K and V head offsets appropriately. + for hqid in range(hkid * GROUP_SIZE, hkid * GROUP_SIZE + GROUP_SIZE): + # offset input and output tensor by batch and Q/K heads + adj_q = bid * stride_qb + hqid * stride_qh + q_start * stride_qm + Q_ptr = Q + adj_q + adj_do = bid * stride_dob + hqid * stride_doh + q_start * stride_dom + DO_ptr = DO + adj_do + adj_delta = bid * stride_deltab + hqid * stride_deltah + q_start * stride_deltam + M_ptr = M + adj_delta + Delta_ptr = Delta + adj_delta + + if USE_ALIBI: + alibi_offset = bid * stride_az + hqid * stride_ah + alibi_slope = tl.load(Alibi_slopes + alibi_offset) + else: + alibi_slope = None + + # batch_philox_offset is the ACTUALLY dropout offset + # dropout_offset is for debug purpose and will be removed later + batch_philox_offset = 0 + dropout_offset = 0 + if ENABLE_DROPOUT: + batch_philox_offset = philox_offset_base + bid * stride_dropoutb + \ + hqid * stride_dropouth + dropout_offset = Dropout_mask + bid * stride_dropoutb + \ + hqid * stride_dropouth + + if IS_FP8: + descale_q = tl.load(Descale_q + bid * stride_descale_q_z + hqid) + descale_k = tl.load(Descale_k + bid * stride_descale_k_z + hkid) + descale_v = tl.load(Descale_v + bid * stride_descale_v_z + hkid) + descale_do = tl.load(Descale_do + bid * stride_descale_do_z + hqid) + else: + descale_q, descale_k, descale_v, descale_do = 1.0, 1.0, 1.0, 1.0 + + # because there is no causal, we always start from the beginning + start_m = 0 + num_steps = tl.cdiv(seqlen_q, BLOCK_M) + dk, dv = _bwd_dkdv_inner( + dk, dv, # output tensors + Q_ptr, k, v, DO_ptr, M_ptr, Delta_ptr, sm_scale, # input tensors + stride_qm, stride_qk, # strides for q + stride_dom, stride_dok, # strides for o + stride_dropoutm, stride_dropoutn, # strides for dropout + stride_deltam, + BLOCK_M, BLOCK_N, # block dim + HEAD_DIM, ACTUAL_HEAD_DIM, # head dim + dropout_p, philox_seed, batch_philox_offset, dropout_offset, # + alibi_slope, + seqlen_q, seqlen_k, # max sequence length for q and k + start_n, start_m, num_steps, # iteration numbers + descale_q, descale_k, descale_v, descale_do, # fp8 descale factors from user + MASK=False, # causal masking + ENABLE_DROPOUT=ENABLE_DROPOUT, # activate dropout + USE_ALIBI=USE_ALIBI, + USE_EXP2=USE_EXP2, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + + # Write back dV and dK. + adj_dkdv = bid * stride_dkb + hkid * stride_kh + k_start * stride_dkn + offs_dkdv = offs_n[:, None] * stride_dkn + offs_k[None, :] * stride_dkk + tl.store(DV + adj_dkdv + offs_dkdv, dv, mask=mask_kv) + dk *= sm_scale + tl.store(DK + adj_dkdv + offs_dkdv, dk, mask=mask_kv) + + +@triton.jit +def _bwd_kernel_dq_noncausal( + Q, K, V, sm_scale, DO, DQ, + M, Delta, + stride_qb, stride_qh, stride_qm, stride_qk, + stride_kb, stride_kh, stride_kn, stride_kk, + stride_vb, stride_vh, stride_vn, stride_vk, + stride_dqb, stride_dqh, stride_dqm, stride_dqk, + stride_deltab, stride_deltah, stride_deltam, + stride_dob, stride_doh, stride_dom, stride_dok, + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn, + stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_do_z, + stride_az, stride_ah, + HQ, HK, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, max_seqlen_k, + Dropout_mask, dropout_p, philox_seed, philox_offset_base, + Alibi_slopes, + Descale_q, Descale_k, Descale_v, Descale_do, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLK_SLICE_FACTOR: tl.constexpr, + HEAD_DIM: tl.constexpr, + ACTUAL_HEAD_DIM: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, + IS_VARLEN: tl.constexpr, + USE_ALIBI: tl.constexpr, + USE_EXP2: tl.constexpr, + IS_FP8: tl.constexpr, + FP8_MAX: tl.constexpr, + FP8_OUTPUT: tl.constexpr, + DEBUG_TRITON: tl.constexpr, + DEBUG_TRITON_DETAIL: tl.constexpr, +): + # program ids + pid = tl.program_id(0) + bid = tl.program_id(1) + hkid = tl.program_id(2) + # figure out varlen start and end + q_start = 0 + k_start = 0 + seqlen_q = max_seqlen_q + seqlen_k = max_seqlen_k + if IS_VARLEN: + # Compute actual sequence lengths + q_start = tl.load(cu_seqlens_q + bid) + q_end = tl.load(cu_seqlens_q + bid + 1) + k_start = tl.load(cu_seqlens_k + bid) + k_end = tl.load(cu_seqlens_k + bid + 1) + seqlen_q = q_end - q_start + seqlen_k = k_end - k_start + + start_m = pid * BLOCK_M + + offs_k = tl.arange(0, HEAD_DIM) + offs_m = start_m + tl.arange(0, BLOCK_M) + # Mask for loading K and V + mask_q = offs_m[:, None] < seqlen_q + PADDED_HEAD: tl.constexpr = (ACTUAL_HEAD_DIM != HEAD_DIM) + if PADDED_HEAD: + mask_k = offs_k < ACTUAL_HEAD_DIM + mask_q &= mask_k[None, :] + offs_q = offs_m[:, None] * stride_qm + offs_k[None, :] * stride_qk + offs_do = offs_m[:, None] * stride_dom + offs_k[None, :] * stride_dok + adj_k = bid * stride_kb + hkid * stride_kh + k_start * stride_kn + adj_v = bid * stride_vb + hkid * stride_vh + k_start * stride_vn + K += adj_k + V += adj_v + # If MQA / GQA, set the K and V head offsets appropriately. + GROUP_SIZE = HQ // HK + for hqid in range(hkid * GROUP_SIZE, hkid * GROUP_SIZE + GROUP_SIZE): + # offset input and output tensor by batch and Q/K heads + adj_q = bid * stride_qb + hqid * stride_qh + q_start * stride_qm + adj_do = bid * stride_dob + hqid * stride_doh + q_start * stride_dom + adj_delta = \ + bid * stride_deltab + hqid * stride_deltah + q_start * stride_deltam + Delta_ptr = Delta + adj_delta + + if USE_ALIBI: + alibi_offset = bid * stride_az + hqid * stride_ah + alibi_slope = tl.load(Alibi_slopes + alibi_offset) + else: + alibi_slope = None + + # batch_philox_offset is the ACTUALLY dropout offset + # dropout_offset is for debug purpose and will be removed later + batch_philox_offset = 0 + dropout_offset = 0 + if ENABLE_DROPOUT: + batch_philox_offset = philox_offset_base + \ + bid * stride_dropoutb + \ + hqid * stride_dropouth + dropout_offset = \ + Dropout_mask + bid * stride_dropoutb + hqid * stride_dropouth + + q = tl.load(Q + adj_q + offs_q, mask=mask_q, other=0.0) + do = tl.load(DO + adj_do + offs_do, mask=mask_q, other=0.0) + m = tl.load(M + adj_delta + offs_m * stride_deltam, + mask=offs_m < seqlen_q) + m = m[:, None] + + if IS_FP8: + descale_q = tl.load(Descale_q + bid * stride_descale_q_z + hqid) + descale_k = tl.load(Descale_k + bid * stride_descale_k_z + hkid) + descale_v = tl.load(Descale_v + bid * stride_descale_v_z + hkid) + descale_do = tl.load(Descale_do + bid * stride_descale_do_z + hqid) + else: + descale_q, descale_k, descale_v, descale_do = 1.0, 1.0, 1.0, 1.0 + + # start can only be 0 at minimum + start_n = 0 + end_n = seqlen_k + num_steps = tl.cdiv(seqlen_k, BLOCK_N) + dq = tl.zeros([BLOCK_M, HEAD_DIM], dtype=tl.float32) + dq = _bwd_dq_inner( + dq, + q, K, V, do, m, Delta_ptr, sm_scale, + stride_qm, stride_qk, stride_kn, stride_kk, stride_vn, stride_vk, + stride_dropoutm, stride_dropoutn, + stride_deltam, + seqlen_q, seqlen_k, + BLOCK_M, BLOCK_N, + HEAD_DIM, ACTUAL_HEAD_DIM, + dropout_p, philox_seed, batch_philox_offset, dropout_offset, + alibi_slope, + start_m, start_n, end_n, num_steps, + descale_q, descale_k, descale_v, descale_do, + MASK=False, + ENABLE_DROPOUT=ENABLE_DROPOUT, + USE_ALIBI=USE_ALIBI, + USE_EXP2=USE_EXP2, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + # Write back dQ. + adj_dq = bid * stride_dqb + hqid * stride_dqh + q_start * stride_dqm + offs_dq = offs_m[:, None] * stride_dqm + offs_k[None, :] * stride_dqk + dq *= sm_scale + tl.store(DQ + adj_dq + offs_dq, dq, mask=mask_q) + + +def attention_prefill_backward_triton_split_impl( + do: torch.Tensor, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + o: torch.Tensor, + softmax_lse: torch.Tensor, + dq: torch.Tensor, + dk: torch.Tensor, + dv: torch.Tensor, + sm_scale: float, + alibi_slopes: Optional[torch.Tensor], + causal: bool, + layout: Literal["bshd", "bhsd", "thd"], + cu_seqlens_q: Optional[torch.Tensor], + cu_seqlens_k: Optional[torch.Tensor], + max_seqlen_q: Optional[int], + max_seqlen_k: Optional[int], + dropout_p: float, + philox_seed: Optional[int], + philox_offset: Optional[int], + use_exp2: bool, + # fp8 + descale_q: Optional[torch.Tensor], + descale_k: Optional[torch.Tensor], + descale_v: Optional[torch.Tensor], + descale_o: Optional[torch.Tensor], + descale_do: Optional[torch.Tensor], + descale_dq: Optional[torch.Tensor], + descale_dk: Optional[torch.Tensor], + descale_dv: Optional[torch.Tensor], +): + # debug + DEBUG_TRITON: bool = False + DEBUG_TRITON_DETAIL: bool = False + + # fp8 + IS_FP8 = is_fp8(q) + if IS_FP8: + FP8_MAX = torch.finfo(q.dtype).max + # assert that the main inputs are fp8 + assert is_fp8(do) and is_fp8(q) and is_fp8(k) and is_fp8(v), f"Non fp8 type found: do.dtype={do.dtype}, q.dtype={q.dtype}, k.dtype={k.dtype}, v.dtype={v.dtype}. All tensors must be fp8." + if is_fp8(o): + FP8_OUTPUT = True + assert descale_o is not None, f"descale_o is None. In fp8, you need to pass a tensor for descale_o along with a tensor o." + assert descale_dq is not None, f"descale_dq is None. In fp8, you need to pass a tensor for descale_dq along with a tensor dq." + assert descale_dk is not None, f"descale_dk is None. In fp8, you need to pass a tensor for descale_dk along with a tensor dk." + assert descale_dv is not None, f"descale_dv is None. In fp8, you need to pass a tensor for descale_dv along with a tensor dv." + else: + FP8_OUTPUT = False + + stride_descale_q_z = descale_q.stride(0) if descale_q is not None else None + stride_descale_k_z = descale_k.stride(0) if descale_k is not None else None + stride_descale_v_z = descale_v.stride(0) if descale_v is not None else None + stride_descale_o_z = descale_o.stride(0) if descale_o is not None else None + stride_descale_do_z = descale_do.stride(0) if descale_do is not None else None + else: + FP8_MAX = None + FP8_OUTPUT = False + stride_descale_q_z = stride_descale_k_z = stride_descale_v_z = stride_descale_o_z = stride_descale_do_z = None + + + # get strides and shape + batch, nheads_q, nheads_k, head_size, max_seqlen_q_final, max_seqlen_k_final = \ + get_shapes_from_layout( + q, k, layout, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q, max_seqlen_k + ) + q_strides, k_strides, v_strides, o_strides = \ + get_strides_from_layout(q, k, v, o, layout) + stride_qb, stride_qh, stride_qm, stride_qk = q_strides + stride_kb, stride_kh, stride_kn, stride_kk = k_strides + stride_vb, stride_vh, stride_vn, stride_vk = v_strides + stride_ob, stride_oh, stride_om, stride_ok = o_strides + dq_strides, dk_strides, dv_strides, do_strides = \ + get_strides_from_layout(dq, dk, dv, do, layout) + stride_dqb, stride_dqh, stride_dqm, stride_dqk = dq_strides + stride_dkb, stride_dkh, stride_dkn, stride_dkk = dk_strides + stride_dvb, stride_dvh, stride_dvn, stride_dvk = dv_strides + stride_dob, stride_doh, stride_dom, stride_dok = do_strides + IS_VARLEN = layout == "thd" + use_dropout = (dropout_p > 0.0) + use_alibi, (stride_az, stride_ah) = (True, alibi_slopes.stride()) if alibi_slopes is not None else (False, (0, 0)) + + # get closest power of 2 over or equal to 32. + padded_d_model = 1 << (head_size - 1).bit_length() + padded_d_model = max(padded_d_model, 32) # NOTE: the causal path expects a min of 32. It will cause a compiler assert. + HEAD_DIM = padded_d_model + ACTUAL_HEAD_DIM = head_size + # meta-parameters + # TODO: fix num_stages later + NUM_WARPS, NUM_STAGES = 4, 1 + WAVES_PER_EU = 1 + PRE_BLOCK = 128 + BLOCK_M1, BLOCK_N1, BLOCK_M2, BLOCK_N2 = 32, 128, 128, 32 + BLK_SLICE_FACTOR = 2 + + # init delta + delta = torch.zeros_like(softmax_lse) + if IS_VARLEN: + stride_deltab = 0 + stride_deltam, stride_deltah = delta.stride() + else: + stride_deltab, stride_deltah, stride_deltam = delta.stride() + pre_grid = (triton.cdiv(max_seqlen_q_final, PRE_BLOCK), batch, nheads_q) + _bwd_preprocess[pre_grid]( + o, do, + delta, + stride_ob, stride_oh, stride_om, stride_ok, + stride_deltab, stride_deltah, stride_deltam, + stride_descale_do_z, + cu_seqlens_q, max_seqlen_q_final, + descale_do, + BLOCK_M=PRE_BLOCK, + HEAD_DIM=HEAD_DIM, + ACTUAL_HEAD_DIM=ACTUAL_HEAD_DIM, + IS_VARLEN=IS_VARLEN, + IS_FP8=IS_FP8 + ) + + if DEBUG: + print("delta:", delta, delta.shape) + + # dropout mask tensor for debugging. We dump the dropout mask created in + # the kernel for testing + dropout_mask = None + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn = \ + (0, 0 , 0 , 0) + if use_dropout: + dropout_mask = torch.zeros( + (batch, nheads_q, max_seqlen_q_final, max_seqlen_k_final), + device=q.device, + dtype=torch.float32 + ) + + if DROPOUT_USE_PYTORCH: + if not IS_VARLEN: + dropout_mask = create_dropout_mask( + dropout_p, + (batch, nheads_q, max_seqlen_q_final, max_seqlen_k_final), + seed = philox_seed + ) + else: + dropout_mask = create_dropout_mask_varlen( + dropout_p, batch, nheads_q, + cu_seqlens_q, cu_seqlens_k, philox_seed + ) + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn = \ + dropout_mask.stride() + + grid_dkdv = ((max_seqlen_k_final + BLOCK_N1 - 1) // BLOCK_N1, batch, nheads_k) + grid_dq = ((max_seqlen_q_final + BLOCK_M2 - 1) // BLOCK_M2, batch, nheads_k) + if causal: + if DEBUG_TRITON: print(f"_bwd_kernel_dkdv: grid = {grid_dkdv}, block_size = ({BLOCK_M1, BLOCK_N1})", ) # noqa: E701 + _bwd_kernel_dkdv_causal[grid_dkdv]( + q, k, v, sm_scale, do, dk, dv, + softmax_lse, delta, + stride_qb, stride_qh, stride_qm, stride_qk, + stride_kb, stride_kh, stride_kn, stride_kk, + stride_vb, stride_vh, stride_vn, stride_vk, + stride_dkb, stride_dkh, stride_dkn, stride_dkk, + stride_deltab, stride_deltah, stride_deltam, + stride_dob, stride_doh, stride_dom, stride_dok, + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn, + stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_do_z, + stride_az, stride_ah, + nheads_q, nheads_k, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q_final, max_seqlen_k_final, + dropout_mask, dropout_p, philox_seed, philox_offset, + alibi_slopes, + descale_q, descale_k, descale_v, descale_do, + BLOCK_M1, BLOCK_N1, BLK_SLICE_FACTOR, + HEAD_DIM, ACTUAL_HEAD_DIM, + ENABLE_DROPOUT=use_dropout, + IS_VARLEN=IS_VARLEN, + USE_ALIBI=use_alibi, + USE_EXP2=use_exp2, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + FP8_OUTPUT=FP8_OUTPUT, + num_warps=NUM_WARPS, + num_stages=NUM_STAGES, + waves_per_eu = WAVES_PER_EU, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + + if DEBUG_TRITON: print(f"\n_bwd_kernel_dq: grid = {grid_dq}, block_size = ({BLOCK_M2, BLOCK_N2})", ) # noqa: E701 + _bwd_kernel_dq_causal[grid_dq]( + q, k, v, sm_scale, do, dq, + softmax_lse, delta, + stride_qb, stride_qh, stride_qm, stride_qk, + stride_kb, stride_kh, stride_kn, stride_kk, + stride_vb, stride_vh, stride_vn, stride_vk, + stride_dqb, stride_dqh, stride_dqm, stride_dqk, + stride_deltab, stride_deltah, stride_deltam, + stride_dob, stride_doh, stride_dom, stride_dok, + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn, + stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_do_z, + stride_az, stride_ah, + nheads_q, nheads_k, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q_final, max_seqlen_k_final, + dropout_mask, dropout_p, philox_seed, philox_offset, + alibi_slopes, + descale_q, descale_k, descale_v, descale_do, + BLOCK_M2, BLOCK_N2, BLK_SLICE_FACTOR, + HEAD_DIM, ACTUAL_HEAD_DIM, + ENABLE_DROPOUT=use_dropout, + IS_VARLEN=IS_VARLEN, + USE_ALIBI=use_alibi, + USE_EXP2=use_exp2, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + FP8_OUTPUT=FP8_OUTPUT, + num_warps=NUM_WARPS, + num_stages=NUM_STAGES, + waves_per_eu = WAVES_PER_EU, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + else: + _bwd_kernel_dkdv_noncausal[grid_dkdv]( + q, k, v, sm_scale, do, dk, dv, + softmax_lse, delta, + stride_qb, stride_qh, stride_qm, stride_qk, + stride_kb, stride_kh, stride_kn, stride_kk, + stride_vb, stride_vh, stride_vn, stride_vk, + stride_dkb, stride_dkh, stride_dkn, stride_dkk, + stride_deltab, stride_deltah, stride_deltam, + stride_dob, stride_doh, stride_dom, stride_dok, + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn, + stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_do_z, + stride_az, stride_ah, + nheads_q, nheads_k, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q_final, max_seqlen_k_final, + dropout_mask, dropout_p, philox_seed, philox_offset, + alibi_slopes, + descale_q, descale_k, descale_v, descale_do, + BLOCK_M1, BLOCK_N1, BLK_SLICE_FACTOR, + HEAD_DIM, ACTUAL_HEAD_DIM, + ENABLE_DROPOUT=use_dropout, + IS_VARLEN=IS_VARLEN, + USE_ALIBI=use_alibi, + USE_EXP2=use_exp2, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + FP8_OUTPUT=FP8_OUTPUT, + num_warps=NUM_WARPS, + num_stages=NUM_STAGES, + waves_per_eu = WAVES_PER_EU, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + + _bwd_kernel_dq_noncausal[grid_dq]( + q, k, v, sm_scale, do, dq, + softmax_lse, delta, + stride_qb, stride_qh, stride_qm, stride_qk, + stride_kb, stride_kh, stride_kn, stride_kk, + stride_vb, stride_vh, stride_vn, stride_vk, + stride_dqb, stride_dqh, stride_dqm, stride_dqk, + stride_deltab, stride_deltah, stride_deltam, + stride_dob, stride_doh, stride_dom, stride_dok, + stride_dropoutb, stride_dropouth, stride_dropoutm, stride_dropoutn, + stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_do_z, + stride_az, stride_ah, + nheads_q, nheads_k, + cu_seqlens_q, cu_seqlens_k, + max_seqlen_q_final, max_seqlen_k_final, + dropout_mask, dropout_p, philox_seed, philox_offset, + alibi_slopes, + descale_q, descale_k, descale_v, descale_do, + BLOCK_M2, BLOCK_N2, BLK_SLICE_FACTOR, + HEAD_DIM, ACTUAL_HEAD_DIM, + ENABLE_DROPOUT=use_dropout, + IS_VARLEN=IS_VARLEN, + USE_ALIBI=use_alibi, + USE_EXP2=use_exp2, + IS_FP8=IS_FP8, + FP8_MAX=FP8_MAX, + FP8_OUTPUT=FP8_OUTPUT, + num_warps=NUM_WARPS, + num_stages=NUM_STAGES, + waves_per_eu = WAVES_PER_EU, + DEBUG_TRITON=DEBUG_TRITON, + DEBUG_TRITON_DETAIL=DEBUG_TRITON_DETAIL, + ) + + return delta diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bwd_ref.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bwd_ref.py new file mode 100644 index 0000000000000000000000000000000000000000..90a98ce4fccbef1c1754b3fd93aacbaa69e8cc8e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/bwd_ref.py @@ -0,0 +1,478 @@ +import torch +import math +from typing import Literal, Optional +from .utils import DEBUG, compute_alibi_tensor_ref + +DEBUG_CORE = False + +def attention_backward_core_ref_impl( + do, q, k, v, o, softmax_lse, sm_scale, causal, dropout_p, philox_seed, philox_offset, alibi_slopes, use_exp2 +): + if DEBUG_CORE: + print() + print("attention_backward_core_ref_impl") + print("do:", do, do.shape) + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("o:", o, o.shape) # is a bad number + print("softmax_lse:", softmax_lse, softmax_lse.shape) + print("sm_scale:", sm_scale) + print("causal:", causal) + print("dropout_p:", dropout_p) + print("philox_seed:", philox_seed) + print("philox_offset:", philox_offset) + print("use_exp2:", use_exp2) + + # cast to float32 + do = do.to(torch.float32) + q = q.to(torch.float32) + k = k.to(torch.float32) + v = v.to(torch.float32) + o = o.to(torch.float32) + softmax_lse = softmax_lse.to(torch.float32) + + + # recompute attention_scores. Make sure it matches the forward impl. i.e. It use float32 + attention_scores = torch.matmul(q, k.transpose(-2, -1)) + if DEBUG_CORE: + print("attention_scores:", attention_scores, attention_scores.shape) + + # scale scores + attention_scaled_scores = sm_scale * attention_scores + if DEBUG_CORE: + print("attention_scaled_scores:", attention_scaled_scores, attention_scaled_scores.shape) + + if alibi_slopes is not None: + L_q, L_k = q.shape[1], k.shape[1] + if DEBUG_CORE: + print("alibi_slopes:", alibi_slopes, alibi_slopes.shape) + alibi_bias = compute_alibi_tensor_ref(alibi_slopes, L_q, L_k) + alibi_bias = alibi_bias.reshape(-1, L_q, L_k) + if True: + print("alibi_bias:", alibi_bias, alibi_bias.shape) + attention_scaled_scores = attention_scaled_scores + alibi_bias + if DEBUG_CORE: + print("attention_scaled_scores after alibi:", attention_scaled_scores, attention_scaled_scores.shape) + + # Apply causal mask if necessary + if causal: + L_q, L_k = q.shape[1], k.shape[1] + row_idx = torch.arange(L_q, device=q.device).unsqueeze(1) + col_idx = torch.arange(L_k, device=q.device).unsqueeze(0) + col_offset = L_q-L_k + causal_mask = row_idx >= (col_offset + col_idx) + if DEBUG_CORE: + print("causal_mask:", causal_mask) + # set -inf to places the causal mask is false + attention_scaled_scores = attention_scaled_scores.masked_fill( + torch.logical_not(causal_mask.unsqueeze(0)), float('-inf') + ) + if DEBUG_CORE: + print("attention_scaled_scores after causal:", attention_scaled_scores, attention_scaled_scores.shape) + + # compute probabilities using softmax_lse + if use_exp2: + RCP_LN = 1 / math.log(2) + attention_scaled_scores_base2 = attention_scaled_scores * RCP_LN + softmax_lse_base2 = softmax_lse * RCP_LN + softmax_lse_3d = softmax_lse_base2.unsqueeze(-1) + p = torch.exp2(attention_scaled_scores_base2 - softmax_lse_3d) + else: + softmax_lse_3d = softmax_lse.unsqueeze(-1) + p = torch.exp(attention_scaled_scores - softmax_lse_3d) + if DEBUG_CORE: + print("softmax_lse_3d:", softmax_lse_3d, softmax_lse_3d.shape) + print("p:", p, p.shape) + + if dropout_p > 0.0: + rand_vals = torch.rand(p.shape, generator=torch.Generator(device=p.device).manual_seed(philox_seed), device=p.device, dtype=p.dtype) + dropout_mask, dropout_scale = rand_vals > dropout_p, (1.0 / (1 - dropout_p)) + if DEBUG: + print("dropout_scale:", dropout_scale) + print("dropout_mask:", dropout_mask) + + p_drop = torch.where(dropout_mask, p, torch.zeros_like(p)) + p_drop_scaled = p_drop * dropout_scale + if DEBUG_CORE: + print("dropout_scale:", dropout_scale) + print("p_drop:", p_drop, p_drop.shape) + print("p_drop_scaled:", p_drop_scaled, p_drop_scaled.shape) + + # compute dv + dv = torch.matmul(p_drop_scaled.transpose(-2, -1), do) + if DEBUG_CORE: + print("dv:", dv, dv.shape) + + # compute dp + dp_dropout = torch.matmul(do, v.transpose(-2, -1)) + dp = torch.where(dropout_mask, dp_dropout , torch.zeros_like(dp_dropout)) * dropout_scale + if DEBUG_CORE: + print("dp_dropout:", dp_dropout, dp_dropout.shape) + print("dp:", dp, dp.shape) + else: + # compute dv + dv = torch.matmul(p.transpose(-2, -1), do) + if DEBUG_CORE: + print("dv:", dv, dv.shape) + + # compute dp + dp = torch.matmul(do, v.transpose(-2, -1)) + if DEBUG_CORE: + print("dp:", dp, dp.shape) + + # calculate ds + if False: + delta = torch.sum(o * do, axis=-1).unsqueeze(-1) + else: + delta = torch.sum(p * dp, axis=-1).unsqueeze(-1) + if DEBUG: + print("delta:", delta, delta.shape) + dscores_scaled = p * (dp - delta) + ds = dscores_scaled * sm_scale + if DEBUG_CORE: + print("dscores_scaled:", dscores_scaled, dscores_scaled.shape) + print("ds:", ds, ds.shape) + + # compute gradient wrt k & q + dk = torch.matmul(ds.transpose(-2, -1), q) + dq = torch.matmul(ds, k) + if DEBUG_CORE: + print("dk:", dk, dk.shape) + print("dq:", dq, dq.shape) + + # cast back to original dtype + dq = dq.to(torch.float16) + dk = dk.to(torch.float16) + dv = dv.to(torch.float16) + # remove d dim with size 1 + delta = delta.squeeze(-1) + + if DEBUG_CORE: + print("attention_backward_core_ref_impl output") + print("delta:", delta, delta.shape) + print("dv:", dv, dv.shape) + print("dk:", dk, dk.shape) + print("dq:", dq, dq.shape) + + return dq, dk, dv, delta + +def attention_varlen_backward_pytorch_ref_impl( + do, + q, + k, + v, + o, + softmax_lse, + sm_scale, + causal, + layout, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + philox_seed, + philox_offset, + alibi_slopes, + use_exp2, +): + # Ensure the layout is 'thd' + if layout != 'thd': + raise ValueError(f"Unsupported layout {layout}. Expected 'thd'.") + + batch_size = cu_seqlens_q.shape[0] - 1 + nheads_q, head_dim = q.shape[1], q.shape[2] + nheads_k = k.shape[1] + + group_size = nheads_q // nheads_k + if nheads_q % nheads_k != 0: + raise ValueError("nheads_q must be divisible by nheads_k") + + # Pre-allocate outputs + total_L_q = q.shape[0] + total_L_k = k.shape[0] + + dq = torch.zeros_like(q) + dk = torch.zeros_like(k) + dv = torch.zeros_like(v) + # delta has the same shape as softmax_lse: [total_L_q, nheads_q] + delta = torch.zeros((total_L_q, nheads_q), dtype=torch.float32, device=o.device) + + for i in range(batch_size): + # Get the start and end indices for the current sequence + start_q = cu_seqlens_q[i].item() + end_q = cu_seqlens_q[i + 1].item() + start_k = cu_seqlens_k[i].item() + end_k = cu_seqlens_k[i + 1].item() + + # Extract q_i, k_i, v_i, do_i, o_i, softmax_lse_i + q_i = q[start_q:end_q, :, :] # [L_q_i, nheads_q, head_dim] + k_i = k[start_k:end_k, :, :] # [L_k_i, nheads_k, head_dim] + v_i = v[start_k:end_k, :, :] # [L_k_i, nheads_k, head_dim] + do_i = do[start_q:end_q, :, :] # [L_q_i, nheads_q, head_dim] + o_i = o[start_q:end_q, :, :] # [L_q_i, nheads_q, head_dim] + softmax_lse_i = softmax_lse[start_q:end_q, :] # [L_q_i, nheads_q] + + if group_size != 1: + # MQA or GQA case + # Reshape tensors to include group dimension + q_i = q_i.view(q_i.shape[0], nheads_k, group_size, head_dim) + do_i = do_i.view(do_i.shape[0], nheads_k, group_size, head_dim) + o_i = o_i.view(o_i.shape[0], nheads_k, group_size, head_dim) + softmax_lse_i = softmax_lse_i.view(softmax_lse_i.shape[0], nheads_k, group_size) + # Expand k_i and v_i to match group_size + k_i = k_i.unsqueeze(2).expand(-1, -1, group_size, -1) + v_i = v_i.unsqueeze(2).expand(-1, -1, group_size, -1) + # Flatten the nheads_k and group_size dimensions + q_i = q_i.reshape(q_i.shape[0], nheads_k * group_size, head_dim) + do_i = do_i.reshape(do_i.shape[0], nheads_k * group_size, head_dim) + o_i = o_i.reshape(o_i.shape[0], nheads_k * group_size, head_dim) + softmax_lse_i = softmax_lse_i.reshape(softmax_lse_i.shape[0], nheads_k * group_size) + k_i = k_i.reshape(k_i.shape[0], nheads_k * group_size, head_dim) + v_i = v_i.reshape(v_i.shape[0], nheads_k * group_size, head_dim) + # Permute to [nheads_total, L, head_dim] + q_i = q_i.permute(1, 0, 2) + k_i = k_i.permute(1, 0, 2) + v_i = v_i.permute(1, 0, 2) + do_i = do_i.permute(1, 0, 2) + o_i = o_i.permute(1, 0, 2) + softmax_lse_i = softmax_lse_i.transpose(0, 1) + if alibi_slopes is not None: + alibi_slopes_i = alibi_slopes[i] + else: + alibi_slopes_i = None + + # Call the core backward function for this sequence + dq_i, dk_i, dv_i, delta_i = attention_backward_core_ref_impl( + do_i, + q_i, + k_i, + v_i, + o_i, + softmax_lse_i, + sm_scale, + causal, + dropout_p, + philox_seed, + philox_offset, + alibi_slopes_i, + use_exp2 + ) + + # Convert back to 'thd' layout + dq_i = dq_i.permute(1, 0, 2) # [L_q_i, nheads_total, head_dim] + dk_i = dk_i.permute(1, 0, 2) # [L_k_i, nheads_total, head_dim] + dv_i = dv_i.permute(1, 0, 2) # [L_k_i, nheads_total, head_dim] + delta_i = delta_i.transpose(1, 0) # [L_q_i, nheads_total] + + if group_size != 1: + # Reshape dq_i and delta_i back to original shape + dq_i = dq_i.view(dq_i.shape[0], nheads_k, group_size, head_dim) + delta_i = delta_i.view(delta_i.shape[0], nheads_k, group_size) + # Sum dk_i and dv_i over group dimension + dk_i = dk_i.view(dk_i.shape[0], nheads_k, group_size, head_dim) + dv_i = dv_i.view(dv_i.shape[0], nheads_k, group_size, head_dim) + dk_i = dk_i.sum(dim=2) + dv_i = dv_i.sum(dim=2) + # Reshape dq_i back to [L_q_i, nheads_q, head_dim] + dq_i = dq_i.reshape(dq_i.shape[0], nheads_q, head_dim) + delta_i = delta_i.reshape(delta_i.shape[0], nheads_q) + else: + # No need to reshape + pass + + # Place outputs in pre-allocated tensors + dq[start_q:end_q, :, :] = dq_i + dk[start_k:end_k, :, :] += dk_i # Accumulate gradients for shared keys + dv[start_k:end_k, :, :] += dv_i # Accumulate gradients for shared values + delta[start_q:end_q, :] = delta_i + + return dq, dk, dv, delta + +def attention_vanilla_backward_pytorch_ref_impl( + do, + q, + k, + v, + o, + softmax_lse, + sm_scale, + causal, + layout, + dropout_p, + philox_seed, + philox_offset, + alibi_slopes, + use_exp2, +): + if layout == "bshd": + if DEBUG: + print() + print("Changing layout to bhsd!") + do = do.transpose(1, 2).contiguous() + q = q.transpose(1, 2).contiguous() + k = k.transpose(1, 2).contiguous() + v = v.transpose(1, 2).contiguous() + o = o.transpose(1, 2).contiguous() + elif layout == "bhsd": + pass + else: + raise ValueError(f"Unknown layout {layout}") + + # Prepare tensors + batch_size, nheads_q, seq_len_q, head_dim = q.shape + batch_size, nheads_k, seq_len_k, head_dim = k.shape + + group_size = nheads_q // nheads_k + if nheads_q % nheads_k != 0: + raise ValueError("nheads_q must be divisible by nheads_k") + + if group_size != 1: + # MQA or GQA case + # Reshape do, q, o to [batch_size, nheads_k, group_size, seq_len_q, head_dim] + do = do.reshape(batch_size, nheads_k, group_size, seq_len_q, head_dim) + q = q.reshape(batch_size, nheads_k, group_size, seq_len_q, head_dim) + o = o.reshape(batch_size, nheads_k, group_size, seq_len_q, head_dim) + # Reshape softmax_lse to [batch_size, nheads_k, group_size, seq_len_q] + softmax_lse = softmax_lse.reshape(batch_size, nheads_k, group_size, seq_len_q) + # Expand k and v to match group_size + k = k.unsqueeze(2).expand(-1, -1, group_size, -1, -1) # [batch_size, nheads_k, group_size, seq_len_k, head_dim] + v = v.unsqueeze(2).expand(-1, -1, group_size, -1, -1) + # Flatten the first three dimensions for computation + do = do.reshape(batch_size * nheads_k * group_size, seq_len_q, head_dim) + q = q.reshape(batch_size * nheads_k * group_size, seq_len_q, head_dim) + k = k.reshape(batch_size * nheads_k * group_size, seq_len_k, head_dim) + v = v.reshape(batch_size * nheads_k * group_size, seq_len_k, head_dim) + o = o.reshape(batch_size * nheads_k * group_size, seq_len_q, head_dim) + softmax_lse = softmax_lse.reshape(batch_size * nheads_k * group_size, seq_len_q) + else: + # Standard case + do = do.reshape(batch_size * nheads_q, seq_len_q, head_dim) + q = q.reshape(batch_size * nheads_q, seq_len_q, head_dim) + k = k.reshape(batch_size * nheads_k, seq_len_k, head_dim) + v = v.reshape(batch_size * nheads_k, seq_len_k, head_dim) + o = o.reshape(batch_size * nheads_q, seq_len_q, head_dim) + softmax_lse = softmax_lse.reshape(batch_size * nheads_q, seq_len_q) + + # Call the core backward function + dq, dk, dv, delta = attention_backward_core_ref_impl( + do, + q, + k, + v, + o, + softmax_lse, + sm_scale, + causal, + dropout_p, + philox_seed, + philox_offset, + alibi_slopes, + use_exp2 + ) + + if group_size != 1: + # Reshape dq back to [batch_size, nheads_k, group_size, seq_len_q, head_dim] + dq = dq.reshape(batch_size, nheads_k, group_size, seq_len_q, head_dim) + # Reshape delta back to [batch_size, nheads_k, group_size, seq_len_q] + delta = delta.reshape(batch_size, nheads_k, group_size, seq_len_q) + # Sum dk and dv over group_size dimension, since k and v are shared across groups + dk = dk.reshape(batch_size, nheads_k, group_size, seq_len_k, head_dim) + dk = dk.sum(dim=2) # Sum over group_size dimension + dv = dv.reshape(batch_size, nheads_k, group_size, seq_len_k, head_dim) + dv = dv.sum(dim=2) + # Reshape dq to [batch_size, nheads_q, seq_len_q, head_dim] + dq = dq.reshape(batch_size, nheads_k * group_size, seq_len_q, head_dim) + delta = delta.reshape(batch_size, nheads_k * group_size, seq_len_q) + else: + # Standard case + dq = dq.reshape(batch_size, nheads_q, seq_len_q, head_dim) + dk = dk.reshape(batch_size, nheads_k, seq_len_k, head_dim) + dv = dv.reshape(batch_size, nheads_k, seq_len_k, head_dim) + delta = delta.reshape(batch_size, nheads_q, seq_len_q) + + # Go back to original layout + if layout == "bshd": + if DEBUG: + print() + print("Changing back to bshd!") + dq = dq.transpose(1, 2) + dk = dk.transpose(1, 2) + dv = dv.transpose(1, 2) + elif layout == "bhsd": + pass + else: + raise ValueError(f"Unknown layout {layout}") + + return dq, dk, dv, delta + +def attention_backward_pytorch_ref_impl( + do: torch.Tensor, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + o: torch.Tensor, + softmax_lse: torch.Tensor, + dq: torch.Tensor, + dk: torch.Tensor, + dv: torch.Tensor, + sm_scale: float, + alibi_slopes: Optional[torch.Tensor], + causal: bool, + layout: Literal["bshd", "bhsd", "thd"], + cu_seqlens_q: Optional[torch.Tensor], + cu_seqlens_k: Optional[torch.Tensor], + max_seqlen_q: Optional[int], + max_seqlen_k: Optional[int], + dropout_p: float, + philox_seed: Optional[int], + philox_offset: Optional[int], + use_exp2: bool +): + if layout == "thd": + dq_ref, dk_ref, dv_ref, delta = attention_varlen_backward_pytorch_ref_impl( + do, + q, + k, + v, + o, + softmax_lse, + sm_scale, + causal, + layout, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + philox_seed, + philox_offset, + alibi_slopes, + use_exp2, + ) + else: + dq_ref, dk_ref, dv_ref, delta = attention_vanilla_backward_pytorch_ref_impl( + do, + q, + k, + v, + o, + softmax_lse, + sm_scale, + causal, + layout, + dropout_p, + philox_seed, + philox_offset, + alibi_slopes, + use_exp2, + ) + + + # copy into output tensor + dv.copy_(dv_ref.to(dv.dtype)) + dk.copy_(dk_ref.to(dk.dtype)) + dq.copy_(dq_ref.to(dq.dtype)) + + return delta diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/fp8.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/fp8.py new file mode 100644 index 0000000000000000000000000000000000000000..df79c7926b256fa019cf132753b2535fdf715502 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/fp8.py @@ -0,0 +1,716 @@ +from typing import Optional, Sequence, Tuple, Union +import torch +import torch.nn as nn +from .utils import cast_to_fp8, is_fp8 +from . import interface_fa as flash_attn_gpu + + +def maybe_contiguous(x): + return x.contiguous() if x is not None and x.stride(-1) != 1 else x + +class FlashAttnFP8Func(torch.autograd.Function): + @staticmethod + def forward( + ctx, + q, + k, + v, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_softmax, + is_grad_enabled, + descale_q: Optional[torch.Tensor] = None, + descale_k: Optional[torch.Tensor] = None, + descale_v: Optional[torch.Tensor] = None, + descale_do: Optional[torch.Tensor] = None + ): + is_grad = is_grad_enabled and any( + x.requires_grad for x in [q, k, v] + ) + if softmax_scale is None: + softmax_scale = q.shape[-1] ** (-0.5) + head_size_og = q.size(3) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + + # figure out fwd parameters + if is_fp8(q) or is_fp8(k) or is_fp8(v): # fp8 input and output + raise ValueError("fp8 input and out not supported yet for this function.") + assert (descale_q is not None) and (descale_k is not None) and (descale_v is not None), f"You need to pass descale factors for q, k and v" + q_fp8 = q + k_fp8 = k + v_fp8 = v + out_fp8, descale_o = torch.zeros_like(q_fp8), torch.zeros_like(descale_q) + else: # cast to fp8 and return output in the fp32. (accumulator type) + assert (descale_q is None) and (descale_k is None) and (descale_v is None), f"Found {q.dtype} input tensor with descale factors. In this case, we cast to fp8 and compute the descale factors. You can pass an fp8 tensor with its descale factors if desired." + q_fp8, descale_q = cast_to_fp8(q, torch.float8_e4m3fnuz, "bshd") + k_fp8, descale_k = cast_to_fp8(k, torch.float8_e4m3fnuz, "bshd") + v_fp8, descale_v = cast_to_fp8(v, torch.float8_e4m3fnuz, "bshd") + out_fp8, descale_o = torch.zeros_like(q_fp8, dtype=torch.float32), None + + q_fp8, k_fp8, v_fp8 = [maybe_contiguous(x) for x in (q_fp8, k_fp8, v_fp8)] + _, softmax_lse, S_dmask, rng_state = flash_attn_gpu.fwd( + q_fp8, + k_fp8, + v_fp8, + out_fp8, + alibi_slopes, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + softcap=softcap, + return_softmax=return_softmax and dropout_p > 0, + descale_q=descale_q, + descale_k=descale_k, + descale_v=descale_v, + descale_o=descale_o + ) + if is_grad: + ctx.save_for_backward(q_fp8, k_fp8, v_fp8, out_fp8, softmax_lse, rng_state, descale_q, descale_k, descale_v, descale_o, descale_do) + ctx.dropout_p = dropout_p + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.softcap = softcap + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + out = out_fp8[..., :head_size_og] # NOTE: this used to be out_padded. It might cause issue doing an empty + + # check output type + assert out.dtype == q.dtype, "Input and output type must match otherwise there will be implicit casting by autograd" + return out if not return_softmax else (out, softmax_lse, S_dmask) + + @staticmethod + def backward(ctx, dout, *args): + q_fp8, k_fp8, v_fp8, out_fp8, softmax_lse, rng_state, descale_q, descale_k, descale_v, descale_o, descale_do = ctx.saved_tensors + head_size_og = dout.size(3) + dout_padded = dout + if head_size_og % 8 != 0: + dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8]) + + # figure out bwd parameters + if is_fp8(dout): # fp8 input and output + raise ValueError("fp8 input and out not supported yet for this function.") + assert (descale_do is not None), f"You need to pass descale factors for do" + dout_padded_fp8 = dout_padded + dq, descale_dq = torch.zeros_like(q_fp8), torch.zeros_like(descale_q) + dk, descale_dk = torch.zeros_like(k_fp8), torch.zeros_like(descale_k) + dv, descale_dv = torch.zeros_like(v_fp8), torch.zeros_like(descale_v) + else: # cast to fp8 and return output in the fp32. (accumulator type) + assert (descale_do is None), f"Found {dout.dtype} input tensor with descale factors. In this case, we cast to fp8 and compute the descale factors. You can pass an fp8 tensor with its descale factors if desired." + dout_padded_fp8, descale_do = cast_to_fp8(dout_padded, torch.float8_e4m3fnuz, "bshd") + dq, descale_dq = torch.zeros_like(q_fp8, dtype=torch.float32), None + dk, descale_dk = torch.zeros_like(k_fp8, dtype=torch.float32), None + dv, descale_dv = torch.zeros_like(v_fp8, dtype=torch.float32), None + + # dq, dk, dv are allocated by us so they should already be contiguous + dout_padded_fp8, q_fp8, k_fp8, v_fp8, out_fp8 = [maybe_contiguous(x) for x in (dout_padded_fp8, q_fp8, k_fp8, v_fp8, out_fp8)] + flash_attn_gpu.bwd( + dout_padded_fp8, + q_fp8, + k_fp8, + v_fp8, + out_fp8, + softmax_lse, + dq, + dk, + dv, + ctx.alibi_slopes, + ctx.dropout_p, + ctx.softmax_scale, + ctx.causal, + ctx.window_size[0], + ctx.window_size[1], + ctx.softcap, + ctx.deterministic, + None, # gen_ + rng_state, + descale_q, + descale_k, + descale_v, + descale_o, + descale_do, + descale_dq, + descale_dk, + descale_dv, + ) + dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension + dk = dk[..., : dout.shape[-1]] + dv = dv[..., : dout.shape[-1]] + return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None + +def flash_attn_fp8_func( + q, + k, + v, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # 0.0 means deactivated + alibi_slopes=None, + deterministic=False, + return_attn_probs=False, + descale_q: Optional[torch.Tensor] = None, + descale_k: Optional[torch.Tensor] = None, + descale_v: Optional[torch.Tensor] = None, + descale_do: Optional[torch.Tensor] = None +): + return FlashAttnFP8Func.apply( + q, + k, + v, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_attn_probs, + torch.is_grad_enabled(), + descale_q, + descale_k, + descale_v, + descale_do + ) + +class FlashAttnVarlenFP8Func(torch.autograd.Function): + @staticmethod + def forward( + ctx, + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_softmax, + block_table, + is_grad_enabled, + descale_q: Optional[torch.Tensor] = None, + descale_k: Optional[torch.Tensor] = None, + descale_v: Optional[torch.Tensor] = None, + descale_do: Optional[torch.Tensor] = None + ): + is_grad = is_grad_enabled and any( + x.requires_grad for x in [q, k, v] + ) + if softmax_scale is None: + softmax_scale = q.shape[-1] ** (-0.5) + head_size_og = q.size(2) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + + # figure out fwd parameters + if is_fp8(q) or is_fp8(k) or is_fp8(v): # fp8 input and output + raise ValueError("fp8 input and out not supported yet for this function.") + assert (descale_q is not None) and (descale_k is not None) and (descale_v is not None), f"You need to pass descale factors for q, k and v" + q_fp8 = q + k_fp8 = k + v_fp8 = v + out_fp8, descale_o = torch.zeros_like(q_fp8), torch.zeros_like(descale_q) + else: # cast to fp8 and return output in the fp32. (accumulator type) + assert (descale_q is None) and (descale_k is None) and (descale_v is None), f"Found {q.dtype} input tensor with descale factors. In this case, we cast to fp8 and compute the descale factors. You can pass an fp8 tensor with its descale factors if desired." + q_fp8, descale_q = cast_to_fp8(q, torch.float8_e4m3fnuz, "thd", cu_seqlens=cu_seqlens_q, max_seqlen=max_seqlen_q) + k_fp8, descale_k = cast_to_fp8(k, torch.float8_e4m3fnuz, "thd", cu_seqlens=cu_seqlens_k, max_seqlen=max_seqlen_k) + v_fp8, descale_v = cast_to_fp8(v, torch.float8_e4m3fnuz, "thd", cu_seqlens=cu_seqlens_k, max_seqlen=max_seqlen_k) + out_fp8, descale_o = torch.zeros_like(q_fp8, dtype=torch.float32), None + + q_fp8, k_fp8, v_fp8 = [maybe_contiguous(x) for x in (q_fp8, k_fp8, v_fp8)] + _, softmax_lse, S_dmask, rng_state = flash_attn_gpu.varlen_fwd( + q_fp8, + k_fp8, + v_fp8, + out_fp8, + cu_seqlens_q, + cu_seqlens_k, + None, + None, + block_table, + alibi_slopes, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + False, + causal, + window_size[0], + window_size[1], + softcap, + return_softmax, + None, + descale_q=descale_q, + descale_k=descale_k, + descale_v=descale_v, + descale_o=descale_o + ) + if is_grad: + ctx.save_for_backward(q_fp8, k_fp8, v_fp8, out_fp8, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state, descale_q, descale_k, descale_v, descale_o, descale_do) + ctx.dropout_p = dropout_p + ctx.max_seqlen_q = max_seqlen_q + ctx.max_seqlen_k = max_seqlen_k + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.softcap = softcap + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + out = out_fp8[..., :head_size_og] # NOTE: this used to be out_padded. It might cause issue doing an empty + + # check output type + assert out.dtype == q.dtype, "Input and output type must match otherwise there will be implicit casting by autograd" + return out if not return_softmax else (out, softmax_lse, S_dmask) + + @staticmethod + def backward(ctx, dout, *args): + q_fp8, k_fp8, v_fp8, out_fp8, softmax_lse, cu_seqlens_q, cu_seqlens_k, rng_state, descale_q, descale_k, descale_v, descale_o, descale_do = ctx.saved_tensors + head_size_og = dout.size(2) + dout_padded = dout + if head_size_og % 8 != 0: + dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8]) + + # figure out bwd parameters + if is_fp8(dout_padded): # fp8 input and output + raise ValueError("fp8 input and out not supported yet for this function.") + assert (descale_do is not None), f"You need to pass descale factors for do" + dout_padded_fp8 = dout_padded + dq, descale_dq = torch.zeros_like(q_fp8), torch.zeros_like(descale_q) + dk, descale_dk = torch.zeros_like(k_fp8), torch.zeros_like(descale_k) + dv, descale_dv = torch.zeros_like(v_fp8), torch.zeros_like(descale_v) + else: # cast to fp8 and return output in the fp32. (accumulator type) + assert (descale_do is None), f"Found {dout.dtype} input tensor with descale factors. In this case, we cast to fp8 and compute the descale factors. You can pass an fp8 tensor with its descale factors if desired." + dout_padded_fp8, descale_do = cast_to_fp8(dout_padded, torch.float8_e4m3fnuz, "thd", cu_seqlens=cu_seqlens_q, max_seqlen=ctx.max_seqlen_q) + dq, descale_dq = torch.zeros_like(q_fp8, dtype=torch.float32), None + dk, descale_dk = torch.zeros_like(k_fp8, dtype=torch.float32), None + dv, descale_dv = torch.zeros_like(v_fp8, dtype=torch.float32), None + + # dq, dk, dv are allocated by us so they should already be contiguous + dout_padded_fp8, q_fp8, k_fp8, v_fp8, out_fp8 = [maybe_contiguous(x) for x in (dout_padded_fp8, q_fp8, k_fp8, v_fp8, out_fp8)] + flash_attn_gpu.varlen_bwd( + dout_padded_fp8, + q_fp8, + k_fp8, + v_fp8, + out_fp8, + softmax_lse, + dq, + dk, + dv, + cu_seqlens_q, + cu_seqlens_k, + ctx.alibi_slopes, + ctx.max_seqlen_q, + ctx.max_seqlen_k, + ctx.dropout_p, + ctx.softmax_scale, + False, + ctx.causal, + ctx.window_size[0], + ctx.window_size[1], + ctx.softcap, + ctx.deterministic, + None, + rng_state, + descale_q, + descale_k, + descale_v, + descale_o, + descale_do, + descale_dq, + descale_dk, + descale_dv, + ) + dq = dq[..., : dout.shape[-1]] # We could have padded the head dimension + dk = dk[..., : dout.shape[-1]] + dv = dv[..., : dout.shape[-1]] + return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None + + +def flash_attn_varlen_fp8_func( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # 0.0 means deactivated + alibi_slopes=None, + deterministic=False, + return_attn_probs=False, + block_table=None +): + return FlashAttnVarlenFP8Func.apply( + q, + k, + v, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_attn_probs, + block_table, + torch.is_grad_enabled() + ) + +class FlashAttnQKVPackedFP8Func(torch.autograd.Function): + @staticmethod + def forward( + ctx, + qkv, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_softmax, + is_grad_enabled, + descale_q: Optional[torch.Tensor] = None, + descale_k: Optional[torch.Tensor] = None, + descale_v: Optional[torch.Tensor] = None, + descale_do: Optional[torch.Tensor] = None + ): + is_grad = is_grad_enabled and qkv.requires_grad + if softmax_scale is None: + softmax_scale = qkv.shape[-1] ** (-0.5) + q, k, v = qkv[:, :, 0].detach(), qkv[:, :, 1].detach(), qkv[:, :, 2].detach() + head_size_og = q.size(3) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + + # figure out fwd parameters + if is_fp8(q) or is_fp8(k) or is_fp8(v): # fp8 input and output + raise ValueError("fp8 input and out not supported yet for this function.") + assert (descale_q is not None) and (descale_k is not None) and (descale_v is not None), f"You need to pass descale factors for q, k and v" + q_fp8 = q + k_fp8 = k + v_fp8 = v + out_fp8, descale_o = torch.zeros_like(q_fp8), torch.zeros_like(descale_q) + else: # cast to fp8 and return output in the fp32. (accumulator type) + assert (descale_q is None) and (descale_k is None) and (descale_v is None), f"Found {q.dtype} input tensor with descale factors. In this case, we cast to fp8 and compute the descale factors. You can pass an fp8 tensor with its descale factors if desired." + q_fp8, descale_q = cast_to_fp8(q, torch.float8_e4m3fnuz, "bshd") + k_fp8, descale_k = cast_to_fp8(k, torch.float8_e4m3fnuz, "bshd") + v_fp8, descale_v = cast_to_fp8(v, torch.float8_e4m3fnuz, "bshd") + out_fp8, descale_o = torch.zeros_like(q_fp8, dtype=torch.float32), None + + q_fp8, k_fp8, v_fp8 = [maybe_contiguous(x) for x in (q_fp8, k_fp8, v_fp8)] + _, softmax_lse, S_dmask, rng_state = flash_attn_gpu.fwd( + q_fp8, + k_fp8, + v_fp8, + out_fp8, + alibi_slopes, + dropout_p, + softmax_scale, + causal=causal, + window_size_left=window_size[0], + window_size_right=window_size[1], + softcap=softcap, + return_softmax=return_softmax and dropout_p > 0, + descale_q=descale_q, + descale_k=descale_k, + descale_v=descale_v, + descale_o=descale_o, + ) + if is_grad: + ctx.save_for_backward(q_fp8, k_fp8, v_fp8, out_fp8, softmax_lse, rng_state, descale_q, descale_k, descale_v, descale_o, descale_do) + ctx.dropout_p = dropout_p + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.softcap = softcap + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + out = out_fp8[..., :head_size_og] + return out if not return_softmax else (out, softmax_lse, S_dmask) + + @staticmethod + def backward(ctx, dout, *args): + q_fp8, k_fp8, v_fp8, out_fp8, softmax_lse, rng_state, descale_q, descale_k, descale_v, descale_o, descale_do = ctx.saved_tensors + qkv_shape = q_fp8.shape[:-2] + (3, *q_fp8.shape[-2:]) + head_size_og = dout.size(3) + dout_padded = dout + if head_size_og % 8 != 0: + dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8]) + + # figure out bwd parameters + if is_fp8(dout): # fp8 input and output + raise ValueError("fp8 input and out not supported yet for this function.") + assert (descale_do is not None), f"You need to pass descale factors for do" + dout_padded_fp8 = dout_padded + dqkv, descale_dqkv = torch.zeros(qkv_shape, device=q_fp8.device), torch.zeros_like(descale_q) + else: # cast to fp8 and return output in the fp32. (accumulator type) + assert (descale_do is None), f"Found {dout.dtype} input tensor with descale factors. In this case, we cast to fp8 and compute the descale factors. You can pass an fp8 tensor with its descale factors if desired." + dout_padded_fp8, descale_do = cast_to_fp8(dout_padded, torch.float8_e4m3fnuz, "bshd") + dqkv, descale_dqkv = torch.zeros(qkv_shape, dtype=torch.float32, device=q_fp8.device), None + + + # dq, dk, dv are allocated by us so they should already be contiguous + dout_padded_fp8, q_fp8, k_fp8, v_fp8, out_fp8 = [maybe_contiguous(x) for x in (dout_padded_fp8, q_fp8, k_fp8, v_fp8, out_fp8)] + flash_attn_gpu.bwd( + dout_padded_fp8, + q_fp8, + k_fp8, + v_fp8, + out_fp8, + softmax_lse, + dqkv[:, :, 0], + dqkv[:, :, 1], + dqkv[:, :, 2], + ctx.alibi_slopes, + ctx.dropout_p, + ctx.softmax_scale, + ctx.causal, + ctx.window_size[0], + ctx.window_size[1], + ctx.softcap, + ctx.deterministic, + None, # gen_ + rng_state, + descale_q, + descale_k, + descale_v, + descale_o, + descale_do, + None, + None, + None, + ) + dqkv = dqkv[..., : dout.shape[-1]] # We could have padded the head dimension + return dqkv, None, None, None, None, None, None, None, None, None + + +def flash_attn_qkvpacked_fp8_func( + qkv, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # <=0.0 means deactivate + alibi_slopes=None, + deterministic=False, + return_attn_probs=False, +): + return FlashAttnQKVPackedFP8Func.apply( + qkv, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_attn_probs, + torch.is_grad_enabled(), + ) + + +class FlashAttnVarlenQKVPackedFP8Func(torch.autograd.Function): + @staticmethod + def forward( + ctx, + qkv, + cu_seqlens, + max_seqlen, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_softmax, + is_grad_enabled, + descale_q: Optional[torch.Tensor] = None, + descale_k: Optional[torch.Tensor] = None, + descale_v: Optional[torch.Tensor] = None, + descale_do: Optional[torch.Tensor] = None + ): + is_grad = is_grad_enabled and qkv.requires_grad + if softmax_scale is None: + softmax_scale = qkv.shape[-1] ** (-0.5) + q, k, v = qkv[:, 0].detach(), qkv[:, 1].detach(), qkv[:, 2].detach() + head_size_og = q.size(2) + if head_size_og % 8 != 0: + q = torch.nn.functional.pad(q, [0, 8 - head_size_og % 8]) + k = torch.nn.functional.pad(k, [0, 8 - head_size_og % 8]) + v = torch.nn.functional.pad(v, [0, 8 - head_size_og % 8]) + + # figure out fwd parameters + if is_fp8(q) or is_fp8(k) or is_fp8(v): # fp8 input and output + raise ValueError("fp8 input and out not supported yet for this function.") + assert (descale_q is not None) and (descale_k is not None) and (descale_v is not None), f"You need to pass descale factors for q, k and v" + q_fp8 = q + k_fp8 = k + v_fp8 = v + out_fp8, descale_o = torch.zeros_like(q_fp8), torch.zeros_like(descale_q) + else: # cast to fp8 and return output in the fp32. (accumulator type) + assert (descale_q is None) and (descale_k is None) and (descale_v is None), f"Found {q.dtype} input tensor with descale factors. In this case, we cast to fp8 and compute the descale factors. You can pass an fp8 tensor with its descale factors if desired." + q_fp8, descale_q = cast_to_fp8(q, torch.float8_e4m3fnuz, "thd", cu_seqlens=cu_seqlens, max_seqlen=max_seqlen) + k_fp8, descale_k = cast_to_fp8(k, torch.float8_e4m3fnuz, "thd", cu_seqlens=cu_seqlens, max_seqlen=max_seqlen) + v_fp8, descale_v = cast_to_fp8(v, torch.float8_e4m3fnuz, "thd", cu_seqlens=cu_seqlens, max_seqlen=max_seqlen) + out_fp8, descale_o = torch.zeros_like(q_fp8, dtype=torch.float32), None + + q_fp8, k_fp8, v_fp8 = [maybe_contiguous(x) for x in (q_fp8, k_fp8, v_fp8)] + _, softmax_lse, S_dmask, rng_state = flash_attn_gpu.varlen_fwd( + q_fp8, + k_fp8, + v_fp8, + out_fp8, + cu_seqlens, + cu_seqlens, + None, + None, + None, + alibi_slopes, + max_seqlen, + max_seqlen, + dropout_p, + softmax_scale, + False, + causal, + window_size[0], + window_size[1], + softcap, + return_softmax, + None, + descale_q=descale_q, + descale_k=descale_k, + descale_v=descale_v, + descale_o=descale_o + ) + if is_grad: + ctx.save_for_backward(q_fp8, k_fp8, v_fp8, out_fp8, softmax_lse, cu_seqlens, rng_state, descale_q, descale_k, descale_v, descale_o, descale_do) + ctx.dropout_p = dropout_p + ctx.max_seqlen = max_seqlen + ctx.softmax_scale = softmax_scale + ctx.causal = causal + ctx.window_size = window_size + ctx.softcap = softcap + ctx.alibi_slopes = alibi_slopes + ctx.deterministic = deterministic + out = out_fp8[..., :head_size_og] + return out if not return_softmax else (out, softmax_lse, S_dmask) + + @staticmethod + def backward(ctx, dout, *args): + q_fp8, k_fp8, v_fp8, out_fp8, softmax_lse, cu_seqlens, rng_state, descale_q, descale_k, descale_v, descale_o, descale_do = ctx.saved_tensors + qkv_shape = q_fp8.shape[:-2] + (3, *q_fp8.shape[-2:]) + head_size_og = dout.size(2) + dout_padded = dout + if head_size_og % 8 != 0: + dout_padded = torch.nn.functional.pad(dout, [0, 8 - head_size_og % 8]) + + # figure out bwd parameters + if is_fp8(dout_padded): # fp8 input and output + raise ValueError("fp8 input and out not supported yet for this function.") + assert (descale_do is not None), f"You need to pass descale factors for do" + dout_padded_fp8 = dout_padded + dqkv, descale_dqkv = torch.zeros(qkv_shape, device=q_fp8.device), torch.zeros_like(descale_q) + else: # cast to fp8 and return output in the fp32. (accumulator type) + assert (descale_do is None), f"Found {dout.dtype} input tensor with descale factors. In this case, we cast to fp8 and compute the descale factors. You can pass an fp8 tensor with its descale factors if desired." + dout_padded_fp8, descale_do = cast_to_fp8(dout_padded, torch.float8_e4m3fnuz, "thd", cu_seqlens=cu_seqlens, max_seqlen=ctx.max_seqlen) + dqkv, descale_dqkv = torch.zeros(qkv_shape, dtype=torch.float32, device=q_fp8.device), None + + # dq, dk, dv are allocated by us so they should already be contiguous + dout_padded_fp8, q_fp8, k_fp8, v_fp8, out_fp8 = [maybe_contiguous(x) for x in (dout_padded_fp8, q_fp8, k_fp8, v_fp8, out_fp8)] + flash_attn_gpu.varlen_bwd( + dout_padded_fp8, + q_fp8, + k_fp8, + v_fp8, + out_fp8, + softmax_lse, + dqkv[:, 0], + dqkv[:, 1], + dqkv[:, 2], + cu_seqlens, + cu_seqlens, + ctx.alibi_slopes, + ctx.max_seqlen, + ctx.max_seqlen, + ctx.dropout_p, + ctx.softmax_scale, + False, + ctx.causal, + ctx.window_size[0], + ctx.window_size[1], + ctx.softcap, + ctx.deterministic, + None, + rng_state, + descale_q, + descale_k, + descale_v, + descale_o, + descale_do, + None, + None, + None, + ) + dqkv = dqkv[..., : dout.shape[-1]] # We could have padded the head dimension + return dqkv, None, None, None, None, None, None, None, None, None, None, None + + +def flash_attn_varlen_qkvpacked_fp8_func( + qkv, + cu_seqlens, + max_seqlen, + dropout_p=0.0, + softmax_scale=None, + causal=False, + window_size=(-1, -1), # -1 means infinite context window + softcap=0.0, # 0.0 means deactivated + alibi_slopes=None, + deterministic=False, + return_attn_probs=False, +): + return FlashAttnVarlenQKVPackedFP8Func.apply( + qkv, + cu_seqlens, + max_seqlen, + dropout_p, + softmax_scale, + causal, + window_size, + softcap, + alibi_slopes, + deterministic, + return_attn_probs, + torch.is_grad_enabled(), + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/fwd_decode.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/fwd_decode.py new file mode 100644 index 0000000000000000000000000000000000000000..3f2d92c22d64149abf9d31f528d843ae800d8839 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/fwd_decode.py @@ -0,0 +1,814 @@ +import torch +import triton +import triton.language as tl +from typing import Literal, Optional, Union +from .utils import AUTOTUNE, DEBUG, get_padded_headsize, get_shape_and_strides_from_layout, is_cdna + +def get_cdna_autotune_configs(): + return [ + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'waves_per_eu': 2, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 64, 'waves_per_eu': 2, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 64, 'waves_per_eu': 3, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 64, 'waves_per_eu': 1, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 32, 'waves_per_eu': 2, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + triton.Config({'BLOCK_M': 64, 'BLOCK_N': 64, 'waves_per_eu': 1, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + # Fall-back config. + triton.Config({'BLOCK_M': 16, 'BLOCK_N': 16, 'waves_per_eu': 1, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + ], ['IS_CAUSAL', 'dropout_p', 'MAX_SEQLENS_Q', 'MAX_SEQLENS_K', 'ACTUAL_BLOCK_DMODEL', 'VARLEN', 'HQ', 'HK'] + +def get_autotune_configs(): + if AUTOTUNE: + if is_cdna(): + autotune_configs, autotune_keys = get_cdna_autotune_configs() + fwd_auto_tune_configs, fwd_autotune_keys= autotune_configs, autotune_keys + reduce_auto_tune_configs, reduce_autotune_keys = autotune_configs, autotune_keys + return (fwd_auto_tune_configs, fwd_autotune_keys), (reduce_auto_tune_configs, reduce_autotune_keys) + else: + raise ValueError("Unknown Device Type") + else: + autotune_configs, autotune_keys = [ + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 64, "waves_per_eu": 1, "PRE_LOAD_V": False}, + num_stages=1, + num_warps=4, + ), + ], [ + "IS_CAUSAL", + "dropout_p", + "MAX_SEQLENS_Q", + "MAX_SEQLENS_K", + "ACTUAL_BLOCK_DMODEL", + "VARLEN", + "HQ", + "HK", + ] + + fwd_auto_tune_configs, fwd_autotune_keys= autotune_configs, autotune_keys + reduce_auto_tune_configs, reduce_autotune_keys = autotune_configs, autotune_keys + return (fwd_auto_tune_configs, fwd_autotune_keys), (reduce_auto_tune_configs, reduce_autotune_keys) + + +(fwd_auto_tune_configs, fwd_autotune_keys), (reduce_auto_tune_configs, reduce_autotune_keys) = get_autotune_configs() + +# @triton.autotune( +# configs=fwd_auto_tune_configs, +# key=fwd_autotune_keys, +# use_cuda_graph=True, +# ) +@triton.jit +def _fwd_kernel_splitK( + Q, + K, + V, + sm_scale, + Out_splitK, # [B*H*G, split_k, Mq, K] + Metadata, # [B*H*G, 2, split_k, M_ceil] contains [mi, li] + K_new, + V_new, + Cache_seqlens, + Cache_batch_idx, + Alibi_slopes, + stride_qz, + stride_qm, + stride_qg, + stride_qh, + stride_qd, + stride_kz, + stride_kn, + stride_kg, + stride_kh, + stride_kd, + stride_vz, + stride_vn, + stride_vg, + stride_vh, + stride_vd, + stride_osk_zhg, + stride_osk_s, + stride_osk_m, + stride_osk_d, + stride_mzhg, + stride_m2, + stride_ms, + stride_mm, + stride_kn_z, + stride_kn_n, + stride_kn_g, + stride_kn_h, + stride_kn_d, + stride_vn_z, + stride_vn_n, + stride_vn_g, + stride_vn_h, + stride_vn_d, + stride_az, + stride_ah, + Z, + N_CTX_Q, + N_CTX_K, + N_CTX_NEW, + BLOCK_N_PER_SPLIT, + H_q: tl.constexpr, + H_kv: tl.constexpr, + G_q: tl.constexpr, + BLOCK_M: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + ACTUAL_BLOCK_DMODEL: tl.constexpr, + BLOCK_N: tl.constexpr, + BOUNDS_CHECKS_N: tl.constexpr, + USE_CACHE_SEQLENs: tl.constexpr, + USE_CACHE_BATCH_IDX: tl.constexpr, + NEW_KV: tl.constexpr, + IS_GQA: tl.constexpr, + IS_CAUSAL: tl.constexpr, + USE_ALIBI: tl.constexpr, + PADDED_HEAD: tl.constexpr, + GROUP_SIZE: tl.constexpr, +): + # get program ids + pid_m = tl.program_id(0) + pid_zhg = tl.program_id(1) + pid_splitk = tl.program_id(2) + + # compute z, h and g ids + z_id = pid_zhg // (H_q * G_q) + hq_id = (pid_zhg // G_q) % H_q + g_id = pid_zhg % G_q + + # is gqa + if IS_GQA: + hk_id = hq_id // GROUP_SIZE + hv_id = hk_id + else: + hk_id = hq_id + hv_id = hq_id + + # figure out seqlens + lo = pid_splitk * BLOCK_N_PER_SPLIT + if USE_CACHE_SEQLENs: + cache_seqlen_last_idx = tl.load(Cache_seqlens + z_id) + if NEW_KV: + N_CTX_K_FINAL = cache_seqlen_last_idx + N_CTX_NEW + else: + N_CTX_K_FINAL = cache_seqlen_last_idx + else: + N_CTX_K_FINAL = N_CTX_K + hi = tl.minimum((pid_splitk + 1) * BLOCK_N_PER_SPLIT, N_CTX_K_FINAL) + + # pick batch index + if USE_CACHE_BATCH_IDX: + cache_batch_idx = tl.load(Cache_batch_idx + z_id) + else: + cache_batch_idx = z_id + + # compute offsets + offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + offs_n = tl.arange(0, BLOCK_N) + offs_d = tl.arange(0, BLOCK_DMODEL) + + # compute ptrs + q_offset = Q + hq_id * stride_qh + z_id * stride_qz + g_id * stride_qg + q_ptrs = q_offset + offs_m[:, None] * stride_qm + offs_d[None, :] * stride_qd + k_offset = K + hk_id * stride_kh + cache_batch_idx * stride_kz + g_id * stride_kg + v_offset = V + hv_id * stride_vh + cache_batch_idx * stride_vz + g_id * stride_vg + + # compute masks + if PADDED_HEAD: + q_mask = (offs_m < N_CTX_Q)[:, None] & (offs_d < ACTUAL_BLOCK_DMODEL)[None, :] + kT_mask = (offs_d < ACTUAL_BLOCK_DMODEL)[:, None] & (offs_n < N_CTX_K_FINAL)[None, :] + v_mask = (offs_n < N_CTX_K_FINAL)[:, None] & (offs_d < ACTUAL_BLOCK_DMODEL)[None, :] + osk_mask = (offs_m < N_CTX_Q)[:, None] & (offs_d < ACTUAL_BLOCK_DMODEL)[None, :] + else: + q_mask = (offs_m < N_CTX_Q)[:, None] + kT_mask = (offs_n < N_CTX_K_FINAL)[None, :] + v_mask = (offs_n < N_CTX_K_FINAL)[:, None] + osk_mask = (offs_m < N_CTX_Q)[:, None] + + # scale sm_scale by log_2(e) and use + # 2^x instead of exp in the loop because CSE and LICM + # don't work as expected with `exp` in the loop + qk_scale = sm_scale * 1.44269504 + + # load q: it will stay in SRAM throughout + q = tl.load(q_ptrs, mask=q_mask, other=0.0) + q = (q * qk_scale).to(q.dtype) + + # load ALiBi slope if enabled + if USE_ALIBI: + a_offset = z_id * stride_az + hq_id * stride_ah + alibi_slope = tl.load(Alibi_slopes + a_offset) + else: + alibi_slope = None + + # Copy new Keys and Values into Cache + if NEW_KV: + knew_base = K_new + hk_id * stride_kn_h + z_id * stride_kn_z + g_id * stride_kn_g + + # Determine the starting position for new data in the cache + if USE_CACHE_SEQLENs: + start_idx = tl.load(Cache_seqlens + z_id) + else: + start_idx = N_CTX_K - N_CTX_NEW + + # Copy new Keys + for i in range(0, N_CTX_NEW, BLOCK_N): + # Load from K_new + k_new_block = tl.load( + knew_base + + tl.arange(0, BLOCK_DMODEL)[:, None] * stride_kn_d + + (tl.arange(0, BLOCK_N) + i)[None, :] * stride_kn_n, + mask=(tl.arange(0, BLOCK_N)[None, :] + i < N_CTX_NEW) & + (tl.arange(0, BLOCK_DMODEL)[:, None] < ACTUAL_BLOCK_DMODEL), + other=0 + ) + + # Store to K + tl.store( + k_offset + + tl.arange(0, BLOCK_DMODEL)[:, None] * stride_kd + + (tl.arange(0, BLOCK_N) + i + start_idx)[None, :] * stride_kn, + k_new_block, + mask=(tl.arange(0, BLOCK_N)[None, :] + i < N_CTX_NEW) & + (tl.arange(0, BLOCK_DMODEL)[:, None] < ACTUAL_BLOCK_DMODEL), + ) + + # Copy new Values + vnew_base = V_new + hv_id * stride_vn_h + z_id * stride_vn_z + g_id * stride_vn_g + for i in range(0, N_CTX_NEW, BLOCK_N): + # Load from V_new + v_new_block = tl.load( + vnew_base + + (tl.arange(0, BLOCK_N) + i)[:, None] * stride_vn_n + + tl.arange(0, BLOCK_DMODEL)[None, :] * stride_vn_d, + mask=(tl.arange(0, BLOCK_N)[:, None] + i < N_CTX_NEW) & + (tl.arange(0, BLOCK_DMODEL)[None, :] < ACTUAL_BLOCK_DMODEL), + other=0 + ) + + # Store to V + tl.store( + v_offset + + (tl.arange(0, BLOCK_N) + i + start_idx)[:, None] * stride_vn + + tl.arange(0, BLOCK_DMODEL)[None, :] * stride_vd, + v_new_block, + mask=(tl.arange(0, BLOCK_N)[:, None] + i < N_CTX_NEW) & + (tl.arange(0, BLOCK_DMODEL)[None, :] < ACTUAL_BLOCK_DMODEL), + ) + + + # initialize pointer to m and l + m_i = tl.full([BLOCK_M], float("-inf"), dtype=tl.float32) + l_i = tl.zeros([BLOCK_M], dtype=tl.float32) + + acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32) # noqa: F821 + + + # loop over k, v and update accumulator + for start_n in range(lo, hi, BLOCK_N): + kT_ptrs = k_offset + offs_d[:, None] * stride_kd + (start_n + offs_n)[None, :] * stride_kn + V_ptrs = v_offset + (start_n + offs_n)[:, None] * stride_vn + offs_d[None, :] * stride_vd + + # load k + kT = tl.load(kT_ptrs, mask=kT_mask, other=0.0) + v = tl.load(V_ptrs, mask=v_mask, other=0.0) + + # -- compute qk --- + qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) + qk += tl.dot(q, kT) # noqa: F821 + + if USE_ALIBI: + row_idx = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + col_idx = start_n + tl.arange(0, BLOCK_N) + + # Compute relative positions + relative_pos = row_idx[:, None] + N_CTX_K_FINAL - (N_CTX_Q + col_idx[None, :]) + relative_pos = tl.abs(relative_pos) + + # Compute ALiBi bias + alibi_bias = -1 * alibi_slope * relative_pos + qk += (alibi_bias * 1.44269504) + + # Apply causal mask if IS_CAUSAL is True + if IS_CAUSAL: + row_idx = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + col_idx = start_n + tl.arange(0, BLOCK_N) + + # create a N_CTX_Q x kv_len causal mask + col_offset = N_CTX_Q - N_CTX_K_FINAL + causal_mask = row_idx[:, None] >= (col_offset + col_idx[None, :]) + + # Apply the mask + qk = tl.where(causal_mask, qk, float("-inf")) + + # TODO: This is slow, and only needed at the last iteration. + # Maybe we can unroll the last iteration instead? + if BOUNDS_CHECKS_N: + qk = tl.where(tl.arange(0, BLOCK_N) < hi - start_n, qk, float("-inf")) + + # -- compute scaling constant --- + m_i_new = tl.maximum(m_i, tl.max(qk, 1)) + if IS_CAUSAL: + alpha = tl.math.exp2(tl.where(m_i > float("-inf"), m_i - m_i_new, float("-inf"))) + else: + alpha = tl.math.exp2(m_i - m_i_new) + # cause of nan because subtracting infs + if IS_CAUSAL: + qk = tl.where(qk > float("-inf"), qk - m_i_new[:, None], float("-inf")) + else: + qk = qk - m_i_new[:, None] + + p = tl.math.exp2(qk) + + # -- update m_i and l_i -- + l_i = l_i * alpha + tl.sum(p, 1) + m_i = m_i_new + p = p.to(Q.dtype.element_ty) + + # -- scale and update acc -- + acc *= alpha[:, None] + acc += tl.dot(p.to(v.dtype), v) + + # write back O + osk_offset = Out_splitK + pid_zhg * stride_osk_zhg + pid_splitk * stride_osk_s + osk_ptrs = osk_offset + offs_m[:, None] * stride_osk_m + offs_d[None, :] * stride_osk_d + tl.store( + osk_ptrs, + acc, + mask=osk_mask, + ) + + # write metadata for split-K reduction + metadata_offset = Metadata + pid_zhg * stride_mzhg + pid_splitk * stride_ms + metadata_ptr = metadata_offset + offs_m + tl.store(metadata_ptr, m_i) + tl.store(metadata_ptr + stride_m2, l_i) + + +# @triton.autotune( +# configs=reduce_auto_tune_configs, +# key=reduce_autotune_keys, +# use_cuda_graph=True, +# ) +@triton.jit +def _splitK_reduce( + Out_splitK, # [B*H*G, split_k, Mq, K] + Metadata, # [B*H*G, 2, split_k, M_ceil] contains [mi, li] + Out, # [B, H, G, M, K] + LSE, # [B*H*G, M] + stride_osk_zhg, + stride_osk_s, + stride_osk_m, + stride_osk_k, + stride_mzhg, + stride_m2, + stride_ms, + stride_mm, + stride_oz, + stride_oh, + stride_og, + stride_om, + stride_ok, + stride_lse_zhg, + stride_lse_m, + K_BLOCK_SIZE: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + ACTUAL_BLOCK_DMODEL: tl.constexpr, + H: tl.constexpr, + G: tl.constexpr, + split_k: tl.constexpr, + splitK_pow2: tl.constexpr, + MASK_SPLITK: tl.constexpr, + IS_CAUSAL: tl.constexpr, + PADDED_HEAD: tl.constexpr, +): + # get pids + pid_zhg = tl.program_id(0) + pid_m = tl.program_id(1) + pid_k = tl.program_id(2) + + # compute offsets + offs_splitK = tl.arange(0, splitK_pow2) + offs_k = pid_k * K_BLOCK_SIZE + tl.arange(0, K_BLOCK_SIZE) + + + # compute masks + if PADDED_HEAD: + o_mask = offs_k < ACTUAL_BLOCK_DMODEL + else: + o_mask = None + + # compute ptrs + metadata_offset = Metadata + pid_zhg * stride_mzhg + metadata_ptr = metadata_offset + offs_splitK * stride_ms + pid_m * stride_mm + + osk_offset = Out_splitK + pid_zhg * stride_osk_zhg + pid_m * stride_osk_m + osk_ptr = osk_offset + offs_splitK[:, None] * stride_osk_s + offs_k[None, :] * stride_osk_k + + # read max values of each splitK + if MASK_SPLITK: + splitK_mask = offs_splitK < split_k + l_m = tl.load(metadata_ptr, mask=splitK_mask, other=float("-inf")) + l_sum = tl.load(metadata_ptr + stride_m2, mask=splitK_mask, other=0.0) + acc = tl.load(osk_ptr, mask=splitK_mask[:, None], other=0.0) + else: + l_m = tl.load(metadata_ptr) + l_sum = tl.load(metadata_ptr + stride_m2) + acc = tl.load(osk_ptr) + + g_m = tl.max(l_m, axis=0) + + if IS_CAUSAL: + l_m_offset = l_m - g_m + alpha = tl.where(l_m_offset > float("-inf"), tl.math.exp2(l_m_offset), 0.0) + else: + alpha = tl.math.exp2(l_m - g_m) + + # read sum + l_sum *= alpha + g_sum = tl.sum(l_sum, axis=0) + acc = acc * alpha[:, None] + + if IS_CAUSAL: + # Avoid division by zero + g_sum_safe = tl.where(g_sum > 0, g_sum, 1.0) + acc_out = tl.sum(acc, axis=0) / g_sum_safe + else: + acc_out = tl.sum(acc, axis=0) / g_sum + + # Store output + z_id = pid_zhg // (H * G) + h_id = (pid_zhg // G) % H + g_id = pid_zhg % G + out_offset = Out + z_id * stride_oz + h_id * stride_oh + g_id * stride_og + out_ptr = out_offset + pid_m * stride_om + offs_k + tl.store(out_ptr, acc_out, mask=o_mask) + + # Store lse + l_ptrs = LSE + pid_zhg * stride_lse_zhg + pid_m + if IS_CAUSAL: + lse = tl.where(g_sum > 0, (g_m + tl.math.log2(g_sum)) / 1.44269504, g_m) + tl.store(l_ptrs, lse) + else: + tl.store(l_ptrs, (g_m + tl.math.log2(g_sum)) / 1.44269504) + + +@triton.jit +def cast_uint32_to_half2(scale_shift): + # Extract two float16 packed into one int32 + scale = scale_shift & 0xFFFF + shift = scale_shift >> 16 + scale = scale.to(tl.uint16).to(tl.float16, bitcast=True) + shift = shift.to(tl.uint16).to(tl.float16, bitcast=True) + return scale, shift + +@triton.jit +def dequantize( + x_, + scale, + shift, + PACKED_PER_VAL: tl.constexpr = 8, +): + # PACKED_PER_VAL is the number of values packed into + # each element x_. For example, for int4 quantization + #and x_ of type int32, PACKED_PER_VAL is 8. + + BLOCK_N: tl.constexpr = x_.shape[0] + BLOCK_DMODEL_PACKED: tl.constexpr = x_.shape[1] + offsets = tl.arange(0, PACKED_PER_VAL) * 4 + quant_offset = (x_[:, None, :] >> offsets[None, :, None]) # (BLOCK_N, PACKED_PER_VAL, D // PACKED_PER_VAL) + + quant_offset = tl.view(quant_offset, (BLOCK_N, BLOCK_DMODEL_PACKED * PACKED_PER_VAL)) + # Trick - instead of converting int4 to float16 we view it as float16 + # and then multiply by 32768 * 512 == 2**24 + quant_offset = (quant_offset & 0xF).to(tl.uint16).to(tl.float16, bitcast=True) + quant_offset = (quant_offset * 32768.0).to(tl.float16) + scale_512 = scale * 512 + + dequant = quant_offset * scale_512 + shift + return dequant + +def quantize_kv_int4(k: torch.Tensor, num_groups: int = 1) -> torch.Tensor: + # Scale and shift are such that quantization linearly maps + # int4 values range [0..15] to input values range min(k)..max(k) + # individually for every row + k = k.reshape(*k.shape[:-1], num_groups, k.shape[-1] // num_groups) + max_vals = torch.max(k, dim=-1, keepdim=True).values + min_vals = torch.min(k, dim=-1, keepdim=True).values + scale_k: torch.Tensor = (max_vals - min_vals) / 15 + + shift_k = torch.min(k, dim=-1, keepdim=True).values + scale_k = scale_k.to(torch.float16) + shift_k = shift_k.to(torch.float16) + + in_bytes = ((k - shift_k.expand(k.shape)) / scale_k.expand(k.shape)) + 0.5 + in_bytes = in_bytes.to(torch.uint8) + in_int4 = in_bytes & 0xF + in_int4_packed = in_int4[..., ::2] + (in_int4[..., 1::2] << 4) + scale_shift = torch.concat([scale_k.view(torch.uint8), shift_k.view(torch.uint8)], dim=-1) + k_quant = torch.concat( + [ + scale_shift.flatten(start_dim=-2), + in_int4_packed.flatten(start_dim=-2), + ], + dim=-1, + ).view(torch.int16) + return k_quant + + +def dequantize_kv_fp16(quant_k: torch.Tensor, num_groups: int = 1) -> torch.Tensor: + k_i16 = quant_k.view(torch.int16) + k_ui8 = k_i16.view(torch.uint8) + + ss_size = num_groups * 4 + scale_shift_ui8 = k_ui8[..., 0:ss_size] + scale_shift_ui8 = scale_shift_ui8.reshape(*scale_shift_ui8.shape[:-1], num_groups, 4) + scale = scale_shift_ui8[..., 0:2].view(torch.float16) + shift = scale_shift_ui8[..., 2:4].view(torch.float16) + + kv_ui8 = k_ui8[..., ss_size:] + k_ui8 = kv_ui8.reshape(*kv_ui8.shape[:-1], num_groups, -1) + k1_i4 = k_ui8 & 0xF + k2_i4 = (k_ui8 & 0xF0) >> 4 + k_shape = k1_i4.shape + k1_f16 = k1_i4.to(torch.float16) * scale.expand(k_shape) + shift.expand(k_shape) + k2_f16 = k2_i4.to(torch.float16) * scale.expand(k_shape) + shift.expand(k_shape) + + out = torch.empty((*k1_f16.shape[:-1], k1_f16.shape[-1] * 2), dtype=torch.float16, device=quant_k.device) + out[..., ::2] = k1_f16 + out[..., 1::2] = k2_f16 + out = out.reshape(*k_shape[:-2], -1) + + return out + + +def get_split_k(B: int, G: int, H: int, Mk: int) -> int: + """Heuristic for the number of splits""" + bh = max(B * H, 1) # NOTE: Handle B*h=0 case + split_k = max(Mk, 1024) // bh + max_chunk_size = 64 + while split_k > 0 and Mk / split_k < max_chunk_size: + split_k = split_k // 2 + while B * H * G * split_k >= 1024: + split_k = split_k // 2 + split_k = min(split_k, 512) + split_k = max(split_k, 1) + return split_k + +def attention_decode_forward_triton_impl( + q: torch.Tensor, + k_cache: torch.Tensor, + v_cache: torch.Tensor, + k_new: Optional[torch.Tensor], + v_new: Optional[torch.Tensor], + out: torch.Tensor, + sm_scale: float, + causal: bool, + alibi_slopes: Optional[torch.Tensor], + layout: Literal["bshd"], + cache_seqlens: Optional[Union[(int, torch.Tensor)]], + cache_batch_idx: Optional[torch.Tensor], +): + # triton configs + BLOCK_M = 16 + BLOCK_N = 64 + num_stages = 1 + num_warps_fwd = 1 + num_warps_reduce = 4 + + # kernel_configs + is_new_kv = True if k_new is not None and v_new is not None else False + use_alibi = False if alibi_slopes is None else True + use_cache_seqlens = cache_seqlens is not None + SPLIT_K = None + NUM_QUANT_GROUPS = 1 + + # get shapes and strides + (batch_size, seqlen_q, nheads_q, dim_q), (stride_qz, stride_qh, stride_qm, stride_qd) = get_shape_and_strides_from_layout(q, layout) + (_, seqlen_kc, nheads_kc, dim_kc), (stride_kc_z, stride_kc_h, stride_kc_n, stride_kc_d) = get_shape_and_strides_from_layout(k_cache, layout) + (_, seqlen_vc, nheads_vc, dim_vc), (stride_vc_z, stride_vc_h, stride_vc_n, stride_vc_d) = get_shape_and_strides_from_layout(v_cache, layout) + if is_new_kv: + ( _, seqlen_kn, nheads_kn, dim_kn), (stride_kn_z, stride_kn_h, stride_kn_n, stride_kn_d) = get_shape_and_strides_from_layout(k_new, layout) + (_, seqlen_vn, nheads_vn, dim_vn), (stride_vn_z, stride_vn_h, stride_vn_n, stride_vn_d) = get_shape_and_strides_from_layout(v_new, layout) + else: + ( _, seqlen_kn, nheads_kn, dim_kn), (stride_kn_z, stride_kn_h, stride_kn_n, stride_kn_d) = (None, None, None, None), (None, None, None, None) + (_, seqlen_vn, nheads_vn, dim_vn), (stride_vn_z, stride_vn_h, stride_vn_n, stride_vn_d) = (None, None, None, None), (None, None, None, None) + (_, seqlen_o, nheads_o, dim_o), (stride_oz, stride_oh, stride_om, stride_od) = get_shape_and_strides_from_layout(out, layout) + if use_alibi: + stride_az, stride_ah = alibi_slopes.stride() + else: + stride_az, stride_ah = (None, None) + + assert dim_q == dim_kc == dim_vc, f"Dimensions must match: {dim_q}, {dim_kc}, {dim_vc}" + + # add extra information needed by the kernels + if layout == "bshd": + (n_group_q, heads_per_group_q), stride_qg = (1, nheads_q), stride_qm + (n_group_k, heads_per_group_k), stride_kc_g = (1, nheads_kc), stride_kc_n + (n_group_v, heads_per_group_v), stride_vc_g = (1, nheads_vc), stride_vc_n + if is_new_kv: + (n_group_kn, heads_per_group_kn), stride_kn_g = (1, nheads_kn), stride_kn_n + (n_group_vn, heads_per_group_vn), stride_vn_g = (1, nheads_vn), stride_vn_n + else: + (n_group_kn, heads_per_group_kn), stride_kn_g = (None, None), None + (n_group_vn, heads_per_group_vn), stride_vn_g = (None, None), None + (n_group_o, heads_per_group_o), stride_og = (1, nheads_o), stride_om + else: + raise ValueError(f"{layout} layout is not supported") + + # get padded size + dim_padded = get_padded_headsize(dim_kc) + is_padded_head = dim_padded != dim_kc + + # Handle MQA/GQA case + group_size = nheads_q // nheads_kc + if group_size > 1: + is_gqa = True + else: + is_gqa = False + + if SPLIT_K is not None: + split_k = SPLIT_K + else: + # Use heuristics + split_k = get_split_k(batch_size, n_group_q, heads_per_group_q, seqlen_kc) # NOTE: should the split think about seqlens? + split_size = (seqlen_kc + split_k - 1) // split_k + + # setup grid + seqlen_q_ceil = (seqlen_q + BLOCK_M - 1) // BLOCK_M * BLOCK_M + grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch_size * n_group_q * heads_per_group_q, split_k) + + # create intermediate tensors + out_splitk = torch.empty([batch_size * n_group_q * heads_per_group_q, split_k, seqlen_q_ceil, dim_kc], dtype=torch.float32, device=q.device) + metadata = torch.empty([batch_size * n_group_q * heads_per_group_q, 2, split_k, seqlen_q_ceil], dtype=torch.float32, device=q.device) + lse = torch.empty((batch_size * n_group_q * heads_per_group_q, seqlen_q), dtype=torch.float32, device=q.device) + + # get intermediate tensor strides + stride_osk_zhg, stride_osk_s, stride_osk_m, stride_osk_d = out_splitk.stride() + stride_mzhg, stride_m2, stride_ms, stride_mm = metadata.stride() + stride_lse_zhg, stride_lse_m = lse.stride() + + if False: + print("batch_size, seqlen_q, nheads_q, dim_q", (batch_size, seqlen_q, nheads_q, dim_q)) + print("_, seqlen_kc, nheads_kc, dim_kc", (_, seqlen_kc, nheads_kc, dim_kc)) + print("dim_padded:", dim_padded) + print("stride_qz, stride_qm, stride_qg, stride_qh, stride_qd", (stride_qz, stride_qm, stride_qg, stride_qh, stride_qd)) + print("stride_kc_z, stride_kc_n, stride_kc_g, stride_kc_h, stride_kc_d", (stride_kc_z, stride_kc_n, stride_kc_g, stride_kc_h, stride_kc_d)) + print("stride_vc_z, stride_vc_n, stride_vc_g, stride_vc_h, stride_vc_d", (stride_vc_z, stride_vc_n, stride_vc_g, stride_vc_h, stride_vc_d)) + if is_new_kv: + print("stride_kn_z, stride_kn_n, stride_kn_g, stride_kn_h, stride_kn_d", (stride_kn_z, stride_kn_n, stride_kn_g, stride_kn_h, stride_kn_d)) + print("stride_vn_z, stride_vn_n, stride_vn_g, stride_vn_h, stride_vn_d", (stride_vn_z, stride_vn_n, stride_vn_g, stride_vn_h, stride_vn_d)) + print("stride_oz, stride_om, stride_og, stride_oh, stride_od", (stride_oz, stride_om, stride_og, stride_oh, stride_od)) + print("stride_osk_zhg, stride_osk_s, stride_osk_m, stride_osk_d", (stride_osk_zhg, stride_osk_s, stride_osk_m, stride_osk_d)) + print("stride_mzhg, stride_m2, stride_ms, stride_mm", (stride_mzhg, stride_m2, stride_ms, stride_mm)) + print("stride_lse_zhg, stride_lse_m", (stride_lse_zhg, stride_lse_m)) + + # TODO: enable quantization + _fwd_kernel_splitK[grid]( + Q=q, + K=k_cache, + V=v_cache, + sm_scale=sm_scale, + Out_splitK=out_splitk, + Metadata=metadata, + K_new=k_new, + V_new=v_new, + Cache_seqlens=cache_seqlens, + Cache_batch_idx=cache_batch_idx, + Alibi_slopes=alibi_slopes, + # q strides + stride_qz=stride_qz, + stride_qm=stride_qm, + stride_qg=stride_qg, + stride_qh=stride_qh, + stride_qd=stride_qd, + # k strides + stride_kz=stride_kc_z, + stride_kn=stride_kc_n, + stride_kg=stride_kc_g, + stride_kh=stride_kc_h, + stride_kd=stride_kc_d, + # v strides + stride_vz=stride_vc_z, + stride_vn=stride_vc_n, + stride_vg=stride_vc_g, + stride_vh=stride_vc_h, + stride_vd=stride_vc_d, + # out_splitk strides + stride_osk_zhg=stride_osk_zhg, + stride_osk_s=stride_osk_s, + stride_osk_m=stride_osk_m, + stride_osk_d=stride_osk_d, + # metadata strides + stride_mzhg=stride_mzhg, + stride_m2=stride_m2, + stride_ms=stride_ms, + stride_mm=stride_mm, + # k_new strides + stride_kn_z=stride_kn_z, + stride_kn_n=stride_kn_n, + stride_kn_g=stride_kn_g, + stride_kn_h=stride_kn_h, + stride_kn_d=stride_kn_d, + # v_new strides + stride_vn_z=stride_vn_z, + stride_vn_n=stride_vn_n, + stride_vn_g=stride_vn_g, + stride_vn_h=stride_vn_h, + stride_vn_d=stride_vn_d, + # alibi strides + stride_az=stride_az, + stride_ah=stride_ah, + Z=batch_size, + H_q=heads_per_group_q, + H_kv=heads_per_group_k, + G_q=n_group_q, + N_CTX_Q=seqlen_q, + N_CTX_K=seqlen_kc, + N_CTX_NEW=seqlen_kn, + BLOCK_N_PER_SPLIT=split_size, + BLOCK_M=BLOCK_M, + BLOCK_N=BLOCK_N, + BLOCK_DMODEL=dim_padded, + ACTUAL_BLOCK_DMODEL=dim_kc, + BOUNDS_CHECKS_N=(split_size % BLOCK_N) > 0 or use_cache_seqlens, + USE_CACHE_SEQLENs=use_cache_seqlens, + USE_CACHE_BATCH_IDX=cache_batch_idx is not None, + NEW_KV=is_new_kv, + IS_GQA=is_gqa, + IS_CAUSAL=causal, + USE_ALIBI=use_alibi, + PADDED_HEAD=is_padded_head, + GROUP_SIZE=group_size, + num_warps=num_warps_fwd, + num_stages=num_stages, + ) + + if DEBUG: + print("Out_splitK:", out_splitk, out_splitk.shape) + print("metadata:", metadata, metadata.shape) + print("lse:", lse, lse.shape) + print("Out:", out, out.shape) + + # Merge together + splitK_pow2 = triton.next_power_of_2(split_k) + mask_split_k = splitK_pow2 > split_k + if batch_size * n_group_q * heads_per_group_q * seqlen_q >= 512: + k_block_num = 1 + else: + k_block_num = 2 + assert dim_padded % k_block_num == 0 + k_block_size = dim_padded // k_block_num + grid = (batch_size * n_group_q * heads_per_group_q, seqlen_q, k_block_num) + + + if DEBUG: + print("splitK_pow2:", splitK_pow2) + print("k_block_num:", k_block_num) + print("k_block_size:", k_block_size) + print("grid:", grid) + + _splitK_reduce[grid]( + out_splitk, + metadata, + out, + lse, + # Split-K output strides + stride_osk_zhg=stride_osk_zhg, + stride_osk_s=stride_osk_s, + stride_osk_m=stride_osk_m, + stride_osk_k=stride_osk_d, + # Metadata strides + stride_mzhg=stride_mzhg, + stride_m2=stride_m2, + stride_ms=stride_ms, + stride_mm=stride_mm, + # Output tensor strides + stride_oz=stride_oz, + stride_oh=stride_oh, + stride_og=stride_og, + stride_om=stride_om, + stride_ok=stride_od, + # LSE strides + stride_lse_zhg=stride_lse_zhg, + stride_lse_m=stride_lse_m, + K_BLOCK_SIZE=k_block_size, + BLOCK_DMODEL=dim_padded, + ACTUAL_BLOCK_DMODEL=dim_kc, + G=n_group_q, + H=heads_per_group_q, + # TODO: Tune num_warps + split_k=split_k, + splitK_pow2=splitK_pow2, + MASK_SPLITK=mask_split_k, + IS_CAUSAL=causal, + PADDED_HEAD=is_padded_head, + num_warps=num_warps_reduce) + + return lse diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/fwd_prefill.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/fwd_prefill.py new file mode 100644 index 0000000000000000000000000000000000000000..dec5673e3e5bc6e480807f1041371f263a665a11 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/fwd_prefill.py @@ -0,0 +1,648 @@ +import torch +import triton +import triton.language as tl +from typing import Literal, Optional, Union +from .utils import DEBUG, DROPOUT_USE_PYTORCH, DROPOUT_DUMP, AUTOTUNE, compute_alibi_block, compute_fp8_scaling_factors, get_shapes_from_layout, get_strides_from_layout, is_cdna, is_fp8, is_rdna, create_dropout_mask + +# NOTE: triton fails to import tl.constexprs so create them here for the file +tl_DROPOUT_USE_PYTORCH: tl.constexpr = triton.language.constexpr(DROPOUT_USE_PYTORCH) +tl_DROPOUT_DUMP: tl.constexpr = triton.language.constexpr(DROPOUT_DUMP) + +# Convenience function to load with optional boundary checks. +# "First" is the major dim, "second" is the minor dim. +@triton.jit +def load_fn(ptrs, offset_first, offset_second, boundary_first, boundary_second): + if offset_first is not None and offset_second is not None: + mask = (offset_first[:, None] < boundary_first) & \ + (offset_second[None, :] < boundary_second) + tensor = tl.load(ptrs, mask=mask, other=0.0) + elif offset_first is not None: + mask = offset_first[:, None] < boundary_first + tensor = tl.load(ptrs, mask=mask, other=0.0) + elif offset_second is not None: + mask = offset_second[None, :] < boundary_second + tensor = tl.load(ptrs, mask=mask, other=0.0) + else: + tensor = tl.load(ptrs) + return tensor + +@triton.jit +def _attn_fwd_inner(acc, l_i, m_i, q, k_ptrs, v_ptrs, bias_ptrs, stride_kn, stride_vk, stride_bn, stride_sn, start_m, + actual_seqlen_k, actual_seqlen_q, dropout_p, philox_seed, philox_ptrs, sd_mask_ptrs, dropout_mask_ptrs, + block_min, block_max, offs_n_causal, masked_blocks, n_extra_tokens, alibi_slope, + descale_q, descale_k, descale_v, IS_FP8: tl.constexpr, FP8_MAX: tl.constexpr, + IS_CAUSAL: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_DMODEL: tl.constexpr, BLOCK_N: tl.constexpr, + OFFS_M: tl.constexpr, OFFS_N: tl.constexpr, PRE_LOAD_V: tl.constexpr, MASK_STEPS: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, PADDED_HEAD: tl.constexpr, + ACTUAL_BLOCK_DMODEL: tl.constexpr, SM_SCALE: tl.constexpr, USE_ALIBI: tl.constexpr, USE_EXP2: tl.constexpr, + RETURN_SCORES: tl.constexpr, ACCUMULATOR_TYPE): + if USE_EXP2: + RCP_LN2: tl.constexpr = 1.4426950408889634 + + # loop over k, v, and update accumulator + for start_n in range(block_min, block_max, BLOCK_N): + # For padded blocks, we will overrun the tensor size if + # we load all BLOCK_N. For others, the blocks are all within range. + if MASK_STEPS: + k_offs_n = start_n + tl.arange(0, BLOCK_N) + else: + k_offs_n = None + k_offs_k = None if not PADDED_HEAD else tl.arange(0, BLOCK_DMODEL) + k = load_fn(k_ptrs, k_offs_k, k_offs_n, ACTUAL_BLOCK_DMODEL, actual_seqlen_k) + if PRE_LOAD_V: + # We can use the same offsets as k, just with dims transposed. + v = load_fn(v_ptrs, k_offs_n, k_offs_k, actual_seqlen_k, ACTUAL_BLOCK_DMODEL) + qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=ACCUMULATOR_TYPE) + # We start from end of seqlen_k so only the first iteration would need + # to be checked for padding if it is not a multiple of block_n + # TODO: This can be optimized to only be true for the padded block. + if MASK_STEPS: + # If this is the last block / iteration, we want to + # mask if the sequence length is not a multiple of block size + # a solution is to always do BLOCK_M // BLOCK_N + 1 steps if not is_modulo_mn. + # last step might get wasted but that is okay. check if this masking works For + # that case. + if (start_n + BLOCK_N == block_max) and (n_extra_tokens != 0): + boundary_m = tl.full([BLOCK_M], actual_seqlen_k, dtype=tl.int32) + size_n = start_n + OFFS_N[None, :] + mask = size_n < boundary_m[:, None] + qk = tl.where(mask, qk, float("-inf")) + + # compute masks + q_mask = (OFFS_M[:, None] < actual_seqlen_q) + k_mask = ((start_n + tl.arange(0, BLOCK_N))[None, :] < actual_seqlen_k) + p_mask = q_mask & k_mask + + # -- compute qk ---- + if IS_FP8 : + qk += (tl.dot(q, k) * descale_q * descale_k) + else: + qk += tl.dot(q, k) + qk_scaled = qk * SM_SCALE + + if IS_CAUSAL: + causal_boundary = start_n + offs_n_causal + causal_mask = OFFS_M[:, None] >= causal_boundary[None, :] + qk_scaled = tl.where(causal_mask, qk_scaled, float("-inf")) + if bias_ptrs is not None: + bias_offs_n = start_n + tl.arange(0, BLOCK_N) if MASK_STEPS else None + bias = load_fn(bias_ptrs, OFFS_M, bias_offs_n, actual_seqlen_q, actual_seqlen_k) + qk_scaled += bias + + if USE_ALIBI: + # compute the global position of each token within the sequence + global_m_positions = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + global_n_positions = start_n + tl.arange(0, BLOCK_N) + alibi_block = compute_alibi_block(alibi_slope, actual_seqlen_q, actual_seqlen_k, global_m_positions, + global_n_positions) + qk_scaled += alibi_block + # get max scores so far + m_ij = tl.maximum(m_i, tl.max(qk_scaled, 1)) + + # scale and subtract max + q_shifted = qk_scaled - m_ij[:, None] + + # Compute scaled QK and softmax probabilities + if USE_EXP2: + p = tl.math.exp2(q_shifted * RCP_LN2) + else: + p = tl.math.exp(q_shifted) + + # CAVEAT: Must update l_ij before applying dropout + l_ij = tl.sum(p, 1) + if ENABLE_DROPOUT: + if tl_DROPOUT_USE_PYTORCH: + dropout_mask = tl.load(dropout_mask_ptrs, mask=p_mask) + else: + rng_output = tl.rand(philox_seed, philox_ptrs) # TODO: use tl.randint for better performance + dropout_mask = rng_output > dropout_p + if tl_DROPOUT_DUMP: + tl.store(dropout_mask_ptrs, dropout_mask, mask=p_mask) + + # return scores with negative values for dropped vals + sd_mask = tl.where(dropout_mask, p, -p) + tl.store(sd_mask_ptrs, sd_mask, mask=p_mask) + + # apply dropout mask in place + p = tl.where(dropout_mask, p, 0.0) + elif RETURN_SCORES: + # NOTE: the returned score is not the same as the reference because we need to adjust as we find new maxes per block. We are not doing that + tl.store(sd_mask_ptrs, p, mask=p_mask) + + # -- update output accumulator -- + # alpha is an adjustment factor for acc and li as we loop and find new maxes + # store the diff in maxes to adjust acc and li as we discover new maxes + m_diff = m_i - m_ij + if USE_EXP2: + alpha = tl.math.exp2(m_diff * RCP_LN2) + else: + alpha = tl.math.exp(m_diff) + acc = acc * alpha[:, None] + if not PRE_LOAD_V: + v = load_fn(v_ptrs, k_offs_n, k_offs_k, actual_seqlen_k, ACTUAL_BLOCK_DMODEL) + # -- update m_i and l_i + l_i = l_i * alpha + l_ij + # update m_i and l_i + m_i = m_ij + + if IS_FP8: + scale_p, descale_p = compute_fp8_scaling_factors(p, FP8_MAX) + acc += (tl.dot((p * scale_p).to(v.type.element_ty), v) * descale_p * descale_v) + else: + acc += tl.dot(p.to(v.type.element_ty), v) + + k_ptrs += BLOCK_N * stride_kn + v_ptrs += BLOCK_N * stride_vk + if bias_ptrs is not None: + bias_ptrs += BLOCK_N * stride_bn + if RETURN_SCORES: + sd_mask_ptrs += BLOCK_N * stride_sn + + if ENABLE_DROPOUT: + dropout_mask_ptrs += BLOCK_N * stride_sn + philox_ptrs += BLOCK_N * stride_sn + return acc, l_i, m_i + + +def get_cdna_autotune_configs(): + return [ + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'waves_per_eu': 2, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 64, 'waves_per_eu': 2, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 64, 'waves_per_eu': 3, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 64, 'waves_per_eu': 1, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + triton.Config({'BLOCK_M': 128, 'BLOCK_N': 32, 'waves_per_eu': 2, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + triton.Config({'BLOCK_M': 64, 'BLOCK_N': 64, 'waves_per_eu': 1, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + # Fall-back config. + triton.Config({'BLOCK_M': 16, 'BLOCK_N': 16, 'waves_per_eu': 1, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=4), + ], ['IS_CAUSAL', 'dropout_p', 'MAX_SEQLENS_Q', 'MAX_SEQLENS_K', 'ACTUAL_BLOCK_DMODEL', 'IS_VARLEN', 'HQ', 'HK'] + + +def get_rdna_autotune_configs(): + return [ + triton.Config({'BLOCK_M': 32, 'BLOCK_N': 32, 'waves_per_eu': 4, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=2), + triton.Config({'BLOCK_M': 32, 'BLOCK_N': 32, 'waves_per_eu': 2, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=2), + triton.Config({'BLOCK_M': 32, 'BLOCK_N': 16, 'waves_per_eu': 4, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=2), + triton.Config({'BLOCK_M': 32, 'BLOCK_N': 16, 'waves_per_eu': 2, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=2), + triton.Config({'BLOCK_M': 16, 'BLOCK_N': 16, 'waves_per_eu': 4, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=2), + triton.Config({'BLOCK_M': 16, 'BLOCK_N': 16, 'waves_per_eu': 2, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=2), + # Fall-back config. + triton.Config({'BLOCK_M': 16, 'BLOCK_N': 16, 'waves_per_eu': 1, 'PRE_LOAD_V': False}, num_stages=1, + num_warps=2), + ], ['IS_CAUSAL', 'dropout_p', 'MAX_SEQLENS_Q', 'MAX_SEQLENS_K', 'ACTUAL_BLOCK_DMODEL', 'IS_VARLEN', 'HQ', 'HK'] + + +def get_autotune_configs(): + if AUTOTUNE: + if is_rdna(): + return get_rdna_autotune_configs() + elif is_cdna(): + return get_cdna_autotune_configs() + else: + raise ValueError("Unknown Device Type") + else: + return [ + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 64, "waves_per_eu": 1, "PRE_LOAD_V": False}, + num_stages=1, + num_warps=4, + ), + ], [ + "IS_CAUSAL", + "dropout_p", + "MAX_SEQLENS_Q", + "MAX_SEQLENS_K", + "ACTUAL_BLOCK_DMODEL", + "IS_VARLEN", + "HQ", + "HK", + ] + + +autotune_configs, autotune_keys = get_autotune_configs() + +@triton.autotune( + configs=autotune_configs, + key=autotune_keys, + use_cuda_graph=True, +) +@triton.jit +def attn_fwd(Q, K, V, bias, Cache_seqlens, Cache_batch_idx, + Descale_Q, Descale_K, Descale_V, Descale_O, stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_o_z, + SM_SCALE: tl.constexpr, LSE, Out, stride_qz, stride_qh, stride_qm, stride_qk, + stride_kz, stride_kh, stride_kn, stride_kk, stride_vz, stride_vh, stride_vk, stride_vn, + stride_oz, stride_oh, stride_om, stride_on, stride_bz, stride_bh, stride_bm, stride_bn, stride_az, stride_ah, + stride_sz, stride_sh, stride_sm, stride_sn, stride_lse_z, stride_lse_h, stride_lse_m, cu_seqlens_q, cu_seqlens_k, + dropout_p, philox_seed, philox_offset_base, sd_mask, dropout_mask, alibi_slopes, HQ: tl.constexpr, + HK: tl.constexpr, ACTUAL_BLOCK_DMODEL: tl.constexpr, MAX_SEQLENS_Q: tl.constexpr, + MAX_SEQLENS_K: tl.constexpr, IS_VARLEN: tl.constexpr, IS_INFERENCE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_M: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, BLOCK_N: tl.constexpr, PRE_LOAD_V: tl.constexpr, USE_BIAS: tl.constexpr, + ENABLE_DROPOUT: tl.constexpr, RETURN_SCORES: tl.constexpr, USE_ALIBI: tl.constexpr, USE_EXP2: tl.constexpr, + IS_FP8: tl.constexpr, FP8_MAX: tl.constexpr, FP8_OUTPUT: tl.constexpr): + # set params + ACCUMULATOR_TYPE = tl.float32 + + # compute offsets + start_m = tl.program_id(0) + off_h_q = tl.program_id(1) + off_z = tl.program_id(2) + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + offs_n = tl.arange(0, BLOCK_N) + offs_d = tl.arange(0, BLOCK_DMODEL) + + # handle seqlen + if IS_VARLEN: + cu_seqlens_q_start = tl.load(cu_seqlens_q + off_z) + cu_seqlens_q_end = tl.load(cu_seqlens_q + off_z + 1) + seqlen_q = cu_seqlens_q_end - cu_seqlens_q_start + + # we have a one-size-fits-all grid in id(0). Some seqlens might be too small for all start_m so for those we return early. + if start_m * BLOCK_M > seqlen_q: + return + cu_seqlens_k_start = tl.load(cu_seqlens_k + off_z) + cu_seqlens_k_end = tl.load(cu_seqlens_k + off_z + 1) + seqlen_k = cu_seqlens_k_end - cu_seqlens_k_start + elif IS_INFERENCE: + cu_seqlens_q_start = 0 + cu_seqlens_k_start = 0 + seqlen_q = MAX_SEQLENS_Q + seqlen_k = tl.load(Cache_seqlens + off_z) + else: + cu_seqlens_q_start = 0 + cu_seqlens_k_start = 0 + seqlen_q = MAX_SEQLENS_Q + seqlen_k = MAX_SEQLENS_K + + # Now we compute whether we need to exit early due to causal masking. + # This is because for seqlen_q > seqlen_k, M rows of the attn scores + # are completely masked, resulting in 0s written to the output, and + # inf written to LSE. We don't need to do any GEMMs in this case. + # This block of code determines what N is, and if this WG is operating + # on those M rows. + n_blocks = tl.cdiv(seqlen_k, BLOCK_N) + if (IS_CAUSAL): + # If seqlen_q == seqlen_k, the attn scores are a square matrix. + # If seqlen_q != seqlen_k, attn scores are rectangular which means + # the causal mask boundary is bottom right aligned, and ends at either + # the top edge (seqlen_q < seqlen_k) or left edge. + # This captures the decrease in n_blocks if we have a rectangular attn matrix + n_blocks_seqlen = tl.cdiv((start_m + 1) * BLOCK_M + seqlen_k - seqlen_q, BLOCK_N) + # This is what adjusts the block_max for the current WG, only + # if IS_CAUSAL. Otherwise we want to always iterate through all n_blocks + n_blocks = min(n_blocks, n_blocks_seqlen) + # If we have no blocks after adjusting for seqlen deltas, this WG is part of + # the blocks that are all 0. We exit early. + if n_blocks <= 0: + o_offset = Out + off_z * stride_oz + off_h_q * stride_oh + cu_seqlens_q_start * stride_om + o_ptrs = o_offset + offs_m[:, None] * stride_om + offs_d[None, :] * stride_on + acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=Out.type.element_ty) + o_ptrs_mask = offs_m[:, None] < seqlen_q + # We still need to write 0s to the result + tl.store(o_ptrs, acc, mask=o_ptrs_mask) + # The tensor allocated for L is based on MAX_SEQLENS_Q as that is + # statically known. + l_offset = LSE + off_z * stride_lse_z + off_h_q * stride_lse_h + cu_seqlens_q_start * stride_lse_m + l_ptrs = l_offset + offs_m * stride_lse_m + + l = tl.full([BLOCK_M], value=0.0, dtype=ACCUMULATOR_TYPE) + + # mask_m_offsets = start_m + tl.arange(0, BLOCK_M) + # lse_mask = mask_m_offsets < causal_start_idx + # softmax_lse = tl.where(lse_mask, 0.0, softmax_lse) + l_ptrs_mask = offs_m < MAX_SEQLENS_Q + tl.store(l_ptrs, l, mask=l_ptrs_mask) + # TODO: Should dropout and return encoded softmax be handled here too? + return + + # If MQA / GQA, set the K and V head offsets appropriately. + GROUP_SIZE: tl.constexpr = HQ // HK + if GROUP_SIZE != 1: + off_h_k = off_h_q // GROUP_SIZE + else: + off_h_k = off_h_q + + n_extra_tokens = 0 + # print("n_extra_tokens:", n_extra_tokens) + # print("seqlen_k:", seqlen_k) + # print("BLOCK_N:", BLOCK_N) + # return + if seqlen_k < BLOCK_N: + n_extra_tokens = BLOCK_N - seqlen_k + elif seqlen_k % BLOCK_N: + n_extra_tokens = seqlen_k % BLOCK_N + PADDED_HEAD: tl.constexpr = (ACTUAL_BLOCK_DMODEL != BLOCK_DMODEL) + + # Compute pointers for all the tensors used in this kernel. + q_offset = Q + off_z * stride_qz + off_h_q * stride_qh + cu_seqlens_q_start * stride_qm + q_ptrs = q_offset + offs_m[:, None] * stride_qm + offs_d[None, :] * stride_qk + k_offset = K + off_z * stride_kz + off_h_k * stride_kh + cu_seqlens_k_start * stride_kn + k_ptrs = k_offset + offs_d[:, None] * stride_kk + offs_n[None, :] * stride_kn + v_offset = V + off_z * stride_vz + off_h_k * stride_vh + cu_seqlens_k_start * stride_vk + v_ptrs = v_offset + offs_n[:, None] * stride_vk + offs_d[None, :] * stride_vn + if USE_BIAS: + # Note: this might get large enough to overflow on some configs + bias_offset = off_h_q * stride_bh + bias_ptrs = bias + bias_offset + offs_m[:, None] * stride_bm + offs_n[None, :] * stride_bn + else: + bias_ptrs = None + + if USE_ALIBI: + a_offset = off_z * stride_az + off_h_q * stride_ah + alibi_slope = tl.load(alibi_slopes + a_offset) + else: + alibi_slope = None + + if RETURN_SCORES: + sd_mask_offset = sd_mask + off_z * stride_sz + off_h_q * stride_sh #+ cu_seqlens_q_start * stride_sm + sd_mask_ptrs = sd_mask_offset + offs_m[:, None] * stride_sm + offs_n[None, :] * stride_sn + else: + sd_mask_ptrs = None + + if ENABLE_DROPOUT: + dropout_mask_offset = dropout_mask + off_z * stride_sz + off_h_q * stride_sh #+ cu_seqlens_q_start * stride_sm + dropout_mask_ptrs = dropout_mask_offset + offs_m[:, None] * stride_sm + offs_n[None, :] * stride_sn + batch_philox_offset = philox_offset_base + off_z * stride_sz + off_h_q * stride_sh #+ cu_seqlens_q_start * stride_sm + philox_ptrs = batch_philox_offset + offs_m[:, None] * stride_sm + offs_n[None, :] * stride_sn + else: + dropout_mask_ptrs = None + philox_ptrs = 0 + # initialize pointer to m and l + m_i = tl.full([BLOCK_M], float("-inf"), dtype=ACCUMULATOR_TYPE) + l_i = tl.full([BLOCK_M], 1.0, dtype=ACCUMULATOR_TYPE) + acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=ACCUMULATOR_TYPE) + # Q is loaded once at the beginning and shared by all N blocks. + q_ptrs_mask = offs_m[:, None] < seqlen_q + if PADDED_HEAD: + q_ptrs_mask = q_ptrs_mask & (offs_d[None, :] < ACTUAL_BLOCK_DMODEL) + q = tl.load(q_ptrs, mask=q_ptrs_mask, other=0.0) + + # Load scale factors if IS_FP8. + if IS_FP8: + descale_q = tl.load(Descale_Q + off_z * stride_descale_q_z + off_h_q) + descale_k = tl.load(Descale_K + off_z * stride_descale_k_z + off_h_k) + descale_v = tl.load(Descale_V + off_z * stride_descale_v_z + off_h_k) + else: + descale_q, descale_k, descale_v = 1.0, 1.0, 1.0 + + # Here we compute how many full and masked blocks we have. + padded_block_k = n_extra_tokens != 0 + is_modulo_mn = not padded_block_k and (seqlen_q % BLOCK_M == 0) + if IS_CAUSAL: + # There are always at least BLOCK_M // BLOCK_N masked blocks. + # Additionally there might be one more due to dissimilar seqlens. + masked_blocks = BLOCK_M // BLOCK_N + (not is_modulo_mn) + else: + # Padding on Q does not need to be masked in the FA loop. + masked_blocks = padded_block_k + # if IS_CAUSAL, not is_modulo_mn does not always result in an additional block. + # In this case we might exceed n_blocks so pick the min. + masked_blocks = min(masked_blocks, n_blocks) + n_full_blocks = n_blocks - masked_blocks + block_min = 0 + block_max = n_blocks * BLOCK_N + # Compute for full blocks. Here we set causal to false regardless of its actual + # value because there is no masking. Similarly we do not need padding. + if n_full_blocks > 0: + block_max = (n_blocks - masked_blocks) * BLOCK_N + acc, l_i, m_i = _attn_fwd_inner(acc, l_i, m_i, q, k_ptrs, v_ptrs, bias_ptrs, stride_kn, stride_vk, stride_bn, stride_sn, + start_m, seqlen_k, seqlen_q, dropout_p, philox_seed, philox_ptrs, + sd_mask_ptrs, dropout_mask_ptrs, + # _, _, offs_n_causal, masked_blocks, n_extra_tokens, _ + block_min, block_max, 0, 0, 0, alibi_slope, + descale_q, descale_k, descale_v, IS_FP8, FP8_MAX, + # IS_CAUSAL, .... + False, BLOCK_M, BLOCK_DMODEL, BLOCK_N, offs_m, offs_n, + # _, MASK_STEPS, ... + PRE_LOAD_V, False, ENABLE_DROPOUT, PADDED_HEAD, + ACTUAL_BLOCK_DMODEL, SM_SCALE, USE_ALIBI=USE_ALIBI, USE_EXP2=USE_EXP2, RETURN_SCORES=RETURN_SCORES, ACCUMULATOR_TYPE=ACCUMULATOR_TYPE) + block_min = block_max + block_max = n_blocks * BLOCK_N + + tl.debug_barrier() + # Remaining blocks, if any, are full / not masked. + if (masked_blocks > 0): + if IS_CAUSAL: + offs_n_causal = offs_n + (seqlen_q - seqlen_k) + else: + offs_n_causal = 0 + k_ptrs += n_full_blocks * BLOCK_N * stride_kn + v_ptrs += n_full_blocks * BLOCK_N * stride_vk + if USE_BIAS: + bias_ptrs += n_full_blocks * BLOCK_N * stride_bn + if RETURN_SCORES: + sd_mask_ptrs += n_full_blocks * BLOCK_N * stride_sn + if ENABLE_DROPOUT: + dropout_mask_ptrs += n_full_blocks * BLOCK_N * stride_sn + philox_ptrs += n_full_blocks * BLOCK_N * stride_sn + acc, l_i, m_i = _attn_fwd_inner(acc, l_i, m_i, q, k_ptrs, v_ptrs, bias_ptrs, stride_kn, stride_vk, stride_bn, stride_sn, + start_m, seqlen_k, seqlen_q, dropout_p, philox_seed, philox_ptrs, + sd_mask_ptrs, dropout_mask_ptrs, block_min, block_max, offs_n_causal, masked_blocks, + n_extra_tokens, alibi_slope, descale_q, descale_k, descale_v, IS_FP8, FP8_MAX, + IS_CAUSAL, BLOCK_M, BLOCK_DMODEL, BLOCK_N, offs_m, offs_n, + # _, MASK_STEPS, ... + PRE_LOAD_V, True, ENABLE_DROPOUT, PADDED_HEAD, + ACTUAL_BLOCK_DMODEL, SM_SCALE, USE_ALIBI=USE_ALIBI, USE_EXP2=USE_EXP2, RETURN_SCORES=RETURN_SCORES, ACCUMULATOR_TYPE=ACCUMULATOR_TYPE) + # epilogue + # This helps the compiler do Newton Raphson on l_i vs on acc which is much larger. + l_recip = 1 / l_i[:, None] + acc = acc * l_recip + if ENABLE_DROPOUT: + dropout_scale = 1 / (1 - dropout_p) + acc = acc * dropout_scale + # If seqlen_q > seqlen_k but the delta is not a multiple of BLOCK_M, + # then we have one block with a row of all NaNs which come from computing + # softmax over a row of all -infs (-inf - inf = NaN). We check for that here + # and store 0s where there are NaNs as these rows should've been zeroed out. + end_m_idx = (start_m + 1) * BLOCK_M + start_m_idx = start_m * BLOCK_M + causal_start_idx = seqlen_q - seqlen_k + if IS_CAUSAL: + if causal_start_idx > start_m_idx and causal_start_idx < end_m_idx: + out_mask_boundary = tl.full((BLOCK_DMODEL, ), causal_start_idx, dtype=tl.int32) + mask_m_offsets = start_m_idx + tl.arange(0, BLOCK_M) + out_ptrs_mask = mask_m_offsets[:, None] >= out_mask_boundary[None, :] + z = 0.0 + acc = tl.where(out_ptrs_mask, acc, z.to(acc.type.element_ty)) + + # write back LSE(Log Sum Exponents), the log of the normalization constant + l_offset = LSE + off_z * stride_lse_z + off_h_q * stride_lse_h + cu_seqlens_q_start * stride_lse_m + l_ptrs = l_offset + offs_m * stride_lse_m + if USE_EXP2: + RCP_LN2: tl.constexpr = 1.4426950408889634 + LN2: tl.constexpr = 0.6931471824645996 + # compute log-sum-exp in base 2 units + mi_base2 = m_i * RCP_LN2 + softmax_lse = mi_base2 + tl.math.log2(l_i) + # convert back to natural units + softmax_lse *= LN2 + else: + softmax_lse = m_i + tl.math.log(l_i) + + if IS_CAUSAL: + # zero out nans caused by -infs when doing causal + lse_mask = (start_m_idx + tl.arange(0, BLOCK_M)) < causal_start_idx + softmax_lse = tl.where(lse_mask, 0.0, softmax_lse) + + # If seqlen_q not multiple of BLOCK_M, we need to mask out the last few rows. + # This is only true for the last M block. For others, overflow_size will be -ve + overflow_size = end_m_idx - seqlen_q + if overflow_size > 0: + boundary = tl.full((BLOCK_M, ), BLOCK_M - overflow_size, dtype=tl.int32) + l_ptrs_mask = tl.arange(0, BLOCK_M) < boundary + tl.store(l_ptrs, softmax_lse, mask=l_ptrs_mask) # the log of the normalization constant + else: + tl.store(l_ptrs, softmax_lse) # the log of the normalization constant + + # write back O + o_offset = Out + off_z * stride_oz + off_h_q * stride_oh + cu_seqlens_q_start * stride_om + o_ptrs = o_offset + offs_m[:, None] * stride_om + offs_d[None, :] * stride_on + o_ptrs_mask = tl.full([BLOCK_M, BLOCK_DMODEL], 1, dtype=tl.int1) + if overflow_size > 0: + o_ptrs_mask = o_ptrs_mask & (offs_m[:, None] < seqlen_q) + if PADDED_HEAD: + o_ptrs_mask = o_ptrs_mask & (offs_d[None, :] < ACTUAL_BLOCK_DMODEL) + + if FP8_OUTPUT: + scale_acc, descale_acc = compute_fp8_scaling_factors(acc, FP8_MAX) + tl.store(Descale_O + off_z * stride_descale_o_z + off_h_q, descale_acc) + tl.store(o_ptrs, (acc * scale_acc).to(Out.type.element_ty), mask=o_ptrs_mask) + else: + tl.store(o_ptrs, acc.to(Out.dtype.element_ty), mask=o_ptrs_mask) + + +def attention_prefill_forward_triton_impl( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + o: torch.Tensor, + sm_scale: float, + alibi_slopes: Optional[torch.Tensor], + causal: bool, + bias: Optional[torch.Tensor], + layout: Literal["bshd", "bhsd", "thd"], + # varlen + cu_seqlens_q: Optional[torch.Tensor], + cu_seqlens_k: Optional[torch.Tensor], + max_seqlens_q: int, + max_seqlens_k: int, + # inference + cache_seqlens: Optional[Union[(int, torch.Tensor)]], + cache_batch_idx: Optional[torch.Tensor], + # dropout + dropout_p: float, + philox_seed: Optional[int], + philox_offset: Optional[int], + # misc + return_softmax: bool, + use_exp2: bool, + # fp8 + descale_q: Optional[torch.Tensor], + descale_k: Optional[torch.Tensor], + descale_v: Optional[torch.Tensor], + descale_o: Optional[torch.Tensor], +): + IS_FP8 = is_fp8(q) + if IS_FP8: + FP8_MAX: tl.constexpr = torch.finfo(q.dtype).max + + assert is_fp8(q) and is_fp8(k) and is_fp8(v), f"Non fp8 type found: q.dtype={q.dtype}, k.dtype={k.dtype}, v.dtype={v.dtype}. All tensors must be fp8." + + if is_fp8(o): + FP8_OUTPUT = True + assert descale_o is not None, f"descale_o is None. In fp8, you need to pass a tensor for descale_o along with a tensor for the output." + else: + FP8_OUTPUT = False + + # Get strides for the kernel + stride_descale_q_z = descale_q.stride(0) if descale_q is not None else None + stride_descale_k_z = descale_k.stride(0) if descale_k is not None else None + stride_descale_v_z = descale_v.stride(0) if descale_v is not None else None + stride_descale_o_z = descale_o.stride(0) if descale_o is not None else None + else: + FP8_MAX = None + FP8_OUTPUT = False + descale_q = descale_k = descale_v = descale_o = None + stride_descale_q_z = stride_descale_k_z = stride_descale_v_z = stride_descale_o_z = None + + # check flags + is_varlen = layout == "thd" + use_alibi, (stride_az, stride_ah) = (True, alibi_slopes.stride()) if alibi_slopes is not None else (False, (0, 0)) + is_inference = False if cache_seqlens is None else True + if is_inference: + assert layout == "bshd", f"{layout} layout is not supported with inference. Use bshd layout" + if DEBUG: + print(f"is_inference:", is_inference) + + # NOTE: a large bias tensor leads to overflow during pointer arithmetic + if (bias is not None): + assert (bias.numel() < 2**31) + + batch, nheads_q, nheads_k, head_size, seqlen_q, seqlen_k = get_shapes_from_layout(q, k, layout, cu_seqlens_q, cu_seqlens_k, max_seqlens_q, max_seqlens_k) + q_strides, k_strides, v_strides, o_strides = get_strides_from_layout(q, k, v, o, layout) + + # Get closest power of 2 over or equal to 32. + padded_d_model = 1 << (head_size - 1).bit_length() + # Smallest head_dim supported is 16. If smaller, the tile in the + # kernel is padded - there is no padding in memory for any dims. + padded_d_model = max(padded_d_model, 16) + + grid = lambda META: (triton.cdiv(max_seqlens_q, META['BLOCK_M']), nheads_q, batch) + + # sd_mask is used to validate dropout behavior vs the PyTorch SDPA math backend reference. We zero this out + # to give a consistent starting point and then populate it with the output of softmax with the sign bit set according + # to the dropout mask. The resulting return allows this mask to be fed into the reference implementation for testing + # only. This return holds no useful output aside from debugging. + use_dropout = (dropout_p > 0.0) + if use_dropout or return_softmax: + sd_mask = torch.zeros((batch, nheads_q, max_seqlens_q, max_seqlens_k), device=q.device, + dtype=torch.float32) + if DROPOUT_USE_PYTORCH: + dropout_mask = create_dropout_mask(dropout_p, (batch, nheads_q, max_seqlens_q, max_seqlens_k), seed = philox_seed) + else: + dropout_mask = torch.zeros((batch, nheads_q, max_seqlens_q, max_seqlens_k), device=q.device, + dtype=torch.float32) + scores_strides = (sd_mask.stride(0), sd_mask.stride(1), sd_mask.stride(2), sd_mask.stride(3)) + else: + sd_mask = None + dropout_mask = None + scores_strides = (0, 0, 0, 0) + + # stores LSE the log of the normalization constant / sum of expoential score(unnormalzied probablities) + if is_varlen: + softmax_lse = torch.zeros((q.shape[0], nheads_q), device=q.device, dtype=torch.float32) + stride_lse_m, stride_lse_h = softmax_lse.stride() + stride_lse_z = 0 + else: + softmax_lse = torch.zeros((batch, nheads_q, max_seqlens_q), device=q.device, dtype=torch.float32) + stride_lse_z, stride_lse_h, stride_lse_m = softmax_lse.stride() + + if bias is not None: + bias_strides = (bias.stride(0), bias.stride(1),bias.stride(2), + bias.stride(3)) + else: + bias_strides = (0, 0, 0, 0) + + attn_fwd[grid](q, k, v, bias, cache_seqlens, cache_batch_idx, + descale_q, descale_k, descale_v, descale_o, stride_descale_q_z, stride_descale_k_z, stride_descale_v_z, stride_descale_o_z, + sm_scale, softmax_lse, o, *q_strides, *k_strides, *v_strides, *o_strides, + *bias_strides, stride_az, stride_ah, *scores_strides, stride_lse_z, stride_lse_h, stride_lse_m, cu_seqlens_q, cu_seqlens_k, + dropout_p=dropout_p, philox_seed=philox_seed, philox_offset_base=philox_offset, sd_mask=sd_mask, dropout_mask=dropout_mask, alibi_slopes=alibi_slopes, + HQ=nheads_q, HK=nheads_k, ACTUAL_BLOCK_DMODEL=head_size, MAX_SEQLENS_Q=max_seqlens_q, + MAX_SEQLENS_K=max_seqlens_k, IS_CAUSAL=causal, IS_VARLEN=is_varlen, IS_INFERENCE=is_inference, + BLOCK_DMODEL=padded_d_model, USE_BIAS=False if bias is None else True, + USE_ALIBI=use_alibi, ENABLE_DROPOUT=dropout_p + > 0.0, USE_EXP2=use_exp2, RETURN_SCORES=return_softmax, IS_FP8=IS_FP8, FP8_MAX=FP8_MAX, FP8_OUTPUT=FP8_OUTPUT) + + return softmax_lse, sd_mask if return_softmax else None diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/fwd_ref.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/fwd_ref.py new file mode 100644 index 0000000000000000000000000000000000000000..baefb2410c1105352ed934b1dfcc653f37f5036b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/fwd_ref.py @@ -0,0 +1,387 @@ +import torch +import math +from typing import Literal, Optional +from .utils import DEBUG, compute_alibi_tensor_ref + +DEBUG_CORE = False + +def attention_forward_core_ref_impl(q, k, v, sm_scale, causal, dropout_p, philox_seed, philox_offset, alibi_slopes, use_exp2): + if DEBUG_CORE: + print() + print("attention_forward_core_ref_impl") + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("sm_scale:", sm_scale) + print("causal:", causal) + print("dropout_p:", dropout_p) + print("philox_seed:", philox_seed) + print("philox_offset:", philox_offset) + print("use_exp2:", use_exp2) + + # cast to float32 + q = q.to(torch.float32) + k = k.to(torch.float32) + v = v.to(torch.float32) + + # Compute attention scores + attention_scores = torch.matmul(q, k.transpose(-2, -1)) + if DEBUG_CORE: + print("attention_scores:", attention_scores, attention_scores.shape) + + # Scale scores + attention_scaled_scores = sm_scale * attention_scores + if DEBUG_CORE: + print("attention_scaled_scores:", attention_scaled_scores, attention_scaled_scores.shape) + + # Apply ALiBi if slopes are provided + if alibi_slopes is not None: + L_q, L_k = q.shape[1], k.shape[1] + if DEBUG_CORE: + print("alibi_slopes:", alibi_slopes, alibi_slopes.shape) + alibi_bias = compute_alibi_tensor_ref(alibi_slopes, L_q, L_k) + if DEBUG_CORE: + print("alibi_bias:", alibi_bias, alibi_bias.shape) + alibi_bias = alibi_bias.reshape(-1, L_q, L_k) + if DEBUG_CORE: + print("alibi_bias_flat:", alibi_bias, alibi_bias.shape) + attention_scaled_scores = attention_scaled_scores + alibi_bias + if DEBUG_CORE: + print("attention_scaled_scores after alibi:", attention_scaled_scores, attention_scaled_scores.shape) + + + # Apply causal mask if necessary + if causal: + L_q, L_k = q.shape[1], k.shape[1] + row_idx = torch.arange(L_q, device=q.device).unsqueeze(1) + col_idx = torch.arange(L_k, device=q.device).unsqueeze(0) + col_offset = L_q-L_k + causal_mask = row_idx >= (col_offset + col_idx) + if DEBUG_CORE: + print("causal_mask:", causal_mask) + # set -inf to places the causal mask is false + attention_scaled_scores = attention_scaled_scores.masked_fill( + torch.logical_not(causal_mask.unsqueeze(0)), float('-inf') + ) + if DEBUG_CORE: + print("attention_scaled_scores after causal:", attention_scaled_scores, attention_scaled_scores.shape) + + # Compute max for numerical stability + max_scores = torch.max(attention_scaled_scores, dim=-1, keepdim=True)[0] + if DEBUG_CORE: + print("max_scores:", max_scores, max_scores.shape) + if causal: + # Replace -inf in max_scores with zeros to avoid NaN in subtraction + max_scores = torch.where( + torch.isinf(max_scores), torch.zeros_like(max_scores), max_scores + ) + if DEBUG: + print("max_scores if causal:", max_scores, max_scores.shape) + + # Shift scores + attention_shifted_scaled_scores = attention_scaled_scores - max_scores + if DEBUG_CORE: + print("attention_shifted_scaled_scores:", attention_shifted_scaled_scores, attention_shifted_scaled_scores.shape) + + # Exponentiate + if use_exp2: + RCP_LN = 1 / math.log(2) + exp_scores = torch.exp2(RCP_LN * attention_shifted_scaled_scores) + else: + exp_scores = torch.exp(attention_shifted_scaled_scores) + + if DEBUG_CORE: + print("exp_scores:", exp_scores, exp_scores.shape) + + # Sum of exponentials + sum_exp_scores = torch.sum(exp_scores, dim=-1, keepdim=True) + if DEBUG_CORE: + print("sum_exp_scores:", sum_exp_scores, sum_exp_scores.shape) + if causal: + # if sum of exp scores is 0.0 it means scores where -inf, we cannot compute softmax and softmax_lse. Setting to 1 deals with -inf case cleanly + sum_exp_scores = torch.where( + sum_exp_scores == 0, + torch.ones_like(sum_exp_scores), + sum_exp_scores + ) + if DEBUG_CORE: + print("sum_exp_scores:", sum_exp_scores, sum_exp_scores.shape) + + # Compute softmax probabilities + p = exp_scores / sum_exp_scores + + if DEBUG_CORE: + print("softmax:", p, p.shape) + + # apply dropout if specified + if dropout_p > 0.0: + rand_vals = torch.rand(p.shape, generator=torch.Generator(device=p.device).manual_seed(philox_seed), device=p.device, dtype=p.dtype) + dropout_mask, dropout_scale = rand_vals > dropout_p, (1.0 / (1 - dropout_p)) + if DEBUG_CORE: + print("dropout_scale:", dropout_scale) + print("dropout_mask:", dropout_mask) + # Apply dropout mask and scale + # Set -1 for dropped positions and 1 for kept positions in exp_scores + sd_mask = torch.where(dropout_mask, exp_scores, -exp_scores) + p = torch.where(dropout_mask, p , torch.zeros_like(p)) * dropout_scale + if DEBUG_CORE: + print("softmax after dropout:", p) + print("sd_mask:", sd_mask) + else: + sd_mask = exp_scores + + # Compute log-sum-exp + if use_exp2: + LN2 = math.log(2) + RCP_LN = 1 / math.log(2) + max_scores_base2 = max_scores * RCP_LN + softmax_lse_base2 = max_scores_base2 + torch.log2(sum_exp_scores) + softmax_lse = softmax_lse_base2 * LN2 + softmax_lse.squeeze_(-1) + else: + softmax_lse = max_scores + torch.log(sum_exp_scores) + softmax_lse = softmax_lse.squeeze(-1) + + if DEBUG_CORE: + print("softmax_lse:", softmax_lse, softmax_lse.shape) + + # Compute output + o = torch.matmul(p, v) + if DEBUG_CORE: + print("o:", o, o.shape) + + # cast back to original dtype + o = o.to(torch.float16) + # softmax_lse = softmax_lse.to(torch.float16) # NOTE: if you cast lse to fp16 it cause accuracy issues. keep fp32 + sd_mask = sd_mask.to(torch.float16) + + return o, softmax_lse, sd_mask + +def attention_vanilla_forward_pytorch_ref_impl(q, k, v, sm_scale, causal, layout, dropout_p, philox_seed, philox_offset, alibi_slopes, use_exp2): + """Compute reference output and softmax_lse using PyTorch's built-in function""" + + # Ensure the layout is 'bhsd' + if layout == "bshd": + q = q.transpose(1, 2).contiguous() + k = k.transpose(1, 2).contiguous() + v = v.transpose(1, 2).contiguous() + elif layout != "bhsd": + raise ValueError(f"Unknown layout {layout}") + + # Prepare tensors + batch_size, nheads_q, seq_len_q, head_dim = q.shape + batch_size, nheads_k, seq_len_k, head_dim = k.shape + group_size = nheads_q // nheads_k + if nheads_q % nheads_k != 0: + raise ValueError("nheads_q must be divisible by nheads_k") + + if group_size != 1: + # MQA or GQA case + # Reshape q to [batch_size, nheads_k, group_size, seq_len_q, head_dim] + q = q.reshape(batch_size, nheads_k, group_size, seq_len_q, head_dim) + # Expand k and v to match group_size + k = k.unsqueeze(2).expand(-1, -1, group_size, -1, -1) + v = v.unsqueeze(2).expand(-1, -1, group_size, -1, -1) + # Flatten the first three dimensions for computation + q = q.reshape(batch_size * nheads_k * group_size, seq_len_q, head_dim) + k = k.reshape(batch_size * nheads_k * group_size, seq_len_k, head_dim) + v = v.reshape(batch_size * nheads_k * group_size, seq_len_k, head_dim) + else: + q = q.reshape(batch_size * nheads_q, seq_len_q, head_dim) + k = k.reshape(batch_size * nheads_k, seq_len_k, head_dim) + v = v.reshape(batch_size * nheads_k, seq_len_k, head_dim) + + # Call the core attention function + o, softmax_lse, sd_mask = attention_forward_core_ref_impl( + q, k, v, sm_scale, causal, dropout_p, philox_seed, philox_offset, alibi_slopes, use_exp2 + ) + + if group_size != 1: + # Reshape outputs back to original dimensions + o = o.reshape(batch_size, nheads_k, group_size, seq_len_q, head_dim) + o = o.reshape(batch_size, nheads_q, seq_len_q, head_dim) + softmax_lse = softmax_lse.reshape(batch_size, nheads_k, group_size, seq_len_q) + softmax_lse = softmax_lse.reshape(batch_size, nheads_q, seq_len_q) + sd_mask = sd_mask.reshape(batch_size, nheads_k, group_size, seq_len_q, seq_len_k) + sd_mask = sd_mask.reshape(batch_size, nheads_q, seq_len_q, seq_len_k) + else: + # Standard case + o = o.reshape(batch_size, nheads_q, seq_len_q, head_dim) + softmax_lse = softmax_lse.reshape(batch_size, nheads_q, seq_len_q) + sd_mask = sd_mask.reshape(batch_size, nheads_q, seq_len_q, seq_len_k) + + # Restore original layout if necessary + if layout == "bshd": + o = o.transpose(1, 2) + + return o, softmax_lse, sd_mask + + +def attention_varlen_forward_pytorch_ref_impl( + q, + k, + v, + sm_scale, + causal, + layout, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + philox_seed, + philox_offset, + alibi_slopes, + use_exp2 +): + # Ensure the layout is 'thd' + if layout != 'thd': + raise ValueError(f"Unsupported layout {layout}. Expected 'thd'.") + + batch_size = cu_seqlens_q.shape[0] - 1 + nheads_q, nheads_k = q.shape[1], k.shape[1] + head_dim = q.shape[2] + + # Pre-allocate outputs + total_L_q = q.shape[0] + total_L_k = k.shape[0] + + o = torch.zeros((total_L_q, nheads_q, head_dim), dtype=q.dtype, device=q.device) + softmax_lse = torch.zeros((total_L_q, nheads_q), dtype=torch.float32, device=q.device) + sd_mask = torch.zeros((batch_size, nheads_q, max_seqlen_q, max_seqlen_k), dtype=torch.float32, device=q.device) + + # Compute group_size for MQA/GQA handling + group_size = nheads_q // nheads_k + if nheads_q % nheads_k != 0: + raise ValueError("nheads_q must be divisible by nheads_k") + + for i in range(batch_size): + # Get the start and end indices for the current sequence + start_q = cu_seqlens_q[i].item() + end_q = cu_seqlens_q[i + 1].item() + start_k = cu_seqlens_k[i].item() + end_k = cu_seqlens_k[i + 1].item() + + seqlen_q = end_q - start_q + seqlen_k = end_k - start_k + + if DEBUG: + print(f"Batch {i} with seqlen_q = {seqlen_q}, seqlen_k = {seqlen_k}, Hq= {nheads_q}, Hk = {nheads_k}") + + # Extract q_i, k_i, v_i + q_i = q[start_q:end_q, :, :] # [L_q_i, nheads_q, head_dim] + k_i = k[start_k:end_k, :, :] # [L_k_i, nheads_k, head_dim] + v_i = v[start_k:end_k, :, :] # [L_k_i, nheads_k, head_dim] + + # Permute to [nheads, L_q_i, head_dim] + q_i = q_i.permute(1, 0, 2) + k_i = k_i.permute(1, 0, 2) + v_i = v_i.permute(1, 0, 2) + + # Handle MQA/GQA by adjusting shapes based on group_size + if group_size != 1: + # Reshape q_i to [nheads_k, group_size, L_q_i, head_dim] + q_i = q_i.reshape(nheads_k, group_size, seqlen_q, head_dim) + # Expand k_i and v_i to match group_size + k_i = k_i.unsqueeze(1).expand(-1, group_size, -1, -1) + v_i = v_i.unsqueeze(1).expand(-1, group_size, -1, -1) + # Flatten the first two dimensions for computation + q_i = q_i.reshape(nheads_k * group_size, seqlen_q, head_dim) + k_i = k_i.reshape(nheads_k * group_size, seqlen_k, head_dim) + v_i = v_i.reshape(nheads_k * group_size, seqlen_k, head_dim) + else: + # Standard case + q_i = q_i.reshape(nheads_q, seqlen_q, head_dim) + k_i = k_i.reshape(nheads_k, seqlen_k, head_dim) + v_i = v_i.reshape(nheads_k, seqlen_k, head_dim) + + if alibi_slopes is not None: + alibi_slopes_i = alibi_slopes[i] + else: + alibi_slopes_i = None + + # Call the core attention function for this sequence + o_i, softmax_lse_i, sd_mask_i = attention_forward_core_ref_impl(q_i, k_i, v_i, sm_scale, causal, dropout_p, philox_seed, philox_offset, alibi_slopes_i, use_exp2) + + # Reshape outputs back to original dimensions + if group_size != 1: + # Reshape outputs to [nheads_k, group_size, seqlen_q, head_dim] + o_i = o_i.reshape(nheads_k, group_size, seqlen_q, head_dim) + # Combine the first two dimensions back to nheads_q + o_i = o_i.reshape(nheads_q, seqlen_q, head_dim) + # Reshape softmax_lse_i similarly + softmax_lse_i = softmax_lse_i.reshape(nheads_k, group_size, seqlen_q) + softmax_lse_i = softmax_lse_i.reshape(nheads_q, seqlen_q) + else: + # Outputs are already in the correct shape + pass + + # Convert back to 'thd' layout + o_i = o_i.permute(1, 0, 2) # [L_q_i, nheads_q, head_dim] + softmax_lse_i = softmax_lse_i.permute(1, 0) # [L_q_i, nheads_q] + sd_mask_i = sd_mask_i # [nheads_q, L_q_i, L_k_i] + + # Place outputs in pre-allocated tensors + o[start_q:end_q, :, :] = o_i + softmax_lse[start_q:end_q, :] = softmax_lse_i + sd_mask[i, :, :seqlen_q, :seqlen_k] = sd_mask_i + + return o, softmax_lse, sd_mask + + + +def attention_forward_pytorch_ref_impl( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + out: torch.Tensor, + sm_scale: float, + alibi_slopes: Optional[torch.Tensor], + causal: bool, + layout: Literal["bshd", "bhsd", "thd"], + cu_seqlens_q: torch.Tensor, + cu_seqlens_k: torch.Tensor, + max_seqlen_q: int, + max_seqlen_k: int, + dropout_p: float, + philox_seed: Optional[int], + philox_offset: Optional[int], + use_exp2: bool +): + # compute reference + if layout == "thd": + o_ref, softmax_lse_ref, sd_mask_ref = attention_varlen_forward_pytorch_ref_impl( + q.clone(), + k.clone(), + v.clone(), + sm_scale, + causal, + layout, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + philox_seed, + philox_offset, + alibi_slopes, + use_exp2, + ) + else: + o_ref, softmax_lse_ref, sd_mask_ref = attention_vanilla_forward_pytorch_ref_impl( + q.clone(), + k.clone(), + v.clone(), + sm_scale, + causal, + layout, + dropout_p, + philox_seed, + philox_offset, + alibi_slopes, + use_exp2) + + # copy back to ouput tensor + out.copy_(o_ref.to(out.dtype)) + + return softmax_lse_ref, sd_mask_ref diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/interface_fa.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/interface_fa.py new file mode 100644 index 0000000000000000000000000000000000000000..bb6e25b509c7be1ad5e165f527dc6f0963deb329 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/interface_fa.py @@ -0,0 +1,798 @@ +import torch +import os +from .fwd_prefill import attention_prefill_forward_triton_impl +from .bwd_prefill import attention_prefill_backward_triton_impl +from .bwd_prefill_split import attention_prefill_backward_triton_split_impl +from .bwd_prefill_fused import _flash_attn_backward as attention_prefill_backward_triton_fused_impl +from .bwd_prefill_onekernel import attention_prefill_backward_triton_split_oneKernel_impl +from .fwd_decode import attention_decode_forward_triton_impl +from .fwd_ref import attention_forward_pytorch_ref_impl +from .bwd_ref import attention_backward_pytorch_ref_impl +from .utils import DEBUG, USE_REF, MetaData, get_shapes_from_layout, is_fp8 +from einops import rearrange, repeat +from flash_attn.layers.rotary import apply_rotary_emb +from typing import Literal, Optional, Union + +def fwd(q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + out: Optional[torch.Tensor], + alibi_slopes: Optional[torch.Tensor], + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int, + window_size_right: int, + softcap: float, + return_softmax: bool, + gen_: Optional[torch.Tensor] = None, + descale_q: Optional[torch.Tensor] = None, + descale_k: Optional[torch.Tensor] = None, + descale_v: Optional[torch.Tensor] = None, + descale_o: Optional[torch.Tensor] = None + ): + + if DEBUG: + print() + print("flash_attn_triton_amd.py::fwd inputs") + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("out:", out, out.shape if out is not None else None) + print("alibi_slopes:", alibi_slopes) + print("dropout_p:", dropout_p) + print("softmax_scale:", softmax_scale) + print("causal:", causal) + print("window_size_left:", window_size_left) + print("window_size_right:", window_size_right) + print("softcap:", softcap) + print("return_softmax:", return_softmax) + print("descale_q:", descale_q, descale_q.shape if descale_q is not None else None) + print("descale_k:", descale_k, descale_k.shape if descale_k is not None else None) + print("descale_v:", descale_v, descale_v.shape if descale_v is not None else None) + print("descale_o:", descale_o, descale_o.shape if descale_o is not None else None) + + if is_fp8(q): + assert out is not None, "fp8 output tensor should be passed in." + assert (descale_q is not None) and (descale_k is not None) and (descale_v is not None), f"For fp8, you need to pass descale factors for q, k and v" + else: + out = torch.zeros_like(q) if out is None else out.zero_() + + # Setup metadata + metadata = MetaData(sm_scale=softmax_scale) + metadata.max_seqlens_q = q.shape[1] + metadata.max_seqlens_k = k.shape[1] + metadata.layout = "bshd" + if return_softmax: + metadata.return_scores = True + + batch, nheads_q, nheads_k, head_size, _, _ = get_shapes_from_layout(q, k, metadata.layout) + + if causal: + metadata.need_causal(True) + + if alibi_slopes is not None: + metadata.need_alibi(alibi_slopes, batch, nheads_q) + + if dropout_p > 0.0: + metadata.need_dropout(dropout_p) + rng_state = torch.as_tensor([metadata.philox_seed, metadata.philox_offset]) # as_tensors uses the underlying data and doesnot cast + else: + rng_state = None + + # check arguments + metadata.check_args(q, k, v, out) + + # call implementation + if USE_REF: + if DEBUG: + print("Using reference implementation") + softmax_lse_ref, sd_mask_ref = attention_forward_pytorch_ref_impl( + q, + k, + v, + out, + metadata.sm_scale, + metadata.alibi_slopes, + metadata.causal, + metadata.layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.dropout_p, + metadata.philox_seed, + metadata.philox_offset, + metadata.use_exp2) + softmax_lse=softmax_lse_ref + sd_mask=sd_mask_ref + else: + if DEBUG: + print("Using Triton implementation") + softmax_lse_triton, sd_mask_triton = attention_prefill_forward_triton_impl( + q, + k, + v, + out, + metadata.sm_scale, + metadata.alibi_slopes, + metadata.causal, + None, + metadata.layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.cache_seqlens, + metadata.cache_batch_idx, + metadata.dropout_p, + metadata.philox_seed, + metadata.philox_offset, + metadata.return_scores, + metadata.use_exp2, + descale_q, + descale_k, + descale_v, + descale_o) + softmax_lse=softmax_lse_triton + sd_mask=sd_mask_triton + + if DEBUG: + print("flash_attn_triton_amd.py::fwd outputs") + print("o:", out, out.shape) + if is_fp8(out): + print("descale_o:", descale_o, descale_o.shape if descale_o is not None else None) + print("softmax_lse:", softmax_lse, softmax_lse.shape) + print("sd_mask:", sd_mask, sd_mask.shape if sd_mask is not None else None ) + + return out, softmax_lse, sd_mask, rng_state + +BWD_MODE = os.environ.get('BWD_MODE', 'split').lower() +def bwd( + dout: torch.Tensor, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + out: torch.Tensor, + softmax_lse: torch.Tensor, + dq: Optional[torch.Tensor], + dk: Optional[torch.Tensor], + dv: Optional[torch.Tensor], + alibi_slopes: Optional[torch.Tensor], + dropout_p: float, + softmax_scale: float, + causal: bool, + window_size_left: int, + window_size_right: int, + softcap: float, + deterministic: bool, + gen_: Optional[torch.Tensor] = None, + rng_state:Optional[torch.Tensor] = None, + descale_q: Optional[torch.Tensor] = None, + descale_k: Optional[torch.Tensor] = None, + descale_v: Optional[torch.Tensor] = None, + descale_o: Optional[torch.Tensor] = None, + descale_do: Optional[torch.Tensor] = None, + descale_dq: Optional[torch.Tensor] = None, + descale_dk: Optional[torch.Tensor] = None, + descale_dv: Optional[torch.Tensor] = None, +): + if DEBUG: + print() + print("flash_attn_triton_amd.py::bwd inputs") + print("dout:", dout, dout.shape) + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("out:", out, out.shape) + print("softmax_lse:", softmax_lse, softmax_lse.shape) + print("dq:", dq, dq.shape if dq is not None else None) + print("dk:", dk, dk.shape if dk is not None else None) + print("dv:", dv, dv.shape if dv is not None else None) + print("alibi_slopes:", alibi_slopes) + print("dropout_p:", dropout_p) + print("out:", out) + print("softmax_scale:", softmax_scale) + print("causal:", causal) + print("window_size_left:", window_size_left) + print("window_size_right:", window_size_right) + print("deterministic:", deterministic) + print("gen_:", gen_) + print("rng_state:", rng_state) + print("descale_q:", descale_q, descale_q.shape if descale_q is not None else None) + print("descale_k:", descale_k, descale_k.shape if descale_k is not None else None) + print("descale_v:", descale_v, descale_v.shape if descale_v is not None else None) + print("descale_o:", descale_o, descale_o.shape if descale_o is not None else None) + print("descale_do:", descale_do, descale_do.shape if descale_do is not None else None) + print("descale_dq:", descale_dq, descale_dq.shape if descale_dq is not None else None) + print("descale_dk:", descale_dk, descale_dk.shape if descale_dk is not None else None) + print("descale_dv:", descale_dv, descale_dv.shape if descale_dv is not None else None) + + dq = torch.zeros_like(q) if dq is None else dq.zero_() + dk = torch.zeros_like(k) if dk is None else dk.zero_() + dv = torch.zeros_like(v) if dv is None else dv.zero_() + + if dropout_p > 0.0: + assert rng_state is not None + philox_seed, philox_offset = rng_state[0].item(), rng_state[1].item() + else: + philox_seed, philox_offset = None, None + + # call implementation + if USE_REF: + if DEBUG: + print("Using reference implementation") + + delta_ref = attention_backward_pytorch_ref_impl( + dout, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + softmax_scale, + alibi_slopes, + causal, + "bshd", + None, + None, + None, + None, + dropout_p, + philox_seed, + philox_offset, + False, + ) + delta = delta_ref + else: + if DEBUG: + print("Using Triton implementation") + if BWD_MODE == "split": + delta_triton = attention_prefill_backward_triton_split_impl( + dout, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + softmax_scale, + alibi_slopes, + causal, + "bshd", + None, + None, + None, + None, + dropout_p, + philox_seed, + philox_offset, + False, + descale_q, + descale_k, + descale_v, + descale_o, + descale_do, + descale_dq, + descale_dk, + descale_dv, + ) + delta = delta_triton + elif BWD_MODE == "fused": + delta_triton = attention_prefill_backward_triton_fused_impl( + dout, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + softmax_scale, + alibi_slopes, + causal, + None, + None, + q.shape[1], + k.shape[1], + dropout_p, + philox_seed, + philox_offset, + descale_q, + descale_k, + descale_v, + descale_o, + True, + ) + delta = delta_triton + elif BWD_MODE == "jingning": + delta_triton = attention_prefill_backward_triton_split_oneKernel_impl( + dout, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + softmax_scale, + alibi_slopes, + causal, + "bshd", + None, + None, + None, + None, + dropout_p, + philox_seed, + philox_offset, + False + ) + delta = delta_triton + else: + raise ValueError(f"Unknown bwd mode {BWD_MODE}") + + if DEBUG: + print("flash_attn_triton_amd.py::bwd outputs") + print("dv:", dv, dv.shape) + if is_fp8(dv): + print("descale_dv:", descale_dv, descale_dv.shape if descale_dv is not None else None) + print("dk:", dk, dk.shape) + if is_fp8(dk): + print("descale_dk:", descale_dk, descale_dk.shape if descale_dk is not None else None) + print("dq:", dq, dq.shape) + if is_fp8(dq): + print("descale_dq:", descale_dq, descale_dq.shape if descale_dq is not None else None) + return dq, dk, dv, delta + +def varlen_fwd( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + out: Optional[torch.Tensor], + cu_seqlens_q: torch.Tensor, + cu_seqlens_k: torch.Tensor, + seqused_k: Optional[torch.Tensor], + leftpad_k: Optional[torch.Tensor], + block_table_: Optional[torch.Tensor], + alibi_slopes: Optional[torch.Tensor], + max_seqlen_q: int, + max_seqlen_k: int, + dropout_p: float, + softmax_scale: float, + zero_tensors: bool , + causal: bool , + window_size_left: int, + window_size_right: int, + softcap: float, + return_softmax: bool, + gen_: Optional[torch.Tensor] = None, + descale_q: Optional[torch.Tensor] = None, + descale_k: Optional[torch.Tensor] = None, + descale_v: Optional[torch.Tensor] = None, + descale_o: Optional[torch.Tensor] = None + ): + + if DEBUG: + print() + print("flash_attn_triton_amd.py::varlen_fwd") + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("cu_seqlens_q:", cu_seqlens_q, cu_seqlens_q.shape) + print("cu_seqlens_k:", cu_seqlens_k, cu_seqlens_k.shape) + print("alibi_slopes:", alibi_slopes) + print("max_seqlen_q:", max_seqlen_q) + print("max_seqlen_k:", max_seqlen_k) + print("dropout_p:", dropout_p) + print("softmax_scale:", softmax_scale) + print("causal:", causal) + print("window_size_left:", window_size_left) + print("window_size_right:", window_size_right) + print("gen_:", gen_) + print("descale_q:", descale_q, descale_q.shape if descale_q is not None else None) + print("descale_k:", descale_k, descale_k.shape if descale_k is not None else None) + print("descale_v:", descale_v, descale_v.shape if descale_v is not None else None) + + if is_fp8(q): + assert out is not None, "fp8 output tensor should be passed in." + assert (descale_q is not None) and (descale_k is not None) and (descale_v is not None), f"For fp8, you need to pass descale factors for q, k and v" + else: + out = torch.zeros_like(q) if out is None else out.zero_() + + # Setup metadata + metadata = MetaData(sm_scale=softmax_scale) + if return_softmax: + metadata.return_scores = True + metadata.set_varlen_params(cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k) # set layout to "thd" and other metdata + assert metadata.layout is not None + + # get shapes + batch, nheads_q, nheads_k, head_size , seqlen_q, seqlen_k = get_shapes_from_layout(q, k, metadata.layout, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k) + + if causal: + metadata.need_causal(True) + + if alibi_slopes is not None: + metadata.need_alibi(alibi_slopes, batch, nheads_q) + + if dropout_p > 0.0: + metadata.need_dropout(dropout_p) + rng_state = torch.as_tensor([metadata.philox_seed, metadata.philox_offset]) # as_tensors uses the underlying data and doesnot cast + else: + rng_state = None + + # Check arguments + metadata.check_args(q, k, v, out) + + # call implementation + if USE_REF: + if DEBUG: + print("Using reference implementation") + softmax_lse_ref, sd_mask_ref = attention_forward_pytorch_ref_impl( + q, + k, + v, + out, + metadata.sm_scale, + metadata.alibi_slopes, + metadata.causal, + metadata.layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.dropout_p, + metadata.philox_seed, + metadata.philox_offset, + metadata.use_exp2) + softmax_lse=softmax_lse_ref + sd_mask=sd_mask_ref + else: + if DEBUG: + print("Using Triton implementation") + softmax_lse_triton, sd_mask_triton = attention_prefill_forward_triton_impl( + q, + k, + v, + out, + metadata.sm_scale, + metadata.alibi_slopes, + metadata.causal, + None, + metadata.layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.cache_seqlens, + metadata.cache_batch_idx, + metadata.dropout_p, + metadata.philox_seed, + metadata.philox_offset, + metadata.return_scores, + metadata.use_exp2, + descale_q, + descale_k, + descale_v, + descale_o) + softmax_lse=softmax_lse_triton + sd_mask=sd_mask_triton + + if DEBUG: + print("varlen_fwd outputs") + print("out:", out, out.shape) + print("softmax_lse:", softmax_lse, softmax_lse.shape) + print("sd_mask:", sd_mask, sd_mask.shape if sd_mask is not None else None ) + + + return out, softmax_lse, sd_mask, rng_state + +def varlen_bwd( + dout: torch.Tensor, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + out: torch.Tensor, + softmax_lse: torch.Tensor, + dq: Optional[torch.Tensor], + dk: Optional[torch.Tensor], + dv: Optional[torch.Tensor], + cu_seqlens_q: torch.Tensor, + cu_seqlens_k: torch.Tensor, + alibi_slopes: Optional[torch.Tensor], + max_seqlen_q: int, + max_seqlen_k: int, + dropout_p: float, + softmax_scale: float, + zero_tensors: bool, + causal: bool, + window_size_left: int, + window_size_right: int, + softcap: float, + deterministic: bool, + gen_ : Optional[torch.Tensor] = None, + rng_state: Optional[torch.Tensor] = None, + descale_q: Optional[torch.Tensor] = None, + descale_k: Optional[torch.Tensor] = None, + descale_v: Optional[torch.Tensor] = None, + descale_o: Optional[torch.Tensor] = None, + descale_do: Optional[torch.Tensor] = None, + descale_dq: Optional[torch.Tensor] = None, + descale_dk: Optional[torch.Tensor] = None, + descale_dv: Optional[torch.Tensor] = None, +): + if DEBUG: + print() + print("varlen_bwd") + print("dout:", dout, dout.shape) + print("q:", q, q.shape) + print("k:", k, k.shape) + print("v:", v, v.shape) + print("out:", out) + print("softmax_lse:", softmax_lse, softmax_lse.shape) + print("dq:", dq, dq.shape if dq is not None else None) + print("dk:", dk, dk.shape if dk is not None else None) + print("dv:", dv, dv.shape if dv is not None else None) + print("cu_seqlens_q:", cu_seqlens_q, cu_seqlens_q.shape) + print("cu_seqlens_k:", cu_seqlens_k, cu_seqlens_k.shape) + print("alibi_slopes:", alibi_slopes) + print("max_seqlen_q:", max_seqlen_q) + print("max_seqlen_k:", max_seqlen_k) + print("dropout_p:", dropout_p) + print("softmax_scale:", softmax_scale) + print("causal:", causal) + print("window_size_left:", window_size_left) + print("window_size_right:", window_size_right) + print("deterministic:", deterministic) + print("gen_:", gen_) + print("rng_state:", rng_state) + print("descale_q:", descale_q, descale_q.shape if descale_q is not None else None) + print("descale_k:", descale_k, descale_k.shape if descale_k is not None else None) + print("descale_v:", descale_v, descale_v.shape if descale_v is not None else None) + print("descale_do:", descale_do, descale_do.shape if descale_do else None) + + dq = torch.zeros_like(q) if dq is None else dq.zero_() + dk = torch.zeros_like(k) if dk is None else dk.zero_() + dv = torch.zeros_like(v) if dv is None else dv.zero_() + + if dropout_p > 0.0: + assert rng_state is not None + philox_seed, philox_offset = rng_state[0].item(), rng_state[1].item() + else: + philox_seed, philox_offset = None, None + + # call implementation + if USE_REF: + if DEBUG: + print("Using reference implementation") + delta_ref = attention_backward_pytorch_ref_impl( + dout, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + softmax_scale, + alibi_slopes, + causal, + "thd", + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + philox_seed, + philox_offset, + False, + ) + delta = delta_ref + else: + if DEBUG: + print("Using Triton implementation") + delta_triton = attention_prefill_backward_triton_split_impl( + dout, + q, + k, + v, + out, + softmax_lse, + dq, + dk, + dv, + softmax_scale, + alibi_slopes, + causal, + "thd", + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + dropout_p, + philox_seed, + philox_offset, + False, + descale_q, + descale_k, + descale_v, + descale_o, + descale_do, + descale_dq, + descale_dk, + descale_dv, + ) + delta = delta_triton + + if DEBUG: + print("varlen_bwd outputs") + print("delta:", delta, delta.shape) + print("dv:", dv, dv.shape) + print("dk:", dk, dk.shape) + print("dq:", dq, dq.shape) + + return dq, dk, dv, delta + +def fwd_kvcache( + q: torch.Tensor, + k_cache: torch.Tensor, + v_cache: torch.Tensor, + k: Optional[torch.Tensor], + v: Optional[torch.Tensor], + cache_seqlens: Optional[Union[(int, torch.Tensor)]], + rotary_cos: Optional[torch.Tensor], + rotary_sin: Optional[torch.Tensor], + cache_batch_idx: Optional[torch.Tensor], + cache_leftpad: Optional[torch.Tensor], + block_table: Optional[torch.Tensor], + alibi_slopes: Optional[torch.Tensor], + out: Optional[torch.Tensor], + softmax_scale: float, + causal: bool, + window_size_left: int, + window_size_right: int, + softcap: float, + rotary_interleaved: bool, + num_splits: int + ): + + if DEBUG: + print() + print("flash_attn_triton_amd.py::fwd_kvcache inputs") + print("q:", q, q.shape) + print("k_cache:", k_cache, k_cache.shape) + print("v_cache:", v_cache, v_cache.shape) + print("k:", k, k.shape if k is not None else None) + print("v:", v, v.shape if v is not None else None) + print("cache_seqlens:", cache_seqlens ) + print("rotary_cos:",rotary_cos ) + print("rotary_sin:",rotary_sin) + print("cache_batch_idx:", cache_batch_idx) + print("cache_leftpad:", cache_leftpad) + print("block_table:", block_table) + print("alibi_slopes:", alibi_slopes) + print("out:", out) + print("softmax_scale:", softmax_scale) + print("causal:", causal) + print("window_size_left:", window_size_left) + print("window_size_right:", window_size_right) + print("softcap:", softcap) + print("rotary_interleaved:", rotary_interleaved) + print("num_splits:", num_splits) + + # output + out = torch.zeros_like(q) if out is None else out.zero_() + + # fill metadata + metadata = MetaData(sm_scale=softmax_scale) + metadata.layout = "bshd" + metadata.max_seqlens_q = q.shape[1] + metadata.max_seqlens_k = k_cache.shape[1] + metadata.cache_seqlens = cache_seqlens + metadata.cache_batch_idx = cache_batch_idx + + k_new = k + v_new = v + + if causal: + metadata.need_causal(True) + + if alibi_slopes is not None: + batch, _ , nheads_q, _= q.shape + metadata.need_alibi(alibi_slopes, batch, nheads_q) + + # rotary boolean + apply_rotary = torch.is_tensor(rotary_cos) and torch.is_tensor(rotary_sin) + if apply_rotary: + metadata.need_rotary(rotary_sin, rotary_cos, rotary_interleaved) + + # Rotary Embedding Implementation + if apply_rotary: + if metadata.causal: # NOTE: when support is added. Add `or metadata.local` + q_ro = apply_rotary_emb( + q, + metadata.rotary_cos, + metadata.rotary_sin, + seqlen_offsets=metadata.cache_seqlens, + interleaved=metadata.rotary_interleaved, + ) + else: + q_ro = rearrange( + apply_rotary_emb( + rearrange(q, "b s h d -> b 1 (s h) d"), + metadata.rotary_cos, + metadata.rotary_sin, + seqlen_offsets=metadata.cache_seqlens, + interleaved=metadata.rotary_interleaved, + ), + "b 1 (s h) d -> b s h d", + s=metadata.max_seqlens_q, + ) + k_ro = apply_rotary_emb( + k_new, + metadata.rotary_cos, + metadata.rotary_sin, + seqlen_offsets=metadata.cache_seqlens, + interleaved=metadata.rotary_interleaved, + ) + + q, k_new = q_ro.to(q.dtype), k_ro.to(q.dtype) + + # launch kernel + DECODE_KERNEL= True # os.environ.get('DECODE_KERNEL', '0').lower() in ('1', 'true', 'yes') + if DECODE_KERNEL: + softmax_lse_triton = attention_decode_forward_triton_impl( + q, + k_cache, + v_cache, + k_new, + v_new, + out, + metadata.sm_scale, + metadata.causal, + metadata.alibi_slopes, + metadata.layout, + metadata.cache_seqlens, + metadata.cache_batch_idx, + ) + else: + softmax_lse_triton, sd_mask_triton = attention_prefill_forward_triton_impl( + q, + k_cache, + v_cache, + out, + metadata.sm_scale, + metadata.alibi_slopes, + metadata.causal, + None, + metadata.layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.cache_seqlens, + metadata.cache_batch_idx, + metadata.dropout_p, + metadata.philox_seed, + metadata.philox_offset, + metadata.return_scores, + metadata.use_exp2, + None, + None, + None, + None) + softmax_lse = softmax_lse_triton + + if DEBUG: + print("out:", out, out.shape) + print("softmax_lse:", softmax_lse, softmax_lse.shape) + return out, softmax_lse diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/test.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/test.py new file mode 100644 index 0000000000000000000000000000000000000000..58e2ae5fc7f88adaf7a3903438c52dbc8b2a8e7c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/test.py @@ -0,0 +1,932 @@ +import os +import glob +import shutil +import time +import torch +import pytest +import logging +import numpy as np +from pathlib import Path +from flash_attn import ( + flash_attn_func, + flash_attn_fp8_func, + flash_attn_kvpacked_func, + flash_attn_qkvpacked_func, + flash_attn_qkvpacked_fp8_func, + flash_attn_varlen_func, + flash_attn_varlen_fp8_func, + flash_attn_varlen_kvpacked_func, + flash_attn_varlen_qkvpacked_func, + flash_attn_varlen_qkvpacked_fp8_func +) + +from .utils import DEBUG, input_helper, arch_supports_fp8 +from .fwd_ref import attention_forward_pytorch_ref_impl +from .fwd_prefill import attention_prefill_forward_triton_impl +from .bwd_prefill_split import attention_prefill_backward_triton_split_impl +from .bwd_ref import attention_backward_pytorch_ref_impl + +# set print options +# torch.set_printoptions(linewidth=5e5, edgeitems=10, sci_mode=False) +# np.set_printoptions(linewidth=5000, threshold=1e4, suppress=True, precision=4) + +# defailt fp16 tolerance is ATOL, RTOL = 1e-5, 1e-3. See table https://pytorch.org/docs/stable/testing.html +ATOL, RTOL = 1e-2, 1e-2 # old standard. maybe to lose. +# ATOL, RTOL = 1e-3, 1e-3 # catchs fa mismatch issues +# ATOL, RTOL = 1e-4, 1e-3 # to strict. there will be small diffs +# ATOL, RTOL = 1e-5, 1e-3 # # default fp16. there will be small diffs +# ATOL_fp8, RTOL_fp8 = 1e-1, 1e-1 # to strict for larger tensors in fp8 +ATOL_fp8, RTOL_fp8 = 2.5e-1, 2.5e-1 # fp8 +# ATOL_fp8, RTOL_fp8 = 2e-2, 2e-2 # fp8 +EQUAL_NAN = True + +@pytest.mark.parametrize( + "BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD", + [ + (1, 1, 1, 1, 1, 1), + (1, 1, 1, 2, 4, 16), + (1, 2, 2, 2, 4, 16), + (1, 4, 1, 2, 4, 16), + (1, 4, 2, 2, 4, 16), + (1, 1, 1, 4, 2, 16), + (1, 1, 1, 4, 4, 16), + (1, 2, 2, 4, 4, 16), + (2, 1, 1, 4, 4, 16), + (2, 2, 2, 4, 4, 16), + (1, 1, 1, 128, 64, 16), + (2, 2, 2, 2, 128, 1), + (2, 3, 3, 2, 128, 16), + (3, 2, 2, 256, 512, 16), + (3, 3, 3, 128, 128, 64), + (2, 4, 4, 1024, 1024, 64), + (4, 6, 6, 108, 256, 224), + (4, 8, 8, 2048, 2048, 128), + (4, 16, 16, 4096, 4096, 64), + (2, 4, 4, 8192, 8192, 32), + # fa configs + (4, 6, 1, 113, 203, 256), + (4, 6, 1, 128, 217, 256), + (4, 6, 2, 113, 211, 128), + (4, 6, 2, 108, 256, 128), + (4, 6, 1, 256, 512, 64), + (4, 6, 1, 512, 256, 64), + (4, 6, 2, 1024, 1024, 32), + (4, 6, 2, 1023, 1024, 32), + (4, 6, 6, 1024, 1023, 32), + (4, 6, 6, 2048, 2048, 32), + ], +) +@pytest.mark.parametrize('causal', [True, False]) +@pytest.mark.parametrize('dropout_p', [0.0]) +@pytest.mark.parametrize('alibi_slopes', [None]) +@pytest.mark.parametrize('layout', ["bshd", "thd"]) +@pytest.mark.parametrize('dtype', [torch.float16]) +@pytest.mark.parametrize('use_exp2', [True, False]) # works when use_exp2 is false +@pytest.mark.parametrize('DEBUG_INPUT', [False]) # NOTE: debug input can overflow when the tensors are large. Just use to figure out issues +def test_op_prefill_fwd_impl(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, causal, dropout_p, alibi_slopes, layout, dtype, use_exp2, DEBUG_INPUT): + torch.manual_seed(42) + device = "cuda" + + q, k, v, do, metadata = input_helper(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, causal, dropout_p, dtype, layout=layout, device=device) + + if DEBUG: + if HQ // HK != 1: + print("MQA/GQA") + else: + print("MHA") + + # update metadata + metadata.use_exp2 = use_exp2 + if causal: + metadata.need_causal(True) + + # NOTE: the returned score is not the same as the reference because we need to adjust as we find new maxes per block. We are not doing that + metadata.need_dropout(dropout_p) + + + # call Triton's forward implementation directly + q_triton = q.clone() + k_triton = k.clone() + v_triton = v.clone() + o_triton = torch.zeros_like(q).contiguous() if DEBUG_INPUT else torch.empty_like(q) + softmax_lse_triton, sd_mask_triton = attention_prefill_forward_triton_impl( + q_triton, + k_triton, + v_triton, + o_triton, + metadata.sm_scale, + metadata.alibi_slopes, + metadata.causal, + metadata.bias, + metadata.layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.cache_seqlens, + metadata.cache_batch_idx, + metadata.dropout_p, + metadata.philox_seed, + metadata.philox_offset, + metadata.return_scores, + metadata.use_exp2, + None, + None, + None, + None) + + # ref forward + q_ref = q.clone() + k_ref = k.clone() + v_ref = v.clone() + o_ref = torch.zeros_like(q).contiguous() if DEBUG_INPUT else torch.empty_like(q) + softmax_lse_ref, sd_mask_ref = attention_forward_pytorch_ref_impl( + q_ref, + k_ref, + v_ref, + o_ref, + metadata.sm_scale, + metadata.alibi_slopes, + causal, + layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.dropout_p, + metadata.philox_seed, + metadata.philox_offset, + use_exp2 + ) + + if DEBUG: + print() + print("Compare Triton Impl with refernce Pytorch Impl") + + # this can be set to true manually or when using dropout + if metadata.return_scores: + if DEBUG: + print("sd_mask_triton:", sd_mask_triton, sd_mask_triton.shape) + print("sd_mask_ref:", sd_mask_ref, sd_mask_ref.shape) + torch.testing.assert_close(sd_mask_triton.to(sd_mask_ref.dtype), sd_mask_ref, atol=ATOL, rtol=RTOL) + + if DEBUG: + print("softmax_lse_triton:", softmax_lse_triton, softmax_lse_triton.shape) + print("softmax_lse_ref:", softmax_lse_ref, softmax_lse_ref.shape) + torch.testing.assert_close(softmax_lse_triton, softmax_lse_ref, atol=ATOL, rtol=RTOL) + + if DEBUG: + print("output_triton:", o_triton, o_triton.shape) + print("output_ref:", o_ref, o_ref.shape) + torch.testing.assert_close(o_triton, o_ref, atol=ATOL, rtol=RTOL) + +@pytest.mark.parametrize( + "BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD", [ + (1, 1, 1, 1, 1, 1), + (1, 1, 1, 4, 4, 4), + (2, 1, 1, 4, 4, 16), + (1, 2, 2, 4, 4, 16), + (1, 4, 1, 2, 4, 16), + (1, 8, 1, 2, 4, 16), + (1, 16, 1, 2, 4, 16), + (1, 32, 1, 2, 4, 16), + (1, 64, 1, 2, 4, 16), + (1, 4, 2, 2, 4, 16), + (2, 2, 2, 4, 4, 16), + (1, 1, 1, 4, 4, 16), + (2, 1, 1, 4, 4 , 16), + (4, 6, 6, 8, 8 , 16), + (1, 1, 1, 4, 4, 32), + (1, 1, 1, 16, 16, 16), + (1, 1, 1, 32, 32, 16), + (1, 1, 1, 64, 64, 16), + (1, 1, 1, 64, 64, 16), + (1, 1, 1, 64, 128, 16), + (1, 1, 1, 64, 64, 32), + (1, 1, 1, 64, 128, 32), + (1, 1, 1, 128, 128, 64), + (1, 1, 1, 128, 256, 45), + (1, 1, 1, 113, 203, 192), + (1, 1, 1, 256, 256, 64), + (1, 1, 1, 256, 512, 16), + (1, 1, 1, 512, 512, 64), + (1, 1, 1, 1024, 1024, 64), + # fa configs + (2, 2, 2, 128, 128, 65), + (2, 2, 2, 128, 128, 224), + (4, 6, 6, 108, 256, 224), + (1, 1, 1, 256, 512, 16), + # old tests that work + (4, 48, 6, 1024, 1024, 64), + (4, 48, 12, 2048, 1024, 64), + (4, 48, 24, 1024, 1024, 64), + (4, 48, 48, 1024, 1024, 64), + (4, 48, 48, 1024, 1024, 73), + (4, 48, 48, 2048, 2048, 64), + (1, 24, 24, 4096, 4096, 64), + (1, 16, 16, 1024, 1024, 64), + (1, 16, 16, 1024, 1024, 128), + # testcase new + # seqlen q == k + (1, 1, 1, 2, 2, 2), # small enough to debug + (1, 1, 1, 128, 128, 32), # only one block + (1, 1, 1, 127, 127, 32), # only one block but with masking + (1, 1, 1, 129, 129, 1), # two blocks with 2nd block small enough to debug + (1, 1, 1, 350, 350, 1), # two blocks with 2nd block small enough to debug + (1, 1, 1, 350, 350, 68), # generic masking on q, k and head + (4, 1, 1, 512, 512, 128), # batch > 1 + (4, 8, 2, 512, 512, 128), # GQA + (4, 8, 2, 512, 512, 68), # non-power-of-2 head_dim + (4, 8, 2, 500, 500, 68), # comprehensive case for seqlen q == k + # seqlen q > k + (1, 1, 1, 64, 32, 8), # seqlen_q > seqlen_k + (1, 1, 1, 192, 128, 32), # seqlen_q > seqlen_k + (4, 8, 2, 1024, 512, 68), # seqlen_q < seqlen_k + (1, 1, 1, 729, 516, 68), # seqlen_q > seqlen_k + (16, 16, 4, 2753, 1528, 68), # a comprehensive seqlen_q > seqlen_k + # seqlen q < k + (1, 1, 1, 32, 64, 8), # seqlen_q > seqlen_k + (1, 1, 1, 128, 192, 32), # seqlen_q < seqlen_k + (4, 8, 2, 512, 1024, 68), # seqlen_q < seqlen_k + (1, 1, 1, 200, 413, 1), # seqlen_q < seqlen_k + (1, 1, 1, 782, 1546, 1), # seqlen_q < seqlen_k + (16, 16, 4, 1528, 2753, 68), # a comprehensive seqlen_q < seqlen_k +]) +@pytest.mark.parametrize('causal', [True, False]) +@pytest.mark.parametrize('dropout_p', [0.0]) +@pytest.mark.parametrize('alibi_slopes', [None]) +@pytest.mark.parametrize('layout', ["bshd", "thd"]) +@pytest.mark.parametrize('dtype', [torch.float16]) +@pytest.mark.parametrize('use_exp2', [False]) # FIXME: using exp2 causes issue when used with causal +@pytest.mark.parametrize('DEBUG_INPUT', [False]) # debug output causes nans on larger tensors +def test_op_prefill_bwd_impl(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, causal, dropout_p, alibi_slopes, layout, dtype, use_exp2, DEBUG_INPUT): + torch.manual_seed(20) + device="cuda" + + # gen inputs + q, k, v, do, metadata = input_helper(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, causal, dropout_p, dtype, layout=layout, device=device) + + # NOTE: the returned score is not the same as the reference because we need to adjust as we find new maxes per block. We are not doing that + metadata.need_dropout(dropout_p) + + # =============================================== Reference ============================================================== + # fwd + q_ref = q.clone() + k_ref = k.clone() + v_ref = v.clone() + output_ref = torch.zeros_like(q).contiguous() if DEBUG_INPUT else torch.empty_like(q) + softmax_lse_ref, sd_mask_ref = attention_forward_pytorch_ref_impl( + q_ref, + k_ref, + v_ref, + output_ref, + metadata.sm_scale, + metadata.alibi_slopes, + causal, + layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.dropout_p, + metadata.philox_seed, + metadata.philox_offset, + use_exp2 + ) + + # bwd + do_ref = do.clone() + dq_ref = torch.zeros_like(q).contiguous() if DEBUG_INPUT else torch.empty_like(q) + dk_ref = torch.zeros_like(k).contiguous() if DEBUG_INPUT else torch.empty_like(k) + dv_ref = torch.zeros_like(v).contiguous() if DEBUG_INPUT else torch.empty_like(v) + delta_ref = attention_backward_pytorch_ref_impl( + do_ref, + q_ref, + k_ref, + v_ref, + output_ref, + softmax_lse_ref, + dq_ref, + dk_ref, + dv_ref, + metadata.sm_scale, + metadata.alibi_slopes, + causal, + layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.dropout_p, + metadata.philox_seed, + metadata.philox_offset, + use_exp2 + ) + + # =============================================== Triton ============================================================== + do_triton = do.clone() + q_triton = q.clone() + k_triton = k.clone() + v_triton = v.clone() + o_triton = output_ref.clone().contiguous() + softmax_lse_triton = softmax_lse_ref.clone().contiguous() + dq_triton = torch.zeros_like(q_triton, dtype=q.dtype) # NOTE: the kernel does inplace accumlation on dq so dq has to be zeros + dk_triton = torch.zeros_like(k_triton, dtype=k.dtype) if DEBUG_INPUT else torch.empty_like(k_triton, dtype=k.dtype) + dv_triton = torch.zeros_like(v_triton, dtype=v.dtype) if DEBUG_INPUT else torch.empty_like(v_triton, dtype=v.dtype) + delta_triton = attention_prefill_backward_triton_split_impl( + do_triton, + q_triton, + k_triton, + v_triton, + o_triton, + softmax_lse_triton, + dq_triton, + dk_triton, + dv_triton, + metadata.sm_scale, + alibi_slopes, + causal, + layout, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + metadata.dropout_p, + metadata.philox_seed, + metadata.philox_offset, + use_exp2, + None, + None, + None, + None, + None, + None, + None, + None, + ) + + # =============================================== Check ============================================================== + if DEBUG: + print() + if DEBUG: + print("delta_triton:", delta_triton, delta_triton.shape) + print("delta_ref:", delta_ref, delta_ref.shape) + torch.testing.assert_close(delta_triton, delta_ref, atol=ATOL, rtol=RTOL, equal_nan=EQUAL_NAN) + + if DEBUG: + print("dv_triton:", dv_triton, dv_triton.shape) + print("dv_ref:", dv_ref, dv_ref.shape) + torch.testing.assert_close(dv_triton, dv_ref, atol=ATOL, rtol=RTOL, equal_nan=EQUAL_NAN) + + if DEBUG: + print("dk_triton:", dk_triton, dk_triton.shape) + print("dk_ref:", dk_ref, dk_ref.shape) + torch.testing.assert_close(dk_triton, dk_ref, atol=ATOL, rtol=RTOL, equal_nan=EQUAL_NAN) + + if DEBUG: + print("dq_triton:", dq_triton, dq_triton.shape) + print("dq_ref:", dq_ref, dq_ref.shape) + torch.testing.assert_close(dq_triton, dq_ref, atol=ATOL, rtol=RTOL, equal_nan=EQUAL_NAN) + +def fp8_assert_close(tensor_a, tensor_b, atol=ATOL_fp8, rtol=RTOL_fp8, max_diff_percentage=0.5): + """Assert tensors are close with tolerance for small percentage of elements""" + # standard comparison + abs_diff = torch.abs(tensor_a - tensor_b) + rel_diff = abs_diff / torch.abs(tensor_b.clamp(min=1e-6)) + + # calculate elements that exceed tolerance + abs_check = abs_diff > atol + rel_check = rel_diff > rtol + failed_check = torch.logical_and(abs_check, rel_check) + + # calculate percentage of failed elements + failed_percentage = failed_check.sum().item() / failed_check.numel() * 100 + + # if percentage is small enough, test passes + if failed_percentage <= max_diff_percentage: + return True + + # Otherwise, provide diagnostic information + max_abs_idx = torch.argmax(abs_diff).item() + max_rel_idx = torch.argmax(rel_diff).item() + + flat_to_idx = lambda flat_idx, shape: np.unravel_index(flat_idx, shape) + + max_abs_pos = flat_to_idx(max_abs_idx, tensor_a.shape) + max_rel_pos = flat_to_idx(max_rel_idx, tensor_a.shape) + + max_abs_diff = abs_diff.flatten()[max_abs_idx].item() + max_rel_diff = rel_diff.flatten()[max_rel_idx].item() + + raise AssertionError( + f"Tensors not close enough! {failed_percentage:.6f}% elements exceed tolerance.\n" + f"Greatest absolute difference: {max_abs_diff} at index {max_abs_pos} (up to {atol} allowed)\n" + f"Greatest relative difference: {max_rel_diff} at index {max_rel_pos} (up to {rtol} allowed)" + ) + +@pytest.mark.parametrize( + "Z, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD", + [ + # seqlen q == k + (1, 1, 1, 1, 1, 1), + (1, 1, 1, 2, 2, 2), # small enough to debug + (1, 1, 1, 4, 4, 16), + (1, 2, 2, 4, 4, 16), + (2, 1, 1, 4, 4, 16), + (2, 2, 2, 4, 4, 16), + (1, 1, 1, 128, 128, 32), # only one block + (3, 3, 3, 128, 128, 64), + (1, 1, 1, 127, 127, 32), # only one block but with masking + # (1, 1, 1, 129, 129, 1), # two blocks with 2nd block small enough to debug # fails + (1, 2, 2, 129, 129, 32), # two blocks with 2nd block small enough to debug + (1, 1, 1, 350, 350, 32), # two blocks with 2nd block small enough to debug + (1, 1, 1, 350, 350, 68), # generic masking on q, k and head + (4, 1, 1, 512, 512, 128), # batch > 1 + (4, 2, 2, 512, 512, 128), + (4, 2, 2, 512, 512, 68), + (4, 2, 2, 500, 500, 68), + (2, 4, 4, 1024, 1024, 64), + (4, 8, 8, 2048, 2048, 128), + (2, 8, 8, 4096, 4096, 64), + (2, 4, 4, 8192, 8192, 32), + # seqlen q > k + (1, 1, 1, 4, 2, 16), + (1, 1, 1, 64, 32, 8), + (1, 1, 1, 128, 64, 16), + (1, 1, 1, 192, 128, 32), + (1, 2, 2, 1024, 512, 68), + (1, 4, 4, 729, 516, 68), + (2, 4, 4, 2753, 1528, 68), # a comprehensive seqlen_q > seqlen_k + # seqlen q < k + (1, 1, 1, 2, 4, 16), + (1, 2, 2, 2, 4, 16), + (1, 4, 1, 2, 4, 16), + (1, 4, 2, 2, 4, 16), + (2, 2, 2, 2, 128, 1), + (2, 3, 3, 2, 128, 16), + (1, 1, 1, 32, 64, 8), + (1, 1, 1, 128, 192, 32), + (4, 6, 6, 108, 256, 32), + (3, 2, 2, 256, 512, 16), + (2, 2, 2, 512, 1024, 68), + (1, 1, 1, 200, 413, 32), + (1, 1, 1, 782, 1546, 32), + # gqa/mqa # mismatch issue on varlen + (4, 8, 2, 500, 500, 68), + (4, 8, 2, 512, 512, 68), + (4, 8, 2, 512, 512, 128), + (4, 8, 2, 512, 1024, 68), + (4, 8, 2, 1024, 512, 64), + (4, 16, 4, 1528, 2753, 68), + # fa configs + (2, 4, 1, 113, 203, 64), + (2, 4, 2, 128, 217, 64), + (2, 6, 2, 113, 211, 128), + (2, 6, 2, 108, 256, 128), + (2, 6, 2, 256, 512, 64), + (2, 6, 2, 512, 256, 64), + (2, 6, 2, 1024, 1024, 32), + (2, 6, 2, 1023, 1024, 32), + (2, 6, 6, 1024, 1023, 32), + (2, 6, 6, 2048, 2048, 32), + ], +) +@pytest.mark.parametrize('causal', [False, True]) +@pytest.mark.parametrize('dropout_p', [0.0]) +@pytest.mark.parametrize('layout', ["bshd", "thd"]) +@pytest.mark.parametrize('packing', [None, "qkv"]) +@pytest.mark.parametrize('DEBUG_INPUT', [False]) +@pytest.mark.flaky(reruns=3, reason="Retry failures") +@pytest.mark.skipif(not arch_supports_fp8(), reason="fp8 not supported on this device") +def test_fp8(Z, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, causal, dropout_p, layout, packing, DEBUG_INPUT): + torch.manual_seed(20) + test_backward = True + device = "cuda" + window_size = (-1, -1) + softcap = 0.0 + alibi_slopes = None + deterministic = False + ref_dtype = torch.float32 + is_varlen = True if layout == "thd" else False + + # skip QKV packing tests for uneven sequence lengths and head sizes + if packing == 'qkv': + if N_CTX_Q != N_CTX_K: + pytest.skip("QKV packing requires N_CTX_Q == N_CTX_K") + if HQ != HK: + pytest.skip("QKV packing requires HQ == HK") + + # test apis + if packing == 'qkv': + # generate inputs + qkv, do, metadata = input_helper(Z, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, causal, dropout_p, ref_dtype, layout, packing=packing, device=device, DEBUG_INPUT=DEBUG_INPUT) + + # ---------------------------------------------------------------- + # --- FP8 --- + # ---------------------------------------------------------------- + qkv_fp8 = qkv.clone() + do_fp8= do.clone() + + if is_varlen: + out_fp8, lse_fp8, S_dmask_fp8 = flash_attn_varlen_qkvpacked_fp8_func( + qkv_fp8, + metadata.cu_seqlens_q, + metadata.max_seqlens_q, + dropout_p, + causal=causal, + window_size=window_size, + softcap=softcap, + alibi_slopes=alibi_slopes, + deterministic=deterministic, + return_attn_probs=True, + ) + else: + out_fp8, lse_fp8, S_dmask_fp8 = flash_attn_qkvpacked_fp8_func( + qkv_fp8, + dropout_p, + causal=causal, + window_size=window_size, + softcap=softcap, + alibi_slopes=alibi_slopes, + deterministic=deterministic, + return_attn_probs=True, + ) + + # ---------------------------------------------------------------- + # --- Reference --- + # ---------------------------------------------------------------- + # reference forward pass + qkv_ref = qkv.clone() + do_ref= do.clone() + + if is_varlen: + out_ref, lse_ref, S_dmask_ref = flash_attn_varlen_qkvpacked_func( + qkv_ref, + metadata.cu_seqlens_q, + metadata.max_seqlens_q, + dropout_p, + causal=causal, + window_size=window_size, + softcap=softcap, + alibi_slopes=alibi_slopes, + deterministic=deterministic, + return_attn_probs=True, + ) + else: + out_ref, lse_ref, S_dmask_ref = flash_attn_qkvpacked_func( + qkv_ref, + dropout_p, + causal=causal, + window_size=window_size, + softcap=softcap, + alibi_slopes=alibi_slopes, + deterministic=deterministic, + return_attn_probs=True, + ) + + # ---------------------------------------------------------------- + # --- Compare --- + # ---------------------------------------------------------------- + # compare forward + if DEBUG: + print() + print(f"Compare fp8 against ref with dtype {ref_dtype}") + + if DEBUG: + print("out_ref:", out_ref, out_ref.shape) + print("out_fp8:", out_fp8, out_fp8.shape) + fp8_assert_close(out_ref, out_fp8, atol=ATOL_fp8, rtol=RTOL_fp8 ) + + + if DEBUG: + print("lse_ref:", lse_ref, lse_ref.shape) + print("lse_fp8:", lse_fp8, lse_fp8.shape) + fp8_assert_close(lse_ref, lse_fp8, atol=ATOL_fp8, rtol=RTOL_fp8) + + + if dropout_p > 0.0: + if DEBUG: + print("S_dmask_ref:", S_dmask_ref, S_dmask_ref.shape) + print("S_dmask_fp8:", S_dmask_fp8, S_dmask_fp8.shape) + fp8_assert_close(S_dmask_ref, S_dmask_fp8, atol=ATOL_fp8, rtol=RTOL_fp8) + + if not test_backward: + return + + # fp8 backward pass + dqkv_fp8, = torch.autograd.grad(out_fp8, (qkv_fp8), do_fp8) + + # ref backward pass + dqkv_ref, = torch.autograd.grad(out_ref, (qkv_ref), do_ref) + + # compare backward gradients + if DEBUG: + print("dqkv_ref:", dqkv_ref, dqkv_ref.shape) + print("dqkv_fp8:", dqkv_fp8, dqkv_fp8.shape) + fp8_assert_close(dqkv_ref, dqkv_fp8, atol=ATOL_fp8, rtol=RTOL_fp8) + + elif packing is None: + # generate inputs + q, k, v, do, metadata = input_helper(Z, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, causal, dropout_p, ref_dtype, layout, device=device, DEBUG_INPUT=DEBUG_INPUT) + + # ---------------------------------------------------------------- + # --- FP8 --- + # ---------------------------------------------------------------- + if DEBUG: + print() + print(f"Compute Fp8 Forward") + q_fp8 = q.clone() + k_fp8 = k.clone() + v_fp8 = v.clone() + do_fp8= do.clone() + + if is_varlen: + out_fp8, lse_fp8, S_dmask_fp8 = flash_attn_varlen_fp8_func( + q_fp8, + k_fp8, + v_fp8, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + dropout_p, + causal=causal, + window_size=window_size, + softcap=softcap, + alibi_slopes=alibi_slopes, + deterministic=deterministic, + return_attn_probs=True, + ) + else: + out_fp8, lse_fp8, S_dmask_fp8 = flash_attn_fp8_func( + q_fp8, + k_fp8, + v_fp8, + dropout_p, + causal=causal, + window_size=window_size, + softcap=softcap, + alibi_slopes=alibi_slopes, + deterministic=deterministic, + return_attn_probs=True, + ) + + # ---------------------------------------------------------------- + # --- Reference --- + # ---------------------------------------------------------------- + if DEBUG: + print() + print(f"Compute Reference Forward") + # reference forward pass + q_ref = q.clone() + k_ref = k.clone() + v_ref = v.clone() + do_ref = do.clone() + + if is_varlen: + out_ref, lse_ref, S_dmask_ref = flash_attn_varlen_func( + q_ref, + k_ref, + v_ref, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + dropout_p, + causal=causal, + window_size=window_size, + softcap=softcap, + alibi_slopes=alibi_slopes, + deterministic=deterministic, + return_attn_probs=True, + ) + else: + out_ref, lse_ref, S_dmask_ref = flash_attn_func( + q_ref, + k_ref, + v_ref, + dropout_p, + causal=causal, + window_size=window_size, + softcap=softcap, + alibi_slopes=alibi_slopes, + deterministic=deterministic, + return_attn_probs=True, + ) + + # ---------------------------------------------------------------- + # --- Compare --- + # ---------------------------------------------------------------- + # compare forward + if DEBUG: + print() + print(f"Compare fp8 against ref with dtype {ref_dtype}") + + if DEBUG: + print("out_ref:", out_ref, out_ref.shape) + print("out_fp8:", out_fp8, out_fp8.shape) + # torch.testing.assert_close(out_ref, out_fp8, atol=ATOL_fp8, rtol=RTOL_fp8) + fp8_assert_close(out_ref, out_fp8, atol=ATOL_fp8, rtol=RTOL_fp8 ) + + + if DEBUG: + print("lse_ref:", lse_ref, lse_ref.shape) + print("lse_fp8:", lse_fp8, lse_fp8.shape) + # torch.testing.assert_close(lse_ref, lse_fp8, atol=ATOL_fp8, rtol=RTOL_fp8) + fp8_assert_close(lse_ref, lse_fp8, atol=ATOL_fp8, rtol=RTOL_fp8) + + + if dropout_p > 0.0: + if DEBUG: + print("S_dmask_ref:", S_dmask_ref, S_dmask_ref.shape) + print("S_dmask_fp8:", S_dmask_fp8, S_dmask_fp8.shape) + # torch.testing.assert_close(S_dmask_ref, S_dmask_fp8, atol=ATOL_fp8, rtol=RTOL_fp8) + fp8_assert_close(S_dmask_ref, S_dmask_fp8, atol=ATOL_fp8, rtol=RTOL_fp8) + + if not test_backward: + return + + if DEBUG: + print() + print(f"Compute Fp8 Backward") + # fp8 backward pass + dq_fp8, dk_fp8, dv_fp8 = torch.autograd.grad(out_fp8, (q_fp8, k_fp8, v_fp8), do_fp8) + + if DEBUG: + print() + print(f"Compute Reference Backward") + # ref backward pass + dq_ref, dk_ref, dv_ref = torch.autograd.grad(out_ref, (q_ref, k_ref, v_ref), do_ref) + + # compare backward gradients + if DEBUG: + print("dv_ref:", dv_ref, dv_ref.shape) + print("dv_fp8:", dv_fp8, dv_fp8.shape) + # torch.testing.assert_close(dv_ref, dv_fp8, atol=ATOL_fp8, rtol=RTOL_fp8, equal_nan=EQUAL_NAN) + fp8_assert_close(dv_ref, dv_fp8, atol=ATOL_fp8, rtol=RTOL_fp8 ) + + if DEBUG: + print("dk_ref:", dk_ref, dk_ref.shape) + print("dk_fp8:", dk_fp8, dk_fp8.shape) + # torch.testing.assert_close(dk_ref, dk_fp8, atol=ATOL_fp8, rtol=RTOL_fp8, equal_nan=EQUAL_NAN) + fp8_assert_close(dk_ref, dk_fp8, atol=ATOL_fp8, rtol=RTOL_fp8 ) + + if DEBUG: + print("dq_ref:", dq_ref, dq_ref.shape) + print("dq_fp8:", dq_fp8, dq_fp8.shape) + # torch.testing.assert_close(dq_ref, dq_fp8, atol=ATOL_fp8, rtol=RTOL_fp8, equal_nan=EQUAL_NAN) + fp8_assert_close(dq_ref, dq_fp8, atol=ATOL_fp8, rtol=RTOL_fp8 ) + +@pytest.mark.parametrize( + "BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD", + [ + (2, 4, 4, 512, 512, 128), + ], +) +@pytest.mark.parametrize('causal', [False, True]) +@pytest.mark.parametrize('dropout_p', [0.0, 0.1]) +@pytest.mark.parametrize('layout', ['bshd']) +@pytest.mark.parametrize('packing', [None]) +@pytest.mark.parametrize('test_backward', [False, True]) +@pytest.mark.skipif(not arch_supports_fp8(), reason="fp8 not supported on this device") +@pytest.mark.skip("Breaks on CI but works locally") +def test_ir(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, causal, dropout_p, layout, packing, test_backward): # Don't run this test in parallel. It clears the cache so it doesnot work properly if run in parallel. + torch.manual_seed(20) + device = "cuda" + window_size = (-1, -1) + softcap = 0.0 + alibi_slopes = None + deterministic = False + ref_dtype = torch.float32 + is_varlen = True if layout == "thd" else False + + # remove cache + cache_path = Path(os.path.expanduser("~/.triton/cache")) + if cache_path.exists(): + shutil.rmtree(cache_path) + os.makedirs(cache_path) + + # inputs + q, k, v, do, metadata = input_helper(BATCH, HQ, HK, N_CTX_Q, N_CTX_K, D_HEAD, causal, dropout_p, ref_dtype, layout=layout, packing=packing, device=device) + + if packing == None: + # fp8 forward pass + if is_varlen: + out, lse, S_dmask = flash_attn_varlen_fp8_func( + q, + k, + v, + metadata.cu_seqlens_q, + metadata.cu_seqlens_k, + metadata.max_seqlens_q, + metadata.max_seqlens_k, + dropout_p, + causal=causal, + window_size=window_size, + softcap=softcap, + alibi_slopes=alibi_slopes, + deterministic=deterministic, + return_attn_probs=True, + ) + else: + out, lse, S_dmask = flash_attn_fp8_func( + q, + k, + v, + dropout_p, + causal=causal, + window_size=window_size, + softcap=softcap, + alibi_slopes=alibi_slopes, + deterministic=deterministic, + return_attn_probs=True, + ) + + # fp8 backward pass + if test_backward: + dq, dk, dv = torch.autograd.grad(out, (q, k, v), do) + elif packing == "qkv": + # qkv packing path + # pack input tensors (use dim=1 for varlen, else dim=2) + if is_varlen: + qkv = torch.stack([q, k, v], dim=1) + else: + qkv = torch.stack([q, k, v], dim=2) + + # fp8 forward pass for qkv-packed input + if is_varlen: + out, lse, S_dmask = flash_attn_varlen_qkvpacked_fp8_func( + qkv, + metadata.cu_seqlens_q, + metadata.max_seqlens_q, + dropout_p, + causal=causal, + window_size=window_size, + softcap=softcap, + alibi_slopes=alibi_slopes, + deterministic=deterministic, + return_attn_probs=True, + ) + else: + out, lse, S_dmask = flash_attn_qkvpacked_fp8_func( + qkv, + dropout_p, + causal=causal, + window_size=window_size, + softcap=softcap, + alibi_slopes=alibi_slopes, + deterministic=deterministic, + return_attn_probs=True, + ) + + # fp8 backward pass for qkv-packed input + if test_backward: + dqkv, = torch.autograd.grad(out, (qkv,), do) + else: + raise ValueError(f"unknown packing type {packing}") + + # search for .ttir files + max_retries = 5 + retry_delay = 0.5 + ttir_files = [] + logging.info(f"Checking for .ttir files in {cache_path}...") + for attempt in range(max_retries): + # search for .ttir files recursively within the cache path + ttir_files = glob.glob(str(cache_path) + "/**/*.ttir", recursive=True) + + if ttir_files: + # Files found, log success and exit the loop + logging.info(f"Found {len(ttir_files)} .ttir files on attempt {attempt + 1}.") + break + else: + # Files not found yet + if attempt < max_retries - 1: + # If not the last attempt, wait and log before retrying + logging.warning( + f"No .ttir files found on attempt {attempt + 1}. " + f"Retrying in {retry_delay}s..." + ) + time.sleep(retry_delay) + else: + pytest.fail( + f"FATAL: No .ttir files found in cache {cache_path} " + f"after {max_retries} attempts." + ) + + # check if there is fp8 + ttir_files_fp8_found_status = {} + fp8_types = ['f8E4M3', 'f8E5M2'] + for ttir_file in ttir_files: + base_name = os.path.basename(ttir_file) + with open(ttir_file, 'r') as f: + content = f.read() + + # check content for fp8 + fp8_found = False + for f8_type in fp8_types: + if f8_type in content: + fp8_found = True + ttir_files_fp8_found_status[base_name] = fp8_found + + for file, fp8_found in ttir_files_fp8_found_status.items(): + assert fp8_found, f"{fp8_types} not found in {file}" diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/train.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/train.py new file mode 100644 index 0000000000000000000000000000000000000000..fc5f5d0b1bf3cfbe81240fd600bb3e281f657624 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/train.py @@ -0,0 +1,403 @@ +import torch +import torch.nn as nn +import torch.optim as optim +from torch.utils.data import DataLoader, Dataset, random_split +import numpy as np +import pandas as pd +from tqdm import tqdm +import matplotlib.pyplot as plt +from datasets import load_dataset +from flash_attn import flash_attn_qkvpacked_func, flash_attn_qkvpacked_fp8_func, flash_attn_varlen_qkvpacked_func, flash_attn_varlen_qkvpacked_fp8_func + +device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') +print(f"using device: {device}") + +# ------------------------------- +# Model +# ------------------------------- +class FlashAttention(nn.Module): + def __init__(self, dim, num_heads=8, causal=True, dropout=0.1, qkv_bias=True, use_fp8=False): + super().__init__() + self.use_fp8 = use_fp8 + self.num_heads = num_heads + self.head_dim = dim // num_heads + self.scale = self.head_dim ** -0.5 + self.causal = causal + self.dropout_p = dropout + + # qkv and output projections + self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) + self.proj = nn.Linear(dim, dim) + + def forward(self, x): + b, n, c = x.shape + # project to qkv + qkv = self.qkv(x).reshape(b, n, 3, self.num_heads, self.head_dim).permute(2, 0, 1, 3, 4) + q, k, v = qkv[0], qkv[1], qkv[2] + + # reshape for flash attention function + qkv_packed = torch.stack([q, k, v], dim=2).reshape(b, n, 3, self.num_heads, self.head_dim) + + # use the appropriate flash attention function + if self.use_fp8: + context = flash_attn_qkvpacked_fp8_func( + qkv_packed, + dropout_p=self.dropout_p, + causal=self.causal + ) + else: + context = flash_attn_qkvpacked_func( + qkv_packed, + dropout_p=self.dropout_p, + causal=self.causal + ) + + # convert back to original shape and type + context = context.reshape(b, n, c) + + # output projection + x = self.proj(context) + + return x + +class TransformerBlock(nn.Module): + def __init__(self, dim, num_heads, mlp_ratio=4.0, causal=True, dropout=0.1, use_fp8=False): + super().__init__() + self.norm1 = nn.LayerNorm(dim) + self.attn = FlashAttention(dim, num_heads=num_heads, causal=causal, dropout=dropout, use_fp8=use_fp8) + + self.norm2 = nn.LayerNorm(dim) + mlp_hidden_dim = int(dim * mlp_ratio) + self.mlp = nn.Sequential( + nn.Linear(dim, mlp_hidden_dim), + nn.GELU(), + nn.Dropout(dropout), + nn.Linear(mlp_hidden_dim, dim), + nn.Dropout(dropout) + ) + + def forward(self, x): + x = x + self.attn(self.norm1(x)) + x = x + self.mlp(self.norm2(x)) + return x + +class FlashLM(nn.Module): + def __init__( + self, + vocab_size, + dim=256, + depth=6, + num_heads=8, + mlp_ratio=4.0, + causal=True, + dropout=0.1, + max_seq_len=256, + use_fp8=False + ): + super().__init__() + + # embedding layers + self.token_embedding = nn.Embedding(vocab_size, dim) + self.position_embedding = nn.Parameter(torch.zeros(1, max_seq_len, dim)) + self.dropout = nn.Dropout(dropout) + + # transformer blocks + self.blocks = nn.ModuleList([ + TransformerBlock(dim, num_heads, mlp_ratio, causal=causal, dropout=dropout, use_fp8=use_fp8) + for _ in range(depth) + ]) + + # lm head: project back to vocabulary dimension for each token + self.norm = nn.LayerNorm(dim) + self.lm_head = nn.Linear(dim, vocab_size) + + def forward(self, x): + b, n = x.shape + + # token + positional embedding + x = self.token_embedding(x) + x = x + self.position_embedding[:, :n, :] + x = self.dropout(x) + + # transformer blocks + for block in self.blocks: + x = block(x) + + # language modeling head + x = self.norm(x) + logits = self.lm_head(x) # shape: (b, n, vocab_size) + return logits + +# ------------------------------- +# Data +# ------------------------------- +class TextDataset(Dataset): + def __init__(self, sequences, max_len=None): + self.sequences = sequences + self.max_len = max_len + + def __len__(self): + return len(self.sequences) + + def __getitem__(self, idx): + seq = self.sequences[idx] + # input: all tokens except the last, target: all tokens except the first + return (torch.tensor(seq[:-1], dtype=torch.long), + torch.tensor(seq[1:], dtype=torch.long)) + +class VarLenTextDataset(Dataset): + def __init__(self, sequences, max_len=256): + self.sequences = sequences + self.max_len = max_len + + def __len__(self): + return len(self.sequences) + + def __getitem__(self, idx): + seq = self.sequences[idx] + # Ensure the sequence doesn't exceed max_len+1 + seq = seq[:self.max_len+1] + # input: all tokens except the last, target: all tokens except the first + return (torch.tensor(seq[:-1], dtype=torch.long), + torch.tensor(seq[1:], dtype=torch.long)) + +def prepare_dataset(batch_size, is_varlen=False, min_len=10, max_len=256, ratio_shorter=0.7): + # load the WikiText-2 + dataset = load_dataset("wikitext", "wikitext-2-raw-v1", split="train") + + # build vocabulary + corpus = " ".join([line for line in dataset["text"] if line.strip() != ""]) # join non-empty lines into a single corpus string + tokens = corpus.split() + vocab = sorted(set(tokens)) + word2idx = {word: idx for idx, word in enumerate(vocab)} + token_ids = [word2idx[word] for word in tokens] + + num_workers = 2 + if is_varlen: + # VARIABLE LENGTH: create sequences of different lengths + sequences = [] + for i in range(0, len(token_ids) - max_len, max_len // 2): # overlap to get more sequences + # Decide target length for this sequence + if np.random.random() < ratio_shorter: + # Shorter sequence + target_len = np.random.randint(min_len + 1, max_len + 1) + else: + # Full length sequence + target_len = max_len + 1 + + # Extract sequence up to target length or whatever's available + seq_end = min(i + target_len, len(token_ids)) + seq = token_ids[i:seq_end] + + # Only keep sequences that are long enough + if len(seq) > min_len + 1: # +1 because we need both input and target + sequences.append(seq) + + print(f"Created {len(sequences)} variable-length sequences") + + # Get some statistics + lens = [len(seq) for seq in sequences] + print(f"Sequence length stats: min={min(lens)}, max={max(lens)}, mean={np.mean(lens):.1f}") + + # split dataset + num_samples = len(sequences) + num_train = int(0.8 * num_samples) + num_val = num_samples - num_train + + # Use appropriate dataset class based on whether we need variable length + dataset_class = VarLenTextDataset + train_sequences = sequences[:num_train] + val_sequences = sequences[num_train:] + + train_dataset = dataset_class(train_sequences, max_len) + val_dataset = dataset_class(val_sequences, max_len) + + + # collate function + def collate_fn(batch): + """ + Collate function that creates a flat representation for variable length flash attention. + """ + # Separate inputs and targets + inputs, targets = zip(*batch) + + # Get sequence lengths + seq_lens = torch.tensor([len(x) for x in inputs], dtype=torch.int32) + + # Concatenate inputs and targets into single tensors + flat_inputs = torch.cat(inputs) + flat_targets = torch.cat(targets) + + # Create cumulative sequence lengths tensor + cu_seqlens = torch.zeros(len(seq_lens) + 1, dtype=torch.int32) + cu_seqlens[1:] = torch.cumsum(seq_lens, dim=0) + + # Calculate max sequence length for this batch + max_seqlen = seq_lens.max().item() + + return flat_inputs, flat_targets, seq_lens, cu_seqlens, max_seqlen + + # data loaders + train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers, collate_fn=collate_fn) + val_dataloader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers, collate_fn=collate_fn) + else: + # FIXED LENGTH: create sequences of length max_len+1 + sequences = [] + for i in range(0, len(token_ids) - max_len, max_len): + seq = token_ids[i : i + max_len + 1] + if len(seq) == max_len + 1: + sequences.append(seq) + + # split dataset + num_samples = len(sequences) + num_train = int(0.8 * num_samples) + num_val = num_samples - num_train + train_dataset, val_dataset = random_split(TextDataset(sequences), [num_train, num_val]) + + # data loaders + train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers) + val_dataloader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers) + + vocab_size = len(vocab) + print(f"vocab size: {vocab_size}, train samples: {len(train_dataset)}, validation samples: {len(val_dataset)}") + return train_dataloader, val_dataloader, vocab_size + +# ------------------------------- +# Training +# ------------------------------- +def train_lm(model, train_dataloader, val_dataloader, optimizer, criterion, num_epochs): + train_losses = [] + val_losses = [] + for epoch in range(num_epochs): + # Training phase + model.train() + epoch_train_loss = 0.0 + for inputs, targets in tqdm(train_dataloader, desc=f"epoch {epoch+1}/{num_epochs} [train]"): + inputs, targets = inputs.to(device), targets.to(device) + + optimizer.zero_grad() + logits = model(inputs) + loss = criterion(logits.view(-1, logits.size(-1)), targets.view(-1)) + loss.backward() + optimizer.step() + + epoch_train_loss += loss.item() + + epoch_train_loss /= len(train_dataloader) + train_losses.append(epoch_train_loss) + print(f"epoch {epoch+1}/{num_epochs} - train loss: {epoch_train_loss:.4f}") + + # Validation phase + model.eval() + epoch_val_loss = 0.0 + with torch.no_grad(): + for inputs, targets in tqdm(val_dataloader, desc=f"epoch {epoch+1}/{num_epochs} [validation]"): + inputs, targets = inputs.to(device), targets.to(device) + logits = model(inputs) + loss = criterion(logits.view(-1, logits.size(-1)), targets.view(-1)) + epoch_val_loss += loss.item() + epoch_val_loss /= len(val_dataloader) + val_losses.append(epoch_val_loss) + print(f"epoch {epoch+1}/{num_epochs} - validation loss: {epoch_val_loss:.4f}") + + return train_losses, val_losses + +# ------------------------------- +# Main +# ------------------------------- +def main(): + # hyperparameters + batch_size = 16 + num_epochs = 20 + learning_rate = 3e-4 + max_len = 128 # total length including both input and target tokens + is_varlen = False + causal=True + dropout=0.1 + + # prep data + print("Preparing Dataset") + train_dataloader, val_dataloader, vocab_size = prepare_dataset(batch_size, max_len=max_len, is_varlen=is_varlen) + + # create language models + print("Creating Models") + model_normal = FlashLM( + vocab_size=vocab_size, + dim=256, + depth=3, + num_heads=8, + causal=causal, + dropout=dropout, + max_seq_len=max_len, + ).to(device) + + model_fp8 = FlashLM( + vocab_size=vocab_size, + dim=256, + depth=3, + num_heads=8, + causal=causal, + dropout=dropout, + max_seq_len=max_len, + use_fp8=True + ).to(device) + + # Train Normal model + print("Starting training for Normal model...") + optimizer_normal = optim.AdamW(model_normal.parameters(), lr=learning_rate) + criterion = nn.CrossEntropyLoss() + normal_train_losses, normal_val_losses = train_lm( + model_normal, train_dataloader, val_dataloader, optimizer_normal, criterion, num_epochs + ) + torch.save(model_normal.state_dict(), 'flash_lm_normal.pth') + print("Normal model training complete and saved.") + + # Train FP8 model + print("Starting training for FP8 model...") + optimizer_fp8 = optim.AdamW(model_fp8.parameters(), lr=learning_rate) + fp8_train_losses, fp8_val_losses = train_lm( + model_fp8, train_dataloader, val_dataloader, optimizer_fp8, criterion, num_epochs + ) + torch.save(model_fp8.state_dict(), 'flash_lm_fp8.pth') + print("FP8 model training complete and saved.") + + # save losses to csv + epochs = range(1, num_epochs+1) + loss_data = { + "Epoch": epochs, + "Normal_Training_Loss": normal_train_losses, + "Normal_Validation_Loss": normal_val_losses, + "FP8_Training_Loss": fp8_train_losses, + "FP8_Validation_Loss": fp8_val_losses, + } + df_losses = pd.DataFrame(loss_data) + df_losses.to_csv("losses.csv", index=False) + print("Loss data saved to losses.csv") + + # plot Training Loss + plt.figure(figsize=(10, 6)) + plt.plot(epochs, normal_train_losses, label="Normal Training Loss", marker='o') + plt.plot(epochs, fp8_train_losses, label="FP8 Training Loss", marker='x') + plt.xlabel("Epoch") + plt.ylabel("Training Loss") + plt.title("Training Loss Comparison: Normal vs FP8 Flash Attention") + plt.legend() + plt.grid(True) + plt.savefig("training_loss.png") # Saves the training loss plot to disk + plt.show() + + # Plot Validation Loss + plt.figure(figsize=(10, 6)) + plt.plot(epochs, normal_val_losses, label="Normal Validation Loss", marker='o') + plt.plot(epochs, fp8_val_losses, label="FP8 Validation Loss", marker='x') + plt.xlabel("Epoch") + plt.ylabel("Validation Loss") + plt.title("Validation Loss Comparison: Normal vs FP8 Flash Attention") + plt.legend() + plt.grid(True) + plt.savefig("validation_loss.png") # Saves the validation loss plot to disk + plt.show() + + +if __name__ == "__main__": + main() diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/utils.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0300e3902a14751762ac965994f9dc6f67ca6363 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_amd/utils.py @@ -0,0 +1,776 @@ +import csv +import math +import torch +import os +import random +import functools +import triton +import triton.language as tl +from typing import Literal, Optional, Union + +# ------------------------------- +# Gloabl Variables +# ------------------------------- +AUTOTUNE = os.environ.get('FLASH_ATTENTION_TRITON_AMD_AUTOTUNE', '0').lower() in ('1', 'true', 'yes') +DEBUG = os.environ.get('FLASH_ATTENTION_TRITON_AMD_DEBUG', '0').lower() in ('1', 'true', 'yes') +USE_REF = os.environ.get('FLASH_ATTENTION_TRITON_AMD_REF', '0').lower() in ('1', 'true', 'yes') +PERF = os.environ.get('FLASH_ATTENTION_TRITON_AMD_PERF', '0').lower() in ('1', 'true', 'yes') +USE_SINGLE_BWD_KERNEL = os.environ.get('USE_SINGLE_BWD_KERNEL', '0').lower() in ('1', 'true', 'yes') +USE_TRITON_ROCM = os.getenv("FLASH_ATTENTION_TRITON_AMD_ENABLE", "FALSE") == "TRUE" +USE_TRITON_INTERPRET = os.environ.get('TRITON_INTERPRET', '0').lower() in ('1', 'true', 'yes') +DEBUG_TRITON = os.environ.get('DEBUG_TRITON', '0').lower() in ('1', 'true', 'yes') and USE_TRITON_INTERPRET +DEBUG_TRITON_DETAIL = os.environ.get('DEBUG_TRITON_DETAIL', '0').lower() in ('1', 'true', 'yes') and USE_TRITON_INTERPRET +if USE_TRITON_ROCM: # TODO remove this + random.seed(42) +DROPOUT_USE_PYTORCH = False +DROPOUT_DUMP = False + + +# ------------------------------- +# Metadata +# ------------------------------- +class MetaData(): + cu_seqlens_q: Optional[torch.Tensor] = None + cu_seqlens_k: Optional[torch.Tensor] = None + max_seqlens_q: int = 0 + max_seqlens_k: int = 0 + bias: Optional[torch.Tensor] = None + alibi_slopes: Optional[torch.Tensor] = None + causal: bool = False + num_contexts = 0 + varlen: bool = False + layout: Optional[Literal["bshd", "bhsd", "thd"]] = None + cache_seqlens: Optional[Union[(int, torch.Tensor)]] = None + cache_batch_idx = None + packing: Optional[bool] = None + return_scores: bool = False + dropout_p: float = 0.0 + philox_seed: Optional[int] = None + philox_offset : Optional[int]= None # if dropout_p > 0.0 seed the RNG so we get reproducible results for testing. + # NOTE: scale sm_scale by log_2(e) and use 2^x in the loop as we do not have native e^x support in HW. + use_exp2: bool = False + rotary_sin: Optional[torch.Tensor] = None + rotary_cos: Optional[torch.Tensor] = None + rotary_interleaved: bool = False + rotary_conjunction: bool = False + + + def __repr__(self) -> str: + return (f"MetaData(\n" + f" sm_scale={self.sm_scale},\n" + f" cu_seqlens_q={self.cu_seqlens_q},\n" + f" cu_seqlens_k={self.cu_seqlens_k},\n" + f" max_seqlens_q={self.max_seqlens_q},\n" + f" max_seqlens_k={self.max_seqlens_k},\n" + f" bias={self.bias},\n" + f" alibi_slopes={self.alibi_slopes},\n" + f" causal={self.causal},\n" + f" num_contexts={self.num_contexts},\n" + f" varlen={self.varlen},\n" + f" layout={self.layout},\n" + f" cache_seqlens={self.cache_seqlens},\n" + f" cache_batch_idx={self.cache_batch_idx},\n" + f" dropout_p={self.dropout_p},\n" + f" return_scores={self.return_scores}\n" + f")") + + def __init__(self, sm_scale=1.0): + self.sm_scale = sm_scale + + def set_varlen_params(self, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k): + self.varlen = True + self.layout = 'thd' + self.cu_seqlens_q = cu_seqlens_q + self.cu_seqlens_k = cu_seqlens_k + self.max_seqlens_q = max_seqlen_q + self.max_seqlens_k = max_seqlen_k + + # Without "varlen", there should still be one sequence. + assert len(cu_seqlens_q) >= 2 + assert len(cu_seqlens_q) == len(cu_seqlens_k) + + def need_bias(self, bias, batch, nheads, seqlen_q, seqlen_k): + assert bias.is_cuda + assert bias.dim() == 4 + assert bias.shape[0] == 1 + assert bias.shape[2:] == (seqlen_q, seqlen_k) + self.bias = bias + + def need_alibi(self, alibi_slopes, batch, nheads): + assert alibi_slopes.is_cuda + assert alibi_slopes.dim() == 2 + assert alibi_slopes.shape[0] == batch + assert alibi_slopes.shape[1] == nheads + self.alibi_slopes = alibi_slopes + + def need_causal(self, causal): + self.causal = causal + + def need_rotary(self, sin, cos, rotary_interleaved, rotary_conjunction=False): + self.rotary_sin = sin + self.rotary_cos = cos + self.rotary_interleaved = rotary_interleaved + self.rotary_conjunction = rotary_conjunction + + def need_dropout(self, dropout_p, return_scores = True): + if dropout_p > 0.0: + self.dropout_p = dropout_p + self.return_scores = return_scores + self.philox_seed, self.philox_offset = 0x1BF58, 0x1D4B49 + + def check_args(self, q, k, v, o): + assert q.dim() == k.dim() and q.dim() == v.dim() + + batch, nheads_q, nheads_k, head_size, _, _ = get_shapes_from_layout(q, k, self.layout, self.cu_seqlens_q, self.cu_seqlens_k, self.max_seqlens_q, self.max_seqlens_k) + if self.varlen: + assert q.dim() == 3 + assert self.cu_seqlens_q is not None + assert self.cu_seqlens_k is not None + assert len(self.cu_seqlens_q) == len(self.cu_seqlens_k) + # TODO: Remove once bias is supported with varlen + assert self.bias is None + # assert not self.return_scores + else: + assert q.dim() == 4 + assert self.max_seqlens_q > 0 and self.max_seqlens_k > 0 + assert self.cu_seqlens_q is None and self.cu_seqlens_k is None + assert k.shape == v.shape + assert q.shape[-1] == k.shape[-1] and q.shape[-1] == v.shape[-1] + # TODO: Change assert if we support qkl f8 and v f16 + assert q.dtype == k.dtype and q.dtype == v.dtype + assert o.shape == q.shape + assert (nheads_q % nheads_k) == 0 + assert self.layout is not None + assert self.layout == 'thd' or not self.varlen + +# ------------------------------- +# Input Helper +# ------------------------------- +def random_seqlens_composition(SEQ_LEN, BATCH): + # generate a random composition of N into Z positive parts. + idx = torch.randperm(SEQ_LEN - 1)[: BATCH - 1] + 1 + idx, _ = torch.sort(idx) + breakpoints = torch.cat([ + torch.tensor([0], dtype=torch.long), + idx, + torch.tensor([SEQ_LEN], dtype=torch.long), + ]) + seqlens = (breakpoints[1:] - breakpoints[:-1]).to(torch.int32) + return seqlens + +def generate_varlen_tensor( + total_seqlen: int, + num_heads: int, + head_size: int, + batch_size: Optional[int] = None, + equal_seqlens: bool = False, + device: str = "cuda", + dtype: torch.dtype = torch.float32, + DEBUG_INPUT: bool = False +): + if DEBUG: + print("total_seqlen", total_seqlen) + print("num_heads", num_heads) + print("head_size", head_size) + + # save fp8 type + is_fp8_dtype = is_dtype_fp8(dtype) + if is_fp8_dtype: + og_fp8_dtype = dtype + dtype = torch.float32 + + # get valid batch_size + if batch_size is None: + valid_batch_sizes = [bs for bs in [1, 2, 4, 8, 16, 32, 64] if bs <= total_seqlen] + batch_size = random.choice(valid_batch_sizes) + + # get seqlens + if equal_seqlens: + seqlens = torch.full( + (batch_size,), + total_seqlen // batch_size, + dtype=torch.int32, + device=device + ) + seqlens[-1] += total_seqlen % batch_size + else: + seqlens = random_seqlens_composition(total_seqlen, batch_size).to(device=device) + + # create cumulative sequence lengths + cu_seqlens = torch.cat([torch.tensor([0], dtype=torch.int32, device=device), seqlens.cumsum(dim=0)]).to(torch.int32).to(device=device) + max_seqlen = torch.max(seqlens).to(torch.int32).item() + + # create varlen tensor + if DEBUG_INPUT: + x = torch.zeros(total_seqlen, num_heads, head_size, dtype=dtype, device=device) + for i in range(batch_size): + start = cu_seqlens[i].item() + end = cu_seqlens[i+1].item() + length = end - start + + x[start:end, :, :] = ( + torch.arange(length, dtype=dtype, device=device) + .view(length, 1, 1) + .expand(length, num_heads, head_size) + ) + else: + x = torch.randn((total_seqlen, num_heads, head_size), dtype=dtype, device=device) + + if is_fp8_dtype: + # cast to fp8 + x, descale_x = cast_to_fp8(x, og_fp8_dtype, "thd", cu_seqlens=cu_seqlens, max_seqlen=max_seqlen) + x.requires_grad_() + return x, cu_seqlens, max_seqlen, descale_x + else: + x.requires_grad_() + return x, cu_seqlens, max_seqlen + +def generate_bshd_tensor(BATCH, SEQ_LEN, NUM_HEADS, D_HEAD, dtype, device="cuda", DEBUG_INPUT=False): + # save fp8 type + is_fp8_dtype = is_dtype_fp8(dtype) + if is_fp8_dtype: + og_fp8_dtype = dtype + dtype = torch.float32 + + # gen tensor + tensor_shape = (BATCH, SEQ_LEN, NUM_HEADS, D_HEAD) + if DEBUG_INPUT: + x = torch.arange(SEQ_LEN, dtype=dtype, device=device).view(1, SEQ_LEN, 1, 1).expand(*tensor_shape).contiguous() + else: + x = torch.randn(tensor_shape, dtype=dtype, device=device) + + if is_fp8_dtype: + # cast to fp8 + x, descale_x = cast_to_fp8(x, og_fp8_dtype, "bshd") + x.requires_grad_() + return x, descale_x + else: + x.requires_grad_() + return x + +def generate_bhsd_tensor(BATCH, NUM_HEADS, SEQ_LEN, D_HEAD, dtype, device="cuda", DEBUG_INPUT=False): + # save fp8 type + is_fp8_dtype = is_dtype_fp8(dtype) + if is_fp8_dtype: + og_fp8_dtype = dtype + dtype = torch.float32 + + # gen tensor + tensor_shape = (BATCH, NUM_HEADS, SEQ_LEN, D_HEAD) + if DEBUG_INPUT: + x = torch.arange(SEQ_LEN, dtype=dtype, device=device).view(1, 1, SEQ_LEN, 1).expand(*tensor_shape).contiguous() + else: + x = torch.randn(tensor_shape, dtype=dtype, device=device) + + + if is_fp8_dtype: + # cast to fp8 + x, descale_x = cast_to_fp8(x, og_fp8_dtype, "bhsd") # FIXME: I don't the casting fn supports this atm + x.requires_grad_() + return x, descale_x + else: + x.requires_grad_() + return x + +def input_helper( + BATCH: int, + HQ: int, + HK: int, + N_CTX_Q: int, + N_CTX_K: int, + D_HEAD: int, + CAUSAL: bool, + DROPOUT_P: float, + dtype: torch.dtype, + layout: Literal["bshd", "bhsd", "thd"], + packing: Optional[Literal["kv", "qkv"]] = None, + device: Literal["cpu", "cuda"] = "cuda", + DEBUG_INPUT: bool = False, +): + torch.manual_seed(20) + is_fp8_dtype = is_dtype_fp8(dtype) + + if layout == "thd": + # set params + TOTAL_SEQLENS_Q = BATCH * N_CTX_Q + TOTAL_SEQLENS_K = BATCH * N_CTX_K + equal_seqlens=False + + # gen tensors + # TODO: the gen functions should maybe have different gen modes like random, ones, increasing seqlen + if is_fp8_dtype: + q, cu_seqlens_q, max_seqlen_q, descale_q = generate_varlen_tensor(TOTAL_SEQLENS_Q, HQ, D_HEAD, batch_size=BATCH, dtype=dtype, device=device, equal_seqlens=equal_seqlens, DEBUG_INPUT=DEBUG_INPUT) + k, cu_seqlens_k, max_seqlen_k, descale_k = generate_varlen_tensor(TOTAL_SEQLENS_K, HK, D_HEAD, batch_size=BATCH, dtype=dtype, device=device, equal_seqlens=equal_seqlens, DEBUG_INPUT=DEBUG_INPUT) + v, _, _ , descale_v = generate_varlen_tensor(TOTAL_SEQLENS_K, HK, D_HEAD, batch_size=BATCH, dtype=dtype, device=device, equal_seqlens=equal_seqlens, DEBUG_INPUT=DEBUG_INPUT) + do, _, _ , descale_do = generate_varlen_tensor(TOTAL_SEQLENS_Q, HQ, D_HEAD, batch_size=BATCH, dtype=dtype, device=device, equal_seqlens=equal_seqlens) + else: + q, cu_seqlens_q, max_seqlen_q = generate_varlen_tensor(TOTAL_SEQLENS_Q, HQ, D_HEAD, batch_size=BATCH, dtype=dtype, device=device, equal_seqlens=equal_seqlens, DEBUG_INPUT=DEBUG_INPUT) + k, cu_seqlens_k, max_seqlen_k = generate_varlen_tensor(TOTAL_SEQLENS_K, HK, D_HEAD, batch_size=BATCH, dtype=dtype, device=device, equal_seqlens=equal_seqlens, DEBUG_INPUT=DEBUG_INPUT) + v, _, _ = generate_varlen_tensor(TOTAL_SEQLENS_K, HK, D_HEAD, batch_size=BATCH, dtype=dtype, device=device, equal_seqlens=equal_seqlens, DEBUG_INPUT=DEBUG_INPUT) + do = torch.ones_like(q) if DEBUG_INPUT else torch.randn_like(q) + + # setup metadata + if DEBUG_INPUT: + sm_scale = 1 + else: + sm_scale = D_HEAD**-0.5 + metadata = MetaData(sm_scale=sm_scale) + metadata.set_varlen_params(cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k) + metadata.need_causal(CAUSAL) + metadata.need_dropout(DROPOUT_P) + elif layout == 'bshd' or layout == "bhsd": + # gen tensors + if layout == "bshd": + if is_fp8_dtype: + q, descale_q = generate_bshd_tensor(BATCH, N_CTX_Q, HQ, D_HEAD, dtype=dtype, device=device, DEBUG_INPUT=DEBUG_INPUT) + k, descale_k = generate_bshd_tensor(BATCH, N_CTX_K, HK, D_HEAD, dtype=dtype, device=device, DEBUG_INPUT=DEBUG_INPUT) + v, descale_v = generate_bshd_tensor(BATCH, N_CTX_K, HK, D_HEAD, dtype=dtype, device=device, DEBUG_INPUT=DEBUG_INPUT) + do, descale_do = generate_bshd_tensor(BATCH, N_CTX_Q, HQ, D_HEAD, dtype=dtype, device=device) + else: + q = generate_bshd_tensor(BATCH, N_CTX_Q, HQ, D_HEAD, dtype=dtype, device=device, DEBUG_INPUT=DEBUG_INPUT) + k = generate_bshd_tensor(BATCH, N_CTX_K, HK, D_HEAD, dtype=dtype, device=device, DEBUG_INPUT=DEBUG_INPUT) + v = generate_bshd_tensor(BATCH, N_CTX_K, HK, D_HEAD, dtype=dtype, device=device, DEBUG_INPUT=DEBUG_INPUT) + do = torch.ones_like(q) if DEBUG_INPUT else torch.randn_like(q) + elif layout == "bhsd": + if is_fp8_dtype: + q, descale_q = generate_bhsd_tensor(BATCH, HQ, N_CTX_Q, D_HEAD, dtype=dtype, device=device, DEBUG_INPUT=DEBUG_INPUT) + k, descale_k = generate_bhsd_tensor(BATCH, HK, N_CTX_K, D_HEAD, dtype=dtype, device=device, DEBUG_INPUT=DEBUG_INPUT) + v, descale_v = generate_bhsd_tensor(BATCH, HK, N_CTX_K, D_HEAD, dtype=dtype, device=device, DEBUG_INPUT=DEBUG_INPUT) + do, descale_do = generate_bhsd_tensor(BATCH, HQ, N_CTX_Q, D_HEAD, dtype=dtype, device=device) + else: + q = generate_bhsd_tensor(BATCH, HQ, N_CTX_Q, D_HEAD, dtype=dtype, device=device, DEBUG_INPUT=DEBUG_INPUT) + k = generate_bhsd_tensor(BATCH, HK, N_CTX_K, D_HEAD, dtype=dtype, device=device, DEBUG_INPUT=DEBUG_INPUT) + v = generate_bhsd_tensor(BATCH, HK, N_CTX_K, D_HEAD, dtype=dtype, device=device, DEBUG_INPUT=DEBUG_INPUT) + do = torch.ones_like(q) if DEBUG_INPUT else torch.randn_like(q) + + # setup metadata + if DEBUG_INPUT: + sm_scale = 1 + else: + sm_scale = D_HEAD**-0.5 + metadata = MetaData(sm_scale=sm_scale) + metadata.max_seqlens_q = N_CTX_Q + metadata.max_seqlens_k = N_CTX_K + metadata.layout = layout + metadata.need_causal(CAUSAL) + metadata.need_dropout(DROPOUT_P) + else: + raise ValueError(f"Unknown layout: {layout}") + + # deal with packing + if packing is None: + if is_fp8_dtype: + return (q, descale_q), (k, descale_k), (v, descale_v), (do, descale_do), metadata + else: + return q, k, v, do, metadata + elif packing == "kv": + # pack k and v + if layout in ["bhsd", "thd"]: + kv = torch.stack([k, v], dim=1) + elif layout == "bshd": + kv = torch.stack([k, v], dim=2) + else: + raise ValueError(f"Unknown layout: {layout}") + + if is_fp8_dtype: + raise ValueError("FP8 not supported kv packing yet") + else: + return q, kv, do, metadata + elif packing == "qkv": + # qkv packing - requires same sequence length for q and k + assert N_CTX_Q == N_CTX_K, "For QKV packing, Q and K must have same sequence length" + assert HQ == HK, "For QKV packing, Q and K must have same number of heads" + + # pack q, k, and v + if layout in ["bhsd", "thd"]: + qkv = torch.stack([q, k, v], dim=1) + elif layout == "bshd": + qkv = torch.stack([q, k, v], dim=2) + else: + raise ValueError(f"Unknown layout: {layout}") + + if is_fp8_dtype: + raise ValueError("FP8 not supported qkv packing yet") + else: + return qkv, do, metadata + else: + assert False, f"Unsupported packing mode: {packing}" + +# ------------------------------- +# Alibi +# ------------------------------- +@triton.jit +def compute_alibi_block(alibi_slope, seqlen_q, seqlen_k, offs_m, offs_n, transpose=False): + # when seqlen_k and seqlen_q are different we want the diagonal to stick to the bottom right of the attention matrix + # for casual mask we want something like this where (1 is kept and 0 is masked) + # seqlen_q = 2 and seqlen_k = 5 + # 1 1 1 1 0 + # 1 1 1 1 1 + # seqlen_q = 5 and seqlen_k = 2 + # 0 0 + # 0 0 + # 0 0 + # 1 0 + # 1 1 + # for alibi the diagonal is 0 indicating no penalty for attending to that spot and increasing penalty for attending further from the diagonal + # e.g. alibi_slope = 1, seqlen_q = 2, seqlen_k = 5, offs_m = [0, 1, 2, 3], offs_n = [0, 1, 2, 3, 4], transpose = False + # 1. offs_m[:,None] = [[0], + # [1], + # 2. offs_m[:,None] + seqlen_k = [[5], + # [6], + # 3. offs_m[:,None] + seqlen_k - seqlen_q = [[3], + # [4], + # 4. offs_m[:,None] + seqlen_k - seqlen_q - offs_n[None,:] = [[3], - [[0, 1, 2, 3, 4]] = [[ 3, 2, 1, 0,-1], + # [4], [ 4, 3, 2, 1, 0]] + # 5. -1 * alibi_slope * tl.abs(relative_pos_block) = [[ -3, -2, -1, 0,-1], + # [ -4, -3, -2, -1, 0]], + relative_pos_block = offs_m[:, None] + seqlen_k - seqlen_q - offs_n[None, :] + alibi_block = -1 * alibi_slope * tl.abs(relative_pos_block) + if transpose: + return alibi_block.T + else: + return alibi_block + +# ------------------------------- +# FP8 +# ------------------------------- +def is_dtype_fp8(dtype): + if dtype in {torch.float8_e4m3fnuz, torch.float8_e4m3fn, torch.float8_e5m2, torch.float8_e5m2fnuz}: + if arch_supports_fp8(): + return True + else: + raise RuntimeError("This device doesnot support fp8") + else: + return False + +def is_fp8(x): + return is_dtype_fp8(x.dtype) + +@triton.jit +def compute_fp8_scaling_factors(x, fp8_max: tl.constexpr): + # compute fp8 scaling and descaling factor for a block + x_amax = tl.max(tl.abs(x)) # NOTE: abs deals with negative values + x_amax = tl.where(x_amax <= 1e-9, 1e-9, x_amax) + scale_x = fp8_max / x_amax + descale_x = x_amax / fp8_max + return scale_x, descale_x + +@triton.jit +def _cast_varlen_to_fp8_kernel_2d( + X, X_fp8, Descale, + cu_seqlens, H, MAX_SEQLEN, + stride_batch, stride_seq, stride_head, stride_dim, + stride_out_batch, stride_out_seq, stride_out_head, stride_out_dim, + stride_desc_batch, stride_desc_head, + FP8_CLAMP_VAL, + FP8_MAX, + BLOCK_SIZE: tl.constexpr, + HEAD_DIM: tl.constexpr, + ACTUAL_HEAD_DIM: tl.constexpr, + IS_VARLEN: tl.constexpr + ): + # Process one (batch, head) pair per kernel + b_id = tl.program_id(0) + h_id = tl.program_id(1) + + # Get sequence bounds for this batch + if IS_VARLEN: + seq_start = tl.load(cu_seqlens + b_id) + seq_end = tl.load(cu_seqlens + b_id + 1) + seqlen = seq_end - seq_start + else: + seq_start = 0 + seqlen = MAX_SEQLEN + + # initialize max value tracker + x_max_val = 0.0 + + # STEP 1: Find max absolute value across the entire sequence + num_of_blocks = tl.cdiv(seqlen, BLOCK_SIZE) + for blk_idx in range(0, num_of_blocks): + # print("blk_idx:", blk_idx) + # offsets + offs_seq = blk_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + offs_dim = tl.arange(0, HEAD_DIM) + + # Create mask for valid elements + mask_seq = offs_seq[:, None] < seqlen + if ACTUAL_HEAD_DIM != HEAD_DIM: + mask_dim = offs_dim[None, :] < ACTUAL_HEAD_DIM + mask_seq = mask_seq & mask_dim + + # Load block + adj_x = b_id * stride_batch + h_id * stride_head + seq_start * stride_seq + offs_seq[:, None] * stride_seq + offs_dim[None, :] * stride_dim + x_block = tl.load(X + adj_x, mask=mask_seq, other=0.0) + # print("x_block:", x_block) + + # Find max absolute value in this block + block_max = tl.max(tl.abs(x_block)) + # print("block_max:", block_max) + + # Update overall max + x_max_val = tl.maximum(x_max_val, block_max) + # print("x_max_val:", x_max_val) + + # clamp to avoid division by zero issues + x_max_val = tl.maximum(x_max_val, FP8_CLAMP_VAL) + + # compute scale and descale factors for the entire sequence + scale = FP8_MAX / x_max_val + descale = x_max_val / FP8_MAX + + # store descale factor for this (batch, head) pair + desc_ptr = Descale + b_id * stride_desc_batch + h_id# * stride_desc_head + tl.store(desc_ptr, descale) + + # STEP 2: Apply scaling to the entire sequence and convert to FP8 + for blk_idx in range(0, num_of_blocks): + # offsets + offs_seq = blk_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + offs_dim = tl.arange(0, HEAD_DIM) + + # Create mask for valid elements + mask_seq = offs_seq[:, None] < seqlen + if ACTUAL_HEAD_DIM != HEAD_DIM: + mask_dim = offs_dim[None, :] < ACTUAL_HEAD_DIM + mask_seq = mask_seq & mask_dim + + # Load block - Using the fixed addressing + addr = b_id * stride_batch + h_id * stride_head + seq_start * stride_seq + offs_seq[:, None] * stride_seq + offs_dim[None, :] * stride_dim + x_block = tl.load(X + addr, mask=mask_seq, other=0.0) + + # Apply scale and convert to FP8 + x_fp8_block = (x_block * scale).to(X_fp8.type.element_ty) + + # Store results + addr_out = b_id * stride_out_batch + h_id * stride_out_head + seq_start * stride_out_seq + offs_seq[:, None] * stride_out_seq + offs_dim[None, :] * stride_out_dim + tl.store(X_fp8 + addr_out, x_fp8_block, mask=mask_seq) + +def cast_to_fp8( + x: torch.Tensor, + fp8_dtype: torch.dtype, + layout: Literal["bshd", "thd"], + clamp_val: float = 1e-9, + cu_seqlens: Optional[torch.Tensor] = None, + max_seqlen: Optional[int] = None +) -> tuple[torch.Tensor, torch.Tensor]: + if False: + print() + print("cast_to_fp8") + print("x:", x, x.shape) + print("fp8_dtype:", fp8_dtype) + print("cu_seqlens:", cu_seqlens) + print("max_seqlen:", max_seqlen) + print("clamp_val:", clamp_val) + + # check types are valid + assert x.dtype in {torch.float16, torch.float32, torch.float64, torch.bfloat16} and is_dtype_fp8(fp8_dtype), f"Cannot cast {x.dtype} to {fp8_dtype}" + + # extract dimensions + batch, max_seqlen_final, num_heads, head_dim = get_shape_from_layout(x, layout, cu_seqlens, max_seqlen) + is_varlen = layout == "thd" + fp8_max = torch.finfo(fp8_dtype).max + if False: + print("batch:", batch) + print("max_seqlen_final:", max_seqlen_final) + print("num_heads:", num_heads) + print("head_dim:", head_dim) + + # get closest power of 2 for head_dim + padded_head_dim = 1 << (head_dim - 1).bit_length() + padded_head_dim = max(padded_head_dim, 32) + + # kernel params + x_fp8 = torch.zeros_like(x, dtype=fp8_dtype) + descale_factors = torch.zeros((batch, num_heads), device=x.device, dtype=torch.float32) + BLOCK_SIZE = 128 + + # calculate strides + stride_batch, stride_head, stride_seq, stride_dim = get_stride_from_layout(x, layout) + stride_out_batch, stride_out_head, stride_out_seq, stride_out_dim = get_stride_from_layout(x_fp8, layout) + stride_desc_batch, stride_desc_head = descale_factors.stride() + + if False: + print("stride_batch", stride_batch) + print("stride_head", stride_head) + print("stride_seq", stride_seq) + print("stride_dim", stride_dim) + print("stride_out_batch", stride_out_batch) + print("stride_out_head", stride_out_head) + print("stride_out_seq", stride_out_seq) + print("stride_out_dim", stride_out_dim) + print("stride_desc_batch", stride_desc_batch) + print("stride_desc_head", stride_desc_head) + + grid = (batch, num_heads) + _cast_varlen_to_fp8_kernel_2d[grid]( + x, x_fp8, descale_factors, + cu_seqlens, num_heads, max_seqlen_final, + stride_batch, stride_seq, stride_head, stride_dim, + stride_out_batch, stride_out_seq, stride_out_head, stride_out_dim, + stride_desc_batch, stride_desc_head, + clamp_val, fp8_max, + BLOCK_SIZE=BLOCK_SIZE, + HEAD_DIM=padded_head_dim, + ACTUAL_HEAD_DIM=head_dim, + IS_VARLEN=is_varlen + ) + + if False: + print("x_fp8:", x_fp8, x_fp8.shape) + print("descale_factors:", descale_factors, descale_factors.shape) + return x_fp8, descale_factors + +# ------------------------------- +# Misc +# ------------------------------- +def get_shape_from_layout( + x: torch.Tensor, + layout: Literal["bshd", "bhsd", "thd"], + cu_seqlens: Optional[torch.Tensor] = None, + max_seqlen: Optional[int] = None, +) -> tuple[int, int, int, int]: + if layout == 'bhsd': + batch, num_heads, max_seqlen_final, head_dim = x.shape + elif layout == 'bshd': + batch, max_seqlen_final, num_heads, head_dim = x.shape + elif layout == 'thd': + total_seqlen, num_heads, head_dim = x.shape + if cu_seqlens is None: + raise ValueError("cu_seqlens must be provided for varlen (thd) layout") + if max_seqlen is None: + raise ValueError("max_seqlen must be provided for varlen (thd) layout") + + batch, max_seqlen_final, num_heads, head_dim = len(cu_seqlens) - 1, max_seqlen, num_heads, head_dim + else: + assert False, "Got unsupported layout." + + return batch, max_seqlen_final, num_heads, head_dim + + +def get_shapes_from_layout(q, k, layout, cu_seqlens_q = None, cu_seqlens_k = None, max_seqlen_q=None, max_seqlen_k=None): + batch_q, seqlen_q, nheads_q, head_size_q = get_shape_from_layout(q, layout, cu_seqlens_q, max_seqlen_q) + batch_k, seqlen_k, nheads_k, head_size_k = get_shape_from_layout(k, layout, cu_seqlens_k, max_seqlen_k) + + # assert + assert batch_q == batch_k + assert head_size_q == head_size_k + + return batch_q, nheads_q, nheads_k, head_size_q, seqlen_q, seqlen_k + +def get_stride_from_layout(x: torch.Tensor, layout:Literal["bshd", "bhsd", "thd"]): + if layout == 'thd': + strides = (0, x.stride(1), x.stride(0), x.stride(2)) + elif layout == 'bhsd': + strides = (x.stride(0), x.stride(1), x.stride(2), x.stride(3)) + elif layout == 'bshd': + strides = (x.stride(0), x.stride(2), x.stride(1), x.stride(3)) + else: + assert False, 'Got unsupported layout.' + return strides + +def get_shape_and_strides_from_layout(x: torch.Tensor, layout: Literal["bshd", "bhsd", "thd"], cu_seqlens: Optional[torch.Tensor] = None, max_seqlen: Optional[int] = None): + return get_shape_from_layout(x, layout, cu_seqlens, max_seqlen), get_stride_from_layout(x, layout) + +def get_strides_from_layout(q, k, v, o, layout): + q_strides = get_stride_from_layout(q, layout) + k_strides = get_stride_from_layout(k, layout) + v_strides = get_stride_from_layout(v, layout) + o_strides = get_stride_from_layout(o, layout) + return q_strides, k_strides, v_strides, o_strides + +def get_padded_headsize(size): + # Get closest power of 2 over or equal to 32. + padded_d_model = 1 << (size - 1).bit_length() + # Smallest head_dim supported is 16. If smaller, the tile in the + # kernel is padded - there is no padding in memory for any dims. + padded_d_model = max(padded_d_model, 16) + return padded_d_model + +def compute_alibi_tensor_ref(alibi_slopes, seqlen_q, seqlen_k): + q_idx = torch.arange(seqlen_q, dtype=torch.int32, device="cuda").unsqueeze(-1) # (N_CTX_Q, 1) + k_idx = torch.arange(seqlen_k, dtype=torch.int32, device="cuda").unsqueeze(0) # (1, N_CTX_K) + relative_pos = torch.abs(q_idx + seqlen_k - seqlen_q - k_idx) # (N_CTX_Q, N_CTX_K) + return -1 * alibi_slopes.unsqueeze(-1).unsqueeze(-1) * relative_pos # (Z, H, N_CTX_Q, N_CTX_K) + +# ------------------------------- +# Dropouts +# ------------------------------- +def create_dropout_mask(dropout_p, shape, seed): + device = "cuda" + rand_vals = torch.rand(shape, generator=torch.Generator(device=device).manual_seed(seed), device=device, dtype=torch.float32) + return rand_vals > dropout_p + +def create_dropout_mask_varlen(dropout_p, batch, nheads_q, cu_seqlens_q, cu_seqlens_k, philox_seed): + device = "cuda" + qlens = (cu_seqlens_q[1:] - cu_seqlens_q[:-1]) + klens = (cu_seqlens_k[1:] - cu_seqlens_k[:-1]) + max_qlen = qlens.max() + max_klen = klens.max() + dropout_mask = torch.zeros((batch, nheads_q, max_qlen, max_klen), device=device) + for b in range(batch): + qlen = qlens[b] + klen = klens[b] + rand_vals = torch.rand((nheads_q, qlen, klen), generator=torch.Generator(device=device).manual_seed(philox_seed), device=device, dtype=torch.float32) + submask = rand_vals > dropout_p + dropout_mask[b, :, :qlen, :klen] = submask + + return dropout_mask + +def write_dropout_mask(x, tensor_name = "tensor"): + batch, head, seqlen_m, seqlen_n = x.shape + x = x.tolist() + + with open(f'{tensor_name}.csv', 'w') as f: + writer = csv.writer(f) + for b in range(batch): + for h in range(head): + dropout_mask = x[b][h] + if True: + BLOCK_M = 64 + BLOCK_N = 64 + + # Calculate number of blocks in each dimension + m_blocks = math.ceil(seqlen_m / BLOCK_M) + n_blocks = math.ceil(seqlen_n / BLOCK_N) + + # Process each block + for m_block in range(m_blocks): + # Calculate row range for current block + row_start = m_block * BLOCK_M + row_end = min(row_start + BLOCK_M, seqlen_m) + + for n_block in range(n_blocks): + # Calculate column range for current block + col_start = n_block * BLOCK_N + col_end = min(col_start + BLOCK_N, seqlen_n) + + # Extract and write the current block + for row_idx in range(row_start, row_end): + row_data = dropout_mask[row_idx][col_start:col_end] + writer.writerow(row_data) + else: + writer.writerows(dropout_mask) + +# ------------------------------- +# Runtime info +# ------------------------------- +@functools.cache +def is_hip(): + return triton.runtime.driver.active.get_current_target().backend == "hip" + +@functools.cache +def get_arch(): + return triton.runtime.driver.active.get_current_target().arch + +@functools.cache +def is_cdna(): + return is_hip() and get_arch() in ('gfx908', 'gfx90a', 'gfx940', 'gfx941', 'gfx942', 'gfx950') + +@functools.cache +def is_rdna(): + return is_hip() and get_arch() in ("gfx1030", "gfx1100", "gfx1101", "gfx1102", "gfx1200", "gfx1201") + +@functools.cache +def arch_supports_fp8(): + return is_hip() and get_arch() in ('gfx942') diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_og.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_og.py new file mode 100644 index 0000000000000000000000000000000000000000..f2ddb99487b4f162745e2f6dd3d1744946dc3fb2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_attn_triton_og.py @@ -0,0 +1,365 @@ +# [2022-10-23] Downloaded from https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py +# for benchmarking. +# We fixed a few dtype cast to make it work for bf16 + +""" +Fused Attention +=============== +This is a Triton implementation of the Flash Attention algorithm +(see: Dao et al., https://arxiv.org/pdf/2205.14135v2.pdf; Rabe and Staats https://arxiv.org/pdf/2112.05682v2.pdf) +""" + +import pytest +import torch +import triton +import triton.language as tl + + +@triton.jit +def _fwd_kernel( + Q, + K, + V, + sm_scale, + TMP, + L, + M, # NOTE: TMP is a scratchpad buffer to workaround a compiler bug + Out, + stride_qz, + stride_qh, + stride_qm, + stride_qk, + stride_kz, + stride_kh, + stride_kn, + stride_kk, + stride_vz, + stride_vh, + stride_vk, + stride_vn, + stride_oz, + stride_oh, + stride_om, + stride_on, + Z, + H, + N_CTX, + BLOCK_M: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + BLOCK_N: tl.constexpr, +): + start_m = tl.program_id(0) + off_hz = tl.program_id(1) + # initialize offsets + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + offs_n = tl.arange(0, BLOCK_N) + offs_d = tl.arange(0, BLOCK_DMODEL) + off_q = off_hz * stride_qh + offs_m[:, None] * stride_qm + offs_d[None, :] * stride_qk + off_k = off_hz * stride_qh + offs_n[:, None] * stride_kn + offs_d[None, :] * stride_kk + off_v = off_hz * stride_qh + offs_n[:, None] * stride_qm + offs_d[None, :] * stride_qk + # Initialize pointers to Q, K, V + q_ptrs = Q + off_q + k_ptrs = K + off_k + v_ptrs = V + off_v + # initialize pointer to m and l + t_ptrs = TMP + off_hz * N_CTX + offs_m + m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf") + l_i = tl.zeros([BLOCK_M], dtype=tl.float32) + acc = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32) + # load q: it will stay in SRAM throughout + q = tl.load(q_ptrs) + # loop over k, v and update accumulator + for start_n in range(0, (start_m + 1) * BLOCK_M, BLOCK_N): + start_n = tl.multiple_of(start_n, BLOCK_N) + # -- compute qk ---- + k = tl.load(k_ptrs + start_n * stride_kn) + qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) + qk += tl.dot(q, k, trans_b=True) + qk *= sm_scale + qk += tl.where(offs_m[:, None] >= (start_n + offs_n[None, :]), 0, float("-inf")) + # -- compute m_ij, p, l_ij + m_ij = tl.max(qk, 1) + p = tl.exp(qk - m_ij[:, None]) + l_ij = tl.sum(p, 1) + # -- update m_i and l_i + m_i_new = tl.maximum(m_i, m_ij) + alpha = tl.exp(m_i - m_i_new) + beta = tl.exp(m_ij - m_i_new) + l_i_new = alpha * l_i + beta * l_ij + # -- update output accumulator -- + # scale p + p_scale = beta / l_i_new + p = p * p_scale[:, None] + # scale acc + acc_scale = l_i / l_i_new * alpha + tl.store(t_ptrs, acc_scale) + acc_scale = tl.load(t_ptrs) # BUG: have to store and immediately load + acc = acc * acc_scale[:, None] + # update acc + v = tl.load(v_ptrs + start_n * stride_vk) + p = p.to(v.dtype) + acc += tl.dot(p, v) + # update m_i and l_i + l_i = l_i_new + m_i = m_i_new + # rematerialize offsets to save registers + start_m = tl.program_id(0) + offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + # write back l and m + l_ptrs = L + off_hz * N_CTX + offs_m + m_ptrs = M + off_hz * N_CTX + offs_m + tl.store(l_ptrs, l_i) + tl.store(m_ptrs, m_i) + # initialize pointers to output + offs_n = tl.arange(0, BLOCK_DMODEL) + off_o = off_hz * stride_oh + offs_m[:, None] * stride_om + offs_n[None, :] * stride_on + out_ptrs = Out + off_o + tl.store(out_ptrs, acc) + + +@triton.jit +def _bwd_preprocess( + Out, + DO, + L, + NewDO, + Delta, + BLOCK_M: tl.constexpr, + D_HEAD: tl.constexpr, +): + off_m = tl.program_id(0) * BLOCK_M + tl.arange(0, BLOCK_M) + off_n = tl.arange(0, D_HEAD) + # load + o = tl.load(Out + off_m[:, None] * D_HEAD + off_n[None, :]).to(tl.float32) + do = tl.load(DO + off_m[:, None] * D_HEAD + off_n[None, :]).to(tl.float32) + denom = tl.load(L + off_m).to(tl.float32) + # compute + do = do / denom[:, None] + delta = tl.sum(o * do, axis=1) + # write-back + tl.store(NewDO + off_m[:, None] * D_HEAD + off_n[None, :], do) + tl.store(Delta + off_m, delta) + + +@triton.jit +def _bwd_kernel( + Q, + K, + V, + sm_scale, + Out, + DO, + DQ, + DK, + DV, + L, + M, + D, + stride_qz, + stride_qh, + stride_qm, + stride_qk, + stride_kz, + stride_kh, + stride_kn, + stride_kk, + stride_vz, + stride_vh, + stride_vk, + stride_vn, + Z, + H, + N_CTX, + num_block, + BLOCK_M: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + BLOCK_N: tl.constexpr, +): + off_hz = tl.program_id(0) + off_z = off_hz // H + off_h = off_hz % H + # offset pointers for batch/head + Q += off_z * stride_qz + off_h * stride_qh + K += off_z * stride_qz + off_h * stride_qh + V += off_z * stride_qz + off_h * stride_qh + DO += off_z * stride_qz + off_h * stride_qh + DQ += off_z * stride_qz + off_h * stride_qh + DK += off_z * stride_qz + off_h * stride_qh + DV += off_z * stride_qz + off_h * stride_qh + for start_n in range(0, num_block): + lo = start_n * BLOCK_M + # initialize row/col offsets + offs_qm = lo + tl.arange(0, BLOCK_M) + offs_n = start_n * BLOCK_M + tl.arange(0, BLOCK_M) + offs_m = tl.arange(0, BLOCK_N) + offs_k = tl.arange(0, BLOCK_DMODEL) + # initialize pointers to value-like data + q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_k[None, :] * stride_qk) + k_ptrs = K + (offs_n[:, None] * stride_kn + offs_k[None, :] * stride_kk) + v_ptrs = V + (offs_n[:, None] * stride_qm + offs_k[None, :] * stride_qk) + do_ptrs = DO + (offs_qm[:, None] * stride_qm + offs_k[None, :] * stride_qk) + dq_ptrs = DQ + (offs_qm[:, None] * stride_qm + offs_k[None, :] * stride_qk) + # pointer to row-wise quantities in value-like data + D_ptrs = D + off_hz * N_CTX + m_ptrs = M + off_hz * N_CTX + # initialize dv amd dk + dv = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32) + dk = tl.zeros([BLOCK_M, BLOCK_DMODEL], dtype=tl.float32) + # k and v stay in SRAM throughout + k = tl.load(k_ptrs) + v = tl.load(v_ptrs) + # loop over rows + for start_m in range(lo, num_block * BLOCK_M, BLOCK_M): + offs_m_curr = start_m + offs_m + # load q, k, v, do on-chip + q = tl.load(q_ptrs) + # recompute p = softmax(qk, dim=-1).T + # NOTE: `do` is pre-divided by `l`; no normalization here + qk = tl.dot(q, k, trans_b=True) + qk = tl.where(offs_m_curr[:, None] >= (offs_n[None, :]), qk, float("-inf")) + m = tl.load(m_ptrs + offs_m_curr) + p = tl.exp(qk * sm_scale - m[:, None]) + # compute dv + do = tl.load(do_ptrs) + dv += tl.dot(p.to(do.dtype), do, trans_a=True) + # compute dp = dot(v, do) + Di = tl.load(D_ptrs + offs_m_curr) + dp = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) - Di[:, None] + dp += tl.dot(do, v, trans_b=True) + # compute ds = p * (dp - delta[:, None]) + ds = p * dp * sm_scale + # compute dk = dot(ds.T, q) + dk += tl.dot(ds.to(q.dtype), q, trans_a=True) + # # compute dq + dq = tl.load(dq_ptrs, eviction_policy="evict_last") + dq += tl.dot(ds.to(k.dtype), k) + tl.store(dq_ptrs, dq, eviction_policy="evict_last") + # # increment pointers + dq_ptrs += BLOCK_M * stride_qm + q_ptrs += BLOCK_M * stride_qm + do_ptrs += BLOCK_M * stride_qm + # write-back + dv_ptrs = DV + (offs_n[:, None] * stride_qm + offs_k[None, :] * stride_qk) + dk_ptrs = DK + (offs_n[:, None] * stride_kn + offs_k[None, :] * stride_kk) + tl.store(dv_ptrs, dv) + tl.store(dk_ptrs, dk) + + +class _attention(torch.autograd.Function): + @staticmethod + def forward(ctx, q, k, v, sm_scale): + BLOCK = 128 + # shape constraints + Lq, Lk, Lv = q.shape[-1], k.shape[-1], v.shape[-1] + assert Lq == Lk and Lk == Lv + assert Lk in {16, 32, 64, 128} + o = torch.empty_like(q) + grid = (triton.cdiv(q.shape[2], BLOCK), q.shape[0] * q.shape[1]) + tmp = torch.empty( + (q.shape[0] * q.shape[1], q.shape[2]), device=q.device, dtype=torch.float32 + ) + L = torch.empty((q.shape[0] * q.shape[1], q.shape[2]), device=q.device, dtype=torch.float32) + m = torch.empty((q.shape[0] * q.shape[1], q.shape[2]), device=q.device, dtype=torch.float32) + num_warps = 4 if Lk <= 64 else 8 + + _fwd_kernel[grid]( + q, + k, + v, + sm_scale, + tmp, + L, + m, + o, + q.stride(0), + q.stride(1), + q.stride(2), + q.stride(3), + k.stride(0), + k.stride(1), + k.stride(2), + k.stride(3), + v.stride(0), + v.stride(1), + v.stride(2), + v.stride(3), + o.stride(0), + o.stride(1), + o.stride(2), + o.stride(3), + q.shape[0], + q.shape[1], + q.shape[2], + BLOCK_M=BLOCK, + BLOCK_N=BLOCK, + BLOCK_DMODEL=Lk, + num_warps=num_warps, + num_stages=1, + ) + ctx.save_for_backward(q, k, v, o, L, m) + ctx.BLOCK = BLOCK + ctx.grid = grid + ctx.sm_scale = sm_scale + ctx.BLOCK_DMODEL = Lk + return o + + @staticmethod + def backward(ctx, do): + q, k, v, o, l, m = ctx.saved_tensors + do = do.contiguous() + dq = torch.zeros_like(q, dtype=torch.float32) + dk = torch.empty_like(k) + dv = torch.empty_like(v) + do_scaled = torch.empty_like(do) + delta = torch.empty_like(l) + _bwd_preprocess[(ctx.grid[0] * ctx.grid[1],)]( + o, + do, + l, + do_scaled, + delta, + BLOCK_M=ctx.BLOCK, + D_HEAD=ctx.BLOCK_DMODEL, + ) + + # NOTE: kernel currently buggy for other values of `num_warps` + num_warps = 8 + _bwd_kernel[(ctx.grid[1],)]( + q, + k, + v, + ctx.sm_scale, + o, + do_scaled, + dq, + dk, + dv, + l, + m, + delta, + q.stride(0), + q.stride(1), + q.stride(2), + q.stride(3), + k.stride(0), + k.stride(1), + k.stride(2), + k.stride(3), + v.stride(0), + v.stride(1), + v.stride(2), + v.stride(3), + q.shape[0], + q.shape[1], + q.shape[2], + ctx.grid[0], + BLOCK_M=ctx.BLOCK, + BLOCK_N=ctx.BLOCK, + BLOCK_DMODEL=ctx.BLOCK_DMODEL, + num_warps=num_warps, + num_stages=1, + ) + return dq.to(q.dtype), dk, dv, None + + +attention = _attention.apply diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_blocksparse_attention.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_blocksparse_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..4c930291063db1350ce05aecf55c6050bad28fd4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_blocksparse_attention.py @@ -0,0 +1,197 @@ +import math + +import hydra +import torch +import torch.nn as nn +from einops import rearrange + +from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input +from flash_attn.flash_blocksparse_attn_interface import ( + convert_blockmask, + flash_blocksparse_attn_func, +) + + +class FlashBlocksparseAttention(nn.Module): + """Implement the scaled dot product attention with softmax. + Arguments + --------- + softmax_temp: The temperature to use for the softmax attention. + (default: 1/sqrt(d_keys) where d_keys is computed at + runtime) + attention_dropout: The dropout rate to apply to the attention + (default: 0.1) + """ + + def __init__( + self, + sparsity_config, + softmax_temp=None, + attention_dropout=0.0, + max_seq_length=2048, + device=None, + dtype=None, + ): + super().__init__() + self.sparsity_config = hydra.utils.instantiate(sparsity_config) + self.softmax_temp = softmax_temp + self.dropout_p = attention_dropout + + # initialize sparse layout and register as buffer + max_seq_length = ((max_seq_length + 256 - 1) // 256) * 256 + layout = self.sparsity_config.make_layout(max_seq_length) + self.register_buffer("layout", layout) + blockmask_converted = convert_blockmask(self.layout, causal=False) + self.register_buffer("blockmask_converted", blockmask_converted) + # logger.info(f'Attention class {self.__class__}: saving={self.layout.float().mean()}') + + def forward( + self, + qkv, + attn_mask=None, + key_padding_mask=None, + causal=False, + cu_seqlens=None, + max_s=None, + need_weights=False, + convert_mask=True, + ): + """Implements the multihead softmax attention. + Arguments + --------- + qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) if key_padding_mask is None + attn_mask: An implementation of BaseMask that encodes where each + query can attend to + key_padding_mask: An implementation of BaseMask that encodes how + many query each sequence in the batch consists of + """ + assert not need_weights + assert attn_mask is None + assert qkv.dtype == torch.float16 + assert qkv.is_cuda + + if cu_seqlens is None: + batch_size = qkv.shape[0] + seqlen = qkv.shape[1] + # Convert mask to take a subset + seqlen_rounded = ((seqlen + 256 - 1) // 256) * 256 + assert seqlen_rounded // 16 <= self.layout.shape[0], ( + seqlen_rounded // 256 <= self.layout.shape[1] + ) + blockmask = self.layout[: seqlen_rounded // 16, : seqlen_rounded // 256] + if key_padding_mask is None: + qkv = rearrange(qkv, "b s ... -> (b s) ...") + max_s = seqlen + cu_seqlens = torch.arange( + 0, (batch_size + 1) * seqlen, step=seqlen, dtype=torch.int32, device=qkv.device + ) + output = flash_blocksparse_attn_func( + qkv, + cu_seqlens, + blockmask, + self.dropout_p if self.training else 0.0, + max_s, + softmax_scale=self.softmax_temp, + causal=causal, + ) + output = rearrange(output, "(b s) ... -> b s ...", b=batch_size) + else: + key_padding_mask_bool = key_padding_mask.bool_matrix + nheads = qkv.shape[-2] + x = rearrange(qkv, "b s three h d -> b s (three h d)") + x_unpad, indices, cu_seqlens, max_s, _ = unpad_input(x, key_padding_mask_bool) + x_unpad = rearrange(x_unpad, "nnz (three h d) -> nnz three h d", three=3, h=nheads) + output_unpad = flash_blocksparse_attn_func( + x_unpad, + cu_seqlens, + blockmask, + self.dropout_p if self.training else 0.0, + max_s, + softmax_scale=self.softmax_temp, + causal=causal, + ) + output = rearrange( + pad_input( + rearrange(output_unpad, "nnz h d -> nnz (h d)"), indices, batch_size, seqlen + ), + "b s (h d) -> b s h d", + h=nheads, + ) + else: + assert max_s is not None + seqlen = max_s + # Convert mask to take a subset + seqlen_rounded = ((seqlen + 256 - 1) // 256) * 256 + assert seqlen_rounded // 16 <= self.layout.shape[0], ( + seqlen_rounded // 256 <= self.layout.shape[1] + ) + blockmask = self.layout[: seqlen_rounded // 16, : seqlen_rounded // 256] + if convert_mask: + output = flash_blocksparse_attn_func( + qkv, + cu_seqlens, + blockmask, + self.dropout_p if self.training else 0.0, + max_s, + softmax_scale=self.softmax_temp, + causal=causal, + ) + else: + output = flash_blocksparse_attn_func( + qkv, + cu_seqlens, + self.blockmask_converted, + self.dropout_p if self.training else 0.0, + max_s, + softmax_scale=self.softmax_temp, + causal=causal, + convert_mask=False, + ) + + return output, None + + +class FlashBlocksparseMHA(nn.Module): + def __init__( + self, + embed_dim, + num_heads, + sparsity_config, + bias=True, + batch_first=True, + attention_dropout=0.0, + causal=False, + max_seq_length=2048, + device=None, + dtype=None, + **kwargs, + ) -> None: + assert batch_first + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.embed_dim = embed_dim + self.causal = causal + + self.num_heads = num_heads + assert self.embed_dim % num_heads == 0, "self.kdim must be divisible by num_heads" + self.head_dim = self.embed_dim // num_heads + assert self.head_dim in [16, 32, 64], "Only support head_dim == 16, 32, or 64" + + self.Wqkv = nn.Linear(embed_dim, 3 * embed_dim, bias=bias, **factory_kwargs) + self.inner_attn = FlashBlocksparseAttention( + sparsity_config, + attention_dropout=attention_dropout, + max_seq_length=max_seq_length, + **factory_kwargs, + ) + self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias, **factory_kwargs) + + def forward( + self, x, x_ignored_, x_ignored_1_, attn_mask=None, key_padding_mask=None, need_weights=False + ): + qkv = self.Wqkv(x) + qkv = rearrange(qkv, "b s (three h d) -> b s three h d", three=3, h=self.num_heads) + context, attn_weights = self.inner_attn( + qkv, key_padding_mask=key_padding_mask, need_weights=need_weights, causal=self.causal + ) + return self.out_proj(rearrange(context, "b s h d -> b s (h d)")), attn_weights diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_blocksparse_attn_interface.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_blocksparse_attn_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..9ce3fe8c1344dd33165c43e4cc1ef0f70feb5d04 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/flash_blocksparse_attn_interface.py @@ -0,0 +1,200 @@ +# Adapted from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/fmha.py +import flash_attn_cuda +import torch +import torch.nn as nn + + +def convert_blockmask(blockmask, causal): + """Convert from the 0-1 format to the format used by the CUDA code. + 0 means the block is skipped. + nonzero means the block is not skipped. + Argument: + blockmask: (row, col): a 0-1 tensor + Return: + blockmask_converted: (col, row), dtype torch.int32: for each column, it contains the row + indices of the nonzero blocks, padded with -1 to reach length @row. + The indices are multiplied by 4, with the smallest bit used to encode whether + it is the first nonzero in its row, and the 2nd smallest bit to encode whether it is + the last nonzero in its row.. + """ + assert not causal + # TD [2022-05-13]: The indexing and sorting is very tricky + nrow, ncol = blockmask.shape + # Sort does not support bool on CUDA + blockmask = blockmask.to(dtype=torch.uint8) + nonzero_val, nonzero_sorted_rowidx = blockmask.sort(dim=0, stable=True, descending=True) + nonzero_unsorted_rowidx = nonzero_sorted_rowidx.argsort(dim=0) + last_nonzero_col_per_row = blockmask.sort(dim=-1, stable=True).indices[:, -1] + last_nonzero_col_per_row_after_sort = nonzero_unsorted_rowidx[ + torch.arange(nrow, device=blockmask.device), last_nonzero_col_per_row + ] + first_nonzero_col_per_row = blockmask.sort(dim=-1, stable=True, descending=True).indices[:, 0] + first_nonzero_col_per_row_after_sort = nonzero_unsorted_rowidx[ + torch.arange(nrow, device=blockmask.device), first_nonzero_col_per_row + ] + nonzero_idx = nonzero_sorted_rowidx * 4 + nonzero_idx[last_nonzero_col_per_row_after_sort, last_nonzero_col_per_row] += 2 + nonzero_idx[first_nonzero_col_per_row_after_sort, first_nonzero_col_per_row] += 1 + nonzero_idx[nonzero_val == 0] = -1 + return nonzero_idx.T.contiguous().to(dtype=torch.int32) + + +def _flash_blocksparse_attn_forward( + qkv, cu_seqlens, blockmask, dropout_p, max_s, softmax_scale, causal, return_softmax +): + context, softmax_lse, *rest = flash_attn_cuda.fwd_block( + qkv, cu_seqlens, blockmask, dropout_p, max_s, softmax_scale, causal, return_softmax, None + ) + # if context.isnan().any() or softmax_lse.isnan().any(): + # breakpoint() + S_dmask = rest[0] if return_softmax else None + return context, softmax_lse, S_dmask + + +def _flash_blocksparse_attn_backward( + dout, + qkv, + out, + S_dmask, + softmax_lse, + cu_seqlens, + blockmask, + dropout_p, + max_s, + softmax_scale, + causal, +): + dqkv, dp, softmax_d = flash_attn_cuda.bwd_block( + dout, + qkv, + out, + S_dmask, + softmax_lse, + cu_seqlens, + blockmask, + dropout_p, + softmax_scale, + max_s, + causal, + None, + ) + # if dqkv.isnan().any() or softmax_d.isnan().any(): + # breakpoint() + return dqkv + + +class FlashBlocksparseAttnFun(torch.autograd.Function): + @staticmethod + def forward(ctx, qkv, cu_seqlens, blockmask, dropout_p, max_s, softmax_scale, causal): + # Save rng_state because the backward pass will regenerate the dropout mask + rng_state = torch.cuda.get_rng_state() if dropout_p > 0 else None + if softmax_scale is None: + softmax_scale = qkv.shape[-1] ** (-0.5) + context, softmax_lse, S_dmask = _flash_blocksparse_attn_forward( + qkv, + cu_seqlens, + blockmask, + dropout_p, + max_s, + softmax_scale, + causal=causal, + return_softmax=False, + ) + ctx.save_for_backward(qkv, context, S_dmask, softmax_lse, cu_seqlens, blockmask, rng_state) + ctx.dropout_p = dropout_p + ctx.max_s = max_s + ctx.softmax_scale = softmax_scale + ctx.causal = causal + return context + + @staticmethod + def backward(ctx, dout): + qkv, context, S_dmask, softmax_lse, cu_seqlens, blockmask, rng_state = ctx.saved_tensors + if rng_state is not None: + cur_rng_state = torch.cuda.get_rng_state() + torch.cuda.set_rng_state(rng_state) + # S_dmask is None, temporarily use another tensor just to get it running + dqkv = _flash_blocksparse_attn_backward( + dout, + qkv, + context, + context, + softmax_lse, + cu_seqlens, + blockmask, + ctx.dropout_p, + ctx.max_s, + ctx.softmax_scale, + ctx.causal, + ) + if rng_state is not None: + torch.cuda.set_rng_state(cur_rng_state) + return dqkv, None, None, None, None, None, None, None + + +# We duplicate code to return both the output and the softmax for testing +# Returning both makes backward a bit slower, so we want to keep using the other version for speed. +class FlashBlocksparseAttnFunWithS(torch.autograd.Function): + @staticmethod + def forward(ctx, qkv, cu_seqlens, blockmask, dropout_p, max_s, softmax_scale, causal): + # Save rng_state because the backward pass is gonna regenerate the dropout mask + rng_state = torch.cuda.get_rng_state() if dropout_p > 0 else None + if softmax_scale is None: + softmax_scale = qkv.shape[-1] ** (-0.5) + context, softmax_lse, S_dmask = _flash_blocksparse_attn_forward( + qkv, + cu_seqlens, + blockmask, + dropout_p, + max_s, + softmax_scale, + causal=causal, + return_softmax=True, + ) + ctx.save_for_backward(qkv, context, S_dmask, softmax_lse, cu_seqlens, blockmask, rng_state) + ctx.dropout_p = dropout_p + ctx.max_s = max_s + ctx.softmax_scale = softmax_scale + ctx.causal = causal + return context, S_dmask, softmax_lse + + @staticmethod + def backward(ctx, dout, _dS_dmask_ignored, _dsoftmax_sum_ignored): + qkv, context, S_dmask, softmax_lse, cu_seqlens, blockmask, rng_state = ctx.saved_tensors + if rng_state is not None: + cur_rng_state = torch.cuda.get_rng_state() + torch.cuda.set_rng_state(rng_state) + dqkv = _flash_blocksparse_attn_backward( + dout, + qkv, + context, + S_dmask, + softmax_lse, + cu_seqlens, + blockmask, + ctx.dropout_p, + ctx.max_s, + ctx.softmax_scale, + ctx.causal, + ) + if rng_state is not None: + torch.cuda.set_rng_state(cur_rng_state) + return dqkv, None, None, None, None, None, None + + +def flash_blocksparse_attn_func( + qkv, + cu_seqlens, + blockmask, + dropout_p, + max_s, + softmax_scale=None, + causal=False, + return_attn_probs=False, + convert_mask=True, +): + """dropout_p should be set to 0.0 during evaluation""" + func = FlashBlocksparseAttnFun if not return_attn_probs else FlashBlocksparseAttnFunWithS + if convert_mask: + blockmask = convert_blockmask(blockmask, causal=causal) + return func.apply(qkv, cu_seqlens, blockmask, dropout_p, max_s, softmax_scale, causal) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/fused_softmax.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/fused_softmax.py new file mode 100644 index 0000000000000000000000000000000000000000..382f94f092cd3999b2378dfc2fa165a7c08017e2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/fused_softmax.py @@ -0,0 +1,201 @@ +# [2022-10-23] Copied from https://github.com/NVIDIA/apex/blob/master/apex/transformer/functional/fused_softmax.py +# for benchmarking. +# We added support for seqlen=2k and seqlen=4k + +# coding=utf-8 +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import torch +from apex._autocast_utils import _cast_if_autocast_enabled +from apex.transformer.enums import AttnMaskType +from fused_softmax_lib import ( + scaled_masked_softmax_backward, + scaled_masked_softmax_forward, + scaled_masked_softmax_get_batch_per_block, + scaled_upper_triang_masked_softmax_backward, + scaled_upper_triang_masked_softmax_forward, +) + + +class ScaledUpperTriangMaskedSoftmax(torch.autograd.Function): + """ + Fused operation which performs following three operations in sequence + 1. Scale the tensor. + 2. Apply upper triangular mask (typically used in gpt models). + 3. Perform softmax. + """ + + @staticmethod + def forward(ctx, inputs, scale): + scale_t = torch.tensor([scale]) + softmax_results = scaled_upper_triang_masked_softmax_forward(inputs, scale_t[0]) + ctx.save_for_backward(softmax_results, scale_t) + return softmax_results + + @staticmethod + def backward(ctx, output_grads): + softmax_results, scale_t = ctx.saved_tensors + input_grads = scaled_upper_triang_masked_softmax_backward( + output_grads, softmax_results, scale_t[0] + ) + return input_grads, None + + +def scaled_upper_triang_masked_softmax(inputs, _, scale): + b, np, sq, sk = inputs.size() + assert sq == sk, "causal mask is only for self attention" + # Reshaping input to 3D tensor (attn_batches, sq, sk) + inputs = inputs.view(-1, sq, sk) + args = _cast_if_autocast_enabled(inputs, scale) + with torch.cuda.amp.autocast(enabled=False): + probs = ScaledUpperTriangMaskedSoftmax.apply(*args) + return probs.view(b, np, sq, sk) + + +# NOTE (mkozuki): `ScaledMaskedSoftmax` somehow doesn't work well with `torch.cuda.amp.custom_fwd`. +# Without `cast_inputs` kwarg, somehow inputs are not cast to dtype used in the autocast context. +# So I needed to manually write two `torch.autograd.Function` inheritances. +# Fused operation which performs following three operations in sequence +# 1. Scale the tensor. +# 2. Apply the mask. +# 3. Perform softmax. +class ScaledMaskedSoftmax(torch.autograd.Function): + @staticmethod + def forward(ctx, inputs, mask, scale): + scale_t = torch.tensor([scale]) + softmax_results = scaled_masked_softmax_forward(inputs, mask, scale_t[0]) + ctx.save_for_backward(softmax_results, scale_t) + return softmax_results + + @staticmethod + def backward(ctx, output_grads): + softmax_results, scale_t = ctx.saved_tensors + input_grads = scaled_masked_softmax_backward(output_grads, softmax_results, scale_t[0]) + return input_grads, None, None + + +def scaled_masked_softmax(inputs, mask, scale): + # input is 4D tensor (b, np, sq, sk) + args = _cast_if_autocast_enabled(inputs, mask, scale) + with torch.cuda.amp.autocast(enabled=False): + return ScaledMaskedSoftmax.apply(*args) + + +class FusedScaleMaskSoftmax(torch.nn.Module): + """ + fused operation: scaling + mask + softmax + + Arguments: + input_in_fp16: flag to indicate if input in fp16 data format. + input_in_bf16: flag to indicate if input in bf16 data format. + attn_mask_type: attention mask type (pad or causal) + scaled_masked_softmax_fusion: flag to indicate user want to use softmax fusion + mask_func: mask function to be applied. + softmax_in_fp32: if true, softmax in performed at fp32 precision. + scale: scaling factor used in input tensor scaling. + """ + + def __init__( + self, + input_in_fp16, + input_in_bf16, + attn_mask_type, + scaled_masked_softmax_fusion, + mask_func, + softmax_in_fp32, + scale, + ): + super().__init__() + self.input_in_fp16 = input_in_fp16 + self.input_in_bf16 = input_in_bf16 + if self.input_in_fp16 and self.input_in_bf16: + raise RuntimeError("both fp16 and bf16 flags cannot be active at the same time.") + self.input_in_float16 = self.input_in_fp16 or self.input_in_bf16 + self.attn_mask_type = attn_mask_type + self.scaled_masked_softmax_fusion = scaled_masked_softmax_fusion + self.mask_func = mask_func + self.softmax_in_fp32 = softmax_in_fp32 + self.scale = scale + + if not (self.scale is None or softmax_in_fp32): + raise RuntimeError("softmax should be in fp32 when scaled") + + if self.scaled_masked_softmax_fusion: + if self.attn_mask_type == AttnMaskType.causal: + self.fused_softmax_func = scaled_upper_triang_masked_softmax + elif self.attn_mask_type == AttnMaskType.padding: + self.fused_softmax_func = scaled_masked_softmax + else: + raise ValueError("Invalid attn_mask_type.") + + def forward(self, input, mask): + # [b, np, sq, sk] + assert input.dim() == 4 + + if self.is_kernel_available(mask, *input.size()): + return self.forward_fused_softmax(input, mask) + else: + return self.forward_torch_softmax(input, mask) + + def is_kernel_available(self, mask, b, np, sq, sk): + attn_batches = b * np + + if ( + self.scaled_masked_softmax_fusion # user want to fuse + and self.input_in_float16 # input must be fp16 + and ( + self.attn_mask_type == AttnMaskType.causal + or (self.attn_mask_type == AttnMaskType.padding and mask is not None) + ) + and 16 < sk <= 8192 # sk must be 16 ~ 8192 + and sq % 4 == 0 # sq must be divisor of 4 + and sk % 4 == 0 # sk must be divisor of 4 + and attn_batches % 4 == 0 # np * b must be divisor of 4 + ): + if 0 <= sk <= 8192: + batch_per_block = self.get_batch_per_block(sq, sk, b, np) + + if self.attn_mask_type == AttnMaskType.causal: + if attn_batches % batch_per_block == 0: + return True + else: + if sq % batch_per_block == 0: + return True + return False + + def forward_fused_softmax(self, input, mask): + # input.shape = [b, np, sq, sk] + scale = self.scale if self.scale is not None else 1.0 + return self.fused_softmax_func(input, mask, scale) + + def forward_torch_softmax(self, input, mask): + if self.input_in_float16 and self.softmax_in_fp32: + input = input.float() + + if self.scale is not None: + input = input * self.scale + mask_output = self.mask_func(input, mask) if mask is not None else input + probs = torch.nn.Softmax(dim=-1)(mask_output) + + if self.input_in_float16 and self.softmax_in_fp32: + if self.input_in_fp16: + probs = probs.half() + else: + probs = probs.bfloat16() + + return probs + + @staticmethod + def get_batch_per_block(sq, sk, b, np): + return scaled_masked_softmax_get_batch_per_block(sq, sk, b, np) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbee93c5495d2636aafe6786528b92e914e32322 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/__pycache__/patch_embed.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/__pycache__/patch_embed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5fb1b3f3c761f25efdf10bc374f58ea11a77ca15 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/__pycache__/patch_embed.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/__pycache__/rotary.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/__pycache__/rotary.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..266ccf3e98d7fba9f8bf4a4128c71061795c6208 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/__pycache__/rotary.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/patch_embed.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/patch_embed.py new file mode 100644 index 0000000000000000000000000000000000000000..05562f8e8bcdb58e947c6f402a49eacd2d031871 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/patch_embed.py @@ -0,0 +1,67 @@ +# We use the same API as https://github.com/rwightman/pytorch-image-models/blob/v0.6.11/timm/models/layers/patch_embed.py +# But we use nn.Linear instead of Conv2d and it's about 8x faster. + +from functools import partial + +import torch.nn as nn +from einops import rearrange +from torch import _assert +from torch.nn.modules.utils import _pair + +try: + from flash_attn.ops.fused_dense import FusedDense +except ImportError: + FusedDense = None + + +class PatchEmbed(nn.Module): + """2D Image to Patch Embedding""" + + def __init__( + self, + img_size=224, + patch_size=16, + in_chans=3, + embed_dim=768, + norm_layer=None, + flatten=True, + bias=True, + fused_bias_fc=False, + ): + super().__init__() + img_size = _pair(img_size) + patch_size = _pair(patch_size) + self.img_size = img_size + self.patch_size = patch_size + self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1]) + self.num_patches = self.grid_size[0] * self.grid_size[1] + self.flatten = flatten + if fused_bias_fc and FusedDense is None: + raise ImportError("fused_dense is not installed") + + linear_cls = nn.Linear if not fused_bias_fc or not bias else FusedDense + self.proj = linear_cls(in_chans * patch_size[0] * patch_size[1], embed_dim, bias=bias) + self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity() + + def forward(self, x): + _, _, H, W = x.shape + _assert( + H == self.img_size[0], + f"Input image height ({H}) doesn't match model ({self.img_size[0]}).", + ) + _assert( + W == self.img_size[1], + f"Input image width ({W}) doesn't match model ({self.img_size[1]}).", + ) + x = self.proj( + rearrange( + x, + "b c (h p1) (w p2) -> b h w (c p1 p2)", + p1=self.patch_size[0], + p2=self.patch_size[1], + ) + ) + if self.flatten: + x = rearrange(x, "b h w c -> b (h w) c") + x = self.norm(x) + return x diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/rotary.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/rotary.py new file mode 100644 index 0000000000000000000000000000000000000000..72e43337ad3c341476b64bf3465847d2c2d2f790 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/layers/rotary.py @@ -0,0 +1,482 @@ +# Copyright (c) 2025, Tri Dao + +import math +from functools import partial +from typing import Optional, Tuple, Union + +import torch +from torch import Tensor + +from einops import rearrange, repeat +from flash_attn.ops.triton.rotary import apply_rotary + + +def rotate_half(x, interleaved=False): + if not interleaved: + x1, x2 = x.chunk(2, dim=-1) + return torch.cat((-x2, x1), dim=-1) + else: + x1, x2 = x[..., ::2], x[..., 1::2] + return rearrange(torch.stack((-x2, x1), dim=-1), "... d two -> ... (d two)", two=2) + + +def apply_rotary_emb_torch(x, cos, sin, interleaved=False): + """ + x: (batch_size, seqlen, nheads, headdim) + cos, sin: (seqlen, rotary_dim / 2) or (batch_size, seqlen, rotary_dim / 2) + """ + ro_dim = cos.shape[-1] * 2 + assert ro_dim <= x.shape[-1] + cos = repeat(cos, "... d -> ... 1 (2 d)" if not interleaved else "... d -> ... 1 (d 2)") + sin = repeat(sin, "... d -> ... 1 (2 d)" if not interleaved else "... d -> ... 1 (d 2)") + return torch.cat( + [x[..., :ro_dim] * cos + rotate_half(x[..., :ro_dim], interleaved) * sin, x[..., ro_dim:]], + dim=-1, + ) + + +class ApplyRotaryEmb(torch.autograd.Function): + @staticmethod + def forward( + ctx, + x, + cos, + sin, + interleaved=False, + inplace=False, + seqlen_offsets: Union[int, Tensor] = 0, + cu_seqlens: Optional[Tensor] = None, + max_seqlen: Optional[int] = None, + ): + out = apply_rotary( + x, + cos, + sin, + seqlen_offsets=seqlen_offsets, + cu_seqlens=cu_seqlens, + max_seqlen=max_seqlen, + interleaved=interleaved, + inplace=inplace, + ) + if isinstance(seqlen_offsets, int): + ctx.save_for_backward(cos, sin, cu_seqlens) # Can't save int with save_for_backward + ctx.seqlen_offsets = seqlen_offsets + else: + ctx.save_for_backward(cos, sin, cu_seqlens, seqlen_offsets) + ctx.seqlen_offsets = None + ctx.interleaved = interleaved + ctx.inplace = inplace + ctx.max_seqlen = max_seqlen + return out if not inplace else x + + @staticmethod + def backward(ctx, do): + seqlen_offsets = ctx.seqlen_offsets + if seqlen_offsets is None: + cos, sin, cu_seqlens, seqlen_offsets = ctx.saved_tensors + else: + cos, sin, cu_seqlens = ctx.saved_tensors + dx = apply_rotary( + do, + cos, + sin, + seqlen_offsets=seqlen_offsets, + cu_seqlens=cu_seqlens, + max_seqlen=ctx.max_seqlen, + interleaved=ctx.interleaved, + inplace=ctx.inplace, + conjugate=True, + ) + return dx, None, None, None, None, None, None, None + + +def apply_rotary_emb( + x, + cos, + sin, + interleaved=False, + inplace=False, + seqlen_offsets: Union[int, Tensor] = 0, + cu_seqlens: Optional[Tensor] = None, + max_seqlen: Optional[int] = None, +): + """ + Arguments: + x: (batch_size, seqlen, nheads, headdim) if cu_seqlens is None + else (total_seqlen, nheads, headdim) + cos, sin: (seqlen_rotary, rotary_dim / 2) + interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead + of 1st half and 2nd half (GPT-NeoX style). + inplace: if True, apply rotary embedding in-place. + seqlen_offsets: (batch_size,) or int. Each sequence in x is shifted by this amount. + Most commonly used in inference when we have KV cache. + cu_seqlens: (batch + 1,) or None + max_seqlen: int + Return: + out: (batch_size, seqlen, nheads, headdim) if cu_seqlens is None + else (total_seqlen, nheads, headdim) + rotary_dim must be <= headdim + Apply rotary embedding to the first rotary_dim of x. + """ + return ApplyRotaryEmb.apply( + x, cos, sin, interleaved, inplace, seqlen_offsets, cu_seqlens, max_seqlen + ) + + +# For backward compatibility +apply_rotary_emb_func = apply_rotary_emb + + +def _apply_rotary_emb_qkv( + qkv, + cos, + sin, + cos_k=None, + sin_k=None, + interleaved=False, + inplace=False, + conjugate=False, + seqlen_offsets: Union[int, Tensor] = 0, + num_heads_q: Optional[int] = None, +): + apply_rotary_fn = partial( + apply_rotary, + interleaved=interleaved, + inplace=inplace, + conjugate=conjugate, + seqlen_offsets=seqlen_offsets + ) + if cos_k is None and sin_k is None and qkv.is_contiguous(): + # Call 1 kernel instead of 2 kernels + # We need qkv to be contiguous so that when we reshape to combine (3, nheads) + # dimensions, we get the same tensor + if qkv.dim() == 5: + batch, seqlen, three, nheads, headdim = qkv.shape + assert three == 3 + # qk = rearrange(qkv[:, :, :2], "b s t h d -> b s (t h) d") + qk = qkv[:, :, :2].reshape(batch, seqlen, -1, headdim) + qk = apply_rotary_fn(qk, cos, sin) + else: + assert qkv.dim() == 4 + assert num_heads_q is not None + num_heads_k = (qkv.shape[2] - num_heads_q) // 2 + assert qkv.shape[2] == num_heads_q + 2 * num_heads_k + qk = qkv[:, :, :num_heads_q + num_heads_k] + qk = apply_rotary_fn(qk, cos, sin) + if not inplace: + if qkv.dim() == 5: + qkv = torch.cat([rearrange(qk, "b s (t h) d -> b s t h d", t=2), qkv[:, :, 2:]], dim=2) + else: + qkv = torch.cat([qk, qkv[:, :, num_heads_q + num_heads_k :]], dim=2) + else: + cos_k = cos if cos_k is None else cos_k + sin_k = sin if sin_k is None else sin_k + if qkv.dim() == 5: + batch, seqlen, three, nheads, headdim = qkv.shape + assert three == 3 + q, k = qkv[:, :, 0], qkv[:, :, 1] + else: + assert qkv.dim() == 4 + assert num_heads_q is not None + num_heads_k = (qkv.shape[2] - num_heads_q) // 2 + assert qkv.shape[2] == num_heads_q + 2 * num_heads_k + q, k = qkv[:, :, :num_heads_q], qkv[:, :, num_heads_q : num_heads_q + num_heads_k] + q = apply_rotary_fn(q, cos, sin) + k = apply_rotary_fn(k, cos_k, sin_k) + if not inplace: + if qkv.dim() == 5: + qkv = torch.stack([q, k, qkv[:, :, 2]], dim=2) + else: + qkv = torch.cat([q, k, qkv[:, :, num_heads_q + num_heads_k:]], dim=2) + return qkv + + +class ApplyRotaryEmbQKV_(torch.autograd.Function): + @staticmethod + def forward( + ctx, + qkv, + cos, + sin, + cos_k=None, + sin_k=None, + interleaved=False, + seqlen_offsets: Union[int, torch.Tensor] = 0, + num_heads_q: Optional[int] = None, + ): + # apply_rotary_emb_qkv_inplace( + qkv = _apply_rotary_emb_qkv( + qkv, cos, sin, cos_k, sin_k, interleaved=interleaved, inplace=True, + seqlen_offsets=seqlen_offsets, num_heads_q=num_heads_q, + ) + if isinstance(seqlen_offsets, int): + ctx.save_for_backward(cos, sin, cos_k, sin_k) + ctx.seqlen_offsets = seqlen_offsets + else: + ctx.save_for_backward(cos, sin, cos_k, sin_k, seqlen_offsets) + ctx.seqlen_offsets = None + ctx.interleaved = interleaved + ctx.num_heads_q = num_heads_q + return qkv + + @staticmethod + def backward(ctx, dqkv): + seqlen_offsets = ctx.seqlen_offsets + if seqlen_offsets is None: + cos, sin, cos_k, sin_k, seqlen_offsets = ctx.saved_tensors + else: + cos, sin, cos_k, sin_k = ctx.saved_tensors + dqkv = _apply_rotary_emb_qkv( + dqkv, cos, sin, cos_k, sin_k, interleaved=ctx.interleaved, inplace=True, + seqlen_offsets=seqlen_offsets, num_heads_q=ctx.num_heads_q, conjugate=True, + ) + return dqkv, None, None, None, None, None, None, None + + +def apply_rotary_emb_qkv_( + qkv, + cos, + sin, + cos_k=None, + sin_k=None, + interleaved=False, + seqlen_offsets: Union[int, torch.Tensor] = 0, + num_heads_q: Optional[int] = None, +): + """ + Arguments: + qkv: (batch_size, seqlen, 3, nheads, headdim) or (batch_size, seqlen, num_heads_q + 2 * num_heads_k, headdim). + If qkv has shape (batch_size, seqlen, num_heads_q + 2 * num_heads_k, headdim) (e.g. MQA / GQA), + then num_heads_q must be provided. + cos, sin: (seqlen, rotary_dim / 2) + cos_k, sin_k: (seqlen, rotary_dim / 2), optional + interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead of + 1st half and 2nd half (GPT-NeoX style). + seqlen_offsets: (batch_size,) or int. Each sequence in Q and K is shifted by this amount. + Most commonly used in inference when we have KV cache. + Return: + qkv: (batch_size, seqlen, 3, nheads, headdim) or (batch_size, seqlen, num_heads_q + 2 * num_heads_k, headdim) + rotary_dim must be <= headdim + Apply rotary embedding *inplace* to the first rotary_dim of Q and K. + """ + return ApplyRotaryEmbQKV_.apply( + qkv, cos, sin, cos_k, sin_k, interleaved, seqlen_offsets, num_heads_q + ) + + +class ApplyRotaryEmbKV_(torch.autograd.Function): + + @staticmethod + def forward(ctx, kv, cos, sin, interleaved=False, seqlen_offsets: Union[int, torch.Tensor] = 0): + batch, seqlen, two, nheads, headdim = kv.shape + assert two == 2 + k = kv[:, :, 0] + apply_rotary( + k, cos, sin, seqlen_offsets=seqlen_offsets, interleaved=interleaved, inplace=True + ) + if isinstance(seqlen_offsets, int): + ctx.save_for_backward(cos, sin) # Can't save int with save_for_backward + ctx.seqlen_offsets = seqlen_offsets + else: + ctx.save_for_backward(cos, sin, seqlen_offsets) + ctx.seqlen_offsets = None + ctx.interleaved = interleaved + return kv + + @staticmethod + def backward(ctx, dkv): + seqlen_offsets = ctx.seqlen_offsets + if seqlen_offsets is None: + cos, sin, seqlen_offsets = ctx.saved_tensors + else: + cos, sin = ctx.saved_tensors + apply_rotary( + dkv[:, :, 0], + cos, + sin, + seqlen_offsets=seqlen_offsets, + interleaved=ctx.interleaved, + inplace=True, + conjugate=True, + ) + return dkv, None, None, None, None + + +apply_rotary_emb_kv_ = ApplyRotaryEmbKV_.apply + + +def apply_rotary_emb_kv_( + kv, + cos, + sin, + interleaved=False, + seqlen_offsets: Union[int, torch.Tensor] = 0, +): + """ + Arguments: + kv: (batch_size, seqlen, 2, nheads, headdim) + cos, sin: (seqlen, rotary_dim / 2) + interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead of + 1st half and 2nd half (GPT-NeoX style). + seqlen_offsets: (batch_size,) or int. Each sequence in Q and K is shifted by this amount. + Most commonly used in inference when we have KV cache. + Return: + kv: (batch_size, seqlen, 2, nheads, headdim) + rotary_dim must be <= headdim + Apply rotary embedding *inplace* to the first rotary_dim of K. + """ + return ApplyRotaryEmbKV_.apply(kv, cos, sin, interleaved, seqlen_offsets) + + +class RotaryEmbedding(torch.nn.Module): + """ + The rotary position embeddings from RoFormer_ (Su et. al). + A crucial insight from the method is that the query and keys are + transformed by rotation matrices which depend on the relative positions. + + Other implementations are available in the Rotary Transformer repo_ and in + GPT-NeoX_, GPT-NeoX was an inspiration + + .. _RoFormer: https://arxiv.org/abs/2104.09864 + .. _repo: https://github.com/ZhuiyiTechnology/roformer + .. _GPT-NeoX: https://github.com/EleutherAI/gpt-neox + + If scale_base is not None, this implements XPos (Sun et al., https://arxiv.org/abs/2212.10554). + A recommended value for scale_base is 512: https://github.com/HazyResearch/flash-attention/issues/96 + Reference: https://github.com/sunyt32/torchscale/blob/main/torchscale/component/xpos_relative_position.py + """ + + def __init__( + self, + dim: int, + base=10000.0, + interleaved=False, + scale_base=None, + device=None, + ): + """ + interleaved: if True, rotate pairs of even and odd dimensions (GPT-J style) instead + of 1st half and 2nd half (GPT-NeoX style). + """ + super().__init__() + self.dim = dim + self.base = float(base) + # Generate and save the inverse frequency buffer (non trainable) + inv_freq = self._compute_inv_freq(device) + self.register_buffer("inv_freq", inv_freq, persistent=False) + self.interleaved = interleaved + self.scale_base = scale_base + scale = ( + (torch.arange(0, dim, 2, device=device, dtype=torch.float32) + 0.4 * dim) / (1.4 * dim) + if scale_base is not None + else None + ) + self.register_buffer("scale", scale, persistent=False) + + self._seq_len_cached = 0 + self._cos_cached = None + self._sin_cached = None + self._cos_k_cached = None + self._sin_k_cached = None + + def _compute_inv_freq(self, device=None): + return 1.0 / ( + self.base + ** (torch.arange(0, self.dim, 2, device=device, dtype=torch.float32) / self.dim) + ) + + def _update_cos_sin_cache(self, seqlen, device=None, dtype=None): + # Reset the tables if the sequence length has changed, + # if we're on a new device (possibly due to tracing for instance), + # or if we're switching from inference mode to training + if ( + seqlen > self._seq_len_cached + or self._cos_cached is None + or self._cos_cached.device != device + or self._cos_cached.dtype != dtype + or (self.training and self._cos_cached.is_inference()) + ): + self._seq_len_cached = seqlen + # We want fp32 here, not self.inv_freq.dtype, since the model could be loaded in bf16 + # And the output of arange can be quite large, so bf16 would lose a lot of precision. + t = torch.arange(seqlen, device=device, dtype=torch.float32) + # We want fp32 here as well since inv_freq will be multiplied with t, and the output + # will be large. Having it in bf16 will lose a lot of precision and cause the + # cos & sin output to change significantly. + # We want to recompute self.inv_freq if it was not loaded in fp32 + if self.inv_freq.dtype != torch.float32: + inv_freq = self._compute_inv_freq(device=device) + else: + inv_freq = self.inv_freq + # Don't do einsum, it converts fp32 to bf16 under AMP + # freqs = torch.einsum("i,j->ij", t, self.inv_freq) + freqs = torch.outer(t, inv_freq) + if self.scale is None: + self._cos_cached = torch.cos(freqs).to(dtype) + self._sin_cached = torch.sin(freqs).to(dtype) + else: + power = ( + torch.arange(seqlen, dtype=self.scale.dtype, device=self.scale.device) + - seqlen // 2 + ) / self.scale_base + scale = self.scale.to(device=power.device) ** rearrange(power, "s -> s 1") + # We want the multiplication by scale to happen in fp32 + self._cos_cached = (torch.cos(freqs) * scale).to(dtype) + self._sin_cached = (torch.sin(freqs) * scale).to(dtype) + self._cos_k_cached = (torch.cos(freqs) / scale).to(dtype) + self._sin_k_cached = (torch.sin(freqs) / scale).to(dtype) + + def forward( + self, + qkv: torch.Tensor, + kv: Optional[torch.Tensor] = None, + seqlen_offset: Union[int, torch.Tensor] = 0, + max_seqlen: Optional[int] = None, + num_heads_q: Optional[int] = None, + ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]: + """ + qkv: (batch, seqlen, 3, nheads, headdim) or (batch, seqlen, num_heads_q + 2 * num_heads_k, headdim) + if kv is none, else it's just q of shape (batch, seqlen, nheads, headdim). + If qkv has shape (batch, seqlen, num_heads_q + 2 * num_heads_k, headdim) (e.g. MQA / GQA), + then num_heads_q must be provided. + kv: (batch, seqlen, 2, nheads, headdim) + seqlen_offset: (batch_size,) or int. Each sequence in x is shifted by this amount. + Most commonly used in inference when we have KV cache. + If it's a tensor of shape (batch_size,), then to update the cos / sin cache, one + should pass in max_seqlen, which will update the cos / sin cache up to that length. + Apply rotary embedding *inplace* to qkv and / or kv. + """ + seqlen = qkv.shape[1] + if max_seqlen is not None: + self._update_cos_sin_cache(max_seqlen, device=qkv.device, dtype=qkv.dtype) + elif isinstance(seqlen_offset, int): + self._update_cos_sin_cache(seqlen + seqlen_offset, device=qkv.device, dtype=qkv.dtype) + if kv is None: + return apply_rotary_emb_qkv_( + qkv, + self._cos_cached, + self._sin_cached, + self._cos_k_cached if self.scale is not None else None, + self._sin_k_cached if self.scale is not None else None, + interleaved=self.interleaved, + seqlen_offsets=seqlen_offset, + num_heads_q=num_heads_q, + ) + else: + q = qkv + q = apply_rotary_emb_func( + q, + self._cos_cached, + self._sin_cached, + interleaved=self.interleaved, + inplace=True, + seqlen_offsets=seqlen_offset, + ) + kv = apply_rotary_emb_kv_( + kv, + self._cos_cached if self.scale is None else self._cos_k_cached, + self._sin_cached if self.scale is None else self._sin_k_cached, + interleaved=self.interleaved, + seqlen_offsets=seqlen_offset, + ) + return q, kv diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/losses/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/losses/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/losses/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/losses/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6eb56951c3a7cb747cf55d82a839bb6840f50ab Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/losses/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/losses/__pycache__/cross_entropy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/losses/__pycache__/cross_entropy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8ec2400d42c4ab859d40cf341ba280ddf8f89ef Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/losses/__pycache__/cross_entropy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/losses/cross_entropy.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/losses/cross_entropy.py new file mode 100644 index 0000000000000000000000000000000000000000..d4dcf66758c353b1094218ac78f6f99db2b32224 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/losses/cross_entropy.py @@ -0,0 +1,85 @@ +# Copyright (c) 2024, Tri Dao. + +import torch +import torch.nn as nn + +from flash_attn.ops.triton.cross_entropy import cross_entropy_loss + + +class CrossEntropyLoss(nn.Module): + def __init__( + self, + ignore_index=-100, + reduction="mean", + label_smoothing=0.0, + logit_scale=1.0, + lse_square_scale=0.0, + inplace_backward=False, + process_group=None, + return_z_loss=False, + ): + """ + Arguments: + ignore_index: int. If labels == ignore_index, the loss is set to 0.0. + label_smoothing: float + lse_square_scale: float. If > 0, we add lse_square_scale * lse(logits) ^ 2 to the loss. + This is also referred to as "z-loss". + inplace_backward: bool. If True, we do the backward pass in-place by modifying the logits. + This saves memory. + process_group: if not None, we're doing Tensor Parallel: each process is responsible for + one part of the vocab. The loss will be aggregated across processes. + return_z_loss: bool. If True, we return the component of the loss contributed by + the lse_square_scale value. This value is only for logging and does not support + backprop. + """ + super().__init__() + if reduction not in ["mean", "none", "sum"]: + raise NotImplementedError("Only support reduction = 'mean' or 'none' or 'sum'") + self.ignore_index = ignore_index + self.reduction = reduction + self.label_smoothing = label_smoothing + self.logit_scale = logit_scale + self.lse_square_scale = lse_square_scale + self.inplace_backward = inplace_backward + self.process_group = process_group + self.return_z_loss = return_z_loss + + def forward(self, input, target, precomputed_lse=None): + """ + Arguments: + input: (batch, vocab_size) + target: (batch,) + Returns: + losses: (batch,) if reduction is 'none', else (1,), dtype float + z_loss: (batch,) if reduction is 'none', else (1,), dtype float (if self.return_z_loss) + """ + assert input.is_cuda and target.is_cuda, "Only support CUDA tensors" + loss, z_loss = cross_entropy_loss( + input, + target, + precomputed_lse=precomputed_lse, + label_smoothing=self.label_smoothing, + logit_scale=self.logit_scale, + lse_square_scale=self.lse_square_scale, + ignore_index=self.ignore_index, + inplace_backward=self.inplace_backward, + process_group=self.process_group, + ) + if self.reduction == "mean": + loss = loss.sum() / (target != self.ignore_index).sum() + elif self.reduction == "sum": + loss = loss.sum() + else: + loss = loss + + if not self.return_z_loss: + return loss + + if self.reduction == "mean": + z_loss = z_loss.sum() / (target != self.ignore_index).sum() + elif self.reduction == "sum": + z_loss = z_loss.sum() + else: + z_loss = z_loss + + return loss, z_loss diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13de413c0b4a70c8b5514de3111c4fd733d37380 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/baichuan.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/baichuan.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d6a60a5efbf4845188bfef80a53bde748a04335 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/baichuan.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/bert.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/bert.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7bd2c81d643dbc1743e4d1a02e486acd317fad2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/bert.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/bigcode.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/bigcode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae423c87197ccc1b2cce367be9becddbe54a5215 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/bigcode.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/btlm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/btlm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e1f9829db1b89b3fad5a698ea073199a68f9351 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/btlm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/falcon.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/falcon.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2871026b5728edeeea1b10045255fe551d1db2d3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/falcon.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/gpt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/gpt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..643affd974b5e75ce3fe9870c3e709828f83975a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/gpt.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/gpt_neox.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/gpt_neox.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0ef2bb6bcd05a9d97d3c2b37ebb0ea41fe95464 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/gpt_neox.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/gptj.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/gptj.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2319d6c49282ccd07206f1ec2a62a567543e136 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/gptj.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/llama.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/llama.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08cb39779ad23f2c4cb3fae1ecc88042eae383f9 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/llama.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/opt.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/opt.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1dced69e4ca6e036654a7f2bc7ffe5b142c5f4eb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/opt.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/vit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/vit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e6e9234d9122c6866925140f4b0a6c6a737b30c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/__pycache__/vit.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/baichuan.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/baichuan.py new file mode 100644 index 0000000000000000000000000000000000000000..97d030782187afdfa22b9ad0a9a264b9f6c0a95e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/baichuan.py @@ -0,0 +1,151 @@ +# Copyright (c) 2023, GGGGGGXY, Tri Dao. + +import math +import json +import re +from pathlib import Path + +from collections import OrderedDict + +import torch +import torch.nn.functional as F + +from einops import rearrange +from transformers import GPT2Config, AutoConfig, PretrainedConfig + + +def remap_state_dict_hf_baichuan(state_dict, config): + def key_mapping_layers(key): + return re.sub(r"^model.", "transformer.", key) + + state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items()) + + # Word embedding + def key_mapping_emb(key): + return re.sub( + r"^transformer.embed_tokens.", + "transformer.embeddings.word_embeddings.", + key, + ) + + state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = ( + math.ceil(word_embeddings.shape[0] / pad_vocab_size_multiple) + * pad_vocab_size_multiple + ) + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + if getattr(config, "tie_word_embeddings"): + state_dict["lm_head.weight"] = state_dict[ + "transformer.embeddings.word_embeddings.weight" + ] + else: + output_embeddings = state_dict.pop("lm_head.weight") + # Need to recompute vocab_size since Baichuan shards the word embeddings and output embeddings + # differently. + vocab_size = ( + math.ceil(output_embeddings.shape[0] / pad_vocab_size_multiple) + * pad_vocab_size_multiple + ) + # It's possible that vocab_size is padded to be a multiple of 8, for example. + state_dict["lm_head.weight"] = F.pad( + output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0]) + ) + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^transformer.norm.", r"transformer.ln_f.", key) + key = re.sub( + r"^transformer.layers.(\d+).input_layernorm.", + r"transformer.layers.\1.norm1.", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).post_attention_layernorm.", + r"transformer.layers.\1.norm2.", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + for l in range(config.n_layer): + w1 = state_dict.pop(f"transformer.layers.{l}.mlp.gate_proj.weight") + w3 = state_dict.pop(f"transformer.layers.{l}.mlp.up_proj.weight") + # Our ordering is different + state_dict[f"transformer.layers.{l}.mlp.fc1.weight"] = torch.cat( + [w3, w1], dim=0 + ) + + def key_mapping_mlp(key): + return re.sub( + r"^transformer.layers.(\d+).mlp.down_proj.", + r"transformer.layers.\1.mlp.fc2.", + key, + ) + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + def key_mapping_attn(key): + key = re.sub( + r"^transformer.layers.(\d+).self_attn.W_pack.", + r"transformer.layers.\1.mixer.Wqkv.", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).self_attn.o_proj.", + r"transformer.layers.\1.mixer.out_proj.", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + for l in range(config.n_layer): + # pop rotary_emb.inv_freq from state dict + state_dict.pop(f"transformer.layers.{l}.self_attn.rotary_emb.inv_freq", None) + return state_dict + + +def baichuan_config_to_gpt2_config(baichuan_config: PretrainedConfig) -> GPT2Config: + # HACK: the config doesn't have say whether it's rotary or alibi. + # So we have to infer from the hidden size (7B -> rotary, 13B -> alibi). + # HACK: the config doesn't have say whether it uses norm head. + # So we have to infer from the vocab size + # (v1, vocab size 64k, no norm head; v2, vocab size 128k, norm head). + use_rotary = baichuan_config.hidden_size < 5000 + return GPT2Config( + vocab_size=baichuan_config.vocab_size, + n_positions=0, # No absolute position embedding + n_embd=baichuan_config.hidden_size, + n_layer=baichuan_config.num_hidden_layers, + n_head=baichuan_config.num_attention_heads, + n_inner=baichuan_config.intermediate_size, + activation_function="swiglu", # Hardcode since HF calls it 'silu' + # baichuan doesn't have dropout, idk if it's because they only release the inference code + resid_pdrop=0.0, + embd_pdrop=0.0, + attn_pdrop=0.0, + layer_norm_epsilon=baichuan_config.rms_norm_eps, + initializer_range=baichuan_config.initializer_range, + bos_token_id=baichuan_config.bos_token_id, + eos_token_id=baichuan_config.eos_token_id, + # These are new arguments not in the original GPT2Config + pad_token_id=baichuan_config.pad_token_id, # Idk if this does anything + rms_norm=True, + rotary_emb_fraction=1.0 if use_rotary else 0.0, + rotary_emb_interleaved=False, + use_alibi=not use_rotary, + use_flash_attn=not use_rotary, # Alibi code path requires flash_attn + tie_word_embeddings=False, + norm_head=baichuan_config.vocab_size > 70000, + qkv_proj_bias=False, + out_proj_bias=False, + mlp_fc1_bias=False, + mlp_fc2_bias=False, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/bert.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/bert.py new file mode 100644 index 0000000000000000000000000000000000000000..0904631968411eb227d729a328a36fa4ec97cf02 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/bert.py @@ -0,0 +1,764 @@ +# Copyright (c) 2022, Tri Dao. +# This BERT implementation is based on our MLPerf 2.0 and MLPerf 2.1 BERT implementation. +# https://github.com/mlcommons/training_results_v2.0/blob/main/HazyResearch/benchmarks/bert/implementations/pytorch/modeling.py +# https://github.com/mlcommons/training_results_v2.1/blob/main/Azure-HazyResearch/benchmarks/bert/implementations/ND96amsr_A100_v4/modeling.py + +# Inspired by https://github.com/huggingface/transformers/blob/main/src/transformers/models/bert/modeling_bert.py + +import logging +import re +from collections import OrderedDict +from collections.abc import Sequence +from functools import partial +from typing import Any, Mapping + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange +from transformers import BertConfig, PretrainedConfig +from transformers.models.bert.modeling_bert import ( + BaseModelOutputWithPoolingAndCrossAttentions, + BertForPreTrainingOutput, +) + +from flash_attn.bert_padding import ( + index_first_axis, + index_first_axis_residual, + pad_input, + unpad_input, +) +from flash_attn.modules.block import Block +from flash_attn.modules.embedding import BertEmbeddings +from flash_attn.modules.mha import MHA +from flash_attn.modules.mlp import FusedMLP, Mlp +from flash_attn.utils.pretrained import state_dict_from_pretrained + +try: + from flash_attn.ops.fused_dense import FusedDense +except ImportError: + FusedDense = None + +try: + from flash_attn.ops.triton.layer_norm import layer_norm_fn +except ImportError: + layer_norm_fn = None + + +try: + from flash_attn.losses.cross_entropy import CrossEntropyLoss +except ImportError: + CrossEntropyLoss = None + + +logger = logging.getLogger(__name__) + + +def create_mixer_cls(config, cross_attn=False, return_residual=False): + use_flash_attn = getattr(config, "use_flash_attn", False) + fused_bias_fc = getattr(config, "fused_bias_fc", False) + rotary_kwargs = {} + if config.position_embedding_type == "rotary": + rotary_kwargs["rotary_emb_dim"] = getattr(config, "rotary_emb_dim", config.hidden_size) + rotary_kwargs["rotary_emb_base"] = getattr(config, "rotary_emb_base", 10000.0) + rotary_kwargs["rotary_emb_scale_base"] = getattr(config, "rotary_emb_scale_base", None) + rotary_kwargs["rotary_emb_interleaved"] = getattr(config, "rotary_emb_interleaved", False) + mixer_cls = partial( + MHA, + num_heads=config.num_attention_heads, + cross_attn=cross_attn, + dropout=config.attention_probs_dropout_prob, + causal=False, + fused_bias_fc=fused_bias_fc, + use_flash_attn=use_flash_attn, + return_residual=return_residual, + **rotary_kwargs, + ) + return mixer_cls + + +def create_mlp_cls(config, layer_idx=None, return_residual=False): + inner_dim = config.intermediate_size + fused_mlp = getattr(config, "fused_mlp", False) + if fused_mlp: + assert config.hidden_act in ["gelu_new", "gelu_fast", "gelu_pytorch_tanh"], ( + "fused_mlp only " "supports approximate gelu" + ) + if not fused_mlp: + approximate = ( + "tanh" + if config.hidden_act in ["gelu_new", "gelu_fast", "gelu_pytorch_tanh"] + else "none" + ) + mlp_cls = partial( + Mlp, + hidden_features=inner_dim, + activation=partial(F.gelu, approximate=approximate), + return_residual=return_residual, + ) + else: + if FusedMLP is None: + raise ImportError("fused_dense is not installed") + mlp_checkpoint_lvl = getattr(config, "mlp_checkpoint_lvl", 0) + # mlp_checkpoint_lvl could be a list, which contains the checkpoint_lvl for each layer + if isinstance(mlp_checkpoint_lvl, Sequence): + assert layer_idx is not None + mlp_checkpoint_lvl = mlp_checkpoint_lvl[layer_idx] + mlp_cls = partial( + FusedMLP, + hidden_features=inner_dim, + checkpoint_lvl=mlp_checkpoint_lvl, + return_residual=return_residual, + ) + return mlp_cls + + +def create_block(config, layer_idx=None): + last_layer_subset = getattr(config, "last_layer_subset", False) + cross_attn = last_layer_subset and layer_idx == config.num_hidden_layers - 1 + # TD [2022-12-19]: For cross attention (last layer), we actually want to return the + # residual x_kv, not residual x. But it's annoying to change the API (and it only affects + # one layer) so we just choose not to return residual in this case. + return_residual = not cross_attn + mixer_cls = create_mixer_cls(config, cross_attn, return_residual=return_residual) + mlp_cls = create_mlp_cls(config, layer_idx, return_residual=return_residual) + norm_cls = partial(nn.LayerNorm, eps=config.layer_norm_eps) + block = Block( + config.hidden_size, + mixer_cls, + mlp_cls, + norm_cls=norm_cls, + prenorm=False, + resid_dropout1=config.hidden_dropout_prob, + resid_dropout2=config.hidden_dropout_prob, + fused_dropout_add_ln=getattr(config, "fused_dropout_add_ln", False), + return_residual=return_residual, + ) + return block + + +# https://github.com/huggingface/transformers/blob/7032e0203262ebb2ebf55da8d2e01f873973e835/src/transformers/models/bert/modeling_bert.py#L748 +def _init_weights(module, initializer_range=0.02): + if isinstance(module, nn.Linear): + nn.init.normal_(module.weight, std=initializer_range) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + nn.init.normal_(module.weight, std=initializer_range) + if module.padding_idx is not None: + nn.init.zeros_(module.weight[module.padding_idx]) + + +class BertEncoder(nn.Module): + def __init__(self, config: BertConfig): + super().__init__() + self.use_flash_attn = getattr(config, "use_flash_attn", False) + self.layers = nn.ModuleList( + [create_block(config, layer_idx=i) for i in range(config.num_hidden_layers)] + ) + + def forward(self, hidden_states, key_padding_mask=None, subset_mask=None): + """If subset_mask is not None, we only want output for the subset of the sequence. + This means that we only compute the last layer output for these tokens. + subset_mask: (batch, seqlen), dtype=torch.bool + """ + if key_padding_mask is None or not self.use_flash_attn: + mixer_kwargs = ( + {"key_padding_mask": key_padding_mask} if key_padding_mask is not None else None + ) + for layer in self.layers: + hidden_states = layer(hidden_states, mixer_kwargs=mixer_kwargs) + if subset_mask is not None: + hidden_states = hidden_states[subset_mask] + else: + batch, seqlen = hidden_states.shape[:2] + hidden_states, indices, cu_seqlens, max_seqlen_in_batch, _ = unpad_input( + hidden_states, key_padding_mask + ) + mixer_kwargs = {"cu_seqlens": cu_seqlens, "max_seqlen": max_seqlen_in_batch} + if subset_mask is None: + for layer in self.layers: + hidden_states = layer(hidden_states, mixer_kwargs=mixer_kwargs) + hidden_states = pad_input(hidden_states, indices, batch, seqlen) + else: + for layer in self.layers[:-1]: + hidden_states = layer(hidden_states, mixer_kwargs=mixer_kwargs) + if key_padding_mask is not None: + subset_idx = torch.nonzero( + subset_mask[key_padding_mask], as_tuple=False + ).flatten() + subset_seqlens = (subset_mask & key_padding_mask).sum(dim=-1, dtype=torch.int32) + subset_cu_seqlens = F.pad( + torch.cumsum(subset_seqlens, dim=0, dtype=torch.int32), (1, 0) + ) + else: + subset_idx = torch.nonzero(subset_mask, as_tuple=False).flatten() + subset_seqlens = subset_mask.sum(dim=-1, dtype=torch.int32) + subset_cu_seqlens = F.pad( + torch.cumsum(subset_seqlens, dim=0, dtype=torch.int32), (1, 0) + ) + hidden_states_subset, hidden_states = index_first_axis_residual( + hidden_states, subset_idx + ) + # It's ok to set max_seqlen_q to be much larger + mixer_kwargs = { + "x_kv": hidden_states, + "cu_seqlens": subset_cu_seqlens, + "max_seqlen": max_seqlen_in_batch, + "cu_seqlens_k": cu_seqlens, + "max_seqlen_k": max_seqlen_in_batch, + } + hidden_states = self.layers[-1](hidden_states_subset, mixer_kwargs=mixer_kwargs) + return hidden_states + + +class BertPooler(nn.Module): + def __init__(self, config): + super().__init__() + fused_bias_fc = getattr(config, "fused_bias_fc", False) + if fused_bias_fc and FusedDense is None: + raise ImportError("fused_dense is not installed") + linear_cls = nn.Linear if not fused_bias_fc else FusedDense + self.dense = linear_cls(config.hidden_size, config.hidden_size) + self.activation = nn.Tanh() + + def forward(self, hidden_states, pool=True): + # We "pool" the model by simply taking the hidden state corresponding + # to the first token. + first_token_tensor = hidden_states[:, 0] if pool else hidden_states + pooled_output = self.dense(first_token_tensor) + pooled_output = self.activation(pooled_output) + return pooled_output + + +class BertPredictionHeadTransform(nn.Module): + def __init__(self, config): + super().__init__() + fused_bias_fc = getattr(config, "fused_bias_fc", False) + if fused_bias_fc and FusedDense is None: + raise ImportError("fused_dense is not installed") + self.fused_dropout_add_ln = getattr(config, "fused_dropout_add_ln", False) + if self.fused_dropout_add_ln and layer_norm_fn is None: + raise ImportError("Triton is not installed") + linear_cls = nn.Linear if not fused_bias_fc else FusedDense + self.dense = linear_cls(config.hidden_size, config.hidden_size) + approximate = ( + "tanh" + if config.hidden_act in ["gelu_new", "gelu_fast", "gelu_pytorch_tanh"] + else "none" + ) + self.transform_act_fn = nn.GELU(approximate=approximate) + self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.transform_act_fn(hidden_states) + if not self.fused_dropout_add_ln: + hidden_states = self.layer_norm(hidden_states) + else: + hidden_states = layer_norm_fn( + hidden_states, self.layer_norm.weight, self.layer_norm.bias, eps=self.layer_norm.eps + ) + return hidden_states + + +class BertLMPredictionHead(nn.Module): + def __init__(self, config): + super().__init__() + fused_bias_fc = getattr(config, "fused_bias_fc", False) + if fused_bias_fc and FusedDense is None: + raise ImportError("fused_dense is not installed") + linear_cls = nn.Linear if not fused_bias_fc else FusedDense + + self.transform = BertPredictionHeadTransform(config) + + # The output weights are the same as the input embeddings, but there is + # an output-only bias for each token. + self.decoder = linear_cls(config.hidden_size, config.vocab_size, bias=True) + + def forward(self, hidden_states): + hidden_states = self.transform(hidden_states) + hidden_states = self.decoder(hidden_states) + return hidden_states + + +class BertPreTrainingHeads(nn.Module): + def __init__(self, config): + super().__init__() + self.predictions = BertLMPredictionHead(config) + self.seq_relationship = nn.Linear(config.hidden_size, 2) + + def forward(self, sequence_output, pooled_output): + prediction_scores = self.predictions(sequence_output) + seq_relationship_score = self.seq_relationship(pooled_output) + return prediction_scores, seq_relationship_score + + +class BertPreTrainedModel(nn.Module): + """An abstract class to handle weights initialization and + a simple interface for dowloading and loading pretrained models. + """ + + def __init__(self, config, *inputs, **kwargs): + super().__init__() + if not isinstance(config, BertConfig): + raise ValueError( + "Parameter config in `{}(config)` should be an instance of class `BertConfig`. " + "To create a model from a Google pretrained model use " + "`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`".format( + self.__class__.__name__, self.__class__.__name__ + ) + ) + self.config = config + + @classmethod + def from_pretrained(cls, model_name, config, *inputs, **kwargs): + """ + Instantiate a BertPreTrainedModel from a pre-trained model file or a pytorch state dict. + Download and cache the pre-trained model file if needed. + + Params: + pretrained_model_name_or_path: either: + - a path or url to a pretrained model archive containing: + . `bert_config.json` a configuration file for the model + . `pytorch_model.bin` a PyTorch dump of a BertForPretraining instance + - a path or url to a pretrained model archive containing: + . `bert_config.json` a configuration file for the model + . `model.chkpt` a TensorFlow checkpoint + *inputs, **kwargs: additional input for the specific Bert class + (ex: num_labels for BertForSequenceClassification) + """ + # Instantiate model. + model = cls(config, *inputs, **kwargs) + load_return = model.load_state_dict( + remap_state_dict(state_dict_from_pretrained(model_name), config), strict=False + ) + logger.info(load_return) + return model + + +class BertModel(BertPreTrainedModel): + def __init__(self, config: BertConfig, add_pooling_layer=True): + super().__init__(config) + self.pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + if config.vocab_size % self.pad_vocab_size_multiple != 0: + config.vocab_size += self.pad_vocab_size_multiple - ( + config.vocab_size % self.pad_vocab_size_multiple + ) + self.fused_dropout_add_ln = getattr(config, "fused_dropout_add_ln", False) + if self.fused_dropout_add_ln and layer_norm_fn is None: + raise ImportError("Triton is not installed") + assert config.hidden_act in ["gelu", "gelu_new", "gelu_fast", "gelu_pytorch_tanh"] + + self.embeddings = BertEmbeddings( + config.hidden_size, + config.vocab_size, + config.max_position_embeddings, + config.type_vocab_size, + padding_idx=config.pad_token_id, + ) + self.emb_drop = nn.Dropout(config.hidden_dropout_prob) + self.emb_ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.encoder = BertEncoder(config) + self.pooler = BertPooler(config) if add_pooling_layer else None + + self.apply(partial(_init_weights, initializer_range=config.initializer_range)) + + def forward( + self, + input_ids, + position_ids=None, + token_type_ids=None, + attention_mask=None, + masked_tokens_mask=None, + ): + """If masked_tokens_mask is not None (i.e. last_layer_subset == True in BertForPreTraining), + we only want the output for the masked tokens. This means that we only compute the last + layer output for these tokens. + masked_tokens_mask: (batch, seqlen), dtype=torch.bool + """ + hidden_states = self.embeddings( + input_ids, position_ids=position_ids, token_type_ids=token_type_ids + ) + # TD [2022-12:18]: Don't need to force residual in fp32 + # BERT puts embedding LayerNorm before embedding dropout. + if not self.fused_dropout_add_ln: + hidden_states = self.emb_ln(hidden_states) + else: + hidden_states = layer_norm_fn( + hidden_states, self.emb_ln.weight, self.emb_ln.bias, eps=self.emb_ln.eps + ) + hidden_states = self.emb_drop(hidden_states) + + if masked_tokens_mask is not None: + batch_size, seqlen = input_ids.shape[:2] + # We also need the first column for the CLS token + first_col_mask = torch.zeros( + batch_size, seqlen, dtype=torch.bool, device=input_ids.device + ) + first_col_mask[:, 0] = True + subset_mask = masked_tokens_mask | first_col_mask + else: + subset_mask = None + + sequence_output = self.encoder( + hidden_states, key_padding_mask=attention_mask, subset_mask=subset_mask + ) + + if masked_tokens_mask is None: + pooled_output = self.pooler(sequence_output) if self.pooler is not None else None + else: + # TD [2022-03-01]: the indexing here is very tricky. + if attention_mask is not None: + subset_idx = subset_mask[attention_mask] + pool_input = sequence_output[first_col_mask[attention_mask][subset_idx]] + sequence_output = sequence_output[masked_tokens_mask[attention_mask][subset_idx]] + else: + pool_input = sequence_output[first_col_mask[subset_mask]] + sequence_output = sequence_output[masked_tokens_mask[subset_mask]] + pooled_output = self.pooler(pool_input, pool=False) if self.pooler is not None else None + + return BaseModelOutputWithPoolingAndCrossAttentions( + last_hidden_state=sequence_output, + pooler_output=pooled_output, + ) + + +class BertForPreTraining(BertPreTrainedModel): + def __init__(self, config: BertConfig): + super().__init__(config) + # If dense_seq_output, we only need to pass the hidden states for the masked out tokens + # (around 15%) to the classifier heads. + self.dense_seq_output = getattr(config, "dense_seq_output", False) + # If last_layer_subset, we only need the compute the last layer for a subset of tokens + # (e.g., the tokens we need to compute the masked LM loss and the next-sentence prediction). + self.last_layer_subset = getattr(config, "last_layer_subset", False) + if self.last_layer_subset: + assert self.dense_seq_output, "last_layer_subset requires dense_seq_output" + use_xentropy = getattr(config, "use_xentropy", False) + if use_xentropy and CrossEntropyLoss is None: + raise ImportError("xentropy_cuda is not installed") + loss_cls = ( + nn.CrossEntropyLoss + if not use_xentropy + else partial(CrossEntropyLoss, inplace_backward=True) + ) + + self.bert = BertModel(config) + self.cls = BertPreTrainingHeads(config) + self.mlm_loss = loss_cls(ignore_index=0) + self.nsp_loss = loss_cls(ignore_index=-1) + + # Initialize weights and apply final processing + self.apply(partial(_init_weights, initializer_range=config.initializer_range)) + self.tie_weights() + + def tie_weights(self): + self.cls.predictions.decoder.weight = self.bert.embeddings.word_embeddings.weight + + def forward( + self, + input_ids, + position_ids=None, + token_type_ids=None, + attention_mask=None, + labels=None, + next_sentence_label=None, + ): + """ + If labels are provided, they must be 0 for masked out tokens (as specified in the attention + mask). + Outputs: + if `labels` and `next_sentence_label` are not `None`: + Outputs the total_loss which is the sum of the masked language modeling loss and the next + sentence classification loss. + if `labels` or `next_sentence_label` is `None`: + Outputs a tuple comprising + - the masked language modeling logits of shape [batch_size, sequence_length, vocab_size], and + - the next sentence classification logits of shape [batch_size, 2]. + + """ + masked_tokens_mask = labels > 0 if (self.last_layer_subset and labels is not None) else None + outputs = self.bert( + input_ids, + position_ids=position_ids, + token_type_ids=token_type_ids, + attention_mask=attention_mask.bool() if attention_mask is not None else None, + masked_tokens_mask=masked_tokens_mask, + ) + sequence_output, pooled_output = outputs.last_hidden_state, outputs.pooler_output + if self.dense_seq_output and labels is not None: + masked_token_idx = torch.nonzero(labels.flatten() > 0, as_tuple=False).flatten() + if not self.last_layer_subset: + sequence_output = index_first_axis( + rearrange(sequence_output, "b s d -> (b s) d"), masked_token_idx + ) + prediction_scores, seq_relationship_score = self.cls(sequence_output, pooled_output) + + total_loss = None + if labels is not None and next_sentence_label is not None: + if ( + self.dense_seq_output and labels is not None + ): # prediction_scores are already flattened + masked_lm_loss = self.mlm_loss( + prediction_scores, labels.flatten()[masked_token_idx] + ) + else: + masked_lm_loss = self.mlm_loss( + rearrange(prediction_scores, "... v -> (...) v"), + rearrange(labels, "... -> (...)"), + ) + next_sentence_loss = self.nsp_loss( + rearrange(seq_relationship_score, "... t -> (...) t"), + rearrange(next_sentence_label, "... -> (...)"), + ) + total_loss = masked_lm_loss.float() + next_sentence_loss.float() + + return BertForPreTrainingOutput( + loss=total_loss, + prediction_logits=prediction_scores, + seq_relationship_logits=seq_relationship_score, + ) + + +def remap_state_dict(state_dict, config: PretrainedConfig): + """ + Map the state_dict of a Huggingface BERT model to be flash_attn compatible. + """ + + # LayerNorm + def key_mapping_ln_gamma_beta(key): + key = re.sub(r"LayerNorm.gamma$", "LayerNorm.weight", key) + key = re.sub(r"LayerNorm.beta$", "LayerNorm.bias", key) + return key + + state_dict = OrderedDict((key_mapping_ln_gamma_beta(k), v) for k, v in state_dict.items()) + + # Layers + def key_mapping_layers(key): + return re.sub(r"^bert.encoder.layer.", "bert.encoder.layers.", key) + + state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items()) + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^bert.embeddings.LayerNorm.", "bert.emb_ln.", key) + key = re.sub( + r"^bert.encoder.layers.(\d+).attention.output.LayerNorm.(weight|bias)", + r"bert.encoder.layers.\1.norm1.\2", + key, + ) + key = re.sub( + r"^bert.encoder.layers.(\d+).output.LayerNorm.(weight|bias)", + r"bert.encoder.layers.\1.norm2.\2", + key, + ) + key = re.sub( + r"^cls.predictions.transform.LayerNorm.(weight|bias)", + r"cls.predictions.transform.layer_norm.\1", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + def key_mapping_mlp(key): + key = re.sub( + r"^bert.encoder.layers.(\d+).intermediate.dense.(weight|bias)", + r"bert.encoder.layers.\1.mlp.fc1.\2", + key, + ) + key = re.sub( + r"^bert.encoder.layers.(\d+).output.dense.(weight|bias)", + r"bert.encoder.layers.\1.mlp.fc2.\2", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + last_layer_subset = getattr(config, "last_layer_subset", False) + for d in range(config.num_hidden_layers): + Wq = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.query.weight") + Wk = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.key.weight") + Wv = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.value.weight") + bq = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.query.bias") + bk = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.key.bias") + bv = state_dict.pop(f"bert.encoder.layers.{d}.attention.self.value.bias") + if not (last_layer_subset and d == config.num_hidden_layers - 1): + state_dict[f"bert.encoder.layers.{d}.mixer.Wqkv.weight"] = torch.cat( + [Wq, Wk, Wv], dim=0 + ) + state_dict[f"bert.encoder.layers.{d}.mixer.Wqkv.bias"] = torch.cat([bq, bk, bv], dim=0) + else: + state_dict[f"bert.encoder.layers.{d}.mixer.Wq.weight"] = Wq + state_dict[f"bert.encoder.layers.{d}.mixer.Wkv.weight"] = torch.cat([Wk, Wv], dim=0) + state_dict[f"bert.encoder.layers.{d}.mixer.Wq.bias"] = bq + state_dict[f"bert.encoder.layers.{d}.mixer.Wkv.bias"] = torch.cat([bk, bv], dim=0) + + def key_mapping_attn(key): + return re.sub( + r"^bert.encoder.layers.(\d+).attention.output.dense.(weight|bias)", + r"bert.encoder.layers.\1.mixer.out_proj.\2", + key, + ) + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + + def key_mapping_decoder_bias(key): + return re.sub(r"^cls.predictions.bias", "cls.predictions.decoder.bias", key) + + state_dict = OrderedDict((key_mapping_decoder_bias(k), v) for k, v in state_dict.items()) + + # Word embedding + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + if pad_vocab_size_multiple > 1: + word_embeddings = state_dict["bert.embeddings.word_embeddings.weight"] + state_dict["bert.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, config.vocab_size - word_embeddings.shape[0]) + ) + decoder_weight = state_dict["cls.predictions.decoder.weight"] + state_dict["cls.predictions.decoder.weight"] = F.pad( + decoder_weight, (0, 0, 0, config.vocab_size - decoder_weight.shape[0]) + ) + # If the vocab was padded, we want to set the decoder bias for those padded indices to be + # strongly negative (i.e. the decoder shouldn't predict those indices). + # TD [2022-05-09]: I don't think it affects the MLPerf training. + decoder_bias = state_dict["cls.predictions.decoder.bias"] + state_dict["cls.predictions.decoder.bias"] = F.pad( + decoder_bias, (0, config.vocab_size - decoder_bias.shape[0]), value=-100.0 + ) + + return state_dict + + +def inv_remap_state_dict(state_dict, config: PretrainedConfig): + """ + Map the state_dict of a flash_attn model to be Huggingface BERT compatible. + + This function is meant to be the inverse of remap_state_dict. + """ + # Word embedding + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + if pad_vocab_size_multiple > 1: + word_embeddings = state_dict["bert.embeddings.word_embeddings.weight"] + decoder_weight = state_dict["cls.predictions.decoder.weight"] + decoder_bias = state_dict["cls.predictions.decoder.bias"] + # unpad embeddings + state_dict["bert.embeddings.word_embeddings.weight"] = word_embeddings[ + : config.orig_vocab_size, : + ] + state_dict["cls.predictions.decoder.weight"] = decoder_weight[: config.orig_vocab_size, :] + state_dict["cls.predictions.decoder.bias"] = decoder_bias[: config.orig_vocab_size] + + for d in range(config.num_hidden_layers): + last_layer_subset = getattr(config, "last_layer_subset", False) + if not last_layer_subset or d != (config.num_hidden_layers - 1): + Wqkv_weights = state_dict.pop(f"bert.encoder.layers.{d}.mixer.Wqkv.weight") + Wqkv_biases = state_dict.pop(f"bert.encoder.layers.{d}.mixer.Wqkv.bias") + state_dict[f"bert.encoder.layers.{d}.attention.self.query.weight"] = Wqkv_weights[ + : Wqkv_weights.shape[0] // 3, : + ] + state_dict[f"bert.encoder.layers.{d}.attention.self.key.weight"] = Wqkv_weights[ + Wqkv_weights.shape[0] // 3 : 2 * Wqkv_weights.shape[0] // 3, : + ] + state_dict[f"bert.encoder.layers.{d}.attention.self.value.weight"] = Wqkv_weights[ + 2 * Wqkv_weights.shape[0] // 3 :, : + ] + state_dict[f"bert.encoder.layers.{d}.attention.self.query.bias"] = Wqkv_biases[ + : Wqkv_biases.shape[0] // 3 + ] + state_dict[f"bert.encoder.layers.{d}.attention.self.key.bias"] = Wqkv_biases[ + Wqkv_biases.shape[0] // 3 : 2 * Wqkv_biases.shape[0] // 3 + ] + state_dict[f"bert.encoder.layers.{d}.attention.self.value.bias"] = Wqkv_biases[ + 2 * Wqkv_biases.shape[0] // 3 : + ] + else: + Wq_weight = state_dict.pop(f"bert.encoder.layers.{d}.mixer.Wq.weight") + Wkv_weights = state_dict.pop(f"bert.encoder.layers.{d}.mixer.Wkv.weight") + Wq_bias = state_dict.pop(f"bert.encoder.layers.{d}.mixer.Wq.bias") + Wkv_biases = state_dict.pop(f"bert.encoder.layers.{d}.mixer.Wkv.bias") + state_dict[f"bert.encoder.layers.{d}.attention.self.query.weight"] = Wq_weight + state_dict[f"bert.encoder.layers.{d}.attention.self.key.weight"] = Wkv_weights[ + : Wkv_weights.shape[0] // 2, : + ] + state_dict[f"bert.encoder.layers.{d}.attention.self.value.weight"] = Wkv_weights[ + Wkv_weights.shape[0] // 2 :, : + ] + state_dict[f"bert.encoder.layers.{d}.attention.self.query.bias"] = Wq_bias + state_dict[f"bert.encoder.layers.{d}.attention.self.key.bias"] = Wkv_biases[ + : Wkv_biases.shape[0] // 2 + ] + state_dict[f"bert.encoder.layers.{d}.attention.self.value.bias"] = Wkv_biases[ + Wkv_biases.shape[0] // 2 : + ] + + def inv_key_mapping_ln(key): + key = re.sub(r"bert.emb_ln.", "bert.embeddings.LayerNorm.", key) + key = re.sub( + r"bert.encoder.layers.(\d+).norm1.(weight|bias)", + r"bert.encoder.layers.\1.attention.output.LayerNorm.\2", + key, + ) + key = re.sub( + r"bert.encoder.layers.(\d+).norm2.(weight|bias)", + r"bert.encoder.layers.\1.output.LayerNorm.\2", + key, + ) + key = re.sub( + r"cls.predictions.transform.layer_norm.(weight|bias)", + r"cls.predictions.transform.LayerNorm.\1", + key, + ) + return key + + def inv_key_mapping_ln_gamma_beta(key): + key = re.sub(r"LayerNorm.weight$", "LayerNorm.gamma", key) + key = re.sub(r"LayerNorm.bias$", "LayerNorm.beta", key) + return key + + def inv_key_mapping_layers(key): + return re.sub(r"bert.encoder.layers.", "bert.encoder.layer.", key) + + def inv_key_mapping_mlp(key): + key = re.sub( + r"bert.encoder.layer.(\d+).mlp.fc1.(weight|bias)", + r"bert.encoder.layer.\1.intermediate.dense.\2", + key, + ) + key = re.sub( + r"bert.encoder.layer.(\d+).mlp.fc2.(weight|bias)", + r"bert.encoder.layer.\1.output.dense.\2", + key, + ) + return key + + def inv_key_mapping_attn(key): + return re.sub( + r"bert.encoder.layer.(\d+).mixer.out_proj.(weight|bias)", + r"bert.encoder.layer.\1.attention.output.dense.\2", + key, + ) + + def inv_key_mapping_decoder_bias(key): + return re.sub(r"cls.predictions.decoder.bias", "cls.predictions.bias", key) + + state_dict = OrderedDict((inv_key_mapping_ln(key), value) for key, value in state_dict.items()) + state_dict = OrderedDict( + (inv_key_mapping_ln_gamma_beta(key), value) for key, value in state_dict.items() + ) + state_dict = OrderedDict( + (inv_key_mapping_layers(key), value) for key, value in state_dict.items() + ) + state_dict = OrderedDict((inv_key_mapping_mlp(key), value) for key, value in state_dict.items()) + state_dict = OrderedDict( + (inv_key_mapping_attn(key), value) for key, value in state_dict.items() + ) + state_dict = OrderedDict( + (inv_key_mapping_decoder_bias(key), value) for key, value in state_dict.items() + ) + + return state_dict diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/bigcode.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/bigcode.py new file mode 100644 index 0000000000000000000000000000000000000000..234944d4d6907fb3e1b0c2c3c315a2bee29d7775 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/bigcode.py @@ -0,0 +1,233 @@ +import math +import re +from collections import OrderedDict + +import torch +import torch.nn.functional as F +from transformers import GPT2Config, GPTBigCodeConfig, PretrainedConfig + + +def remap_state_dict_hf_bigcode(state_dict, config: PretrainedConfig): + """ + Map the state_dict of a Huggingface BigCode model to be flash_attn compatible. + """ + + # Word embedding and position embedding + def key_mapping_pos_emb(key): + return re.sub(r"^transformer.wpe.", "transformer.embeddings.position_embeddings.", key) + + state_dict = OrderedDict((key_mapping_pos_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.wte.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^transformer.ln_f.(weight|bias)", r"transformer.ln_f.\1", key) + key = re.sub( + r"^transformer.h.(\d+).ln_(1|2).(weight|bias)", + r"transformer.layers.\1.norm\2.\3", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + def key_mapping_mlp(key): + key = re.sub( + r"^transformer.h.(\d+).mlp.c_fc.weight", + r"transformer.layers.\1.mlp.fc1.weight", + key, + ) + key = re.sub( + r"^transformer.h.(\d+).mlp.c_proj.weight", + r"transformer.layers.\1.mlp.fc2.weight", + key, + ) + key = re.sub( + r"^transformer.h.(\d+).mlp.c_fc.bias", + r"transformer.layers.\1.mlp.fc1.bias", + key, + ) + key = re.sub( + r"^transformer.h.(\d+).mlp.c_proj.bias", + r"transformer.layers.\1.mlp.fc2.bias", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # TODO: add support for multi-head attention + assert config.multi_query, "Only multi-query attention is supported" + + # Attention + for d in range(config.num_hidden_layers): + embed_dim = config.n_embd + head_dim = embed_dim // config.n_head + + c_attn_weight = state_dict.pop(f"transformer.h.{d}.attn.c_attn.weight") + # with multi-query attention, the weights have shape (embed_dim, embed_dim + head_dim + head_dim) + # see https://github.com/huggingface/transformers/blob/95b374952dc27d8511541d6f5a4e22c9ec11fb24/src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py#L112 + # see also https://github.com/ggerganov/ggml/blob/dd1d575956e54c5bdc07632f25506b3b1884dbd2/examples/starcoder/convert-hf-to-ggml.py#L183 + # ((n_head + 2) * head_dim, embed_dim) -> (3 * n_heads * head_dim, hidden_dim) + q, k, v = torch.split(c_attn_weight, [embed_dim, head_dim, head_dim], dim=0) + # duplicate k, v along the first axis (head_dim, hidden_dim) -> (n_heads * head_dim, hidden_dim) + k = torch.tile(k, (config.n_head, 1)) + v = torch.tile(v, (config.n_head, 1)) + state_dict[f"transformer.layers.{d}.mixer.Wqkv.weight"] = torch.cat((q, k, v), dim=0) + + # same deal with the bias + c_attn_bias = state_dict.pop(f"transformer.h.{d}.attn.c_attn.bias") + # ((n_head + 2) * head_dim, embed_dim) -> (3 * n_heads * head_dim, hidden_dim) + q, k, v = torch.split(c_attn_bias, [embed_dim, head_dim, head_dim], dim=0) + # duplicate k, v along the first axis (head_dim, hidden_dim) -> (n_heads * head_dim, hidden_dim) + k = torch.tile(k, (config.n_head,)) + v = torch.tile(v, (config.n_head,)) + state_dict[f"transformer.layers.{d}.mixer.Wqkv.bias"] = torch.cat((q, k, v), dim=0) + + def key_mapping_attn(key): + key = re.sub( + r"^transformer.h.(\d+).attn.c_proj.weight", + r"transformer.layers.\1.mixer.out_proj.weight", + key, + ) + key = re.sub( + r"^transformer.h.(\d+).attn.c_proj.bias", + r"transformer.layers.\1.mixer.out_proj.bias", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + + return state_dict + + +def inv_remap_state_dict_hf_bigcode(state_dict, config: PretrainedConfig): + """ + Map the state_dict of a flash_attn model to be Huggingface BigCode compatible. + + This function is meant to be the inverse of remap_state_dict_hf_bigcode. + """ + + # Word embedding and position embeddings + def inv_key_mapping_pos_emb(key): + return re.sub(r"^transformer.embeddings.position_embeddings.", "transformer.wpe.", key) + + state_dict = OrderedDict((inv_key_mapping_pos_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight") + + word_embeddings = word_embeddings[:, : config.vocab_size] + state_dict["transformer.wte.weight"] = word_embeddings + state_dict["lm_head.weight"] = word_embeddings + + # LayerNorm + def inv_key_mapping_ln(key): + key = re.sub(r"^transformer.ln_f.(weight|bias)", r"transformer.ln_f.\1", key) + key = re.sub( + r"^transformer.layers.(\d+).norm(1|2).(weight|bias)", + r"transformer.h.\1.ln_\2.\3", + key, + ) + return key + + state_dict = OrderedDict((inv_key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLPs + def inv_key_mapping_mlp(key): + key = re.sub( + r"^transformer.layers.(\d+).mlp.fc1.weight", + r"transformer.h.\1.mlp.c_fc.weight", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).mlp.fc2.weight", + r"transformer.h.\1.mlp.c_proj.weight", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).mlp.fc1.bias", + r"transformer.h.\1.mlp.c_fc.bias", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).mlp.fc2.bias", + r"transformer.h.\1.mlp.c_proj.bias", + key, + ) + return key + + state_dict = OrderedDict((inv_key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + for d in range(config.num_hidden_layers): + embed_dim = config.n_embd + head_dim = embed_dim // config.n_head + + Wqkv_weight = state_dict.pop(f"transformer.layers.{d}.mixer.Wqkv.weight") + q, k, v = torch.split( + Wqkv_weight, [embed_dim, head_dim * config.n_head, head_dim * config.n_head], dim=0 + ) + c_attn_weight = torch.cat((q, k[:head_dim], v[:head_dim]), dim=0) + state_dict[f"transformer.h.{d}.attn.c_attn.weight"] = c_attn_weight + + # Same deal with the bias + Wqkv_bias = state_dict.pop(f"transformer.layers.{d}.mixer.Wqkv.bias") + q, k, v = torch.split( + Wqkv_bias, [embed_dim, head_dim * config.n_head, head_dim * config.n_head], dim=0 + ) + c_attn_bias = torch.cat((q, k[:head_dim], v[:head_dim]), dim=0) + state_dict[f"transformer.h.{d}.attn.c_attn.bias"] = c_attn_bias + + def inv_key_mapping_attn(key): + key = re.sub( + r"^transformer.layers.(\d+).mixer.out_proj.weight", + r"transformer.h.\1.attn.c_proj.weight", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).mixer.out_proj.bias", + r"transformer.h.\1.attn.c_proj.bias", + key, + ) + return key + + state_dict = OrderedDict((inv_key_mapping_attn(k), v) for k, v in state_dict.items()) + + return state_dict + + +def bigcode_config_to_gpt2_config(bigcode_config: GPTBigCodeConfig) -> GPT2Config: + return GPT2Config( + activation_function=bigcode_config.activation_function, + attn_pdrop=bigcode_config.attn_pdrop, + bos_token_id=bigcode_config.bos_token_id, + embd_pdrop=bigcode_config.embd_pdrop, + eos_token_id=bigcode_config.eos_token_id, + initializer_range=bigcode_config.initializer_range, + layer_norm_epsilon=bigcode_config.layer_norm_epsilon, + max_batch_size=bigcode_config.max_batch_size, + max_sequence_length=bigcode_config.max_sequence_length, + model_type=bigcode_config.model_type, + multi_query=bigcode_config.multi_query, + n_embd=bigcode_config.n_embd, + n_head=bigcode_config.n_head, + n_inner=bigcode_config.n_inner, + n_layer=bigcode_config.n_layer, + n_positions=bigcode_config.n_positions, + resid_pdrop=bigcode_config.resid_pdrop, + scale_attn_weights=bigcode_config.scale_attn_weights, + summary_activation=bigcode_config.summary_activation, + summary_first_dropout=bigcode_config.summary_first_dropout, + summary_proj_to_labels=bigcode_config.summary_proj_to_labels, + summary_type=bigcode_config.summary_type, + summary_use_proj=bigcode_config.summary_use_proj, + use_cache=bigcode_config.use_cache, + vocab_size=bigcode_config.vocab_size, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/btlm.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/btlm.py new file mode 100644 index 0000000000000000000000000000000000000000..295e12062320be819dd835de4a866607650431b2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/btlm.py @@ -0,0 +1,102 @@ +# Copyright (c) 2023, Tri Dao. + +import math +import json +import re +from pathlib import Path + +from collections import OrderedDict + +import torch +import torch.nn.functional as F + +from einops import rearrange +from transformers import GPT2Config, AutoConfig, PretrainedConfig + + +def remap_state_dict_hf_btlm(state_dict, config): + # Word embedding and position embedding + def key_mapping_pos_emb(key): + return re.sub(r"^transformer.wpe.", "transformer.embeddings.position_embeddings.", key) + + if "transformer.wpe.weight" in state_dict: + state_dict = OrderedDict((key_mapping_pos_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.wte.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^transformer.ln_f.(weight|bias)", r"transformer.ln_f.\1", key) + key = re.sub(r"^transformer.h.(\d+).ln_(1|2).(weight|bias)", r"transformer.layers.\1.norm\2.\3", key) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + for d in range(config.num_hidden_layers): + W1 = state_dict.pop(f"transformer.h.{d}.mlp.c_fc.weight") + W3 = state_dict.pop(f"transformer.h.{d}.mlp.c_fc2.weight") + state_dict[f"transformer.layers.{d}.mlp.fc1.weight"] = torch.cat([W1.t(), W3.t()], dim=0) + b1 = state_dict.pop(f"transformer.h.{d}.mlp.c_fc.bias") + b3 = state_dict.pop(f"transformer.h.{d}.mlp.c_fc2.bias") + state_dict[f"transformer.layers.{d}.mlp.fc1.bias"] = torch.cat([b1, b3], dim=0) + W2 = state_dict.pop(f"transformer.h.{d}.mlp.c_proj.weight") + state_dict[f"transformer.layers.{d}.mlp.fc2.weight"] = W2.t() + + def key_mapping_mlp(key): + key = re.sub(r"^transformer.h.(\d+).mlp.c_proj.bias", r"transformer.layers.\1.mlp.fc2.bias", key) + return key + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + for d in range(config.num_hidden_layers): + Wqkv = state_dict.pop(f"transformer.h.{d}.attn.c_attn.weight") + state_dict[f"transformer.layers.{d}.mixer.Wqkv.weight"] = Wqkv.t() + Wout = state_dict.pop(f"transformer.h.{d}.attn.c_proj.weight") + state_dict[f"transformer.layers.{d}.mixer.out_proj.weight"] = Wout.t() + state_dict.pop(f"transformer.relative_pe.slopes") # We don't store the Alibi slopes + + def key_mapping_attn(key): + key = re.sub(r"^transformer.h.(\d+).attn.c_attn.bias", r"transformer.layers.\1.mixer.Wqkv.bias", key) + key = re.sub( + r"^transformer.h.(\d+).attn.c_proj.bias", r"transformer.layers.\1.mixer.out_proj.bias", key + ) + return key + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + + return state_dict + + +def btlm_config_to_gpt2_config(btlm_config: PretrainedConfig) -> GPT2Config: + return GPT2Config( + vocab_size=btlm_config.vocab_size, + n_positions=0 if btlm_config.position_embedding_type == "alibi" else btlm_config.n_positions, + n_embd=btlm_config.hidden_size, + n_layer=btlm_config.num_hidden_layers, + n_head=btlm_config.num_attention_heads, + n_inner=btlm_config.n_inner, + activation_function=btlm_config.activation_function, + resid_pdrop=btlm_config.resid_pdrop, + embd_pdrop=btlm_config.embd_pdrop, + attn_pdrop=btlm_config.attn_pdrop, + layer_norm_epsilon=btlm_config.layer_norm_epsilon, + initializer_range=btlm_config.initializer_range, + bos_token_id=btlm_config.bos_token_id, + eos_token_id=btlm_config.eos_token_id, + # These are new arguments not in the original GPT2Config + use_alibi=btlm_config.position_embedding_type == "alibi", + use_flash_attn=btlm_config.position_embedding_type == "alibi", # Alibi code path requires flash_attn + mup_width_scale=btlm_config.mup_width_scale, + mup_embeddings_multiplier=btlm_config.mup_embeddings_scale, + mup_output_multiplier=btlm_config.mup_output_alpha, + mup_scale_qk_dot_by_d=btlm_config.mup_scale_qk_dot_by_d, + mlp_multiple_of=1, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/falcon.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/falcon.py new file mode 100644 index 0000000000000000000000000000000000000000..4b02ec7727740eaa9ca70a7f0ca64df94fff4c3a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/falcon.py @@ -0,0 +1,143 @@ +# Copyright (c) 2023, Tri Dao. + +import math +import re +from collections import OrderedDict + +import torch +import torch.nn.functional as F +from einops import rearrange +from transformers import FalconConfig, GPT2Config + + +def remap_state_dict_hf_falcon(state_dict, config): + def key_mapping_layers(key): + return re.sub(r"^transformer.h.", "transformer.layers.", key) + + state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items()) + # Word embedding + def key_mapping_emb(key): + return re.sub( + r"^transformer.word_embeddings.", "transformer.embeddings.word_embeddings.", key + ) + + state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + if getattr(config, "tie_word_embeddings"): + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + else: + output_embeddings = state_dict.pop("lm_head.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + state_dict["lm_head.weight"] = F.pad( + output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0]) + ) + output_embeddings_bias = state_dict.pop("lm_head.bias") + state_dict["lm_head.bias"] = F.pad( + output_embeddings_bias, (0, vocab_size - output_embeddings_bias.shape[0]) + ) + + # LayerNorm + def key_mapping_ln(key): + key = re.sub( + r"^transformer.layers.(\d+).input_layernorm.", r"transformer.layers.\1.norm1.", key + ) + key = re.sub( + r"^transformer.layers.(\d+).post_attention_layernorm.", + r"transformer.layers.\1.norm2.", + key, + ) + key = re.sub(r"^transformer.layers.(\d+).ln_attn.", r"transformer.layers.\1.norm1.", key) + key = re.sub(r"^transformer.layers.(\d+).ln_mlp.", r"transformer.layers.\1.norm2.", key) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + def key_mapping_mlp(key): + key = re.sub( + r"^transformer.layers.(\d+).mlp.dense_h_to_4h.", r"transformer.layers.\1.mlp.fc1.", key + ) + key = re.sub( + r"^transformer.layers.(\d+).mlp.dense_4h_to_h.", r"transformer.layers.\1.mlp.fc2.", key + ) + return key + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + def key_mapping_attn(key): + key = re.sub( + r"^transformer.layers.(\d+).self_attention.query_key_value.", + r"transformer.layers.\1.mixer.Wqkv.", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).self_attention.dense.", + r"transformer.layers.\1.mixer.out_proj.", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + n_head = config.n_head + n_head_kv = getattr(config, "n_head_kv", 1) + headdim = config.hidden_size // n_head + for l in range(config.n_layer): + # The weights are stored in a different layout compared to our implementation + Wqkv = rearrange( + state_dict.pop(f"transformer.layers.{l}.mixer.Wqkv.weight"), + "(group ratio headdim) ... -> group ratio headdim ...", + ratio=n_head // n_head_kv + 2, + headdim=headdim, + ) + Wq = rearrange(Wqkv[:, :-2], "group ratio headdim ... -> (group ratio headdim) ...") + Wk = rearrange(Wqkv[:, [-2]], "group ratio headdim ... -> (group ratio headdim) ...") + Wv = rearrange(Wqkv[:, [-1]], "group ratio headdim ... -> (group ratio headdim) ...") + state_dict[f"transformer.layers.{l}.mixer.Wqkv.weight"] = torch.cat([Wq, Wk, Wv], dim=0) + + return state_dict + + +def falcon_config_to_gpt2_config(falcon_config: FalconConfig) -> GPT2Config: + # The 40b config uses "n_head_kv" instead of "num_kv_heads" + n_head_kv = getattr( + falcon_config, + "n_head_kv", + 1 if getattr(falcon_config, "multi_query", False) else falcon_config.n_head, + ) + # HACK: the 40b config has 2 LN per layer instead of 1, but that's not reflected in the config. + # So we have to infer it from the number of heads in the key/value block + parallel_block_tied_norm = n_head_kv == 1 + return GPT2Config( + vocab_size=falcon_config.vocab_size, + n_positions=0, # No absolute position embedding + n_embd=falcon_config.hidden_size, + n_layer=falcon_config.n_layer, + n_head=falcon_config.n_head, + n_inner=falcon_config.hidden_size * 4, + activation_function="gelu", + resid_pdrop=falcon_config.hidden_dropout, + embd_pdrop=0.0, # There doesn't seem to be any embedding dropout + attn_pdrop=falcon_config.attention_dropout, + layer_norm_epsilon=falcon_config.layer_norm_epsilon, + initializer_range=falcon_config.initializer_range, + bos_token_id=falcon_config.bos_token_id, + eos_token_id=falcon_config.eos_token_id, + # These are new arguments not in the original GPT2Config + parallel_block=falcon_config.parallel_attn, + n_head_kv=n_head_kv, + parallel_block_tied_norm=parallel_block_tied_norm, + rotary_emb_fraction=1.0, + rotary_emb_interleaved=False, + tie_word_embeddings=True, + qkv_proj_bias=falcon_config.bias, + out_proj_bias=falcon_config.bias, + mlp_fc1_bias=falcon_config.bias, + mlp_fc2_bias=falcon_config.bias, + lm_head_bias=False, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/gpt.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/gpt.py new file mode 100644 index 0000000000000000000000000000000000000000..3539f8f901695b29454358972d65031f4c4fabeb --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/gpt.py @@ -0,0 +1,1080 @@ +# Copyright (c) 2024, Tri Dao. + +import logging +import math +import re +from collections import OrderedDict, namedtuple +from collections.abc import Sequence +from functools import partial +from typing import Dict, List + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange +from transformers import GPT2Config + +from flash_attn.models.bigcode import remap_state_dict_hf_bigcode +from flash_attn.models.falcon import remap_state_dict_hf_falcon +from flash_attn.models.gpt_neox import remap_state_dict_hf_gpt_neox +from flash_attn.models.gptj import remap_state_dict_hf_gptj +from flash_attn.models.llama import remap_state_dict_hf_llama +from flash_attn.models.opt import remap_state_dict_hf_opt +from flash_attn.modules.block import Block, ParallelBlock +from flash_attn.modules.embedding import GPT2Embeddings, ParallelGPT2Embeddings +from flash_attn.modules.mha import MHA, ParallelMHA +from flash_attn.modules.mlp import ( + FusedMLP, + GatedMlp, + Mlp, + ParallelFusedMLP, + ParallelGatedMlp, + ParallelMLP, +) +from flash_attn.ops.activations import sqrelu_fwd +from flash_attn.utils.distributed import ( + all_gather, + all_gather_raw, + get_dim_for_local_rank, + sync_shared_params, +) +from flash_attn.utils.generation import GenerationMixin +from flash_attn.utils.pretrained import state_dict_from_pretrained + +try: + from flash_attn.ops.fused_dense import ColumnParallelLinear +except ImportError: + ColumnParallelLinear = None + +try: + from flash_attn.ops.triton.mlp import FusedDenseSqreluDense +except ImportError: + FusedDenseSqreluDense = None + +try: + from flash_attn.ops.triton.layer_norm import layer_norm_fn, RMSNorm +except ImportError: + layer_norm_fn, RMSNorm = None, None + +logger = logging.getLogger(__name__) + + +def create_mixer_cls(config, layer_idx=None, process_group=None, device=None, dtype=None): + factory_kwargs = {"device": device, "dtype": dtype} + head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads) + attn_scale_power = 0.5 if not getattr(config, "mup_scale_qk_dot_by_d", False) else 1.0 + softmax_scale = 1.0 if not config.scale_attn_weights else (head_dim ** (-attn_scale_power)) + softmax_scale *= getattr(config, "mup_attn_multiplier", 1.0) + if config.scale_attn_by_inverse_layer_idx: + assert layer_idx is not None + softmax_scale /= float(layer_idx + 1) + dwconv = getattr(config, "attn_dwconv", False) + if dwconv: + assert process_group is None, "TensorParallel MHA does not support dwconv yet" + qkv_proj_bias = getattr(config, "qkv_proj_bias", True) + out_proj_bias = getattr(config, "out_proj_bias", True) + rotary_emb_dim = int(getattr(config, "rotary_emb_fraction", 0.0) * head_dim) + rotary_emb_base = getattr(config, "rotary_emb_base", 10000.0) + rotary_emb_scale_base = getattr(config, "rotary_emb_scale_base", None) + rotary_emb_interleaved = getattr(config, "rotary_emb_interleaved", False) + use_alibi = getattr(config, "use_alibi", False) + window_size = getattr(config, "window_size", (-1, -1)) + use_flash_attn = getattr(config, "use_flash_attn", False) + fused_bias_fc = getattr(config, "fused_bias_fc", False) + if not fused_bias_fc: + assert process_group is None, "TensorParallel MHA requires fused_bias_fc" + mha_cls = MHA if process_group is None else ParallelMHA + serial_kwargs = ( + {"fused_bias_fc": fused_bias_fc, "dwconv": dwconv} if process_group is None else {} + ) + parallel_kwargs = ( + { + "process_group": process_group, + "sequence_parallel": getattr(config, "sequence_parallel", True), + } + if process_group is not None + else {} + ) + num_heads_kv = getattr(config, "n_head_kv", None) + mixer_cls = partial( + mha_cls, + num_heads=config.num_attention_heads, + num_heads_kv=num_heads_kv, + qkv_proj_bias=qkv_proj_bias, + out_proj_bias=out_proj_bias, + dropout=config.attn_pdrop, + softmax_scale=softmax_scale, + causal=True, + layer_idx=layer_idx, + rotary_emb_dim=rotary_emb_dim, + rotary_emb_base=rotary_emb_base, + rotary_emb_scale_base=rotary_emb_scale_base, + rotary_emb_interleaved=rotary_emb_interleaved, + use_alibi=use_alibi, + window_size=window_size, + use_flash_attn=use_flash_attn, + **serial_kwargs, + **parallel_kwargs, + **factory_kwargs, + ) + return mixer_cls + + +def create_mlp_cls(config, layer_idx=None, process_group=None, device=None, dtype=None): + factory_kwargs = {"device": device, "dtype": dtype} + mlp_fc1_bias = getattr(config, "mlp_fc1_bias", True) + mlp_fc2_bias = getattr(config, "mlp_fc2_bias", True) + fused_mlp = getattr(config, "fused_mlp", False) + if fused_mlp: + assert config.activation_function in [ + "gelu_new", + "gelu_fast", + "gelu_approx", + "gelu_pytorch_tanh", + "relu", + "sqrelu", + ] + fused_dense_sqrelu_dense = getattr(config, "fused_dense_sqrelu_dense", False) + if fused_dense_sqrelu_dense: + assert config.activation_function == "sqrelu", ( + "fused_dense_sqrelu_dense only " "supports approximate activation_function sqrelu" + ) + assert not (fused_dense_sqrelu_dense and fused_mlp) + if not fused_mlp and not fused_dense_sqrelu_dense: + assert config.activation_function in [ + "gelu", + "gelu_new", + "gelu_fast", + "gelu_approx", + "gelu_pytorch_tanh", + "relu", + "sqrelu", + "glu", + "swiglu", + "geglu", + ] + if config.activation_function in ["glu", "swiglu", "geglu"]: + activation = ( + F.sigmoid + if config.activation_function == "glu" + else (F.silu if config.activation_function == "swiglu" else F.gelu) + ) + mlp_cls = GatedMlp if process_group is None else ParallelGatedMlp + parallel_kwargs = ( + { + "process_group": process_group, + "sequence_parallel": getattr(config, "sequence_parallel", True), + } + if process_group is not None + else {} + ) + mlp_multiple_of = getattr(config, "mlp_multiple_of", 128) + mlp_cls = partial( + mlp_cls, + hidden_features=config.n_inner, + activation=activation, + bias1=mlp_fc1_bias, + bias2=mlp_fc2_bias, + multiple_of=mlp_multiple_of, + **parallel_kwargs, + **factory_kwargs, + ) + else: + if config.activation_function == "relu": + activation = partial(F.relu, inplace=True) + elif config.activation_function == "sqrelu": + activation = sqrelu_fwd + else: + approximate = ( + "tanh" + if config.activation_function + in ["gelu_new", "gelu_fast", "gelu_approx", "gelu_pytorch_tanh"] + else "none" + ) + activation = partial(F.gelu, approximate=approximate) + mlp_cls = Mlp if process_group is None else ParallelMLP + parallel_kwargs = ( + { + "process_group": process_group, + "sequence_parallel": getattr(config, "sequence_parallel", True), + } + if process_group is not None + else {} + ) + mlp_cls = partial( + mlp_cls, + hidden_features=config.n_inner, + activation=activation, + bias1=mlp_fc1_bias, + bias2=mlp_fc2_bias, + **parallel_kwargs, + **factory_kwargs, + ) + else: + mlp_checkpoint_lvl = getattr(config, "mlp_checkpoint_lvl", 0) + # mlp_checkpoint_lvl could be a list, which contains the checkpoint_lvl for each layer + if isinstance(mlp_checkpoint_lvl, Sequence): + assert layer_idx is not None + mlp_checkpoint_lvl = mlp_checkpoint_lvl[layer_idx] + if fused_mlp: + if FusedMLP is None: + raise ImportError("fused_dense is not installed") + activation = ( + "gelu_approx" + if config.activation_function + in ["gelu_new", "gelu_fast", "gelu_approx", "gelu_pytorch_tanh"] + else config.activation_function + ) + mlp_cls = FusedMLP if process_group is None else ParallelFusedMLP + parallel_kwargs = ( + { + "process_group": process_group, + "sequence_parallel": getattr(config, "sequence_parallel", True), + } + if process_group is not None + else {} + ) + mlp_cls = partial( + mlp_cls, + hidden_features=config.n_inner, + activation=activation, + checkpoint_lvl=mlp_checkpoint_lvl, + bias1=mlp_fc1_bias, + bias2=mlp_fc2_bias, + **parallel_kwargs, + **factory_kwargs, + ) + elif fused_dense_sqrelu_dense: + if process_group is not None: + assert fused_mlp, "Tensor Parallel is not implemented for FusedDenseSqreluDense" + assert FusedDenseSqreluDense is not None + mlp_cls = partial( + FusedDenseSqreluDense, + hidden_features=config.n_inner, + checkpoint_lvl=mlp_checkpoint_lvl, + **factory_kwargs, + ) + else: + raise RuntimeError("MLP type not supported") + return mlp_cls + + +def create_block(config, layer_idx=None, process_group=None, device=None, dtype=None): + factory_kwargs = {"device": device, "dtype": dtype} + sequence_parallel = getattr(config, "sequence_parallel", True) + mixer_cls = create_mixer_cls(config, layer_idx, process_group=process_group, **factory_kwargs) + mlp_cls = create_mlp_cls(config, layer_idx, process_group=process_group, **factory_kwargs) + use_rms_norm = getattr(config, "rms_norm", False) + norm_cls = partial( + nn.LayerNorm if not use_rms_norm else RMSNorm, + eps=config.layer_norm_epsilon, + **factory_kwargs, + ) + # TD [2022-07-30]: Force residual in fp32, seems to make fp16 training more stable + residual_in_fp32 = getattr(config, "residual_in_fp32", False) + resid_dropout1 = config.resid_pdrop if layer_idx is None or layer_idx > 0 else config.embd_pdrop + prenorm = getattr(config, "prenorm", True) + parallel_block = getattr(config, "parallel_block", False) + if not parallel_block: + block = Block( + config.hidden_size, + mixer_cls, + mlp_cls, + norm_cls=norm_cls, + prenorm=prenorm, + resid_dropout1=resid_dropout1, + resid_dropout2=config.resid_pdrop, + fused_dropout_add_ln=getattr(config, "fused_dropout_add_ln", False), + residual_in_fp32=residual_in_fp32, + sequence_parallel=sequence_parallel and process_group is not None, + mark_shared_params=process_group is not None, + ) + else: + assert prenorm + block = ParallelBlock( + config.hidden_size, + mixer_cls, + mlp_cls, + norm_cls=norm_cls, + resid_dropout1=resid_dropout1, + resid_dropout2=config.resid_pdrop, + tied_norm=getattr(config, "parallel_block_tied_norm", False), + fused_dropout_add_ln=getattr(config, "fused_dropout_add_ln", False), + residual_in_fp32=residual_in_fp32, + sequence_parallel=sequence_parallel and process_group is not None, + mark_shared_params=process_group is not None, + ) + block.layer_idx = layer_idx + return block + + +class GPTPreTrainedModel(nn.Module): + """An abstract class to handle weights initialization and + a simple interface for dowloading and loading pretrained models. + """ + + def __init__(self, config, *inputs, **kwargs): + super().__init__() + if not isinstance(config, GPT2Config): + raise ValueError( + "Parameter config in `{}(config)` should be an instance of class `GPT2Config`. " + "To create a model from a Google pretrained model use " + "`model = {}.from_pretrained(PRETRAINED_MODEL_NAME)`".format( + self.__class__.__name__, self.__class__.__name__ + ) + ) + self.config = config + + @classmethod + def from_pretrained( + cls, + model_name, + config, + *args, + strict=True, + device=None, + dtype=None, + world_size=1, + rank=0, + **kwargs, + ): + """ + Instantiate a GPTPreTrainedModel from a pre-trained model file or a pytorch state dict. + Download and cache the pre-trained model file if needed. + """ + # Instantiate model. + model = cls(config, *args, device=device, dtype=dtype, **kwargs) + # Load state_dict in cpu because we already initialized the model in GPU, and we don't + # want extra stuff taking up more GPU memory + state_dict = state_dict_from_pretrained(model_name, device="cpu", dtype=dtype) + if model_name.startswith("gpt2"): + state_dict = remap_state_dict_hf_gpt2(state_dict, config) + elif model_name.startswith("facebook/opt"): + state_dict = remap_state_dict_hf_opt(state_dict, config) + elif model_name.startswith("EleutherAI/gpt-j-") or model_name.startswith( + "togethercomputer/GPT-JT-" + ): + state_dict = remap_state_dict_hf_gptj(state_dict, config) + elif ( + model_name.startswith("EleutherAI/gpt-neox-") + or model_name.startswith("EleutherAI/pythia-") + or model_name.startswith("togethercomputer/RedPajama-INCITE-") + ): + state_dict = remap_state_dict_hf_gpt_neox(state_dict, config) + elif model_name.startswith("tiiuae/falcon-"): + state_dict = remap_state_dict_hf_falcon(state_dict, config) + elif model_name.startswith("meta-llama/Llama-"): + state_dict = remap_state_dict_hf_llama(state_dict, config) + elif model_name.startswith("bigcode/") or model_name.startswith("WizardLM/"): + state_dict = remap_state_dict_hf_bigcode(state_dict, config) + else: + raise NotImplementedError(f"Model {model_name} not supported") + if world_size > 1: + state_dict = shard_state_dict_tp(state_dict, config, world_size, rank) + load_return = model.load_state_dict(state_dict, strict=strict) + logger.info(load_return) + return model + + +# https://github.com/huggingface/transformers/blob/c28d04e9e252a1a099944e325685f14d242ecdcd/src/transformers/models/gpt2/modeling_gpt2.py#L454 +def _init_weights( + module, n_layer, initializer_range=0.02, mup_width_scale=1.0, rescale_prenorm_residual=True +): + mup_init_scale = math.sqrt(mup_width_scale) + if isinstance(module, nn.Linear): + nn.init.normal_(module.weight, std=initializer_range * mup_init_scale) + optim_cfg = getattr(module.weight, "_optim", {}) + optim_cfg.update({"lr_multiplier": mup_width_scale}) + setattr(module.weight, "_optim", optim_cfg) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif isinstance(module, nn.Embedding): + nn.init.normal_(module.weight, std=initializer_range) + + if rescale_prenorm_residual: + # Reinitialize selected weights subject to the OpenAI GPT-2 Paper Scheme: + # > A modified initialization which accounts for the accumulation on the residual path with model depth. Scale + # > the weights of residual layers at initialization by a factor of 1/√N where N is the # of residual layers. + # > -- GPT-2 :: https://openai.com/blog/better-language-models/ + # + # Reference (Megatron-LM): https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py + for name, p in module.named_parameters(): + if name in ["out_proj.weight", "fc2.weight"]: + # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block + nn.init.normal_( + p, mean=0.0, std=initializer_range * mup_init_scale / math.sqrt(2 * n_layer) + ) + + +class GPTModel(GPTPreTrainedModel): + def __init__(self, config: GPT2Config, process_group=None, device=None, dtype=None): + super().__init__(config) + factory_kwargs = {"device": device, "dtype": dtype} + self.process_group = process_group + self.sequence_parallel = getattr(config, "sequence_parallel", True) + assert config.activation_function in [ + "gelu", + "gelu_new", + "gelu_fast", + "gelu_approx", + "gelu_pytorch_tanh", + "relu", + "sqrelu", + "glu", + "swiglu", + "geglu", + ] + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = ( + math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + ) + self.embeddings_multiplier = getattr(config, "mup_embeddings_multiplier", 1.0) + # TD [2022-07-30]: Force residual in fp32, seems to make fp16 training more stable + self.residual_in_fp32 = getattr(config, "residual_in_fp32", False) + # These 2 options are for OPT-350m + self.prenorm = getattr(config, "prenorm", True) + use_rms_norm = getattr(config, "rms_norm", False) + word_embed_proj_dim = getattr(config, "word_embed_proj_dim", None) + # For GPT-J, GPT-NeoX + self.parallel_block = getattr(config, "parallel_block", False) + + if process_group is None: + self.embeddings = GPT2Embeddings( + config.hidden_size, + vocab_size, + config.max_position_embeddings, + word_embed_proj_dim=word_embed_proj_dim, + **factory_kwargs, + ) + else: + self.embeddings = ParallelGPT2Embeddings( + config.hidden_size, + vocab_size, + config.max_position_embeddings, + process_group=process_group, + sequence_parallel=self.sequence_parallel, + **factory_kwargs, + ) + + # We change the order of dropout, residual and layer norm: + # Instead of LN -> Attn / MLP -> Dropout -> Add, we do: + # Dropout -> Add -> LN -> Attn / MLP, returning both the residual branch (output of Add) and + # the main branch (output of MLP). The model definition is unchanged, but the mapping of the + # nn.Dropout probabilities are changed. + # This is for performance reason: we can fuse dropout + add + layer_norm. + self.layers = nn.ModuleList( + [ + create_block(config, layer_idx=i, process_group=process_group, **factory_kwargs) + for i in range(config.num_hidden_layers) + ] + ) + rotary_emb_fraction = getattr(config, "rotary_emb_fraction", 0.0) + if rotary_emb_fraction > 0.0: # Tie all the RotaryEmbedding modules to share the same cos/sin cache + for layer in self.layers[1:]: + layer.mixer.rotary_emb = self.layers[0].mixer.rotary_emb + + self.fused_dropout_add_ln = getattr(config, "fused_dropout_add_ln", False) + if self.fused_dropout_add_ln: + if layer_norm_fn is None: + raise ImportError("Triton is not installed") + if self.prenorm: + self.drop_f = nn.Dropout(config.resid_pdrop) + norm_cls = nn.LayerNorm if not use_rms_norm else RMSNorm + self.ln_f = norm_cls( + config.hidden_size, eps=config.layer_norm_epsilon, **factory_kwargs + ) + if process_group is not None: + for p in self.ln_f.parameters(): + # Mark the norm parameters as "shared_params" so that we sync their values at init. + p._shared_params = True + # Mark the norm params as "sequence_parallel" so we run all-reduce on their grads. + if self.sequence_parallel: + p._sequence_parallel = True + + self.apply( + partial( + _init_weights, + n_layer=config.num_hidden_layers, + initializer_range=config.initializer_range, + mup_width_scale=getattr(config, "mup_width_scale", 1.0), + ) + ) + self.tie_weights() + + def tie_weights(self): + if self.process_group is not None: + sync_shared_params(self, self.process_group) + + def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs): + return { + i: layer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs) + for i, layer in enumerate(self.layers) + } + + def forward(self, input_ids, position_ids=None, inference_params=None): + # If using Tensor Parallel with sequence parallel, we combine the batch and the seqlen + # dimensions so that we can split on it easily, in case of small batch size. + # Only the attention layers need to know the seqlen. + embedding_kwargs = ( + {"combine_batch_seqlen_dim": True} + if self.process_group is not None and self.sequence_parallel + else {} + ) + hidden_states = self.embeddings(input_ids, position_ids=position_ids, **embedding_kwargs) + if self.embeddings_multiplier != 1.0: + hidden_states = hidden_states * self.embeddings_multiplier + if self.parallel_block: + hidden_states2 = None + residual = None + mixer_kwargs = ( + {"seqlen": input_ids.shape[1]} + if self.process_group is not None and self.sequence_parallel + else {} + ) + if inference_params is not None: + mixer_kwargs["inference_params"] = inference_params + for layer in self.layers: + if self.prenorm: + if not self.parallel_block: + hidden_states, residual = layer( + hidden_states, residual, mixer_kwargs=mixer_kwargs + ) + else: + hidden_states, hidden_states2, residual = layer( + hidden_states, hidden_states2, residual, mixer_kwargs=mixer_kwargs + ) + else: + hidden_states = layer(hidden_states, mixer_kwargs=mixer_kwargs) + if self.prenorm: + if not self.fused_dropout_add_ln: + dropped = self.drop_f(hidden_states) + if not self.parallel_block: + residual = (dropped + residual) if residual is not None else dropped + else: + dropped2 = self.drop_f(hidden_states2) + residual = ( + (residual + dropped + dropped2) + if residual is not None + else dropped + dropped2 + ) + hidden_states = self.ln_f(residual.to(dtype=self.ln_f.weight.dtype)) + else: + # Set prenorm=False here since we don't need the residual + hidden_states = layer_norm_fn( + hidden_states, + self.ln_f.weight, + self.ln_f.bias, + residual=residual, + x1=None if not self.parallel_block else hidden_states2, + eps=self.ln_f.eps, + dropout_p=self.drop_f.p if self.training else 0.0, + prenorm=False, + is_rms_norm=isinstance(self.ln_f, RMSNorm) + ) + return hidden_states + + +class GPTLMHeadModel(GPTPreTrainedModel, GenerationMixin): + def __init__(self, config: GPT2Config, process_group=None, device=None, dtype=None): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__(config) + self.process_group = process_group + self.transformer = GPTModel(config, process_group=process_group, **factory_kwargs) + self.tie_word_embeddings = getattr(config, "tie_word_embeddings", True) + lm_head_bias = getattr(config, "lm_head_bias", False) + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = ( + math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + ) + # This option is for OPT-350m + word_embed_proj_dim = getattr(config, "word_embed_proj_dim", None) + embed_dim = config.n_embd if word_embed_proj_dim is None else word_embed_proj_dim + if word_embed_proj_dim is not None: + self.project_out = nn.Linear(config.n_embd, embed_dim, bias=False, **factory_kwargs) + else: + self.project_out = None + mup_width_scale = getattr(config, "mup_width_scale", 1.0) + mup_output_multiplier = getattr(config, "mup_output_multiplier", 1.0) + self.output_scale = mup_output_multiplier * mup_width_scale + if process_group is None: + self.lm_head = nn.Linear(embed_dim, vocab_size, bias=lm_head_bias, **factory_kwargs) + else: + if ColumnParallelLinear is None: + raise ImportError("fused_dense_lib is not installed") + self.lm_head = ColumnParallelLinear( + embed_dim, + vocab_size, + process_group, + bias=lm_head_bias, + sequence_parallel=getattr(config, "sequence_parallel", True), + **factory_kwargs, + ) + self.norm_head = getattr(config, "norm_head", False) + # Initialize weights and apply final processing + self.apply( + partial( + _init_weights, + n_layer=config.num_hidden_layers, + initializer_range=config.initializer_range, + mup_width_scale=mup_width_scale, + ) + ) + self.tie_weights() + + def tie_weights(self): + if self.tie_word_embeddings: + self.lm_head.weight = self.transformer.embeddings.word_embeddings.weight + if self.process_group is not None: + sync_shared_params(self, self.process_group) + + def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs): + return self.transformer.allocate_inference_cache( + batch_size, max_seqlen, dtype=dtype, **kwargs + ) + + def forward(self, input_ids, position_ids=None, inference_params=None, num_last_tokens=0): + """ + input_ids: (batch, seqlen) int tensor + inference_params: for generation. Adapted from Megatron-LM (and Apex) + https://github.com/NVIDIA/apex/blob/3ff1a10f72ec07067c4e44759442329804ac5162/apex/transformer/testing/standalone_transformer_lm.py#L470 + num_last_tokens: if > 0, only return the logits for the last n tokens + """ + assert ( + input_ids.ndim == 2 + ), f"Expected `input_ids` to have shape [b, slen], but got shape {input_ids.shape}" + b, slen = input_ids.shape + hidden_states = self.transformer( + input_ids, position_ids=position_ids, inference_params=inference_params + ) + if inference_params is not None: + assert hidden_states.ndim == 3, "sequence_parallel is not supported in generation mode" + if num_last_tokens > 0: + hidden_states = hidden_states[:, -num_last_tokens:] + if self.project_out is not None: + hidden_states = self.project_out(hidden_states) + if self.output_scale != 1.0: + hidden_states = hidden_states * self.output_scale + if not self.norm_head: + lm_logits = self.lm_head(hidden_states) + else: + lm_head_weight = F.normalize(self.lm_head.weight) + if isinstance(self.lm_head, ColumnParallelLinear) and self.lm_head.sequence_parallel: + hidden_states = all_gather(hidden_states, self.lm_head.process_group) + lm_logits = F.linear(hidden_states, lm_head_weight, bias=self.lm_head.bias) + # During inference, we want the full logit for sampling + if isinstance(self.lm_head, ColumnParallelLinear) and inference_params is not None: + lm_logits, _ = all_gather_raw(lm_logits, self.lm_head.process_group) + lm_logits = rearrange(lm_logits, "(n b) ... d -> b ... (n d)", b=b) + CausalLMOutput = namedtuple("CausalLMOutput", ["logits"]) + return CausalLMOutput(logits=lm_logits) + + def load_state_dict(self, state_dict, strict=True): + # Remapping from our checkpoints that used a different ordering of layers in the block + # Previous: Attn / MLP -> Dropout -> Add -> LN + # Current: Dropout -> Add -> LN -> Attn / MLP + if "transformer.ln_0.weight" in state_dict: + n_layers = len(self.transformer.layers) + ln_weight = state_dict.pop(f"transformer.layers.{n_layers - 1}.norm2.weight") + ln_bias = state_dict.pop(f"transformer.layers.{n_layers - 1}.norm2.bias") + state_dict["transformer.ln_f.weight"] = ln_weight + state_dict["transformer.ln_f.bias"] = ln_bias + for l in reversed(range(n_layers)): + ln_weight = state_dict.pop(f"transformer.layers.{l}.norm1.weight") + ln_bias = state_dict.pop(f"transformer.layers.{l}.norm1.bias") + state_dict[f"transformer.layers.{l}.norm2.weight"] = ln_weight + state_dict[f"transformer.layers.{l}.norm2.bias"] = ln_bias + if l > 0: + ln_weight = state_dict.pop(f"transformer.layers.{l - 1}.norm2.weight") + ln_bias = state_dict.pop(f"transformer.layers.{l - 1}.norm2.bias") + state_dict[f"transformer.layers.{l}.norm1.weight"] = ln_weight + state_dict[f"transformer.layers.{l}.norm1.bias"] = ln_bias + ln_weight = state_dict.pop("transformer.ln_0.weight") + ln_bias = state_dict.pop("transformer.ln_0.bias") + state_dict[f"transformer.layers.0.norm1.weight"] = ln_weight + state_dict[f"transformer.layers.0.norm1.bias"] = ln_bias + return super().load_state_dict(state_dict, strict=strict) + + +def shard_state_dict_tp(state_dict, config, world_size, rank): + """Convert the state_dict of a standard GPT model to the state_dict of a GPT model + with tensor parallel. + + This function modifies state_dict in place. + """ + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + assert vocab_size % world_size == 0 + assert config.hidden_size % world_size == 0 + inner_dim = config.n_inner if config.n_inner is not None else 4 * config.hidden_size + assert inner_dim % world_size == 0 + + n_head = config.n_head + n_head_kv = getattr(config, "n_head_kv", n_head) + + embed_dim = config.hidden_size + head_dim = embed_dim // n_head + + def shard_first_dim(state_dict, key): + if key in state_dict: + x = state_dict[key] + dim = x.shape[0] // world_size + state_dict[key] = x[rank * dim : (rank + 1) * dim] + + def shard_last_dim(state_dict, key, multiple_of=1): + if key in state_dict: + x = state_dict[key] + dim_each_rank = [ + get_dim_for_local_rank(x.size(-1), world_size, local_rank, multiple_of) + for local_rank in range(world_size) + ] + beg, end = tuple(sum(dim_each_rank[:pos]) for pos in (rank, rank + 1)) + state_dict[key] = x[..., beg:end] + + def shard_gatedmlp_fc1_dim(state_dict, key): + if key in state_dict: + x = state_dict[key] + dim = x.shape[0] // world_size // 2 + state_dict[key] = rearrange( + rearrange(x, "(two o) ... -> two o ...", two=2)[:, rank * dim : (rank + 1) * dim], + "two o ... -> (two o) ...", + ) + + def shard_qkv_headdim(state_dict, key): + if key in state_dict: + n_head_each_rank = [ + get_dim_for_local_rank(n_head, world_size, local_rank) + for local_rank in range(world_size) + ] + n_head_kv_each_rank = [ + get_dim_for_local_rank(n_head_kv, world_size, local_rank) + for local_rank in range(world_size) + ] + + beg_n_head = sum(n_head_each_rank[:rank]) + end_n_head = sum(n_head_each_rank[: rank + 1]) + + beg_n_head_kv = sum(n_head_kv_each_rank[:rank]) + end_n_head_kv = sum(n_head_kv_each_rank[: rank + 1]) + + if n_head_kv == n_head: + x = rearrange(state_dict[key], "(three d) ... -> three d ...", three=3) + state_dict[key] = rearrange( + x[:, beg_n_head * head_dim : end_n_head * head_dim], + "three d ... -> (three d) ...", + ) + else: + x = rearrange( + state_dict[key], + "(nheadqkv headdim) ... -> nheadqkv headdim ...", + nheadqkv=n_head + 2 * n_head_kv, + ) + state_dict[key] = rearrange( + torch.cat( + [ + x[beg_n_head:end_n_head], + x[n_head + beg_n_head_kv : n_head + end_n_head_kv], + x[ + n_head + + n_head_kv + + beg_n_head_kv : n_head + + n_head_kv + + end_n_head_kv + ], + ], + dim=0, + ), + "nheadqkv headdim ... -> (nheadqkv headdim) ...", + ) + + shard_first_dim(state_dict, "transformer.embeddings.word_embeddings.weight") + if "lm_head.weight" in state_dict: + shard_first_dim(state_dict, "lm_head.weight") + if "transformer.embeddings.position_embeddings.weight" in state_dict: + shard_last_dim(state_dict, "transformer.embeddings.position_embeddings.weight") + for i in range(config.num_hidden_layers): + shard_qkv_headdim(state_dict, f"transformer.layers.{i}.mixer.Wqkv.weight") + shard_qkv_headdim(state_dict, f"transformer.layers.{i}.mixer.Wqkv.bias") + shard_last_dim( + state_dict, f"transformer.layers.{i}.mixer.out_proj.weight", multiple_of=head_dim + ) + if rank != 0: + state_dict.pop(f"transformer.layers.{i}.mixer.out_proj.bias", None) + if config.activation_function in ["glu", "swiglu", "geglu"]: + shard_gatedmlp_fc1_dim(state_dict, f"transformer.layers.{i}.mlp.fc1.weight") + shard_gatedmlp_fc1_dim(state_dict, f"transformer.layers.{i}.mlp.fc1.bias") + else: + shard_first_dim(state_dict, f"transformer.layers.{i}.mlp.fc1.weight") + shard_first_dim(state_dict, f"transformer.layers.{i}.mlp.fc1.bias") + shard_last_dim(state_dict, f"transformer.layers.{i}.mlp.fc2.weight") + if rank != 0: + state_dict.pop(f"transformer.layers.{i}.mlp.fc2.bias", None) + return state_dict + + +def combine_state_dicts_tp(state_dicts: List[Dict[str, torch.Tensor]], config: GPT2Config): + """Convert the list of sharded state_dict of a GPT model with tensor parallel to + the state_dict of a standard GPT model. + + This function is meant to be the "reverse" of shard_state_dict_tp. + + Precondition: + - state_dicts should be ordered in the same way as the shards were created. + """ + world_size = len(state_dicts) + keys = state_dicts[0].keys() + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + assert vocab_size % world_size == 0 + assert config.hidden_size % world_size == 0 + inner_dim = config.n_inner if config.n_inner is not None else 4 * config.hidden_size + assert inner_dim % world_size == 0 + assert config.hidden_size % config.n_head == 0 + headdim = config.hidden_size // config.n_head + + # Sometimes the word embeddings are sharded on the 0th dim, sometimes on the 1st dim. + # vocab_size // world_size coordinates are nonzero. + def combine_word_embeddings(state_dicts, state_dict, key): + dim = 0 if state_dicts[0][key].shape[0] == vocab_size // world_size else 1 + state_dict[key] = torch.cat([s[key] for s in state_dicts], dim=dim) + + def combine_dim(state_dicts, state_dict, key, dim=-1): + if key in state_dict: + state_dict[key] = torch.cat([s[key] for s in state_dicts], dim=dim) + + def combine_qkv_headdim(state_dicts, state_dict, key): + n_head = config.n_head + n_head_kv = getattr(config, "n_head_kv", n_head) + if key in state_dict: + if n_head_kv == n_head: + xs = [ + rearrange(s[key], "(three d) ... -> three d ...", three=3) for s in state_dicts + ] + state_dict[key] = rearrange(torch.cat(xs, dim=1), "three d ... -> (three d) ...") + else: + n_head_each_rank = [ + get_dim_for_local_rank(n_head, world_size, local_rank) + for local_rank in range(world_size) + ] + n_head_kv_each_rank = [ + get_dim_for_local_rank(n_head_kv, world_size, local_rank) + for local_rank in range(world_size) + ] + xs = [ + rearrange( + s[key], + "(nheadqkv headdim) ... -> nheadqkv headdim ...", + nheadqkv=rank_n_head + 2 * rank_n_head_kv, + headdim=headdim, + ) + for s, rank_n_head, rank_n_head_kv in zip( + state_dicts, n_head_each_rank, n_head_kv_each_rank + ) + ] + wq = torch.cat([x[: n_head_each_rank[rank]] for rank, x in enumerate(xs)], dim=0) + wk = torch.cat( + [ + x[ + n_head_each_rank[rank] : n_head_each_rank[rank] + + n_head_kv_each_rank[rank] + ] + for rank, x in enumerate(xs) + ], + dim=0, + ) + wv = torch.cat( + [ + x[n_head_each_rank[rank] + n_head_kv_each_rank[rank] :] + for rank, x in enumerate(xs) + ], + dim=0, + ) + wqkv = torch.cat( + [wq, wk, wv], + dim=0, + ) + state_dict[key] = rearrange( + wqkv, + "nheadqkv headdim ... -> (nheadqkv headdim) ...", + ) + + def combine_gated_mlp(state_dicts, state_dict, key): + if key in state_dict: + xs = [rearrange(s[key], "(two d) ... -> two d ...", two=2) for s in state_dicts] + state_dict[key] = rearrange(torch.cat(xs, dim=1), "two d ... -> (two d) ...") + + state_dict = state_dicts[0].copy() # don't modify state_dict[0] inplace + combine_word_embeddings( + state_dicts, state_dict, "transformer.embeddings.word_embeddings.weight" + ) + if "lm_head.weight" in state_dict: + combine_word_embeddings(state_dicts, state_dict, "lm_head.weight") + if "transformer.embeddings.position_embeddings.weight" in state_dict: + combine_dim( + state_dicts, state_dict, "transformer.embeddings.position_embeddings.weight", -1 + ) + mlp_combine_fn = ( + combine_gated_mlp + if config.activation_function in ["glu", "swiglu", "geglu"] + else partial(combine_dim, dim=0) + ) + for i in range(config.num_hidden_layers): + combine_qkv_headdim(state_dicts, state_dict, f"transformer.layers.{i}.mixer.Wqkv.weight") + combine_qkv_headdim(state_dicts, state_dict, f"transformer.layers.{i}.mixer.Wqkv.bias") + combine_dim(state_dicts, state_dict, f"transformer.layers.{i}.mixer.out_proj.weight", -1) + mlp_combine_fn(state_dicts, state_dict, f"transformer.layers.{i}.mlp.fc1.weight") + combine_dim(state_dicts, state_dict, f"transformer.layers.{i}.mlp.fc1.bias", 0) + combine_dim(state_dicts, state_dict, f"transformer.layers.{i}.mlp.fc2.weight", -1) + return state_dict + + +def remap_state_dict_hf_gpt2(state_dict, config): + # Word embedding and position embedding + def key_mapping_pos_emb(key): + return re.sub(r"^wpe.", "transformer.embeddings.position_embeddings.", key) + + state_dict = OrderedDict((key_mapping_pos_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("wte.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^ln_f.(weight|bias)", r"transformer.ln_f.\1", key) + key = re.sub(r"^h.(\d+).ln_(1|2).(weight|bias)", r"transformer.layers.\1.norm\2.\3", key) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + for d in range(config.num_hidden_layers): + W1 = state_dict.pop(f"h.{d}.mlp.c_fc.weight") + state_dict[f"transformer.layers.{d}.mlp.fc1.weight"] = W1.t() + W2 = state_dict.pop(f"h.{d}.mlp.c_proj.weight") + state_dict[f"transformer.layers.{d}.mlp.fc2.weight"] = W2.t() + + def key_mapping_mlp(key): + key = re.sub(r"^h.(\d+).mlp.c_fc.bias", r"transformer.layers.\1.mlp.fc1.bias", key) + key = re.sub(r"^h.(\d+).mlp.c_proj.bias", r"transformer.layers.\1.mlp.fc2.bias", key) + return key + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + for d in range(config.num_hidden_layers): + state_dict.pop(f"h.{d}.attn.bias", None) # We don't store this bias + Wqkv = state_dict.pop(f"h.{d}.attn.c_attn.weight") + state_dict[f"transformer.layers.{d}.mixer.Wqkv.weight"] = Wqkv.t() + Wout = state_dict.pop(f"h.{d}.attn.c_proj.weight") + state_dict[f"transformer.layers.{d}.mixer.out_proj.weight"] = Wout.t() + + def key_mapping_attn(key): + key = re.sub(r"^h.(\d+).attn.c_attn.bias", r"transformer.layers.\1.mixer.Wqkv.bias", key) + key = re.sub( + r"^h.(\d+).attn.c_proj.bias", r"transformer.layers.\1.mixer.out_proj.bias", key + ) + return key + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + + return state_dict + + +def remap_state_dict_megatron(state_dict, config): + def key_mapping_transformer(key): + key = re.sub(r"^language_model.encoder.", "transformer.", key) + key = re.sub(r"^language_model.", "transformer.", key) + return key + + state_dict = OrderedDict((key_mapping_transformer(k), v) for k, v in state_dict.items()) + + # Word embedding and position embedding + def key_mapping_pos_emb(key): + return re.sub(r"^wpe.", "transformer.embeddings.position_embeddings.", key) + + state_dict = OrderedDict((key_mapping_pos_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.embedding.word_embeddings.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = ( + math.ceil(word_embeddings.shape[0] / pad_vocab_size_multiple) * pad_vocab_size_multiple + ) + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^transformer.final_layernorm.(weight|bias)", r"transformer.ln_f.\1", key) + key = re.sub( + r"^transformer.layers.(\d+).input_layernorm.(weight|bias)", + r"transformer.layers.\1.norm1.\2", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).post_attention_layernorm.(weight|bias)", + r"transformer.layers.\1.norm2.\2", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + def key_mapping_mlp(key): + key = re.sub( + r"^transformer.layers.(\d+).mlp.dense_h_to_4h.(weight|bias)", + r"transformer.layers.\1.mlp.fc1.\2", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).mlp.dense_4h_to_h.(weight|bias)", + r"transformer.layers.\1.mlp.fc2.\2", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + def key_mapping_attn(key): + key = re.sub( + r"^transformer.layers.(\d+).self_attention.rotary_emb.inv_freq", + r"transformer.layers.\1.mixer.rotary_emb.inv_freq", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).self_attention.query_key_value.(weight|bias)", + r"transformer.layers.\1.mixer.Wqkv.\2", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).self_attention.dense.(weight|bias)", + r"transformer.layers.\1.mixer.out_proj.\2", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + # Megatron stores Wqkv as ((nheads 3 headdim), hidden_dim) + # while we store Wqkv as ((3 nheads headdim), hidden_dim) + headdim = config.hidden_size // config.num_attention_heads + for d in range(config.num_hidden_layers): + Wqkv = state_dict.pop(f"transformer.layers.{d}.mixer.Wqkv.weight") + state_dict[f"transformer.layers.{d}.mixer.Wqkv.weight"] = rearrange( + Wqkv, + "(nheads three headdim) ... -> (three nheads headdim) ...", + three=3, + headdim=headdim, + ) + bqkv = state_dict.pop(f"transformer.layers.{d}.mixer.Wqkv.bias") + state_dict[f"transformer.layers.{d}.mixer.Wqkv.bias"] = rearrange( + bqkv, "(nheads three headdim) -> (three nheads headdim)", three=3, headdim=headdim + ) + + return state_dict diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/gpt_neox.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/gpt_neox.py new file mode 100644 index 0000000000000000000000000000000000000000..c3894044172260a25c9c561fbaac8add91db5b23 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/gpt_neox.py @@ -0,0 +1,124 @@ +# Copyright (c) 2023, Tri Dao. + +import math +import re +from collections import OrderedDict + +import torch +import torch.nn.functional as F +from einops import rearrange +from transformers import GPT2Config, GPTNeoXConfig + + +def remap_state_dict_hf_gpt_neox(state_dict, config): + def key_mapping_layers(key): + return re.sub(r"^gpt_neox.", "transformer.", key) + + state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items()) + # Word embedding + def key_mapping_emb(key): + return re.sub(r"^transformer.embed_in.", "transformer.embeddings.word_embeddings.", key) + + state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + if getattr(config, "tie_word_embeddings", False): + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + else: + output_embeddings = state_dict.pop("embed_out.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + state_dict["lm_head.weight"] = F.pad( + output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0]) + ) + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^transformer.final_layer_norm.", r"transformer.ln_f.", key) + key = re.sub( + r"^transformer.layers.(\d+).input_layernorm.", r"transformer.layers.\1.norm1.", key + ) + key = re.sub( + r"^transformer.layers.(\d+).post_attention_layernorm.", + r"transformer.layers.\1.norm2.", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + def key_mapping_mlp(key): + key = re.sub( + r"^transformer.layers.(\d+).mlp.dense_h_to_4h.", r"transformer.layers.\1.mlp.fc1.", key + ) + key = re.sub( + r"^transformer.layers.(\d+).mlp.dense_4h_to_h.", r"transformer.layers.\1.mlp.fc2.", key + ) + return key + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + for l in range(config.n_layer): + # We don't store these biases + state_dict.pop(f"transformer.layers.{l}.attention.bias") + state_dict.pop(f"transformer.layers.{l}.attention.masked_bias") + # We don't store these + state_dict.pop(f"transformer.layers.{l}.attention.rotary_emb.inv_freq", None) + # GPT-NeoX stores Wqkv as ((nheads 3 headdim), hidden_dim) + # while we store Wqkv as ((3 nheads headdim), hidden_dim) + headdim = config.hidden_size // config.num_attention_heads + Wqkv = state_dict.pop(f"transformer.layers.{l}.attention.query_key_value.weight") + state_dict[f"transformer.layers.{l}.mixer.Wqkv.weight"] = rearrange( + Wqkv, + "(nheads three headdim) ... -> (three nheads headdim) ...", + three=3, + headdim=headdim, + ) + bqkv = state_dict.pop(f"transformer.layers.{l}.attention.query_key_value.bias") + state_dict[f"transformer.layers.{l}.mixer.Wqkv.bias"] = rearrange( + bqkv, "(nheads three headdim) -> (three nheads headdim)", three=3, headdim=headdim + ) + + def key_mapping_attn(key): + key = re.sub( + r"^transformer.layers.(\d+).attention.dense.", + r"transformer.layers.\1.mixer.out_proj.", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + + return state_dict + + +def gpt_neox_config_to_gpt2_config(gpt_neox_config: GPTNeoXConfig) -> GPT2Config: + assert gpt_neox_config.rotary_emb_base == 10000 + return GPT2Config( + vocab_size=gpt_neox_config.vocab_size, + n_positions=0, # No absolute position embedding + n_embd=gpt_neox_config.hidden_size, + n_layer=gpt_neox_config.num_hidden_layers, + n_head=gpt_neox_config.num_attention_heads, + n_inner=gpt_neox_config.intermediate_size, + activation_function=gpt_neox_config.hidden_act, + resid_pdrop=0.0, # No dropout + embd_pdrop=0.0, + attn_pdrop=0.0, + layer_norm_epsilon=gpt_neox_config.layer_norm_eps, + initializer_range=gpt_neox_config.initializer_range, + bos_token_id=gpt_neox_config.bos_token_id, + eos_token_id=gpt_neox_config.eos_token_id, + # These are new arguments not in the original GPT2Config + prenorm=True, + parallel_block=gpt_neox_config.use_parallel_residual, + parallel_block_tied_norm=False, + rotary_emb_fraction=gpt_neox_config.rotary_pct, + tie_word_embeddings=gpt_neox_config.tie_word_embeddings, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/gptj.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/gptj.py new file mode 100644 index 0000000000000000000000000000000000000000..ca2330d79ce5b78a1229351956da20d88e356083 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/gptj.py @@ -0,0 +1,109 @@ +# Copyright (c) 2023, Tri Dao. + +import math +import re +from collections import OrderedDict + +import torch +import torch.nn.functional as F +from transformers import GPT2Config, GPTJConfig + + +def remap_state_dict_hf_gptj(state_dict, config): + def key_mapping_layers(key): + return re.sub(r"^transformer.h.", "transformer.layers.", key) + + state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items()) + # Word embedding + def key_mapping_emb(key): + return re.sub(r"^transformer.wte.", "transformer.embeddings.word_embeddings.", key) + + state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + if getattr(config, "tie_word_embeddings"): + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + else: + output_embeddings = state_dict.pop("lm_head.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + state_dict["lm_head.weight"] = F.pad( + output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0]) + ) + output_embeddings_bias = state_dict.pop("lm_head.bias") + state_dict["lm_head.bias"] = F.pad( + output_embeddings_bias, (0, vocab_size - output_embeddings_bias.shape[0]) + ) + + # LayerNorm + def key_mapping_ln(key): + return re.sub(r"^transformer.layers.(\d+).ln_1.", r"transformer.layers.\1.norm1.", key) + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + def key_mapping_mlp(key): + key = re.sub( + r"^transformer.layers.(\d+).mlp.fc_in.", r"transformer.layers.\1.mlp.fc1.", key + ) + key = re.sub( + r"^transformer.layers.(\d+).mlp.fc_out.", r"transformer.layers.\1.mlp.fc2.", key + ) + return key + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + for l in range(config.n_layer): + Wq = state_dict.pop(f"transformer.layers.{l}.attn.q_proj.weight") + Wk = state_dict.pop(f"transformer.layers.{l}.attn.k_proj.weight") + Wv = state_dict.pop(f"transformer.layers.{l}.attn.v_proj.weight") + state_dict[f"transformer.layers.{l}.mixer.Wqkv.weight"] = torch.cat([Wq, Wk, Wv], dim=0) + # We don't store these biases + state_dict.pop(f"transformer.layers.{l}.attn.bias") + state_dict.pop(f"transformer.layers.{l}.attn.masked_bias") + + def key_mapping_attn(key): + return re.sub( + r"^transformer.layers.(\d+).attn.out_proj.", + r"transformer.layers.\1.mixer.out_proj.", + key, + ) + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + + return state_dict + + +def gptj_config_to_gpt2_config(gptj_config: GPTJConfig) -> GPT2Config: + headdim = gptj_config.n_embd // gptj_config.n_head + return GPT2Config( + vocab_size=gptj_config.vocab_size, + n_positions=0, # No absolute position embedding + n_embd=gptj_config.n_embd, + n_layer=gptj_config.n_layer, + n_head=gptj_config.n_head, + n_inner=gptj_config.n_inner, + activation_function=gptj_config.activation_function, + resid_pdrop=gptj_config.resid_pdrop, + embd_pdrop=gptj_config.embd_pdrop, + attn_pdrop=gptj_config.attn_pdrop, + layer_norm_epsilon=gptj_config.layer_norm_epsilon, + initializer_range=gptj_config.initializer_range, + bos_token_id=gptj_config.bos_token_id, + eos_token_id=gptj_config.eos_token_id, + # These are new arguments not in the original GPT2Config + prenorm=True, + parallel_block=True, + parallel_block_tied_norm=True, + rotary_emb_fraction=gptj_config.rotary_dim / headdim, + rotary_emb_interleaved=True, + tie_word_embeddings=False, + qkv_proj_bias=False, + out_proj_bias=False, + lm_head_bias=True, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/llama.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/llama.py new file mode 100644 index 0000000000000000000000000000000000000000..3bfb51d17e27c1eeb5f09293b773cda8f4d81233 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/llama.py @@ -0,0 +1,422 @@ +# Copyright (c) 2023, Tri Dao. + +import json +import math +import os +import re +from collections import OrderedDict +from pathlib import Path +from typing import Dict, List, Union + +import torch +import torch.nn.functional as F +from sentencepiece import SentencePieceProcessor +from transformers import GPT2Config, LlamaConfig + +from einops import rearrange + + +def remap_state_dict_meta_llama( + state_dict: Dict[str, torch.Tensor], config: GPT2Config +) -> Dict[str, torch.Tensor]: + """Convert the state_dict in Meta format to standard GPT format. + + This function modifies state_dict in place. + """ + + def key_mapping_layers(key): + return f"transformer.{key}" if not key.startswith("output.") else key + + state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items()) + + # Word embedding + def key_mapping_emb(key): + return re.sub( + r"^transformer.tok_embeddings.", "transformer.embeddings.word_embeddings.", key + ) + + state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = ( + math.ceil(word_embeddings.shape[0] / pad_vocab_size_multiple) * pad_vocab_size_multiple + ) + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + if getattr(config, "tie_word_embeddings"): + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + else: + output_embeddings = state_dict.pop("output.weight") + # Need to recompute vocab_size since LLaMa shards the word embeddings and output embeddings + # differently. + vocab_size = ( + math.ceil(output_embeddings.shape[0] / pad_vocab_size_multiple) + * pad_vocab_size_multiple + ) + # It's possible that vocab_size is padded to be a multiple of 8, for example. + state_dict["lm_head.weight"] = F.pad( + output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0]) + ) + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^transformer.norm.", r"transformer.ln_f.", key) + key = re.sub( + r"^transformer.layers.(\d+).attention_norm.", + r"transformer.layers.\1.norm1.", + key, + ) + key = re.sub(r"^transformer.layers.(\d+).ffn_norm.", r"transformer.layers.\1.norm2.", key) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + for l in range(config.n_layer): + w1 = state_dict.pop(f"transformer.layers.{l}.feed_forward.w1.weight") + w3 = state_dict.pop(f"transformer.layers.{l}.feed_forward.w3.weight") + # Our ordering is different + state_dict[f"transformer.layers.{l}.mlp.fc1.weight"] = torch.cat([w3, w1], dim=0) + + def key_mapping_mlp(key): + return re.sub( + r"^transformer.layers.(\d+).feed_forward.w2.", + r"transformer.layers.\1.mlp.fc2.", + key, + ) + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + for l in range(config.n_layer): + Wq = state_dict.pop(f"transformer.layers.{l}.attention.wq.weight") + Wk = state_dict.pop(f"transformer.layers.{l}.attention.wk.weight") + Wv = state_dict.pop(f"transformer.layers.{l}.attention.wv.weight") + state_dict[f"transformer.layers.{l}.mixer.Wqkv.weight"] = torch.cat([Wq, Wk, Wv], dim=0) + # We don't store these + state_dict.pop(f"transformer.layers.{l}.attention.inner_attention.rope.freqs", None) + + def key_mapping_attn(key): + return re.sub( + r"^transformer.layers.(\d+).attention.wo.", + r"transformer.layers.\1.mixer.out_proj.", + key, + ) + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + + state_dict.pop("transformer.rope.freqs", None) + + return state_dict + + +def remap_state_dict_hf_llama( + state_dict: Dict[str, torch.Tensor], config: GPT2Config +) -> Dict[str, torch.Tensor]: + """Convert the state_dict in Hugging Face format to standard GPT format. + + This function modifies state_dict in place. + """ + + # Embedding + def key_mapping_emb(key): + return re.sub(r"^model.embed_tokens.", "transformer.embeddings.word_embeddings.", key) + + state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = ( + math.ceil(word_embeddings.shape[0] / pad_vocab_size_multiple) * pad_vocab_size_multiple + ) + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + + # LM head + if getattr(config, "tie_word_embeddings"): + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + else: + output_embeddings = state_dict.pop("lm_head.weight") + # Need to recompute vocab_size since LLaMa shards the word embeddings and output embeddings + # differently. + vocab_size = ( + math.ceil(output_embeddings.shape[0] / pad_vocab_size_multiple) + * pad_vocab_size_multiple + ) + # It's possible that vocab_size is padded to be a multiple of 8, for example. + state_dict["lm_head.weight"] = F.pad( + output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0]) + ) + + # MLP + for l in range(config.n_layer): + # Fusing weights this way based on difference in the following: + # https://github.com/huggingface/transformers/blob/b42010bb1d3cbf262d27e0a328661885be46dfdb/src/transformers/models/llama/modeling_llama.py#L220 + # https://github.com/Dao-AILab/flash-attention/blob/c60851a8253257eb970e06a022c82517a8033e8c/flash_attn/modules/mlp.py#L115 + w1 = state_dict.pop(f"model.layers.{l}.mlp.gate_proj.weight") + w3 = state_dict.pop(f"model.layers.{l}.mlp.up_proj.weight") + state_dict[f"transformer.layers.{l}.mlp.fc1.weight"] = torch.cat([w3, w1], dim=0) + + def key_mapping_mlp(key): + return re.sub( + r"^model.layers.(\d+).mlp.down_proj.", + r"transformer.layers.\1.mlp.fc2.", + key, + ) + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^model.norm.", r"transformer.ln_f.", key) + key = re.sub( + r"^model.layers.(\d+).input_layernorm.", + r"transformer.layers.\1.norm1.", + key, + ) + key = re.sub( + r"^model.layers.(\d+).post_attention_layernorm.", + r"transformer.layers.\1.norm2.", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + def inv_permute(w): + # Inverse of permute implemented in: + # https://github.com/huggingface/transformers/blob/b42010bb1d3cbf262d27e0a328661885be46dfdb/src/transformers/models/llama/convert_llama_weights_to_hf.py#L114 + return rearrange( + w, "(h two d) n -> (h d two) n", d=config.n_embd // config.n_head // 2, two=2 + ) + + # Attention + for l in range(config.n_layer): + Wq = state_dict.pop(f"model.layers.{l}.self_attn.q_proj.weight") + Wk = state_dict.pop(f"model.layers.{l}.self_attn.k_proj.weight") + Wv = state_dict.pop(f"model.layers.{l}.self_attn.v_proj.weight") + + state_dict[f"transformer.layers.{l}.mixer.Wqkv.weight"] = torch.cat( + [inv_permute(Wq), inv_permute(Wk), Wv], dim=0 + ) + # We don't store these + state_dict.pop(f"model.layers.{l}.self_attn.rotary_emb.inv_freq", None) + + def key_mapping_attn(key): + return re.sub( + r"^model.layers.(\d+).self_attn.o_proj.", + r"transformer.layers.\1.mixer.out_proj.", + key, + ) + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + return state_dict + + +def inv_remap_state_dict_hf_llama( + state_dict: Dict[str, torch.Tensor], config: GPT2Config +) -> Dict[str, torch.Tensor]: + """Convert the state_dict in standard GPT format to Hugging Face format. + + This function is meant to be the inverse of remap_state_dict_hf_llama, up to a + multiplier pad in the embedding and lm_head. That is if the original embedding + isn't a multiple of pad_vocab_size_multiple, then + inv_remap_state_dict_hf_llama(remap_state_dict_hf_llama(state_dict)) != state_dict. + + This function modifies state_dict in place. + """ + + # Embedding + def key_mapping_emb(key): + return re.sub(r"^transformer.embeddings.word_embeddings.", "model.embed_tokens.", key) + + state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items()) + word_embeddings = state_dict.pop("model.embed_tokens.weight") + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = ( + math.ceil(word_embeddings.shape[0] / pad_vocab_size_multiple) * pad_vocab_size_multiple + ) + state_dict["model.embed_tokens.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + + # LM head + if getattr(config, "tie_word_embeddings"): + state_dict["lm_head.weight"] = state_dict["model.embed_tokens.weight"] + else: + output_embeddings = state_dict.pop("lm_head.weight") + vocab_size = ( + math.ceil(output_embeddings.shape[0] / pad_vocab_size_multiple) + * pad_vocab_size_multiple + ) + state_dict["lm_head.weight"] = F.pad( + output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0]) + ) + + # MLP + for l in range(config.n_layer): + w3, w1 = torch.chunk( + state_dict.pop(f"transformer.layers.{l}.mlp.fc1.weight"), chunks=2, dim=0 + ) + state_dict[f"model.layers.{l}.mlp.gate_proj.weight"] = w1 + state_dict[f"model.layers.{l}.mlp.up_proj.weight"] = w3 + + def key_mapping_mlp(key): + return re.sub( + r"^transformer.layers.(\d+).mlp.fc2.", + r"model.layers.\1.mlp.down_proj.", + key, + ) + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^transformer.ln_f.", r"model.norm.", key) + key = re.sub( + r"^transformer.layers.(\d+).norm1.", + r"model.layers.\1.input_layernorm.", + key, + ) + key = re.sub( + r"^transformer.layers.(\d+).norm2.", + r"model.layers.\1.post_attention_layernorm.", + key, + ) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + def permute(w): + return rearrange( + w, "(h d two) n -> (h two d) n", d=config.n_embd // config.n_head // 2, two=2 + ) + + n_head = config.n_head + n_head_kv = getattr(config, "n_head_kv", n_head) + + embed_dim = config.hidden_size + head_dim = embed_dim // n_head + + q_dim = n_head * head_dim + k_dim = v_dim = n_head_kv * head_dim + + # Attention + for l in range(config.n_layer): + Wqkv = state_dict.pop(f"transformer.layers.{l}.mixer.Wqkv.weight") + Wq = Wqkv[:q_dim] + Wk = Wqkv[q_dim : q_dim + k_dim] + Wv = Wqkv[q_dim + k_dim : q_dim + k_dim + v_dim] + state_dict[f"model.layers.{l}.self_attn.q_proj.weight"] = permute(Wq) + state_dict[f"model.layers.{l}.self_attn.k_proj.weight"] = permute(Wk) + state_dict[f"model.layers.{l}.self_attn.v_proj.weight"] = Wv + state_dict.pop(f"transformer.layers.{l}.attention.inner_attention.rope.freqs", None) + + def key_mapping_attn(key): + return re.sub( + r"^transformer.layers.(\d+).mixer.out_proj.", + r"model.layers.\1.self_attn.o_proj.", + key, + ) + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + return state_dict + + +def config_from_meta_checkpoint( + checkpoint_path: Union[str, os.PathLike], model_name: str +) -> LlamaConfig: + """Load a LlamaConfig from a checkpoint path.""" + with open(Path(checkpoint_path) / model_name / "params.json") as f: + params = json.load(f) + config = LlamaConfig( + hidden_size=params["dim"], + intermediate_size=None, + num_attention_heads=params["n_heads"], + num_hidden_layers=params["n_layers"], + rms_norm_eps=params["norm_eps"], + num_key_value_heads=params.get("n_kv_heads", None), + ) + multiple_of = params.get("multiple_of", 1) + ffn_dim_multiplier = params.get("ffn_dim_multiplier", None) + + # Compute the hidden dimension of the MLP + # https://github.com/facebookresearch/llama/blob/1a240688810f8036049e8da36b073f63d2ac552c/llama/model.py#L224 + intermediate_size = 4 * config.hidden_size + # https://github.com/facebookresearch/llama/blob/1a240688810f8036049e8da36b073f63d2ac552c/llama/model.py#L195-L199 + intermediate_size = int(2 * intermediate_size / 3) + # custom dim factor multiplier + if ffn_dim_multiplier is not None: + intermediate_size = int(ffn_dim_multiplier * intermediate_size) + intermediate_size = multiple_of * ((intermediate_size + multiple_of - 1) // multiple_of) + + config.intermediate_size = intermediate_size + if "rope_theta" in params: + config.rotary_emb_base = params["rope_theta"] + config.vocab_size = 32000 + # some CodeLLaMa have vocab_size 32000, some 32016 + # Sadly it's not specified in the `params.json` file :( + tokenizer = Path(checkpoint_path) / model_name / "tokenizer.model" + if tokenizer.is_file(): + config.vocab_size = SentencePieceProcessor(str(tokenizer)).vocab_size() + return config + + +def config_from_hf_checkpoint( + checkpoint_path: Union[str, os.PathLike], model_name: str +) -> LlamaConfig: + return LlamaConfig.from_pretrained(Path(checkpoint_path) / f"{model_name}-hf" / "config.json") + + +def config_from_checkpoint( + checkpoint_path: Union[str, os.PathLike], model_name: str, checkpoint_format="meta" +) -> LlamaConfig: + if checkpoint_format == "meta": + return config_from_meta_checkpoint(checkpoint_path, model_name) + else: + return config_from_hf_checkpoint(checkpoint_path, model_name) + + +def state_dicts_from_checkpoint( + checkpoint_path: Union[str, os.PathLike], model_name: str +) -> List[dict]: + # Need to sort, otherwise we mess up the ordering and the weights are wrong + return [ + torch.load(path, map_location="cpu") + for path in sorted((Path(checkpoint_path) / model_name).glob("consolidated.*.pth")) + ] + + +def llama_config_to_gpt2_config(llama_config: LlamaConfig) -> GPT2Config: + return GPT2Config( + vocab_size=llama_config.vocab_size, + n_positions=0, # No absolute position embedding + n_embd=llama_config.hidden_size, + n_layer=llama_config.num_hidden_layers, + n_head=llama_config.num_attention_heads, + n_inner=llama_config.intermediate_size, + activation_function="swiglu", # Hardcode since HF calls it 'silu' + # Llama doesn't have dropout, idk if it's because they only release the inference code + resid_pdrop=0.0, + embd_pdrop=0.0, + attn_pdrop=0.0, + layer_norm_epsilon=llama_config.rms_norm_eps, + initializer_range=llama_config.initializer_range, + bos_token_id=llama_config.bos_token_id, + eos_token_id=llama_config.eos_token_id, + # These are new arguments not in the original GPT2Config + pad_token_id=llama_config.pad_token_id, # Idk if this does anything + rms_norm=True, + rotary_emb_fraction=1.0, + rotary_emb_interleaved=True, + tie_word_embeddings=False, + qkv_proj_bias=False, + out_proj_bias=False, + mlp_fc1_bias=False, + mlp_fc2_bias=False, + rotary_emb_base=getattr(llama_config, "rotary_emb_base", 10000.0), + n_head_kv=llama_config.num_key_value_heads, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/opt.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/opt.py new file mode 100644 index 0000000000000000000000000000000000000000..501f9eb6cf44be86aeb77a4e0f35048255850c30 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/opt.py @@ -0,0 +1,116 @@ +# Copyright (c) 2023, Tri Dao. + +import math +import re +from collections import OrderedDict + +import torch +import torch.nn.functional as F +from transformers import GPT2Config, OPTConfig + + +def remap_state_dict_hf_opt(state_dict, config): + def key_mapping_model(key): + key = re.sub(r"^model.decoder.", "transformer.", key) + # The OPT-350m model uses '^decoder' instead of '^model.decoder' + key = re.sub(r"^decoder.", "transformer.", key) + return key + + state_dict = OrderedDict((key_mapping_model(k), v) for k, v in state_dict.items()) + # Word embedding and position embedding + def key_mapping_emb(key): + key = re.sub(r"^transformer.embed_tokens.", "transformer.embeddings.word_embeddings.", key) + # The OPT-350m model uses has project_in and project_out + key = re.sub(r"^transformer.project_in.", "transformer.embeddings.project_in.", key) + key = re.sub(r"^transformer.project_out.", "project_out.", key) + key = re.sub( + r"^transformer.embed_positions.", "transformer.embeddings.position_embeddings.", key + ) + return key + + state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items()) + # OPT uses the first 2 indices of pos_emb for padding tokens + pos_embeddings = state_dict.pop("transformer.embeddings.position_embeddings.weight") + state_dict["transformer.embeddings.position_embeddings.weight"] = pos_embeddings[2:] + word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight") + # It's possible that vocab_size is padded to be a multiple of 8, for example. + pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1) + vocab_size = math.ceil(config.vocab_size / pad_vocab_size_multiple) * pad_vocab_size_multiple + state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad( + word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0]) + ) + state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"] + + # LayerNorm + def key_mapping_ln(key): + key = re.sub(r"^transformer.final_layer_norm.", r"transformer.ln_f.", key) + # The OPT-175B checkpoint calls this 'decoder.layer_norm' instead of 'decoder.final_layer_norm' + key = re.sub(r"^transformer.layer_norm.", r"transformer.ln_f.", key) + key = re.sub( + r"^transformer.layers.(\d+).self_attn_layer_norm.", r"transformer.layers.\1.norm1.", key + ) + key = re.sub( + r"^transformer.layers.(\d+).final_layer_norm.", r"transformer.layers.\1.norm2.", key + ) + return key + + state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items()) + + # MLP + def key_mapping_mlp(key): + return re.sub( + r"^transformer.layers.(\d+).fc(1|2).", r"transformer.layers.\1.mlp.fc\2.", key + ) + + state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items()) + + # Attention + for l in range(config.n_layer): + Wq = state_dict.pop(f"transformer.layers.{l}.self_attn.q_proj.weight") + Wk = state_dict.pop(f"transformer.layers.{l}.self_attn.k_proj.weight") + Wv = state_dict.pop(f"transformer.layers.{l}.self_attn.v_proj.weight") + bq = state_dict.pop(f"transformer.layers.{l}.self_attn.q_proj.bias") + bk = state_dict.pop(f"transformer.layers.{l}.self_attn.k_proj.bias") + bv = state_dict.pop(f"transformer.layers.{l}.self_attn.v_proj.bias") + state_dict[f"transformer.layers.{l}.mixer.Wqkv.weight"] = torch.cat([Wq, Wk, Wv], dim=0) + state_dict[f"transformer.layers.{l}.mixer.Wqkv.bias"] = torch.cat([bq, bk, bv], dim=0) + + def key_mapping_attn(key): + return re.sub( + r"^transformer.layers.(\d+).self_attn.out_proj.", + r"transformer.layers.\1.mixer.out_proj.", + key, + ) + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + + return state_dict + + +def opt_config_to_gpt2_config(opt_config: OPTConfig) -> GPT2Config: + assert opt_config.layerdrop == 0.0 + assert opt_config.layer_norm_elementwise_affine + word_embed_proj_dim = ( + None + if opt_config.word_embed_proj_dim == opt_config.hidden_size + else opt_config.word_embed_proj_dim + ) + return GPT2Config( + vocab_size=opt_config.vocab_size, + n_positions=opt_config.max_position_embeddings, + n_embd=opt_config.hidden_size, + n_layer=opt_config.num_hidden_layers, + n_head=opt_config.num_attention_heads, + n_inner=opt_config.ffn_dim, + activation_function=opt_config.activation_function, + resid_pdrop=opt_config.dropout, + # HF's implementation of OPT doesn't seem to have embedding dropout + embd_pdrop=opt_config.dropout, + attn_pdrop=opt_config.attention_dropout, + initializer_range=opt_config.init_std, + bos_token_id=opt_config.bos_token_id, + eos_token_id=opt_config.eos_token_id, + # These are new arguments not in the original GPT2Config + prenorm=opt_config.do_layer_norm_before, + word_embed_proj_dim=word_embed_proj_dim, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/vit.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/vit.py new file mode 100644 index 0000000000000000000000000000000000000000..4602fd7414d251e40f9d42250c23cc974d596661 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/models/vit.py @@ -0,0 +1,373 @@ +# Copyright (c) 2022, Tri Dao. +# Inspired by / adapted from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py +import math +import re +from collections import OrderedDict +from copy import deepcopy +from functools import partial + +import torch +import torch.nn as nn +import torch.nn.functional as F +from einops import rearrange +from timm.models.helpers import named_apply +from torch.nn.init import trunc_normal_ +from torchvision.ops import StochasticDepth + +from flash_attn.layers.patch_embed import PatchEmbed +from flash_attn.modules.block import Block +from flash_attn.modules.mha import MHA +from flash_attn.modules.mlp import FusedMLP, Mlp + +try: + from flash_attn.ops.triton.layer_norm import layer_norm_fn +except ImportError: + layer_norm_fn = None + + +def create_mixer_cls( + num_heads, qkv_bias, attn_drop, use_flash_attn, fused_bias_fc, cross_attn=False +): + mixer_cls = partial( + MHA, + num_heads=num_heads, + cross_attn=cross_attn, + qkv_proj_bias=qkv_bias, + dropout=attn_drop, + fused_bias_fc=fused_bias_fc, + use_flash_attn=use_flash_attn, + ) + return mixer_cls + + +def create_mlp_cls(embed_dim, mlp_ratio, act_layer, fused_mlp): + inner_dim = int(embed_dim * mlp_ratio) + if not fused_mlp: + mlp_cls = partial(Mlp, hidden_features=inner_dim, activation=act_layer()) + else: + mlp_cls = partial(FusedMLP, hidden_features=inner_dim) + return mlp_cls + + +def create_block( + embed_dim, + num_heads, + mlp_ratio, + qkv_bias, + drop_rate, + attn_drop_rate, + drop_path1, + drop_path2, + norm_layer, + act_layer, + use_flash_attn, + fused_bias_fc, + fused_mlp, + fused_dropout_add_ln, + layer_idx=None, + n_layer=None, + last_layer_subset=False, +): + mixer_cls = create_mixer_cls( + num_heads, + qkv_bias, + attn_drop_rate, + use_flash_attn, + fused_bias_fc, + cross_attn=(last_layer_subset and layer_idx == n_layer - 1), + ) + mlp_cls = create_mlp_cls(embed_dim, mlp_ratio, act_layer, fused_mlp) + # TD [2022-10-15]: Force residual in fp32 in case of DeepSpeed + block = Block( + embed_dim, + mixer_cls, + mlp_cls, + norm_cls=norm_layer, + prenorm=True, + resid_dropout1=drop_rate, + resid_dropout2=drop_rate, + drop_path1=drop_path1, + drop_path2=drop_path2, + fused_dropout_add_ln=fused_dropout_add_ln, + residual_in_fp32=True, + ) + return block + + +class VisionTransformer(nn.Module): + """Vision Transformer + A PyTorch impl of : `An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale` + - https://arxiv.org/abs/2010.11929 + """ + + def __init__( + self, + img_size=224, + patch_size=16, + in_chans=3, + num_classes=1000, + global_pool="token", + embed_dim=768, + depth=12, + num_heads=12, + mlp_ratio=4.0, + qkv_bias=True, + init_values=None, + class_token=True, + no_embed_class=False, + pre_norm=False, + fc_norm=None, + drop_rate=0.0, + attn_drop_rate=0.0, + drop_path_rate=0.0, + weight_init="", + embed_layer=PatchEmbed, + norm_layer=None, + act_layer=None, + use_flash_attn=False, + fused_bias_fc=False, + fused_mlp=False, + fused_dropout_add_ln=False, + ): + """ + Args: + img_size (int, tuple): input image size + patch_size (int, tuple): patch size + in_chans (int): number of input channels + num_classes (int): number of classes for classification head + global_pool (str): type of global pooling for final sequence (default: 'token') + embed_dim (int): embedding dimension + depth (int): depth of transformer + num_heads (int): number of attention heads + mlp_ratio (int): ratio of mlp hidden dim to embedding dim + qkv_bias (bool): enable bias for qkv if True + init_values: (float): layer-scale init values + class_token (bool): use class token + fc_norm (Optional[bool]): pre-fc norm after pool, set if global_pool == 'avg' if None (default: None) + drop_rate (float): dropout rate + attn_drop_rate (float): attention dropout rate + drop_path_rate (float): stochastic depth rate + weight_init (str): weight init scheme + embed_layer (nn.Module): patch embedding layer + norm_layer: (nn.Module): normalization layer + act_layer: (nn.Module): MLP activation layer + """ + super().__init__() + assert global_pool == "token", "Only support pooling with CLS token" + assert class_token + assert init_values is None, "LayerScale is not supported yet" + assert weight_init == "" + assert fc_norm is None + # pre_norm seems redundant, as there's a LayerNorm right at the start of each block, idk + assert not pre_norm + use_fc_norm = global_pool == "avg" if fc_norm is None else fc_norm + norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6) + act_layer = act_layer or nn.GELU + + self.num_classes = num_classes + self.global_pool = global_pool + self.num_features = ( + self.embed_dim + ) = embed_dim # num_features for consistency with other models + self.num_prefix_tokens = 1 if class_token else 0 + self.no_embed_class = no_embed_class + + patch_embed_extra_kwargs = ( + {"fused_bias_fc": fused_bias_fc} if embed_layer is PatchEmbed else {} + ) + self.patch_embed = embed_layer( + img_size=img_size, + patch_size=patch_size, + in_chans=in_chans, + embed_dim=embed_dim, + bias=not pre_norm, # disable bias if pre-norm is used (e.g. CLIP) + **patch_embed_extra_kwargs, + ) + num_patches = self.patch_embed.num_patches + + self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) if class_token else None + embed_len = num_patches if no_embed_class else num_patches + self.num_prefix_tokens + self.pos_embed = nn.Parameter(torch.randn(1, embed_len, embed_dim) * 0.02) + + dpr = [ + x.item() for x in torch.linspace(0, drop_path_rate, depth) + ] # stochastic depth decay rule + + # We change the order of dropout, residual and layer norm: + # Instead of LN -> Attn / MLP -> Dropout -> Add, we do: + # Dropout -> Add -> LN -> Attn / MLP, returning both the residual branch (output of Add) and + # the main branch (output of MLP). The model definition is unchanged, but the mapping of the + # nn.Dropout probabilities are changed. + # This is for performance reason: we can fuse dropout + add + layer_norm. + self.blocks = nn.ModuleList( + [ + create_block( + embed_dim, + num_heads, + mlp_ratio, + qkv_bias, + drop_rate, + attn_drop_rate, + drop_path1=dpr[i - 1] if i > 0 else 0.0, + drop_path2=dpr[i], + norm_layer=norm_layer, + act_layer=act_layer, + use_flash_attn=use_flash_attn, + fused_bias_fc=fused_bias_fc, + fused_mlp=fused_mlp, + fused_dropout_add_ln=fused_dropout_add_ln, + layer_idx=i, + n_layer=depth, + last_layer_subset=(global_pool == "token"), + ) + for i in range(depth) + ] + ) + + self.dropout = nn.Dropout(p=drop_rate) + self.drop_path = StochasticDepth(p=dpr[-1], mode="row") + self.norm = norm_layer(embed_dim) + + self.fused_dropout_add_ln = fused_dropout_add_ln + if self.fused_dropout_add_ln and layer_norm_fn is None: + raise ImportError("Triton is not installed") + + # Classifier Head + self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity() + + self.init_weights(weight_init) + + def init_weights(self, mode=""): + assert mode == "" + trunc_normal_(self.pos_embed, std=0.02) + if self.cls_token is not None: + nn.init.normal_(self.cls_token, std=1e-6) + named_apply(init_weights_vit_timm, self) + + def _init_weights(self, m): + # this fn left here for compat with downstream users + init_weights_vit_timm(m) + + @torch.jit.ignore + def no_weight_decay(self): + return {"pos_embed", "cls_token"} + + def _pos_embed(self, x): + if self.no_embed_class: + # deit-3, updated JAX (big vision) + # position embedding does not overlap with class token, add then concat + x = x + self.pos_embed + if self.cls_token is not None: + x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) + else: + # original timm, JAX, and deit vit impl + # pos_embed has entry for class token, concat then add + if self.cls_token is not None: + x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1) + x = x + self.pos_embed + return x + + def forward_features(self, x, all_tokens=True): + """ + If all_tokens==False and self.global_pool == 'token', we only return the features for the + cls token. + """ + x = self.patch_embed(x) + hidden_states = self._pos_embed(x) + residual = None + if self.global_pool != "token" or all_tokens: + # if True: + for block in self.blocks: + hidden_states, residual = block(hidden_states, residual) + else: + for block in self.blocks[:-1]: + hidden_states, residual = block(hidden_states, residual) + # For the last layer, we only want the 1st token of the output. So we do cross-attention + # where the query is the 1st token and the key/value is the whole sequence. + hidden_states, residual = self.blocks[-1]( + hidden_states, residual, mixer_subset=slice(0, 1) + ) + if not self.fused_dropout_add_ln: + residual = self.drop_path(self.dropout(hidden_states)) + residual + hidden_states = self.norm(residual.to(dtype=self.norm.weight.dtype)) + else: + if self.drop_path.p == 0 or not self.training: + rowscale = None + else: + rowscale = self.drop_path( + torch.ones( + hidden_states.shape[:-1], + device=hidden_states.device, + dtype=hidden_states.dtype, + ) + ) + # Set prenorm=False here since we don't need to the residual + hidden_states = layer_norm_fn( + hidden_states, + self.norm.weight, + self.norm.bias, + residual=residual, + eps=self.norm.eps, + dropout_p=self.dropout.p if self.training else 0.0, + rowscale=rowscale, + prenorm=False, + ) + return hidden_states + + def forward_head(self, x, pre_logits: bool = False): + if self.global_pool: + x = x[:, self.num_prefix_tokens :].mean(dim=1) if self.global_pool == "avg" else x[:, 0] + return x if pre_logits else self.head(x) + + def forward(self, x): + x = self.forward_features(x, all_tokens=False) + x = self.forward_head(x) + return x + + def load_state_dict(self, state_dict, strict=True): + patch_embed_weight = state_dict["patch_embed.proj.weight"] + if patch_embed_weight.dim() == 4: + # convert from Conv2d to Linear + state_dict["patch_embed.proj.weight"] = rearrange( + patch_embed_weight, "o c h w -> o (c h w)" + ) + + def key_mapping_attn(key): + key = re.sub(r"^blocks.(\d+).attn.qkv.", r"blocks.\1.mixer.Wqkv.", key) + key = re.sub(r"^blocks.(\d+).attn.proj.", r"blocks.\1.mixer.out_proj.", key) + return key + + state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items()) + n_layer = len(self.blocks) + # Convert from Wqkv to Wq and Wkv for cross attention (last layer) + if ( + self.blocks[-1].mixer.cross_attn + and f"blocks.{n_layer - 1}.mixer.Wqkv.weight" in state_dict + ): + Wqkv = state_dict.pop(f"blocks.{n_layer - 1}.mixer.Wqkv.weight") + bqkv = state_dict.pop(f"blocks.{n_layer - 1}.mixer.Wqkv.bias") + state_dict[f"blocks.{n_layer - 1}.mixer.Wq.weight"] = Wqkv[: self.embed_dim] + state_dict[f"blocks.{n_layer - 1}.mixer.Wkv.weight"] = Wqkv[self.embed_dim :] + state_dict[f"blocks.{n_layer - 1}.mixer.Wq.bias"] = bqkv[: self.embed_dim] + state_dict[f"blocks.{n_layer - 1}.mixer.Wkv.bias"] = bqkv[self.embed_dim :] + return super().load_state_dict(state_dict, strict=strict) + + +def init_weights_vit_timm(module: nn.Module, name: str = ""): + """ViT weight initialization, original timm impl (for reproducibility)""" + if isinstance(module, nn.Linear): + trunc_normal_(module.weight, std=0.02) + if module.bias is not None: + nn.init.zeros_(module.bias) + elif hasattr(module, "init_weights"): + module.init_weights() + + +def vit_base_patch16_224(pretrained=False, **kwargs): + """ViT-Base (ViT-B/16) from original paper (https://arxiv.org/abs/2010.11929). + ImageNet-1k weights fine-tuned from in21k @ 224x224, source https://github.com/google-research/vision_transformer. + """ + assert not pretrained + model_kwargs = dict(patch_size=16, embed_dim=768, depth=12, num_heads=12, **kwargs) + model = VisionTransformer(**model_kwargs) + return model diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a79da6343d37e30f3f35390ae43166bbea916b71 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__pycache__/block.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__pycache__/block.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49fedcb364d37eed870defc869d15f42a16b2171 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__pycache__/block.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__pycache__/embedding.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__pycache__/embedding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..745746a920f3f3e7d1298c641280304d9c1db987 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__pycache__/embedding.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__pycache__/mha.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__pycache__/mha.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31f745232ea0b0b8d0e29365feb3f685e9142c23 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__pycache__/mha.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__pycache__/mlp.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__pycache__/mlp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db6b13c57d2d201db9efdf1e0b0fc7cf82510243 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/__pycache__/mlp.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/block.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/block.py new file mode 100644 index 0000000000000000000000000000000000000000..be8e8b864b600220068c2ec16aba5e2f1a81c121 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/block.py @@ -0,0 +1,397 @@ +# Copyright (c) 2024, Tri Dao. + +from functools import partial +from typing import Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor +from torchvision.ops import StochasticDepth + +from flash_attn.modules.mha import MHA +from flash_attn.modules.mlp import Mlp + +try: + from flash_attn.ops.triton.layer_norm import layer_norm_fn, RMSNorm +except ImportError: + layer_norm_fn, RMSNorm = None, None + + +class Block(nn.Module): + def __init__( + self, + dim, + mixer_cls=None, + mlp_cls=None, + norm_cls=nn.LayerNorm, + dropout_cls=nn.Dropout, + prenorm=True, + resid_dropout1=0.0, + resid_dropout2=0.0, + drop_path1=0.0, + drop_path2=0.0, + fused_dropout_add_ln=False, + return_residual=False, + residual_in_fp32=False, + sequence_parallel=False, + mark_shared_params=False, + ): + """ + For prenorm=True, this Block has a slightly different structure compared to a regular + prenorm Transformer block. + The standard block is: LN -> MHA -> Dropout -> Add -> LN -> MLP -> Dropout -> Add. + [Ref: https://arxiv.org/abs/2002.04745] + Here we have: Dropout -> Add -> LN -> MHA -> Dropout -> Add -> LN -> MLP, returning both + the hidden_states (output of the MLP) and the residual. + This is for performance reasons, as we can fuse the dropout, add and LayerNorm. + The residual needs to be provided (except for the very first block). + + For prenorm=False, this Block has the same structure as a regular postnorm Transformer + block: MHA -> Dropout -> Add -> LN -> MLP -> Dropout -> Add -> LN. + + return_residual: whether each of the sub-layers (mixer and mlp) will return the residual. + This is for performance reason: for post-norm architecture, returning the input allows us + to fuse the backward of nn.Linear with the residual connection. + """ + super().__init__() + self.prenorm = prenorm + self.fused_dropout_add_ln = fused_dropout_add_ln + self.return_residual = return_residual + self.residual_in_fp32 = residual_in_fp32 + if self.residual_in_fp32: + assert self.prenorm, "residual_in_fp32 is only compatible with prenorm=True" + if mixer_cls is None: + mixer_cls = partial(MHA, num_heads=dim // 64) + if mlp_cls is None: + mlp_cls = partial(Mlp, hidden_features=4 * dim) + self.mixer = mixer_cls(dim) + self.dropout1 = dropout_cls(resid_dropout1) + self.drop_path1 = StochasticDepth(drop_path1, mode="row") + self.norm1 = norm_cls(dim) + self.mlp = mlp_cls(dim) + if not isinstance(self.mlp, nn.Identity): + self.dropout2 = dropout_cls(resid_dropout2) + self.drop_path2 = StochasticDepth(drop_path2, mode="row") + self.norm2 = norm_cls(dim) + + if self.fused_dropout_add_ln: + assert layer_norm_fn is not None, "Triton is not installed" + assert isinstance(self.norm1, (nn.LayerNorm, RMSNorm)) and isinstance( + self.dropout1, nn.Dropout + ) + + # TD [2023-01-07]: TODO: During training, if sequence_parallel is False and dropout != 0.0, + # then the input to each worker in the tensor parallel group will be different. + # This would produce wrong outputs? Somehow we'd need to sync the RNG state across workers. + # For now this is not an issue because we always use sequence_parallel=True during training + # and only use sequence_parallel=False during inference. + + # Mark the norm parameters as "sequence_parallel" so that we run all-reduce on their grads. + if sequence_parallel: + for p in self.norm1.parameters(): + p._sequence_parallel = True + if hasattr(self, "norm2"): + for p in self.norm2.parameters(): + p._sequence_parallel = True + # Mark the norm parameters as "shared_params" so that we sync their values at init. + if mark_shared_params: + for p in self.norm1.parameters(): + p._shared_params = True + if hasattr(self, "norm2"): + for p in self.norm2.parameters(): + p._shared_params = True + + def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs): + return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs) + + def forward( + self, + hidden_states: Tensor, + residual: Optional[Tensor] = None, + mixer_subset=None, + mixer_kwargs=None, + ): + r"""Pass the input through the encoder layer. + + Args: + hidden_states: the sequence to the encoder layer (required). + residual: if postnorm, residual=None, If prenorm, hidden_states = Attn/MLP(LN(residual)) + mixer_subset: for cross-attention only. If not None, will take a subset of x + before applying the query projection. Useful for e.g., ViT where we only care + about the CLS token in the last layer. + """ + if self.prenorm: + if not self.fused_dropout_add_ln: + dropped = self.drop_path1(self.dropout1(hidden_states)) + residual = (dropped + residual) if residual is not None else dropped + hidden_states = self.norm1(residual.to(dtype=self.norm1.weight.dtype)) + if self.residual_in_fp32: + residual = residual.to(torch.float32) + else: + if self.drop_path1.p == 0 or not self.training: + rowscale1 = None + else: + rowscale1 = self.drop_path1( + torch.ones( + hidden_states.shape[:-1], + device=hidden_states.device, + dtype=hidden_states.dtype, + ) + ) + hidden_states, residual = layer_norm_fn( + hidden_states, + self.norm1.weight, + self.norm1.bias, + residual=residual, + eps=self.norm1.eps, + dropout_p=self.dropout1.p if self.training else 0.0, + rowscale=rowscale1, + prenorm=True, + residual_in_fp32=self.residual_in_fp32, + is_rms_norm=isinstance(self.norm1, RMSNorm) + ) + if mixer_kwargs is None: + mixer_kwargs = {} + if mixer_subset is not None: + mixer_kwargs["mixer_subset"] = mixer_subset + hidden_states = self.mixer(hidden_states, **mixer_kwargs) + if mixer_subset is not None: + residual = residual[:, mixer_subset] + if not isinstance(self.mlp, nn.Identity): + if not self.fused_dropout_add_ln: + dropped = self.drop_path2(self.dropout2(hidden_states)) + residual = (dropped + residual) if residual is not None else dropped + hidden_states = self.norm2(residual.to(dtype=self.norm2.weight.dtype)) + if self.residual_in_fp32: + residual = residual.to(torch.float32) + else: + if self.drop_path2.p == 0 or not self.training: + rowscale2 = None + else: + rowscale2 = self.drop_path2( + torch.ones( + hidden_states.shape[:-1], + device=hidden_states.device, + dtype=hidden_states.dtype, + ) + ) + hidden_states, residual = layer_norm_fn( + hidden_states, + self.norm2.weight, + self.norm2.bias, + residual=residual, + eps=self.norm2.eps, + dropout_p=self.dropout2.p if self.training else 0.0, + rowscale=rowscale2, + prenorm=True, + residual_in_fp32=self.residual_in_fp32, + is_rms_norm=isinstance(self.norm2, RMSNorm) + ) + hidden_states = self.mlp(hidden_states) + return hidden_states, residual + else: + assert residual is None + mixer_out = self.mixer( + hidden_states, **(mixer_kwargs if mixer_kwargs is not None else {}) + ) + if self.return_residual: # mixer out is actually a pair here + mixer_out, hidden_states = mixer_out + if not self.fused_dropout_add_ln: + hidden_states = self.norm1( + (self.drop_path1(self.dropout1(mixer_out)) + hidden_states).to( + dtype=self.norm1.weight.dtype + ) + ) + else: + if self.drop_path1.p == 0 or not self.training: + rowscale1 = None + else: + rowscale1 = self.drop_path1( + torch.ones( + mixer_out.shape[:-1], device=mixer_out.device, dtype=mixer_out.dtype + ) + ) + hidden_states = layer_norm_fn( + mixer_out, + self.norm1.weight, + self.norm1.bias, + residual=hidden_states, + eps=self.norm1.eps, + dropout_p=self.dropout1.p if self.training else 0.0, + rowscale=rowscale1, + prenorm=False, + is_rms_norm=isinstance(self.norm1, RMSNorm) + ) + if not isinstance(self.mlp, nn.Identity): + mlp_out = self.mlp(hidden_states) + if self.return_residual: # mlp out is actually a pair here + mlp_out, hidden_states = mlp_out + if not self.fused_dropout_add_ln: + hidden_states = self.norm2( + (self.drop_path2(self.dropout2(mlp_out)) + hidden_states).to( + dtype=self.norm2.weight.dtype + ) + ) + else: + if self.drop_path2.p == 0 or not self.training: + rowscale2 = None + else: + rowscale2 = self.drop_path2( + torch.ones( + mlp_out.shape[:-1], device=mlp_out.device, dtype=mlp_out.dtype + ) + ) + hidden_states = layer_norm_fn( + mlp_out, + self.norm2.weight, + self.norm2.bias, + residual=hidden_states, + eps=self.norm2.eps, + dropout_p=self.dropout2.p if self.training else 0.0, + rowscale=rowscale2, + prenorm=False, + is_rms_norm=isinstance(self.norm2, RMSNorm) + ) + return hidden_states + + +class ParallelBlock(nn.Module): + """The attention (mixer) and MLP blocks are done in parallel, similar to GPT-J, GPT-NeoX, + and PaLM. + """ + + def __init__( + self, + dim, + mixer_cls=None, + mlp_cls=None, + norm_cls=nn.LayerNorm, + dropout_cls=nn.Dropout, + resid_dropout1=0.0, + resid_dropout2=0.0, + tied_norm=False, + fused_dropout_add_ln=False, + residual_in_fp32=False, + sequence_parallel=False, + mark_shared_params=False, + ): + """ + This Block has a slightly different structure compared to a regular + prenorm Transformer block. + The standard block is: LN -> MHA / MLP -> Dropout -> Add. + [Ref: https://arxiv.org/abs/2002.04745] + Here we have: Dropout -> Add -> LN -> MHA / MLP, returning both + the hidden_states (output1 of the MHA / MLP) and the residual. + This is for performance reasons, as we can fuse the dropout, add and LayerNorm. + The residual needs to be provided (except for the very first block). + """ + super().__init__() + self.tied_norm = tied_norm + self.fused_dropout_add_ln = fused_dropout_add_ln + self.residual_in_fp32 = residual_in_fp32 + if mixer_cls is None: + mixer_cls = partial(MHA, num_heads=dim // 64) + if mlp_cls is None: + mlp_cls = partial(Mlp, hidden_features=4 * dim) + self.mixer = mixer_cls(dim) + self.dropout1 = dropout_cls(resid_dropout1) + self.norm1 = norm_cls(dim) + self.mlp = mlp_cls(dim) + self.dropout2 = dropout_cls(resid_dropout2) + if not self.tied_norm: + self.norm2 = norm_cls(dim) + + if self.fused_dropout_add_ln: + assert layer_norm_fn is not None, "Triton is not installed" + assert isinstance(self.norm1, (nn.LayerNorm, RMSNorm)) and isinstance( + self.dropout1, nn.Dropout + ) + + # TD [2023-01-07]: TODO: During training, if sequence_parallel is False and dropout != 0.0, + # then the input to each worker in the tensor parallel group will be different. + # This would produce wrong outputs? Somehow we'd need to sync the RNG state across workers. + # For now this is not an issue because we always use sequence_parallel=True during training + # and only use sequence_parallel=False during inference. + + # Mark the norm parameters as "sequence_parallel" so that we run all-reduce on their grads. + if sequence_parallel: + for p in self.norm1.parameters(): + p._sequence_parallel = True + if hasattr(self, "norm2"): + for p in self.norm2.parameters(): + p._sequence_parallel = True + # Mark the norm parameters as "shared_params" so that we sync their values at init. + if mark_shared_params: + for p in self.norm1.parameters(): + p._shared_params = True + if hasattr(self, "norm2"): + for p in self.norm2.parameters(): + p._shared_params = True + + def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs): + return self.mixer.allocate_inference_cache(batch_size, max_seqlen, dtype=dtype, **kwargs) + + def forward( + self, + hidden_states1: Tensor, + hidden_states2: Optional[Tensor] = None, + residual: Optional[Tensor] = None, + mixer_kwargs=None, + ): + r"""Pass the input through the encoder layer. + + Args: + hidden_states1: the output of the previous attention (mixer) or embedding layer. + hidden_states2: the output of the previous MLP layer (if None, will use hidden_states1). + residual. + """ + # TODO: Ideally we should only do the allgather / allreduce once for + # the Linear to MLP & Attention + if not self.fused_dropout_add_ln: + dropped1 = self.dropout1(hidden_states1) + # For the very 1st block, we only want 1 dropout, not two different dropouts + if hidden_states2 is not None: + dropped2 = self.dropout2(hidden_states2) + residual = ( + (residual + dropped1 + dropped2) + if residual is not None + else dropped1 + dropped2 + ) + else: + residual = (residual + dropped1) if residual is not None else dropped1 + hidden_states1 = self.norm1(residual.to(dtype=self.norm1.weight.dtype)) + hidden_states2 = ( + self.norm2(residual.to(dtype=self.norm2.weight.dtype)) + if not self.tied_norm + else hidden_states1 + ) + if self.residual_in_fp32: + residual = residual.to(torch.float32) + else: + weight2, bias2 = ( + (self.norm2.weight, self.norm2.bias) if not self.tied_norm else (None, None) + ) + hidden_states1, *rest, residual = layer_norm_fn( + hidden_states1, + self.norm1.weight, + self.norm1.bias, + residual=residual, + x1=hidden_states2, + weight1=weight2, + bias1=bias2, + eps=self.norm1.eps, + dropout_p=self.dropout1.p if self.training else 0.0, + prenorm=True, + residual_in_fp32=self.residual_in_fp32, + is_rms_norm=isinstance(self.norm1, RMSNorm) + ) + if self.tied_norm: + hidden_states2 = hidden_states1 + else: + hidden_states2, = rest + if mixer_kwargs is None: + mixer_kwargs = {} + hidden_states1 = self.mixer(hidden_states1, **mixer_kwargs) + hidden_states2 = self.mlp(hidden_states2) + return hidden_states1, hidden_states2, residual diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/embedding.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..33587d09413dbab5edccfa3806fca829a6f9f9da --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/embedding.py @@ -0,0 +1,216 @@ +# Copyright (c) 2022, Tri Dao. + +import torch +import torch.nn as nn +from einops import rearrange +from torch import Tensor + +from flash_attn.utils.distributed import all_reduce, reduce_scatter + + +class GPT2Embeddings(nn.Module): + def __init__( + self, + embed_dim, + vocab_size, + max_position_embeddings, + padding_idx=None, + word_embed_proj_dim=None, + device=None, + dtype=None, + ): + """ + If max_position_embeddings <= 0, there's no position embeddings + If word_embe_proj_dim is not None (e.g., OPT-350m), we embed to that dimension + the project up to embed_dim + """ + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + if word_embed_proj_dim is None: + self.word_embeddings = nn.Embedding( + vocab_size, embed_dim, padding_idx=padding_idx, **factory_kwargs + ) + self.project_in = None + else: + self.word_embeddings = nn.Embedding( + vocab_size, word_embed_proj_dim, padding_idx=padding_idx, **factory_kwargs + ) + self.project_in = nn.Linear( + word_embed_proj_dim, embed_dim, bias=False, **factory_kwargs + ) + self.max_position_embeddings = max_position_embeddings + if self.max_position_embeddings > 0: + self.position_embeddings = nn.Embedding( + max_position_embeddings, embed_dim, **factory_kwargs + ) + + def forward(self, input_ids, position_ids=None): + """ + input_ids: (batch, seqlen) + position_ids: (batch, seqlen) + """ + batch_size, seqlen = input_ids.shape + embeddings = self.word_embeddings(input_ids) + if self.project_in is not None: + embeddings = self.project_in(embeddings) + if self.max_position_embeddings > 0: + if position_ids is None: + position_ids = torch.arange(seqlen, dtype=torch.long, device=input_ids.device) + position_embeddings = self.position_embeddings(position_ids) + embeddings = embeddings + position_embeddings + return embeddings + + +class BertEmbeddings(nn.Module): + def __init__( + self, + embed_dim, + vocab_size, + max_position_embeddings, + type_vocab_size, + padding_idx=None, + device=None, + dtype=None, + ): + """ + If max_position_embeddings <= 0, there's no position embeddings + If type_vocab_size <= 0, there's no token type embeddings + """ + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.word_embeddings = nn.Embedding( + vocab_size, embed_dim, padding_idx=padding_idx, **factory_kwargs + ) + self.max_position_embeddings = max_position_embeddings + self.type_vocab_size = type_vocab_size + if self.max_position_embeddings > 0: + self.position_embeddings = nn.Embedding( + max_position_embeddings, embed_dim, **factory_kwargs + ) + if self.type_vocab_size > 0: + self.token_type_embeddings = nn.Embedding(type_vocab_size, embed_dim, **factory_kwargs) + + def forward(self, input_ids, position_ids=None, token_type_ids=None): + """ + input_ids: (batch, seqlen) + position_ids: (batch, seqlen) + token_type_ids: (batch, seqlen) + """ + batch_size, seqlen = input_ids.shape + embeddings = self.word_embeddings(input_ids) + if self.max_position_embeddings > 0: + if position_ids is None: + position_ids = torch.arange(seqlen, dtype=torch.long, device=input_ids.device) + position_embeddings = self.position_embeddings(position_ids) + embeddings = embeddings + position_embeddings + if self.type_vocab_size > 0: + if token_type_ids is None: + token_type_ids = torch.zeros(seqlen, dtype=torch.long, device=input_ids.device) + token_type_embeddings = self.token_type_embeddings(token_type_ids) + embeddings = embeddings + token_type_embeddings + return embeddings + + +class VocabParallelEmbedding(nn.Embedding): + def __init__(self, num_embeddings, *args, process_group=None, padding_idx=None, **kwargs): + self.process_group = process_group + if process_group is not None: + world_size = torch.distributed.get_world_size(process_group) + if num_embeddings % world_size != 0: + raise ValueError( + f"num_embeddings ({num_embeddings}) must be divisible by " + f"world_size ({world_size})" + ) + if world_size > 1 and padding_idx is not None: + raise RuntimeError("ParallelEmbedding does not support padding_idx") + else: + world_size = 1 + super().__init__(num_embeddings // world_size, *args, padding_idx=padding_idx, **kwargs) + + def forward(self, input: Tensor) -> Tensor: + if self.process_group is None: + return super().forward(input) + else: + rank = torch.distributed.get_rank(self.process_group) + vocab_size = self.num_embeddings + vocab_start_index, vocab_end_index = rank * vocab_size, (rank + 1) * vocab_size + # Create a mask of valid vocab ids (1 means it needs to be masked). + input_ids_mask = (input < vocab_start_index) | (input >= vocab_end_index) + input = input - vocab_start_index + input[input_ids_mask] = 0 + embeddings = super().forward(input) + embeddings[input_ids_mask] = 0.0 + return embeddings + + +class ColumnParallelEmbedding(nn.Embedding): + def __init__(self, num_embeddings, embedding_dim, *args, process_group=None, **kwargs): + self.process_group = process_group + if process_group is not None: + world_size = torch.distributed.get_world_size(process_group) + if embedding_dim % world_size != 0: + raise ValueError( + f"embedding_dim ({embedding_dim}) must be divisible by " + f"world_size ({world_size})" + ) + else: + world_size = 1 + super().__init__(num_embeddings, embedding_dim // world_size, *args, **kwargs) + + +class ParallelGPT2Embeddings(nn.Module): + def __init__( + self, + embed_dim, + vocab_size, + max_position_embeddings, + process_group, + padding_idx=None, + sequence_parallel=True, + device=None, + dtype=None, + ): + """ + If max_position_embeddings <= 0, there's no position embeddings + """ + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.process_group = process_group + self.sequence_parallel = sequence_parallel + self.word_embeddings = VocabParallelEmbedding( + vocab_size, + embed_dim, + padding_idx=padding_idx, + process_group=process_group, + **factory_kwargs, + ) + self.max_position_embeddings = max_position_embeddings + if self.max_position_embeddings > 0: + self.position_embeddings = ColumnParallelEmbedding( + max_position_embeddings, embed_dim, process_group=process_group, **factory_kwargs + ) + + def forward(self, input_ids, position_ids=None, combine_batch_seqlen_dim=False): + """ + input_ids: (batch, seqlen) + position_ids: (batch, seqlen) + """ + batch_size, seqlen = input_ids.shape + world_size = torch.distributed.get_world_size(self.process_group) + embeddings = self.word_embeddings(input_ids) + if self.max_position_embeddings > 0: + if position_ids is None: + position_ids = torch.arange(seqlen, dtype=torch.long, device=input_ids.device) + position_embeddings = self.position_embeddings(position_ids) + if world_size <= 1: + embeddings = embeddings + position_embeddings + else: + partition_dim = self.position_embeddings.embedding_dim + rank = torch.distributed.get_rank(self.process_group) + embeddings[ + ..., rank * partition_dim : (rank + 1) * partition_dim + ] += position_embeddings + if combine_batch_seqlen_dim: + embeddings = rearrange(embeddings, "b s d -> (b s) d") + reduce_fn = reduce_scatter if self.sequence_parallel else all_reduce + return embeddings if world_size <= 1 else reduce_fn(embeddings, self.process_group) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/mha.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/mha.py new file mode 100644 index 0000000000000000000000000000000000000000..b2a7f22d2435bb43ae24b877b3a1b58a0d15abbb --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/mha.py @@ -0,0 +1,993 @@ +# Copyright (c) 2023, Tri Dao. + +import math +from functools import partial + +import torch +import torch.nn as nn +from einops import rearrange, repeat + +from flash_attn.utils.distributed import get_dim_for_local_rank + +try: + from flash_attn import ( + flash_attn_kvpacked_func, + flash_attn_qkvpacked_func, + flash_attn_varlen_kvpacked_func, + flash_attn_varlen_qkvpacked_func, + flash_attn_with_kvcache, + ) +except ImportError: + flash_attn_varlen_qkvpacked_func, flash_attn_varlen_kvpacked_func = None, None + flash_attn_qkvpacked_func, flash_attn_kvpacked_func = None, None + flash_attn_with_kvcache = None + +try: + from flash_attn.ops.fused_dense import ColumnParallelLinear, RowParallelLinear +except ImportError: + ColumnParallelLinear, RowParallelLinear = None, None + +try: + from flash_attn.layers.rotary import RotaryEmbedding +except ImportError: + RotaryEmbedding = None + + +# From https://github.com/ofirpress/attention_with_linear_biases/blob/4b92f28a005ead2567abe2359f633e73e08f3833/fairseq/models/transformer.py#L742 +def get_alibi_slopes(nheads): + def get_slopes_power_of_2(nheads): + start = 2 ** (-(2 ** -(math.log2(nheads) - 3))) + ratio = start + return [start * ratio**i for i in range(nheads)] + + if math.log2(nheads).is_integer(): + return get_slopes_power_of_2(nheads) + else: + closest_power_of_2 = 2 ** math.floor(math.log2(nheads)) + return ( + get_slopes_power_of_2(closest_power_of_2) + + get_alibi_slopes(2 * closest_power_of_2)[0::2][: nheads - closest_power_of_2] + ) + + +class FlashSelfAttention(nn.Module): + """Implement the scaled dot product attention with softmax. + Arguments + --------- + softmax_scale: The temperature to use for the softmax attention. + (default: 1/sqrt(d_keys) where d_keys is computed at + runtime) + attention_dropout: The dropout rate to apply to the attention + (default: 0.0) + """ + + def __init__( + self, + causal=False, + softmax_scale=None, + attention_dropout=0.0, + window_size=(-1, -1), + alibi_slopes=None, + deterministic=False, + ): + super().__init__() + assert flash_attn_varlen_qkvpacked_func is not None, "FlashAttention is not installed" + assert flash_attn_qkvpacked_func is not None, "FlashAttention is not installed" + self.causal = causal + self.softmax_scale = softmax_scale + self.drop = nn.Dropout(attention_dropout) + self.register_buffer("alibi_slopes", alibi_slopes, persistent=False) + self.window_size = window_size + self.deterministic = deterministic + + def forward(self, qkv, causal=None, cu_seqlens=None, max_seqlen=None): + """Implements the multihead softmax attention. + Arguments + --------- + qkv: The tensor containing the query, key, and value. + If cu_seqlens is None and max_seqlen is None, then qkv has shape (B, S, 3, H, D). + If cu_seqlens is not None and max_seqlen is not None, then qkv has shape + (total, 3, H, D), where total is the sum of the sequence lengths in the batch. + causal: if passed, will override self.causal + cu_seqlens: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into qkv. + max_seqlen: int. Maximum sequence length in the batch. + Returns: + -------- + out: (total, H, D) if cu_seqlens is not None and max_seqlen is not None, + else (B, S, H, D). + """ + assert qkv.dtype in [torch.float16, torch.bfloat16] + assert qkv.is_cuda + causal = self.causal if causal is None else causal + unpadded = cu_seqlens is not None + if self.alibi_slopes is not None: + self.alibi_slopes = self.alibi_slopes.to(torch.float32) + if unpadded: + assert cu_seqlens.dtype == torch.int32 + assert max_seqlen is not None + assert isinstance(max_seqlen, int) + return flash_attn_varlen_qkvpacked_func( + qkv, + cu_seqlens, + max_seqlen, + self.drop.p if self.training else 0.0, + softmax_scale=self.softmax_scale, + causal=causal, + alibi_slopes=self.alibi_slopes, + window_size=self.window_size, + deterministic=self.deterministic, + ) + else: + return flash_attn_qkvpacked_func( + qkv, + self.drop.p if self.training else 0.0, + softmax_scale=self.softmax_scale, + causal=causal, + alibi_slopes=self.alibi_slopes, + window_size=self.window_size, + deterministic=self.deterministic, + ) + + +class FlashCrossAttention(nn.Module): + """Implement the scaled dot product attention with softmax. + Arguments + --------- + softmax_scale: The temperature to use for the softmax attention. + (default: 1/sqrt(d_keys) where d_keys is computed at + runtime) + attention_dropout: The dropout rate to apply to the attention + (default: 0.0) + """ + + def __init__( + self, + causal=False, + softmax_scale=None, + attention_dropout=0.0, + alibi_slopes=None, + window_size=(-1, -1), + deterministic=False, + ): + super().__init__() + assert flash_attn_varlen_kvpacked_func is not None, "FlashAttention is not installed" + assert flash_attn_kvpacked_func is not None, "FlashAttention is not installed" + self.causal = causal + self.softmax_scale = softmax_scale + self.drop = nn.Dropout(attention_dropout) + self.register_buffer("alibi_slopes", alibi_slopes, persistent=False) + self.window_size = window_size + self.deterministic = deterministic + + def forward( + self, + q, + kv, + causal=None, + cu_seqlens=None, + max_seqlen=None, + cu_seqlens_k=None, + max_seqlen_k=None, + ): + """Implements the multihead softmax attention. + Arguments + --------- + q: The tensor containing the query. (B, Sq, H, D) + kv: The tensor containing the key and value. (B, Sk, 2, H_k, D) + causal: if passed, will override self.causal + cu_seqlens: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into q. + max_seqlen: int. Maximum sequence length in the batch of q. + cu_seqlens_k: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into kv. + max_seqlen_k: int. Maximum sequence length in the batch of k and v. + """ + assert q.dtype in [torch.float16, torch.bfloat16] + assert q.is_cuda and kv.is_cuda + causal = self.causal if causal is None else causal + unpadded = cu_seqlens is not None + if self.alibi_slopes is not None: + self.alibi_slopes = self.alibi_slopes.to(torch.float32) + if unpadded: + assert cu_seqlens.dtype == torch.int32 + assert max_seqlen is not None + assert isinstance(max_seqlen, int) + assert cu_seqlens_k is not None + assert cu_seqlens_k.dtype == torch.int32 + assert max_seqlen_k is not None + assert isinstance(max_seqlen_k, int) + return flash_attn_varlen_kvpacked_func( + q, + kv, + cu_seqlens, + cu_seqlens_k, + max_seqlen, + max_seqlen_k, + self.drop.p if self.training else 0.0, + softmax_scale=self.softmax_scale, + causal=causal, + alibi_slopes=self.alibi_slopes, + window_size=self.window_size, + deterministic=self.deterministic, + ) + else: + batch_size, seqlen_q = q.shape[0], q.shape[1] + seqlen_k = kv.shape[1] + assert kv.shape[0] == batch_size and kv.shape[4] == q.shape[3] + return flash_attn_kvpacked_func( + q, + kv, + self.drop.p if self.training else 0.0, + causal=causal, + softmax_scale=self.softmax_scale, + alibi_slopes=self.alibi_slopes, + window_size=self.window_size, + deterministic=self.deterministic, + ) + + +class SelfAttention(nn.Module): + """Implement the scaled dot product attention with softmax. + Arguments + --------- + softmax_scale: The temperature to use for the softmax attention. + (default: 1/sqrt(d_keys) where d_keys is computed at + runtime) + attention_dropout: The dropout rate to apply to the attention + (default: 0.0) + """ + + def __init__(self, causal=False, softmax_scale=None, attention_dropout=0.0): + super().__init__() + self.causal = causal + self.softmax_scale = softmax_scale + self.drop = nn.Dropout(attention_dropout) + + def forward(self, qkv, causal=None, key_padding_mask=None): + """Implements the multihead softmax attention. + Arguments + --------- + qkv: The tensor containing the query, key, and value. (B, S, 3, H, D) + causal: if passed, will override self.causal + key_padding_mask: boolean mask to apply to the attention weights. True means to keep, + False means to mask out. (B, S) + """ + batch_size, seqlen = qkv.shape[0], qkv.shape[1] + causal = self.causal if causal is None else causal + q, k, v = qkv.unbind(dim=2) + softmax_scale = self.softmax_scale or 1.0 / math.sqrt(q.shape[-1]) + scores = torch.einsum("bthd,bshd->bhts", q, k * softmax_scale) + if key_padding_mask is not None: + padding_mask = torch.full( + (batch_size, seqlen), -10000.0, dtype=scores.dtype, device=scores.device + ) + padding_mask.masked_fill_(key_padding_mask, 0.0) + # TD [2022-09-30]: Adding is faster than masked_fill_ (idk why, just better kernel I guess) + scores = scores + rearrange(padding_mask, "b s -> b 1 1 s") + if causal: + # "triu_tril_cuda_template" not implemented for 'BFloat16' + # So we have to construct the mask in float + causal_mask = torch.triu( + torch.full((seqlen, seqlen), -10000.0, device=scores.device), 1 + ) + # TD [2022-09-30]: Adding is faster than masked_fill_ (idk why, just better kernel I guess) + scores = scores + causal_mask.to(dtype=scores.dtype) + attention = torch.softmax(scores, dim=-1, dtype=v.dtype) + attention_drop = self.drop(attention) + output = torch.einsum("bhts,bshd->bthd", attention_drop, v) + return output + + +class CrossAttention(nn.Module): + """Implement the scaled dot product attention with softmax. + Arguments + --------- + softmax_scale: The temperature to use for the softmax attention. + (default: 1/sqrt(d_keys) where d_keys is computed at + runtime) + attention_dropout: The dropout rate to apply to the attention + (default: 0.0) + """ + + def __init__(self, causal=False, softmax_scale=None, attention_dropout=0.0): + super().__init__() + self.causal = causal + self.softmax_scale = softmax_scale + self.drop = nn.Dropout(attention_dropout) + + def forward(self, q, kv, causal=None, key_padding_mask=None): + """Implements the multihead softmax attention. + Arguments + --------- + q: The tensor containing the query. (B, Sq, H, D) + kv: The tensor containing the key and value. (B, Sk, 2, H_k, D) + causal: if passed, will override self.causal + key_padding_mask: boolean mask to apply to the attention weights. True means to keep, + False means to mask out. (B, Sk) + """ + batch_size, seqlen_q = q.shape[0], q.shape[1] + causal = self.causal if causal is None else causal + seqlen_k = kv.shape[1] + assert kv.shape[0] == batch_size and kv.shape[4] == q.shape[3] + if kv.shape[3] != q.shape[2]: # MQA/GQA + kv = repeat(kv, "... hkv d -> ... (hkv g) d", g=q.shape[2] // kv.shape[3]) + k, v = kv.unbind(dim=2) + softmax_scale = self.softmax_scale or 1.0 / math.sqrt(q.shape[-1]) + scores = torch.einsum("bthd,bshd->bhts", q, k * softmax_scale) + if key_padding_mask is not None: + padding_mask = torch.full( + (batch_size, seqlen_k), -10000.0, dtype=scores.dtype, device=scores.device + ) + padding_mask.masked_fill_(key_padding_mask, 0.0) + # TD [2022-09-30]: Adding is faster than masked_fill_ (idk why, just better kernel I guess) + scores = scores + rearrange(padding_mask, "b s -> b 1 1 s") + if causal: + # causal mask needs to take into account the difference between seqlen_q and seqlen_k + row_idx = rearrange( + torch.arange(seqlen_q, device=q.device, dtype=torch.long), "s -> s 1" + ) + col_idx = torch.arange(seqlen_k, device=kv.device, dtype=torch.long) + sk = ( + seqlen_k + if key_padding_mask is None + else rearrange(key_padding_mask.sum(-1), "b -> b 1 1 1") + ) + causal_mask = col_idx > row_idx + sk - seqlen_q + scores = scores.masked_fill(causal_mask, -10000.0) + attention = torch.softmax(scores, dim=-1, dtype=v.dtype) + attention_drop = self.drop(attention) + output = torch.einsum("bhts,bshd->bthd", attention_drop, v) + return output + + +def _update_kv_cache(kv, inference_params, layer_idx): + """kv: (batch_size, seqlen, 2, nheads, head_dim) or (batch_size, 1, 2, nheads, head_dim)""" + # Pre-allocate memory for key-values for inference. + num_heads, head_dim = kv.shape[-2:] + if layer_idx not in inference_params.key_value_memory_dict: + kv_cache = torch.empty( + inference_params.max_batch_size, + inference_params.max_seqlen, + 2, + num_heads, + head_dim, + dtype=kv.dtype, + device=kv.device, + ) + inference_params.key_value_memory_dict[layer_idx] = kv_cache + else: + kv_cache = inference_params.key_value_memory_dict[layer_idx] + # Adjust key and value for inference + batch_start = inference_params.batch_size_offset + batch_end = batch_start + kv.shape[0] + sequence_start = inference_params.seqlen_offset + sequence_end = sequence_start + kv.shape[1] + assert batch_end <= kv_cache.shape[0] + assert sequence_end <= kv_cache.shape[1] + assert kv_cache is not None + kv_cache[batch_start:batch_end, sequence_start:sequence_end, ...] = kv + return kv_cache[batch_start:batch_end, :sequence_end, ...] + + +class MHA(nn.Module): + """Multi-head self-attention and cross-attention""" + + def __init__( + self, + embed_dim, + num_heads, + num_heads_kv=None, + cross_attn=False, + qkv_proj_bias=True, + out_proj_bias=True, + dropout=0.0, + softmax_scale=None, + causal=False, + layer_idx=None, + dwconv=False, + rotary_emb_dim=0, + rotary_emb_base=10000.0, + rotary_emb_scale_base=None, + rotary_emb_interleaved=False, + use_alibi=False, + window_size=(-1, -1), + fused_bias_fc=False, + use_flash_attn=False, + return_residual=False, + checkpointing=False, + device=None, + dtype=None, + ) -> None: + """ + num_heads_kv: can be used to toggle MQA / GQA. If None, use num_heads. + return_residual: whether to return the input x along with the output. This is for + performance reason: for post-norm architecture, returning the input allows us + to fuse the backward of nn.Linear with the residual connection. + """ + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.embed_dim = embed_dim + self.cross_attn = cross_attn + self.causal = causal + self.layer_idx = layer_idx + self.dwconv = dwconv + self.rotary_emb_dim = rotary_emb_dim + self.use_flash_attn = use_flash_attn + self.return_residual = return_residual + self.checkpointing = checkpointing + if use_alibi: + assert use_flash_attn, "ALiBi code path requires flash_attn" + alibi_slopes = torch.tensor(get_alibi_slopes(num_heads), device=device) + else: + alibi_slopes = None + if window_size != (-1, -1): + assert use_flash_attn, "Local (sliding window) attention code path requires flash_attn" + + self.num_heads = num_heads + self.num_heads_kv = num_heads_kv if num_heads_kv is not None else num_heads + assert ( + self.num_heads % self.num_heads_kv == 0 + ), "num_heads must be divisible by num_heads_kv" + assert self.embed_dim % num_heads == 0, "embed_dim must be divisible by num_heads" + self.head_dim = self.embed_dim // num_heads + qkv_dim = self.head_dim * (self.num_heads + 2 * self.num_heads_kv) + kv_dim = 2 * self.head_dim * self.num_heads_kv + + if self.rotary_emb_dim > 0: + assert not cross_attn, "MHA with rotary embedding does not support cross-attention yet" + assert RotaryEmbedding is not None, "rotary_emb is not installed" + self.rotary_emb = RotaryEmbedding( + self.rotary_emb_dim, + base=rotary_emb_base, + scale_base=rotary_emb_scale_base, + interleaved=rotary_emb_interleaved, + device=device, + ) + + inner_attn_cls = ( + partial(FlashSelfAttention, alibi_slopes=alibi_slopes, window_size=window_size) + if use_flash_attn + else SelfAttention + ) + inner_cross_attn_cls = ( + partial(FlashCrossAttention, alibi_slopes=alibi_slopes, window_size=window_size) + if use_flash_attn + else CrossAttention + ) + if not self.cross_attn: + self.Wqkv = nn.Linear(embed_dim, qkv_dim, bias=qkv_proj_bias, **factory_kwargs) + else: + self.Wq = nn.Linear(embed_dim, embed_dim, bias=qkv_proj_bias, **factory_kwargs) + self.Wkv = nn.Linear(embed_dim, kv_dim, bias=qkv_proj_bias, **factory_kwargs) + if self.dwconv: + if self.num_heads_kv == self.num_heads: + self.dwconv_qkv = nn.Conv1d( + qkv_dim, qkv_dim, kernel_size=3, padding=2, groups=qkv_dim + ) + else: + self.dwconv_q = nn.Conv1d( + embed_dim, embed_dim, kernel_size=3, padding=2, groups=embed_dim + ) + self.dwconv_kv = nn.Conv1d(kv_dim, kv_dim, kernel_size=3, padding=2, groups=kv_dim) + self.inner_attn = inner_attn_cls( + causal=causal, + softmax_scale=softmax_scale, + attention_dropout=dropout, + ) + self.inner_cross_attn = inner_cross_attn_cls( + causal=causal, softmax_scale=softmax_scale, attention_dropout=dropout + ) + self.out_proj = nn.Linear(embed_dim, embed_dim, bias=out_proj_bias, **factory_kwargs) + + def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None): + dtype = self.out_proj.weight.dtype if dtype is None else dtype + device = self.out_proj.weight.device + return torch.empty( + batch_size, + max_seqlen, + 2, + self.num_heads_kv, + self.head_dim, + dtype=dtype, + device=device, + ) + + def _update_kv_cache(self, kv, inference_params): + """kv: (batch_size, seqlen, 2, nheads, head_dim) or (batch_size, 1, 2, nheads, head_dim)""" + assert not self.dwconv, "Generation does not support dwconv yet" + assert self.layer_idx is not None, "Generation requires layer_idx in the constructor" + return _update_kv_cache(kv, inference_params, self.layer_idx) + + def _apply_rotary_update_kvcache_attention(self, q, kv, inference_params): + """ + Fast path that combine 3 steps: apply rotary to Q and K, update kv cache, and apply attention. + q: (batch_size, seqlen_q, nheads, head_dim) + kv: (batch_size, seqlen_k, 2, nheads_kv, head_dim) + """ + assert inference_params is not None and inference_params.seqlen_offset > 0 + assert self.use_flash_attn + if self.rotary_emb_dim > 0: + assert self.rotary_emb.scale is None, "This code path does not support xPos" + self.rotary_emb._update_cos_sin_cache( + inference_params.max_seqlen, device=q.device, dtype=q.dtype + ) + rotary_cos, rotary_sin = self.rotary_emb._cos_cached, self.rotary_emb._sin_cached + else: + rotary_cos, rotary_sin = None, None + batch = q.shape[0] + kv_cache = inference_params.key_value_memory_dict[self.layer_idx][:batch] + cache_seqlens = ( + inference_params.lengths_per_sample[:batch] + if inference_params.lengths_per_sample is not None + else inference_params.seqlen_offset + ) + alibi_slopes = getattr(self.inner_cross_attn, "alibi_slopes", None) + context = flash_attn_with_kvcache( + q, + kv_cache[:, :, 0], + kv_cache[:, :, 1], + kv[:, :, 0], + kv[:, :, 1], + rotary_cos=rotary_cos, + rotary_sin=rotary_sin, + cache_seqlens=cache_seqlens, + softmax_scale=self.inner_cross_attn.softmax_scale, + causal=self.inner_cross_attn.causal, + rotary_interleaved=self.rotary_emb.interleaved if self.rotary_emb_dim > 0 else False, + alibi_slopes=alibi_slopes, + ) + return context + + def _update_kvcache_attention(self, q, kv, inference_params): + """Write kv to inference_params, then do attention""" + if ( + inference_params.seqlen_offset == 0 + or flash_attn_with_kvcache is None + or not self.use_flash_attn + ): + # TODO: this only uses seqlen_offset and not lengths_per_sample. + kv = self._update_kv_cache(kv, inference_params) + return self.inner_cross_attn(q, kv) + else: + batch = q.shape[0] + kv_cache = inference_params.key_value_memory_dict[self.layer_idx][:batch] + cache_seqlens = ( + inference_params.lengths_per_sample[:batch] + if inference_params.lengths_per_sample is not None + else inference_params.seqlen_offset + ) + alibi_slopes = getattr(self.inner_cross_attn, "alibi_slopes", None) + return flash_attn_with_kvcache( + q, + kv_cache[:, :, 0], + kv_cache[:, :, 1], + kv[:, :, 0], + kv[:, :, 1], + cache_seqlens=cache_seqlens, + softmax_scale=self.inner_cross_attn.softmax_scale, + causal=self.inner_cross_attn.causal, + alibi_slopes=alibi_slopes, + ) + + def forward( + self, + x, + x_kv=None, + key_padding_mask=None, + cu_seqlens=None, + max_seqlen=None, + mixer_subset=None, + inference_params=None, + **kwargs, + ): + """ + Arguments: + x: (batch, seqlen, hidden_dim) (where hidden_dim = num heads * head dim) if + cu_seqlens is None and max_seqlen is None, else (total, hidden_dim) where total + is the is the sum of the sequence lengths in the batch. + x_kv: (batch, seqlen, hidden_dim), only applicable for cross-attention. If None, use x. + cu_seqlens: (batch_size + 1,), dtype torch.int32. The cumulative sequence lengths + of the sequences in the batch, used to index into x. Only applicable when using + FlashAttention. + max_seqlen: int. Maximum sequence length in the batch. + key_padding_mask: boolean mask, True means to keep, False means to mask out. + (batch, seqlen). Only applicable when not using FlashAttention. + mixer_subset: for cross-attention only. If not None, will take a subset of x + before applying the query projection. Useful for e.g., ViT where we only care + about the CLS token in the last layer. + inference_params: for generation. Adapted from Megatron-LM (and Apex) + https://github.com/NVIDIA/apex/blob/3ff1a10f72ec07067c4e44759442329804ac5162/apex/transformer/testing/standalone_transformer_lm.py#L470 + """ + if cu_seqlens is not None: + assert max_seqlen is not None + assert key_padding_mask is None + assert self.use_flash_attn + assert not self.dwconv + assert self.rotary_emb_dim == 0 + if key_padding_mask is not None: + assert cu_seqlens is None + assert max_seqlen is None + assert not self.use_flash_attn + if inference_params is not None: + assert key_padding_mask is None + assert cu_seqlens is None and max_seqlen is None + assert not self.dwconv + + kwargs = ( + {"cu_seqlens": cu_seqlens, "max_seqlen": max_seqlen, **kwargs} + if self.use_flash_attn + else {"key_padding_mask": key_padding_mask, **kwargs} + ) + seqlen_offset = ( + 0 + if inference_params is None + else ( + inference_params.lengths_per_sample + if inference_params.lengths_per_sample is not None + else inference_params.seqlen_offset + ) + ) + rotary_max_seqlen = inference_params.max_seqlen if inference_params is not None else None + batch, seqlen = x.shape[:2] + if not self.cross_attn and self.num_heads_kv == self.num_heads: + assert x_kv is None and mixer_subset is None + qkv = self.Wqkv(x) + if self.dwconv: + qkv = rearrange( + self.dwconv_qkv(rearrange(qkv, "b s d -> b d s"))[..., :-2], "b d s -> b s d" + ).contiguous() + qkv = rearrange(qkv, "... (three h d) -> ... three h d", three=3, d=self.head_dim) + if ( + inference_params is None + or inference_params.seqlen_offset == 0 + or (self.rotary_emb_dim == 0 or self.rotary_emb_dim % 16 != 0) + or not self.use_flash_attn + ): + if self.rotary_emb_dim > 0: + qkv = self.rotary_emb( + qkv, seqlen_offset=seqlen_offset, max_seqlen=rotary_max_seqlen + ) + if inference_params is None: + if not self.checkpointing: + context = self.inner_attn(qkv, **kwargs) + else: + context = torch.utils.checkpoint.checkpoint(self.inner_attn, qkv, **kwargs) + else: + context = self._update_kvcache_attention( + qkv[:, :, 0], qkv[:, :, 1:], inference_params + ) + else: + context = self._apply_rotary_update_kvcache_attention( + qkv[:, :, 0], qkv[:, :, 1:], inference_params + ) + else: + if self.cross_attn: + q = self.Wq(x if mixer_subset is None else x[:, mixer_subset]) + kv = self.Wkv(x_kv if x_kv is not None else x) + else: + assert self.num_heads_kv != self.num_heads + qkv = self.Wqkv(x) + q = qkv[..., : self.num_heads * self.head_dim] + kv = qkv[..., self.num_heads * self.head_dim :] + q = rearrange(q, "... (h d) -> ... h d", d=self.head_dim) + kv = rearrange(kv, "... (two hkv d) -> ... two hkv d", two=2, d=self.head_dim) + if self.dwconv: + q = rearrange( + self.dwconv_q(rearrange(q, "b s d -> b d s"))[..., :-2], "b d s -> b s d" + ).contiguous() + kv = rearrange( + self.dwconv_kv(rearrange(kv, "b s d -> b d s"))[..., :-2], "b d s -> b s d" + ).contiguous() + if ( + inference_params is None + or inference_params.seqlen_offset == 0 + or (self.rotary_emb_dim == 0 or self.rotary_emb_dim % 16 != 0) + or not self.use_flash_attn + ): + if self.rotary_emb_dim > 0: + q, kv = self.rotary_emb( + q, kv, seqlen_offset=seqlen_offset, max_seqlen=rotary_max_seqlen + ) + if inference_params is None: + if not self.checkpointing: + context = self.inner_cross_attn(q, kv, **kwargs) + else: + context = torch.utils.checkpoint.checkpoint( + self.inner_cross_attn, q, kv, **kwargs + ) + else: + context = self._update_kvcache_attention(q, kv, inference_params) + else: + context = self._apply_rotary_update_kvcache_attention(q, kv, inference_params) + out = self.out_proj(rearrange(context, "... h d -> ... (h d)")) + return out if not self.return_residual else (out, x) + + +class ParallelMHA(nn.Module): + """Multi-head self-attention and cross-attention""" + + def __init__( + self, + embed_dim, + num_heads, + process_group, + num_heads_kv=None, + qkv_proj_bias=True, + out_proj_bias=True, + dropout=0.0, + softmax_scale=None, + causal=False, + layer_idx=None, + rotary_emb_dim=0, + rotary_emb_base=10000.0, + rotary_emb_scale_base=None, + rotary_emb_interleaved=False, + use_alibi=False, + window_size=(-1, -1), + use_flash_attn=False, + checkpointing=False, + sequence_parallel=True, + device=None, + dtype=None, + ) -> None: + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.embed_dim = embed_dim + self.causal = causal + self.layer_idx = layer_idx + self.rotary_emb_dim = rotary_emb_dim + self.use_flash_attn = use_flash_attn + self.checkpointing = checkpointing + self.process_group = process_group + self.world_size = process_group.size() + self.local_rank = torch.distributed.get_rank(process_group) + + self.num_heads = num_heads + assert self.embed_dim % self.num_heads == 0, "embed_dim must be divisible by num_heads" + + self.num_heads_kv = num_heads_kv if num_heads_kv is not None else num_heads + assert ( + self.num_heads % self.num_heads_kv == 0 + ), "num_heads must be divisible by num_heads_kv" + + self.num_heads_per_rank = get_dim_for_local_rank( + self.num_heads, self.world_size, self.local_rank + ) + self.num_heads_kv_per_rank = get_dim_for_local_rank( + self.num_heads_kv, self.world_size, self.local_rank + ) + self.head_dim = self.embed_dim // num_heads + qkv_dim = self.head_dim * (self.num_heads + 2 * self.num_heads_kv) + + if use_alibi: + assert use_flash_attn, "ALiBi code path requires flash_attn" + num_heads_local = math.ceil(self.num_heads / self.world_size) + alibi_slopes = torch.tensor( + get_alibi_slopes(num_heads)[ + self.local_rank * num_heads_local : (self.local_rank + 1) * num_heads_local + ], + device=device, + ) + else: + alibi_slopes = None + if window_size != (-1, -1): + assert use_flash_attn, "Local (sliding window) attention code path requires flash_attn" + + if self.rotary_emb_dim > 0: + assert RotaryEmbedding is not None, "rotary_emb is not installed" + self.rotary_emb = RotaryEmbedding( + self.rotary_emb_dim, + base=rotary_emb_base, + scale_base=rotary_emb_scale_base, + interleaved=rotary_emb_interleaved, + device=device, + ) + + if ColumnParallelLinear is None or RowParallelLinear is None: + raise ImportError("fused_dense is not installed") + self.Wqkv = ColumnParallelLinear( + embed_dim, + qkv_dim, + process_group, + bias=qkv_proj_bias, + sequence_parallel=sequence_parallel, + multiple_of=self.head_dim * (self.num_heads // self.num_heads_kv + 2), + **factory_kwargs, + ) + inner_attn_cls = ( + partial(FlashSelfAttention, alibi_slopes=alibi_slopes, window_size=window_size) + if use_flash_attn + else SelfAttention + ) + inner_cross_attn_cls = ( + partial(FlashCrossAttention, alibi_slopes=alibi_slopes, window_size=window_size) + if use_flash_attn + else CrossAttention + ) + self.inner_attn = inner_attn_cls( + causal=causal, softmax_scale=softmax_scale, attention_dropout=dropout + ) + self.inner_cross_attn = inner_cross_attn_cls( + causal=causal, softmax_scale=softmax_scale, attention_dropout=dropout + ) + self.out_proj = RowParallelLinear( + embed_dim, + embed_dim, + process_group, + bias=out_proj_bias, + sequence_parallel=sequence_parallel, + multiple_of=self.head_dim, + **factory_kwargs, + ) + + def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None): + dtype = self.out_proj.weight.dtype if dtype is None else dtype + device = self.out_proj.weight.device + return torch.empty( + batch_size, + max_seqlen, + 2, + self.num_heads_kv_per_rank, + self.head_dim, + dtype=dtype, + device=device, + ) + + def _update_kv_cache(self, kv, inference_params): + """kv: (batch_size, seqlen, 2, nheads, head_dim) or (batch_size, 1, 2, nheads, head_dim)""" + assert self.layer_idx is not None, "Generation requires layer_idx in the constructor" + return _update_kv_cache(kv, inference_params, self.layer_idx) + + def _apply_rotary_update_kvcache_attention(self, q, kv, inference_params): + """ + Fast path that combine 3 steps: apply rotary to Q and K, update kv cache, and apply attention. + q: (batch_size, seqlen_q, nheads, head_dim) + kv: (batch_size, seqlen_k, 2, nheads_kv, head_dim) + """ + assert inference_params is not None and inference_params.seqlen_offset > 0 + assert self.use_flash_attn + if self.rotary_emb_dim > 0: + assert self.rotary_emb.scale is None, "This code path does not support xPos" + self.rotary_emb._update_cos_sin_cache( + inference_params.max_seqlen, device=q.device, dtype=q.dtype + ) + rotary_cos, rotary_sin = self.rotary_emb._cos_cached, self.rotary_emb._sin_cached + else: + rotary_cos, rotary_sin = None, None + batch = q.shape[0] + kv_cache = inference_params.key_value_memory_dict[self.layer_idx][:batch] + cache_seqlens = ( + inference_params.lengths_per_sample[:batch] + if inference_params.lengths_per_sample is not None + else inference_params.seqlen_offset + ) + alibi_slopes = getattr(self.inner_cross_attn, "alibi_slopes", None) + context = flash_attn_with_kvcache( + q, + kv_cache[:, :, 0], + kv_cache[:, :, 1], + kv[:, :, 0], + kv[:, :, 1], + rotary_cos=rotary_cos, + rotary_sin=rotary_sin, + cache_seqlens=cache_seqlens, + softmax_scale=self.inner_cross_attn.softmax_scale, + causal=self.inner_cross_attn.causal, + rotary_interleaved=self.rotary_emb.interleaved if self.rotary_emb_dim > 0 else False, + alibi_slopes=alibi_slopes, + ) + return context + + def _update_kvcache_attention(self, q, kv, inference_params): + """Write kv to inference_params, then do attention""" + if inference_params.seqlen_offset == 0 or not self.use_flash_attn: + # TODO: this only uses seqlen_offset and not lengths_per_sample. + kv = self._update_kv_cache(kv, inference_params) + return self.inner_cross_attn(q, kv) + else: + batch = q.shape[0] + kv_cache = inference_params.key_value_memory_dict[self.layer_idx][:batch] + cache_seqlens = ( + inference_params.lengths_per_sample[:batch] + if inference_params.lengths_per_sample is not None + else inference_params.seqlen_offset + ) + alibi_slopes = getattr(self.inner_cross_attn, "alibi_slopes", None) + context = flash_attn_with_kvcache( + q, + kv_cache[:, :, 0], + kv_cache[:, :, 1], + kv[:, :, 0], + kv[:, :, 1], + cache_seqlens=cache_seqlens, + softmax_scale=self.inner_cross_attn.softmax_scale, + causal=self.inner_cross_attn.causal, + alibi_slopes=alibi_slopes, + ) + return context + + def forward(self, x, seqlen=None, inference_params=None, **kwargs): + """ + Arguments: + x: (batch, seqlen, hidden_dim) (where hidden_dim = num heads * head dim) if seqlen=None. + If seqlen is not None, x is (batch * seqlen, hidden_dim). This is so that when we + split x during sequence parallel, we split the batch * seqlen dimension + (in case batch is small). + """ + qkv = self.Wqkv(x) + if seqlen is not None: + qkv = rearrange(qkv, "(b s) ... -> b s ...", s=seqlen) + seqlen_offset = ( + 0 + if inference_params is None + else ( + inference_params.lengths_per_sample + if inference_params.lengths_per_sample is not None + else inference_params.seqlen_offset + ) + ) + rotary_max_seqlen = inference_params.max_seqlen if inference_params is not None else None + if self.num_heads_kv == self.num_heads: + qkv = rearrange(qkv, "b s (three h d) -> b s three h d", three=3, d=self.head_dim) + if ( + inference_params is None + or inference_params.seqlen_offset == 0 + or (self.rotary_emb_dim == 0 or self.rotary_emb_dim % 16 != 0) + or not self.use_flash_attn + ): + if self.rotary_emb_dim > 0: + qkv = self.rotary_emb( + qkv, seqlen_offset=seqlen_offset, max_seqlen=rotary_max_seqlen + ) + if inference_params is None: + if not self.checkpointing: + context = self.inner_attn(qkv, **kwargs) + else: + context = torch.utils.checkpoint.checkpoint(self.inner_attn, qkv, **kwargs) + else: + context = self._update_kvcache_attention( + qkv[:, :, 0], qkv[:, :, 1:], inference_params + ) + else: + context = self._apply_rotary_update_kvcache_attention( + qkv[:, :, 0], qkv[:, :, 1:], inference_params + ) + else: + q = rearrange( + qkv[..., : self.num_heads_per_rank * self.head_dim], + "... (h d) -> ... h d", + d=self.head_dim, + ) + kv = rearrange( + qkv[..., self.num_heads_per_rank * self.head_dim :], + "... (two hkv d) -> ... two hkv d", + two=2, + d=self.head_dim, + ) + if ( + inference_params is None + or inference_params.seqlen_offset == 0 + or (self.rotary_emb_dim == 0 or self.rotary_emb_dim % 16 != 0) + or not self.use_flash_attn + ): + if self.rotary_emb_dim > 0: + q, kv = self.rotary_emb( + q, kv, seqlen_offset=seqlen_offset, max_seqlen=rotary_max_seqlen + ) + if inference_params is None: + if not self.checkpointing: + context = self.inner_cross_attn(q, kv, **kwargs) + else: + context = torch.utils.checkpoint.checkpoint( + self.inner_cross_attn, q, kv, **kwargs + ) + else: + context = self._update_kvcache_attention(q, kv, inference_params) + else: + context = self._apply_rotary_update_kvcache_attention(q, kv, inference_params) + context = rearrange(context, "b s h d -> b s (h d)") + if seqlen is not None: + context = rearrange(context, "b s d -> (b s) d") + out = self.out_proj(context) + return out diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/mlp.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..23584d3098a245bcb2b09653bdf0f426eb63bde2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/modules/mlp.py @@ -0,0 +1,191 @@ +# Copyright (c) 2023, Tri Dao. + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.distributed import ProcessGroup + + +try: + from flash_attn.ops.activations import swiglu +except ImportError: + swiglu = None + +try: + from flash_attn.ops.fused_dense import ColumnParallelLinear, RowParallelLinear +except ImportError: + ColumnParallelLinear, RowParallelLinear = None, None + +try: + from flash_attn.ops.fused_dense import FusedMLP, ParallelFusedMLP +except ImportError: + FusedMLP, ParallelFusedMLP = None, None + + +class Mlp(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + activation=F.gelu, + bias1=True, + bias2=True, + return_residual=False, + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + out_features = out_features if out_features is not None else in_features + hidden_features = hidden_features if hidden_features is not None else in_features * 4 + self.return_residual = return_residual + self.fc1 = nn.Linear(in_features, hidden_features, bias=bias1, **factory_kwargs) + self.activation = activation + self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2, **factory_kwargs) + + def forward(self, x): + y = self.fc1(x) + y = self.activation(y) + y = self.fc2(y) + return y if not self.return_residual else (y, x) + + +class ParallelMLP(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + activation=F.gelu, + process_group: ProcessGroup = None, + sequence_parallel=True, + bias1=True, + bias2=True, + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + assert ColumnParallelLinear is not None, "Need to install fused_dense" + assert RowParallelLinear is not None, "Need to install fused_dense" + out_features = out_features if out_features is not None else in_features + hidden_features = hidden_features if hidden_features is not None else in_features * 4 + self.fc1 = ColumnParallelLinear( + in_features, + hidden_features, + process_group, + bias=bias1, + sequence_parallel=sequence_parallel, + **factory_kwargs, + ) + self.activation = activation + self.fc2 = RowParallelLinear( + hidden_features, + out_features, + process_group, + bias=bias2, + sequence_parallel=sequence_parallel, + **factory_kwargs, + ) + + def forward(self, x): + y = self.fc1(x) + y = self.activation(y) + y = self.fc2(y) + return y + + +class GatedMlp(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + activation=F.sigmoid, + bias1=True, + bias2=True, + multiple_of=128, + return_residual=False, + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + out_features = out_features if out_features is not None else in_features + hidden_features = ( + hidden_features if hidden_features is not None else int(8 * in_features / 3) + ) + hidden_features = (hidden_features + multiple_of - 1) // multiple_of * multiple_of + self.return_residual = return_residual + self.fc1 = nn.Linear(in_features, 2 * hidden_features, bias=bias1, **factory_kwargs) + self.activation = activation + self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2, **factory_kwargs) + + def forward(self, x): + y = self.fc1(x) + if self.activation == F.sigmoid: # Special case for GLU + y = F.glu(y, dim=-1) + elif self.activation == F.silu and swiglu is not None: # Special case for SwiGLU + y, gate = y.chunk(2, dim=-1) + y = swiglu(gate, y) + else: + y, gate = y.chunk(2, dim=-1) + y = y * self.activation(gate) + y = self.fc2(y) + return y if not self.return_residual else (y, x) + + +class ParallelGatedMlp(nn.Module): + """Parallel GatedMlp""" + + def __init__( + self, + in_features, + process_group, + hidden_features=None, + out_features=None, + activation=F.sigmoid, + bias1=True, + bias2=True, + multiple_of=128, + sequence_parallel=True, + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + out_features = out_features if out_features is not None else in_features + hidden_features = ( + hidden_features if hidden_features is not None else int(8 * in_features / 3) + ) + hidden_features = (hidden_features + multiple_of - 1) // multiple_of * multiple_of + if ColumnParallelLinear is None or RowParallelLinear is None: + raise ImportError("fused_dense is not installed") + self.fc1 = ColumnParallelLinear( + in_features, + 2 * hidden_features, + process_group, + bias=bias1, + sequence_parallel=sequence_parallel, + **factory_kwargs, + ) + self.activation = activation + self.fc2 = RowParallelLinear( + hidden_features, + out_features, + process_group, + bias=bias2, + sequence_parallel=sequence_parallel, + **factory_kwargs, + ) + + def forward(self, x): + y = self.fc1(x) + if self.activation == F.sigmoid: # Special case for GLU + y = F.glu(y, dim=-1) + else: + y, gate = y.chunk(2, dim=-1) + y = y * self.activation(gate) + y = self.fc2(y) + return y diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23d6d64852635f295847885da08db5b3d2eee7be Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__pycache__/activations.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__pycache__/activations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ad5642e1d7fd13c9887c98781f71219366f25c7 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__pycache__/activations.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__pycache__/fused_dense.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__pycache__/fused_dense.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..10f526a0867cb5feecf765124b9ccc2ce2a1e30d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__pycache__/fused_dense.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__pycache__/layer_norm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__pycache__/layer_norm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de7d0ff09ea16b9f1cd288125e96516d942a9f49 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__pycache__/layer_norm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__pycache__/rms_norm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__pycache__/rms_norm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c75a63856bf6c0838c2f14a07abb565089bed770 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/__pycache__/rms_norm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/activations.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/activations.py new file mode 100644 index 0000000000000000000000000000000000000000..7c09649fc41e12d5a360c5672825d8380bc7ec80 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/activations.py @@ -0,0 +1,135 @@ +# Copied from https://github.com/mlcommons/training_results_v1.1/blob/main/NVIDIA/benchmarks/bert/implementations/pytorch/model/layers/activations.py +import math + +import torch +import torch.nn as nn +import torch.nn.functional as F + +# 1/sqrt(2*pi)-> 0.3989423 +# 1/sqrt(2) -> 0.70710678 +# sqrt(2/pi) -> 0.79788456 + +# this function is tanh approximation of gelu +# actual gelu is: +# x * 0.5 * (1.0 + torch.erf(x * 0.70710678)) +@torch.jit.script +def bias_gelu(y, bias): + x = bias + y + return (x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))).to(dtype=y.dtype) + + +# gradient of tanh approximation of gelu +# gradient of actual gelu is: +# 0.5 * (1. + torch.erf(x * 0.70710678)) + 0.3989423 * x * torch.exp(-0.5 * x * x) +@torch.jit.script +def bias_gelu_back(g, y, bias): + """Assume that y has shape (B, D) and bias has shape (D)""" + x = bias + y + tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)) + # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243 + ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * ( + 1 + tanh_out + ) + grad_y = ff * g + return grad_y.to(dtype=y.dtype), grad_y.sum(dim=(0), dtype=bias.dtype) + + +class GeLUFunction(torch.autograd.Function): + @staticmethod + # bias is an optional argument + def forward(ctx, input, bias): + ctx.save_for_backward(input, bias) + return bias_gelu(input, bias) + + @staticmethod + def backward(ctx, grad_output): + input, bias = ctx.saved_tensors + tmp = bias_gelu_back(grad_output, input, bias) + return tmp, tmp + + +bias_gelu_impl = GeLUFunction.apply + +# this function is tanh approximation of gelu +# actual gelu is: +# x * 0.5 * (1.0 + torch.erf(x * 0.70710678)) +@torch.jit.script +def gelu_fwd(x): + return (x * 0.5 * (1.0 + torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)))).to(dtype=x.dtype) + + +# gradient of tanh approximation of gelu +# gradient of actual gelu is: +# 0.5 * (1. + torch.erf(x * 0.70710678)) + 0.3989423 * x * torch.exp(-0.5 * x * x) +@torch.jit.script +def gelu_bwd(g, x): + tanh_out = torch.tanh(0.79788456 * x * (1 + 0.044715 * x * x)) + # sqrt(2/pi) * 3 * 0.044715 -> 0.1070322243 + ff = 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * ( + 1 + tanh_out + ) + return (ff * g).to(dtype=x.dtype) + + +class FastGeLUFunction(torch.autograd.Function): + @staticmethod + # bias is an optional argument + def forward(ctx, input): + ctx.save_for_backward(input) + return gelu_fwd(input) + + @staticmethod + def backward(ctx, grad_output): + (input,) = ctx.saved_tensors + tmp = gelu_bwd(grad_output, input) + return tmp + + +fast_gelu_impl = FastGeLUFunction.apply + + +@torch.jit.script +def relu_bwd(g, x): + return torch.where(x >= 0, g, 0.0).to(dtype=x.dtype) + + +@torch.jit.script +def sqrelu_fwd(x): + r = F.relu(x) + return (r * r).to(dtype=x.dtype) + + +@torch.jit.script +def sqrelu_bwd(g, x): + return (2.0 * g * F.relu(x)).to(dtype=x.dtype) + + +swiglu_fwd_codestring = """ +template T swiglu_fwd(T x, T y) { + return float(x) * float(y) / (1.0f + ::exp(-float(x))); +} +""" +swiglu_bwd_codestring = """ +template void swiglu_bwd(T x, T y, T g, T& dx, T& dy) { + float x_sigmoid = 1.0f / (1.0f + ::exp(-float(x))); + dx = x_sigmoid * (1 + float(x) * (1.0f - x_sigmoid)) * float(g) * float(y); + dy = float(x) * x_sigmoid * float(g); +} +""" +swiglu_fwd = torch.cuda.jiterator._create_jit_fn(swiglu_fwd_codestring) +swiglu_bwd = torch.cuda.jiterator._create_multi_output_jit_fn(swiglu_bwd_codestring, num_outputs=2) + + +class SwiGLUFunction(torch.autograd.Function): + + @staticmethod + def forward(ctx, x, y): + ctx.save_for_backward(x, y) + return swiglu_fwd(x, y) + + @staticmethod + def backward(ctx, dout): + x, y = ctx.saved_tensors + return swiglu_bwd(x, y, dout) + +swiglu = SwiGLUFunction.apply diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/fused_dense.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/fused_dense.py new file mode 100644 index 0000000000000000000000000000000000000000..6b4033d134e4093fe278f7b3f8c7d3128ce9f36d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/fused_dense.py @@ -0,0 +1,688 @@ +# Copyright (c) 2023, Tri Dao. +# Inspired by https://github.com/NVIDIA/apex/blob/master/apex/fused_dense/fused_dense.py +# We make it work with pytorch amp and with bfloat16. +# The TensorParallel linear modules are inspired by https://github.com/NVIDIA/apex/blob/master/apex/transformer/tensor_parallel/layers.py +from functools import partial +from typing import Optional + +# import fused_dense_cuda # from apex +import fused_dense_lib as fused_dense_cuda +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor +from torch.distributed import ProcessGroup + +from flash_attn.utils.torch import custom_fwd, custom_bwd +from flash_attn.ops.activations import gelu_bwd, relu_bwd, sqrelu_bwd, sqrelu_fwd +from flash_attn.utils.distributed import ( + all_gather_raw, + all_reduce, + all_reduce_raw, + reduce_scatter, + reduce_scatter_raw, +) + + +class FusedDenseFunc(torch.autograd.Function): + @staticmethod + @custom_fwd + def forward( + ctx, x, weight, bias, return_residual=False, process_group=None, sequence_parallel=True + ): + """ + If process_group is not None and sequence_parallel=True, we're doing Tensor Parallel + with sequence parallelism: we do an all_gather_raw of x before doing the matmul. + """ + ctx.compute_weight_gradient = weight.requires_grad + ctx.return_residual = return_residual + ctx.process_group = process_group + ctx.sequence_parallel = sequence_parallel + + if torch.is_autocast_enabled(): + x = x.to(dtype=torch.get_autocast_gpu_dtype()) + x = x.contiguous() + if process_group is not None and sequence_parallel: + # We want to kick off the all_gather early, before weight dtype conversion + total_x, handle_x = all_gather_raw(x, process_group, async_op=True) + else: + total_x = x + + if torch.is_autocast_enabled(): + weight = weight.to(dtype=torch.get_autocast_gpu_dtype()) + bias = bias.to(dtype=torch.get_autocast_gpu_dtype()) if bias is not None else None + weight = weight.contiguous() + if process_group is not None and sequence_parallel: + handle_x.wait() + batch_shape, n = total_x.shape[:-1], total_x.shape[-1] + batch_dim = batch_shape.numel() + # https://github.com/pytorch/pytorch/blob/5b51849b48a7dbccd297286cc0110def4706f9e7/aten/src/ATen/native/cuda/Blas.cpp#L174 + if min(batch_dim, n, *weight.shape) > 65535 * 32: + raise RuntimeError("fused_dense only supports matrix dims <= 2M") + output = F.linear(total_x, weight, bias) + if ctx.compute_weight_gradient: + ctx.save_for_backward(x, weight) + else: + ctx.save_for_backward(weight) + return output if not return_residual else (output, x) + + @staticmethod + @custom_bwd + def backward(ctx, grad_output, *args): + grad_output = grad_output.contiguous() + if ctx.return_residual: + (grad_input,) = args + grad_input = grad_input.contiguous() + process_group = ctx.process_group + sequence_parallel = ctx.sequence_parallel + if ctx.compute_weight_gradient: + x, weight = ctx.saved_tensors + if process_group is not None and sequence_parallel: + total_x, handle_x = all_gather_raw(x, process_group, async_op=True) + else: + total_x = x + else: + (weight,) = ctx.saved_tensors + total_x = None + batch_shape = grad_output.shape[:-1] + batch_dim = batch_shape.numel() + grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1]) + if ctx.needs_input_grad[0]: + if not ctx.return_residual: + grad_input = F.linear(grad_output, weight.t()) + else: + grad_input = torch.addmm( + grad_input.reshape(batch_dim, grad_input.shape[-1]), grad_output, weight + ) + grad_input = grad_input.reshape(*batch_shape, grad_input.shape[-1]) + if process_group is not None: + reduce_fn = reduce_scatter_raw if sequence_parallel else all_reduce_raw + grad_input, handle_grad_input = reduce_fn(grad_input, process_group, async_op=True) + else: + grad_input = None + if ctx.needs_input_grad[1]: + assert ctx.compute_weight_gradient + if process_group is not None and sequence_parallel: + handle_x.wait() + grad_weight, grad_bias = fused_dense_cuda.linear_bias_wgrad( + total_x.reshape(batch_dim, total_x.shape[-1]), grad_output, ctx.needs_input_grad[2] + ) + else: + grad_weight = None + grad_bias = grad_output if ctx.needs_input_grad[2] else None + if process_group is not None and ctx.needs_input_grad[0]: + handle_grad_input.wait() + return grad_input, grad_weight, grad_bias, None, None, None + + +def fused_dense_func( + x: Tensor, + weight: Tensor, + bias: Optional[Tensor] = None, + return_residual: bool = False, + process_group: Optional[ProcessGroup] = None, + sequence_parallel: bool = True, +): + dtype_eligible = x.dtype in [torch.float16, torch.bfloat16] or ( + x.dtype == torch.float32 and torch.is_autocast_enabled() + ) + if x.is_cuda and weight.is_cuda and (bias is None or bias.is_cuda) and dtype_eligible: + return FusedDenseFunc.apply( + x, weight, bias, return_residual, process_group, sequence_parallel + ) + else: + assert process_group is None + out = F.linear(x, weight, bias) + return out if not return_residual else (out, x) + + +class FusedDense(nn.Linear): + def __init__( + self, + in_features: int, + out_features: int, + bias: bool = True, + return_residual: bool = False, + device=None, + dtype=None, + ) -> None: + super().__init__(in_features, out_features, bias=bias, device=device, dtype=dtype) + self.return_residual = return_residual + + def forward(self, x, process_group=None): + """ + If process_group is not None, we're doing Tensor Parallel with sequence parallelism: + we do an all_gather of x before doing the matmul. + """ + return fused_dense_func( + x, + self.weight, + self.bias, + return_residual=self.return_residual, + process_group=process_group, + ) + + +class ColumnParallelLinear(nn.Linear): + def __init__( + self, + in_features: int, + out_features: int, + process_group: ProcessGroup, + bias: bool = True, + sequence_parallel=True, + multiple_of=1, + device=None, + dtype=None, + ) -> None: + world_size = torch.distributed.get_world_size(process_group) + if out_features % multiple_of: + raise ValueError(f"out_features ({out_features}) must be a multiple of {multiple_of}") + multiple = out_features // multiple_of + # We want to split @multiple across world_size, but it could be an uneven split + div = multiple // world_size + mod = multiple % world_size + # The first @mod ranks get @div + 1 copies, the rest get @div copies + local_multiple = div + int(torch.distributed.get_rank(process_group) < mod) + super().__init__( + in_features, local_multiple * multiple_of, bias=bias, device=device, dtype=dtype + ) + self.process_group = process_group + self.sequence_parallel = sequence_parallel + + def forward(self, x): + # If self.sequence_parallel is True, we're doing Tensor Parallel with sequence parallelism: + # we do an all_gather of x before doing the matmul. + # If not, then the input is already gathered. + return fused_dense_func( + x, + self.weight, + self.bias, + process_group=self.process_group, + sequence_parallel=self.sequence_parallel, + ) + + +class RowParallelLinear(nn.Linear): + def __init__( + self, + in_features: int, + out_features: int, + process_group: ProcessGroup, + bias: bool = True, + sequence_parallel=True, + multiple_of=1, + device=None, + dtype=None, + ) -> None: + world_size = torch.distributed.get_world_size(process_group) + rank = torch.distributed.get_rank(process_group) + if in_features % multiple_of: + raise ValueError(f"in_features ({in_features}) must be a multiple of {multiple_of}") + multiple = in_features // multiple_of + # We want to split @multiple across world_size, but it could be an uneven split + div = multiple // world_size + mod = multiple % world_size + # The first @mod ranks get @div + 1 copies, the rest get @div copies + local_multiple = div + int(torch.distributed.get_rank(process_group) < mod) + # Only rank 0 will have bias + super().__init__( + local_multiple * multiple_of, + out_features, + bias=bias and rank == 0, + device=device, + dtype=dtype, + ) + self.process_group = process_group + self.sequence_parallel = sequence_parallel + + def forward(self, x): + """ + We're doing Tensor Parallel with sequence parallelism: we do the matmul and then + a reduce_scatter of the result. + """ + out = fused_dense_func(x, self.weight, self.bias) + reduce_fn = reduce_scatter if self.sequence_parallel else all_reduce + return reduce_fn(out, self.process_group) + + +class FusedMLPFunc(torch.autograd.Function): + @staticmethod + @custom_fwd + def forward( + ctx, + x, + weight1, + bias1, + weight2, + bias2, + activation="gelu_approx", + save_pre_act=True, + return_residual=False, + checkpoint_lvl=0, + heuristic=0, + process_group=None, + sequence_parallel=True, + ): + """ + If process_group is not None and sequence_parallel=True, we're doing Tensor Parallel + with sequence parallelism: we do an all_gather of x before doing the matmul. + If sequence_parallel=False, then the input is already gathered. + + checkpoint_lvl: + 0: no recomputation in the bwd + 1: recompute gelu_out / relu_out in the bwd + 2: recompute pre_act and gelu_out / relu_out in the bwd + """ + assert -1 <= heuristic <= 4 + assert activation in ["gelu_approx", "relu", "sqrelu"] + if activation == "sqrelu": + assert heuristic == -1 + if not save_pre_act: + checkpoint_lvl = 2 + assert checkpoint_lvl in [0, 1, 2] + ctx.return_residual = return_residual + ctx.process_group = process_group + ctx.sequence_parallel = sequence_parallel + ctx.checkpoint_lvl = checkpoint_lvl + ctx.activation = activation + ctx.heuristic = heuristic + + if torch.is_autocast_enabled(): + x = x.to(dtype=torch.get_autocast_gpu_dtype()) + x = x.contiguous() + if process_group is not None and sequence_parallel: + # We want to kick off the all_gather early, before weight dtype conversion + total_x, handle_x = all_gather_raw(x, process_group, async_op=True) + else: + total_x = x + + if torch.is_autocast_enabled(): + dtype = torch.get_autocast_gpu_dtype() + weight1, weight2 = [a.to(dtype=dtype) for a in [weight1, weight2]] + bias1 = bias1.to(dtype=dtype) if bias1 is not None else None + bias2 = bias2.to(dtype=dtype) if bias2 is not None else None + weight1 = weight1.contiguous() + bias1 = bias1.contiguous() if bias1 is not None else None + weight2 = weight2.contiguous() + bias2 = bias2.contiguous() if bias2 is not None else None + if process_group is not None and sequence_parallel: + handle_x.wait() + batch_shape, n = total_x.shape[:-1], total_x.shape[-1] + batch_dim = batch_shape.numel() + # https://github.com/pytorch/pytorch/blob/5b51849b48a7dbccd297286cc0110def4706f9e7/aten/src/ATen/native/cuda/Blas.cpp#L174 + if min(batch_dim, n, *weight1.shape, *weight2.shape) > 65535 * 32: + raise RuntimeError("fused_dense only supports matrix dims <= 2M") + if heuristic == -1: + pre_act = F.linear(total_x, weight1, bias1) + activation_fn = ( + partial(F.gelu, approximate="tanh") + if activation == "gelu_approx" + else (sqrelu_fwd if activation == "sqrelu" else F.relu) + ) + with torch.jit.fuser("fuser2"): + output1 = activation_fn(pre_act) + # This is before adding bias1 + # pre_act = F.linear(total_x.reshape(batch_dim, n), weight1) + # with torch.jit.fuser('fuser2'): + # output1 = bias_gelu(pre_act, bias1) + else: + is_gelu = activation == "gelu_approx" + output1, *rest = fused_dense_cuda.linear_act_forward( + total_x.reshape(batch_dim, n), weight1, bias1, is_gelu, save_pre_act, heuristic + ) + if save_pre_act: + pre_act = rest[0] + output2 = F.linear(output1, weight2, bias2) + if checkpoint_lvl == 0 or (checkpoint_lvl == 1 and activation == "relu"): + # For RELU the pre_act is very small (just a bit-mask) so we just save it + ctx.save_for_backward(x, weight1, weight2, pre_act, output1) + elif checkpoint_lvl == 1: + ctx.save_for_backward(x, weight1, weight2, pre_act) + elif checkpoint_lvl == 2: + ctx.save_for_backward(x, weight1, weight2, bias1) + output2 = output2.reshape(*batch_shape, output2.shape[-1]) + return output2 if not return_residual else (output2, x) + + @staticmethod + @custom_bwd + def backward(ctx, grad_output, *args): + grad_output = grad_output.contiguous() + checkpoint_lvl = ctx.checkpoint_lvl + activation = ctx.activation + activation_fn = ( + partial(F.gelu, approximate="tanh") + if activation == "gelu_approx" + else (sqrelu_fwd if activation == "sqrelu" else F.relu) + ) + if ctx.return_residual: + (grad_input,) = args + grad_input = grad_input.contiguous() + process_group = ctx.process_group + sequence_parallel = ctx.sequence_parallel + x, weight1, weight2, *rest = ctx.saved_tensors + if process_group is None or not sequence_parallel: + total_x = x + batch_shape = grad_output.shape[:-1] + batch_dim = batch_shape.numel() + if checkpoint_lvl in [0, 1]: + if process_group is not None and sequence_parallel: + total_x, handle_x = all_gather_raw(x, process_group, async_op=True) + if checkpoint_lvl == 0 or (checkpoint_lvl == 1 and activation == "relu"): + pre_act, output1 = rest + elif checkpoint_lvl == 1: + (pre_act,) = rest + with torch.jit.fuser("fuser2"): + output1 = activation_fn(pre_act) + elif checkpoint_lvl == 2: + (bias1,) = rest + if process_group is not None and sequence_parallel: + total_x, _ = all_gather_raw(x, process_group) + if ctx.heuristic == -1: + pre_act = F.linear(total_x, weight1, bias1) + with torch.jit.fuser("fuser2"): + output1 = activation_fn(pre_act) + else: + output1, pre_act = fused_dense_cuda.linear_act_forward( + total_x.reshape(batch_dim, total_x.shape[-1]), + weight1, + bias1, + activation == "gelu_approx", + True, + ctx.heuristic, + ) + + grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1]) + output1 = output1.reshape(batch_dim, output1.shape[-1]) + pre_act = pre_act.reshape(batch_dim, pre_act.shape[-1]) + if ctx.needs_input_grad[3]: + grad_weight2, grad_bias2 = fused_dense_cuda.linear_bias_wgrad( + output1, grad_output, ctx.needs_input_grad[4] + ) + else: + grad_weight2 = None + grad_bias2 = grad_output if ctx.needs_input_grad[4] else None + if ctx.heuristic == -1: + # grad_pre_act = matmul_dgelu(grad_output, weight2, pre_act) + grad_output1 = F.linear(grad_output, weight2.t()) + activation_grad_fn = ( + gelu_bwd + if activation == "gelu_approx" + else (sqrelu_bwd if activation == "sqrelu" else relu_bwd) + ) + with torch.jit.fuser("fuser2"): + grad_pre_act = activation_grad_fn(grad_output1, pre_act) + else: + # The cublasLt epilogue has to compute both gelu/relu grad and bias grad, we can't + # just compute gelu/relu grad + grad_pre_act, grad_bias1 = fused_dense_cuda.bias_act_linear_dgrad_bgrad( + weight2, grad_output, pre_act, activation == "gelu_approx", ctx.heuristic + ) + if not ctx.needs_input_grad[2]: + grad_bias1 = None + if ctx.needs_input_grad[0]: + if not ctx.return_residual: + grad_input = F.linear(grad_pre_act, weight1.t()) + else: + grad_input = torch.addmm( + grad_input.reshape(batch_dim, grad_input.shape[-1]), grad_pre_act, weight1 + ) + grad_input = grad_input.reshape(*batch_shape, grad_input.shape[-1]) + if process_group is not None: + reduce_fn = reduce_scatter_raw if sequence_parallel else all_reduce_raw + grad_input, handle_grad_input = reduce_fn(grad_input, process_group, async_op=True) + else: + grad_input = None + if ctx.heuristic == -1: + if ctx.needs_input_grad[1]: + if process_group is not None and sequence_parallel and checkpoint_lvl != 2: + handle_x.wait() + grad_weight1, grad_bias1 = fused_dense_cuda.linear_bias_wgrad( + total_x.reshape(batch_dim, total_x.shape[-1]), + grad_pre_act, + ctx.needs_input_grad[2], + ) + else: + grad_weight1 = None + grad_bias1 = grad_pre_act if ctx.needs_input_grad[2] else None + else: + if ctx.needs_input_grad[1]: + if process_group is not None and sequence_parallel and checkpoint_lvl != 2: + handle_x.wait() + grad_weight1 = F.linear( + grad_pre_act.t(), total_x.reshape(batch_dim, total_x.shape[-1]).t() + ) + else: + grad_weight1 = None + if process_group is not None and ctx.needs_input_grad[0]: + handle_grad_input.wait() + return ( + grad_input, + grad_weight1, + grad_bias1, + grad_weight2, + grad_bias2, + None, + None, + None, + None, + None, + None, + None, + ) + + +def fused_mlp_func( + x: Tensor, + weight1: Tensor, + weight2: Tensor, + bias1: Optional[Tensor] = None, + bias2: Optional[Tensor] = None, + activation: str = "gelu_approx", + save_pre_act: bool = True, + return_residual: bool = False, + checkpoint_lvl: int = 0, + heuristic: int = 0, + process_group: Optional[ProcessGroup] = None, + sequence_parallel: bool = True, +): + assert activation in ["gelu_approx", "relu", "sqrelu"] + dtype_eligible = x.dtype in [torch.float16, torch.bfloat16] or ( + x.dtype == torch.float32 and torch.is_autocast_enabled() + ) + # If we save pre-activation, dimension must be divisible by 128 (relu) or 8 (gelu) + dim_eligible = not save_pre_act or (x.shape[-1] % (128 if activation == "relu" else 8) == 0) + if ( + x.is_cuda + and weight1.is_cuda + and weight2.is_cuda + and (bias1 is None or bias1.is_cuda) + and (bias2 is None or bias2.is_cuda) + and dtype_eligible + and dim_eligible + ): + return FusedMLPFunc.apply( + x, + weight1, + bias1, + weight2, + bias2, + activation, + save_pre_act, + return_residual, + checkpoint_lvl, + heuristic, + process_group, + sequence_parallel, + ) + else: + assert process_group is None + pre_act = F.linear(x, weight1, bias1) + activation_fn = ( + partial(F.gelu, approximate="tanh") + if activation == "gelu_approx" + else partial(F.relu, inplace=True) + ) + output1 = activation_fn(pre_act) + output2 = F.linear(output1, weight2, bias2) + return output2 if not return_residual else (output2, x) + + +class FusedMLP(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + bias1=True, + bias2=True, + activation="gelu_approx", + return_residual=False, + checkpoint_lvl=0, + heuristic="auto", + device=None, + dtype=None, + ): + """ + If process_group is not None, we're doing Tensor Parallel with sequence parallelism: + we do an all_gather of x before doing the matmul, gelu, then matmul. + Finally we do a reduce_scatter of the output. + + checkpoint_lvl (increasing lvl means slower but more memory saving): + 0: no recomputation in the bwd + 1: recompute gelu_out in the bwd + 2: recompute pre_act and gelu_out in the bwd + heuristic: + -1: don't fuse gemm + gelu (separate kernel) + 0..4: use this heuristic for the algo section in the fused gemm + gelu + 'auto': heuristic will be picked automatically: + For CUDA >= 11.8, we set heuristic=0 for both fp16 and bf16 for best perf. + For CUDA <= 11.7, we set heuristic=1 for fp16 and heuristic=-1 for bf16. + For H100, we set heuristic=-1 for both fp16 and bf16 as the fused cuBlasLt implementation + is slower than the unfused version. + return_residual: whether to return the input x along with the output. This is for + performance reason: for post-norm architecture, returning the input allows us + to fuse the backward of nn.Linear with the residual connection. + """ + assert checkpoint_lvl in [0, 1, 2] + assert activation in ["gelu_approx", "relu", "sqrelu"] + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features * 4 + self.activation = activation + self.return_residual = return_residual + self.checkpoint_lvl = checkpoint_lvl + self.heuristic = heuristic if activation != "sqrelu" else -1 + self.fc1 = nn.Linear(in_features, hidden_features, bias=bias1, **factory_kwargs) + self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2, **factory_kwargs) + + def forward(self, x, process_group=None): + dtype = x.dtype if not torch.is_autocast_enabled() else torch.get_autocast_gpu_dtype() + if self.heuristic == "auto": + if self.activation == "gelu_approx": + if torch.cuda.get_device_capability("cuda") == (9, 0): + heuristic = -1 + else: + cuda_ver = tuple(map(int, torch.version.cuda.split("."))) + heuristic = 0 if cuda_ver >= (11, 8) else (1 if dtype == torch.float16 else -1) + else: + heuristic = 0 + else: + heuristic = self.heuristic + out = fused_mlp_func( + x, + self.fc1.weight, + self.fc2.weight, + self.fc1.bias, + self.fc2.bias, + activation=self.activation, + save_pre_act=self.training, + return_residual=self.return_residual, + checkpoint_lvl=self.checkpoint_lvl, + heuristic=heuristic, + process_group=process_group, + ) + if self.return_residual: + out, x = out + if process_group is not None: + out = reduce_scatter(out, process_group) + return out if not self.return_residual else (out, x) + + +class ParallelFusedMLP(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + activation="gelu_approx", + process_group: ProcessGroup = None, + bias1=True, + bias2=True, + sequence_parallel=True, + checkpoint_lvl=0, + heuristic="auto", + device=None, + dtype=None, + ): + """ + process_group is required. We're doing Tensor Parallel with sequence parallelism: + we do an all_gather of x before doing the matmul, gelu, then matmul. + Finally we do a reduce_scatter of the output. + + checkpoint_lvl (increasing lvl means slower but more memory saving): + 0: no recomputation in the bwd + 1: recompute gelu_out in the bwd + 2: recompute pre_act and gelu_out in the bwd + heuristic: + -1: don't fuse gemm + gelu (separate kernel) + 0..4: use this heuristic for the algo section in the fused gemm + gelu + 'auto': heuristic will be picked automatically: + For CUDA >= 11.8, we set heuristic=0 for both fp16 and bf16 for best perf. + For CUDA <= 11.7, we set heuristic=1 for fp16 and heuristic=-1 for bf16. + """ + assert checkpoint_lvl in [0, 1, 2] + assert activation in ["gelu_approx", "relu", "sqrelu"] + assert process_group is not None + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features * 4 + self.activation = activation + self.process_group = process_group + self.sequence_parallel = sequence_parallel + self.checkpoint_lvl = checkpoint_lvl + self.heuristic = heuristic if activation != "sqrelu" else -1 + self.fc1 = ColumnParallelLinear( + in_features, hidden_features, process_group, bias=bias1, **factory_kwargs + ) + self.fc2 = RowParallelLinear( + hidden_features, out_features, process_group, bias=bias2, **factory_kwargs + ) + + def forward(self, x): + dtype = x.dtype if not torch.is_autocast_enabled() else torch.get_autocast_gpu_dtype() + if self.heuristic == "auto": + if self.activation == "gelu_approx": + cuda_ver = tuple(map(int, torch.version.cuda.split("."))) + heuristic = 0 if cuda_ver >= (11, 8) else (1 if dtype == torch.float16 else -1) + else: + heuristic = 0 + else: + heuristic = self.heuristic + out = fused_mlp_func( + x, + self.fc1.weight, + self.fc2.weight, + self.fc1.bias, + self.fc2.bias, + activation=self.activation, + save_pre_act=self.training, + checkpoint_lvl=self.checkpoint_lvl, + heuristic=heuristic, + process_group=self.process_group, + sequence_parallel=self.sequence_parallel, + ) + reduce_fn = reduce_scatter if self.sequence_parallel else all_reduce + return reduce_fn(out, self.process_group) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/layer_norm.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/layer_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..4b6cd798fd02844ef9cd3897f8ab95e490e638bf --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/layer_norm.py @@ -0,0 +1,800 @@ +# Copyright (c) 2022, Tri Dao. +# Adapted from https://github.com/NVIDIA/apex/blob/master/apex/contrib/layer_norm/layer_norm.py + +import dropout_layer_norm +import torch +from torch.nn import init + + +def maybe_align(x, alignment_in_bytes=16): + """Assume that x already has last dim divisible by alignment_in_bytes""" + # TD [2023-07-04] I'm not 100% sure that clone will align the memory + # https://discuss.pytorch.org/t/how-to-ensure-that-tensor-data-ptr-is-aligned-to-16-bytes/183440 + return x if x.data_ptr() % alignment_in_bytes == 0 else x.clone() + + +def _dropout_add_layer_norm_forward( + x0, + residual, + gamma, + beta, + rowscale, + colscale, + dropout_p, + epsilon, + residual_in_fp32=False, + is_rms_norm=False, +): + """Assume that arguments are contiguous and aligned to 16 bytes""" + hidden_size = gamma.numel() + x0mat = x0.view((-1, hidden_size)) + residualmat = residual.view((-1, hidden_size)) if residual is not None else None + rowscale = rowscale.view(-1) if rowscale is not None else None + zmat, xmat, dmask, mu, rsigma = dropout_layer_norm.dropout_add_ln_fwd( + x0mat, + residualmat, + gamma, + beta, + rowscale, + colscale, + None, + None, + dropout_p, + epsilon, + 1.0, + 0, + None, + residual_in_fp32, + is_rms_norm, + ) + # dmask is None if dropout_p == 0.0 + # xmat is None if dropout_p == 0.0 and residual is None and residual_dtype != input_dtype + return zmat, xmat if xmat is not None else x0mat, dmask, mu, rsigma + + +def _dropout_add_layer_norm_backward( + dz, + dx, + x, + x0, + dmask, + mu, + rsigma, + gamma, + rowscale, + colscale, + dropout_p, + has_residual, + is_rms_norm=False, +): + """Assume that arguments are contiguous and aligned to 16 bytes + dx == None means that it was a post-norm architecture + (x = drop(x0) + residual was not returned in the fwd). + x0 must not be None if we have colscale. + """ + hidden_size = gamma.numel() + xmat = x.view((-1, hidden_size)) + dzmat = dz.view(xmat.shape) + dxmat = dx.view(xmat.shape) if dx is not None else None + x0mat = x0.view((-1, hidden_size)) if x0 is not None else None + rowscale = rowscale.view(-1) if rowscale is not None else None + if colscale is not None: + assert x0 is not None, "x0 is required to compute the gradient of colscale" + dx0mat, dresidualmat, dgamma, dbeta, _, _, *rest = dropout_layer_norm.dropout_add_ln_bwd( + dzmat, + dxmat, + xmat, + x0mat, + dmask, + mu, + rsigma, + gamma, + rowscale, + colscale, + None, + None, + dropout_p, + 1.0, + 0, + has_residual, + is_rms_norm, + ) + # dresidualmat is None if not has_residual + if colscale is None: + return dx0mat, dresidualmat, dgamma, dbeta + else: + dcolscale = rest[0] + return dx0mat, dresidualmat, dgamma, dbeta, dcolscale + + +def _dropout_add_layer_norm_subset_forward( + x0, + residual, + gamma, + beta, + colscale, + x0_subset, + out_subset, + dropout_p, + epsilon, + rowscale_const, + out_numrows, + residual_in_fp32=False, + is_rms_norm=False, +): + """Assume that arguments are contiguous and aligned to 16 bytes""" + hidden_size = gamma.numel() + x0mat = x0.view((-1, hidden_size)) + residualmat = residual.view((-1, hidden_size)) if residual is not None else None + x0_subset = x0_subset.view(-1) if x0_subset is not None else None + out_subset = out_subset.view(-1) if out_subset is not None else None + zmat, xmat, dmask, mu, rsigma = dropout_layer_norm.dropout_add_ln_fwd( + x0mat, + residualmat, + gamma, + beta, + None, + colscale, + x0_subset, + out_subset, + dropout_p, + epsilon, + rowscale_const, + out_numrows, + None, + residual_in_fp32, + is_rms_norm, + ) + # dmask is None if dropout_p == 0.0 + # xmat is None if dropout_p == 0.0 and residual is None and residual_dtype != input_dtype + return zmat, xmat if xmat is not None else x0mat, dmask, mu, rsigma + + +def _dropout_add_layer_norm_subset_backward( + dz, + dx, + x, + x0, + dmask, + mu, + rsigma, + gamma, + colscale, + x0_subset, + out_subset, + dropout_p, + rowscale_const, + x0_numrows, + has_residual, + is_rms_norm=False, +): + """Assume that arguments are contiguous and aligned to 16 bytes + dx == None means that it was a post-norm architecture + (x = drop(x0) + residual was not returned in the fwd). + x0 must not be None if we have colscale. + """ + hidden_size = gamma.numel() + xmat = x.view((-1, hidden_size)) + dzmat = dz.view(-1, hidden_size) + dxmat = dx.view(xmat.shape) if dx is not None else None + x0mat = x0.view((-1, hidden_size)) if x0 is not None else None + x0_subset = x0_subset.view(-1) if x0_subset is not None else None + out_subset = out_subset.view(-1) if out_subset is not None else None + if colscale is not None: + assert x0 is not None, "x0 is required to compute the gradient of colscale" + dx0mat, dresidualmat, dgamma, dbeta, _, _, *rest = dropout_layer_norm.dropout_add_ln_bwd( + dzmat, + dxmat, + xmat, + x0mat, + dmask, + mu, + rsigma, + gamma, + None, + colscale, + x0_subset, + out_subset, + dropout_p, + rowscale_const, + x0_numrows, + has_residual, + is_rms_norm, + ) + # dresidualmat is None if not has_residual + if colscale is None: + return dx0mat, dresidualmat, dgamma, dbeta + else: + dcolscale = rest[0] + return dx0mat, dresidualmat, dgamma, dbeta, dcolscale + + +def _dropout_add_layer_norm_parallel_residual_forward( + x0, + x1, + residual, + gamma0, + beta0, + gamma1, + beta1, + dropout_p, + epsilon, + residual_in_fp32=False, + is_rms_norm=False, +): + """Assume that arguments are contiguous and aligned to 16 bytes""" + hidden_size = gamma0.numel() + x0mat = x0.view((-1, hidden_size)) + x1mat = x1.view((-1, hidden_size)) if x1 is not None else None + residualmat = residual.view((-1, hidden_size)) if residual is not None else None + ( + z0mat, + z1mat, + xmat, + dmask0, + dmask1, + mu, + rsigma, + ) = dropout_layer_norm.dropout_add_ln_parallel_residual_fwd( + x0mat, + x1mat, + residualmat, + gamma0, + beta0, + gamma1, + beta1, + dropout_p, + epsilon, + None, + residual_in_fp32, + is_rms_norm, + ) + # dmask0 and dmask1 are None if dropout_p == 0.0 + # xmat is None if dropout_p == 0.0 and residual is None and residual_dtype != input_dtype + return z0mat, z1mat, xmat if xmat is not None else x0mat, dmask0, dmask1, mu, rsigma + + +def _dropout_add_layer_norm_parallel_residual_backward( + dz0, + dz1, + dx, + x, + dmask0, + dmask1, + mu, + rsigma, + gamma0, + gamma1, + dropout_p, + has_x1, + has_residual, + is_rms_norm=False, +): + """Assume that arguments are contiguous and aligned to 16 bytes + dx == None means that it was a post-norm architecture + (x = drop(x0) + residual was not returned in the fwd). + """ + hidden_size = gamma0.numel() + xmat = x.view((-1, hidden_size)) + dz0mat = dz0.view(xmat.shape) + dz1mat = dz1.view(xmat.shape) if dz1 is not None else None + dxmat = dx.view(xmat.shape) if dx is not None else None + ( + dx0mat, + dx1mat, + dresidualmat, + dgamma0, + dbeta0, + dgamma1, + dbeta1, + *rest, + ) = dropout_layer_norm.dropout_add_ln_parallel_residual_bwd( + dz0mat, + dz1mat, + dxmat, + xmat, + dmask0, + dmask1, + mu, + rsigma, + gamma0, + gamma1, + dropout_p, + has_x1, + has_residual, + is_rms_norm, + ) + # dresidualmat is None if not has_residual + return dx0mat, dx1mat, dresidualmat, dgamma0, dbeta0, dgamma1, dbeta1 + + +class DropoutAddLayerNormFn(torch.autograd.Function): + @staticmethod + def forward( + ctx, + x0, + residual, + gamma, + beta, + rowscale, + colscale, + dropout_p, + epsilon, + residual_in_fp32=False, + prenorm=False, + is_rms_norm=False, + return_dmask=False, + ): + x0 = maybe_align(x0.contiguous(), 16) + residual = maybe_align(residual.contiguous(), 16) if residual is not None else None + gamma = maybe_align(gamma.contiguous(), 16) + beta = maybe_align(beta.contiguous(), 16) if beta is not None else None + rowscale = maybe_align(rowscale.contiguous(), 16) if rowscale is not None else None + colscale = maybe_align(colscale.contiguous(), 16) if colscale is not None else None + zmat, xmat, dmask, mu, rsigma = _dropout_add_layer_norm_forward( + x0, + residual, + gamma, + beta, + rowscale, + colscale, + dropout_p, + epsilon, + residual_in_fp32, + is_rms_norm, + ) + # Only need to save x0 if we need to compute gradient wrt colscale + x0_saved = x0 if colscale is not None else None + ctx.save_for_backward( + xmat.view(x0.shape), x0_saved, dmask, gamma, mu, rsigma, rowscale, colscale + ) + ctx.prenorm = prenorm + ctx.dropout_p = dropout_p + ctx.has_residual = residual is not None + ctx.is_rms_norm = is_rms_norm + ctx.has_beta = beta is not None + if not return_dmask: + return ( + zmat.view(x0.shape) if not prenorm else (zmat.view(x0.shape), xmat.view(x0.shape)) + ) + else: + dmask = ( + dmask.view(x0.shape) + if dropout_p > 0.0 + else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device) + ) + ctx.mark_non_differentiable(dmask) + return ( + (zmat.view(x0.shape), dmask) + if not prenorm + else (zmat.view(x0.shape), xmat.view(x0.shape), dmask) + ) + + @staticmethod + def backward(ctx, dz, *args): + # assert dz.is_contiguous() + dz = maybe_align(dz.contiguous(), 16) # this happens! + dx = maybe_align(args[0].contiguous(), 16) if ctx.prenorm else None + x, x0, dmask, gamma, mu, rsigma, rowscale, colscale = ctx.saved_tensors + # x0 is None if colscale is None + dropout_p = ctx.dropout_p + has_residual = ctx.has_residual + dx0mat, dresidualmat, dgamma, dbeta, *rest = _dropout_add_layer_norm_backward( + dz, + dx, + x, + x0, + dmask, + mu, + rsigma, + gamma, + rowscale, + colscale, + dropout_p, + has_residual, + ctx.is_rms_norm, + ) + dx0 = dx0mat.view(x.shape) + dresidual = dresidualmat.view(x.shape) if dresidualmat is not None else None + dcolscale = rest[0] if colscale is not None else None + return ( + dx0, + dresidual, + dgamma, + dbeta if ctx.has_beta else None, + None, + dcolscale, + None, + None, + None, + None, + None, + None, + ) + + +class DropoutAddLayerNormSubsetFn(torch.autograd.Function): + @staticmethod + def forward( + ctx, + x0, + residual, + gamma, + beta, + colscale, + x0_subset, + out_subset, + dropout_p, + epsilon, + rowscale_const, + out_numrows, + residual_in_fp32=False, + prenorm=False, + is_rms_norm=False, + return_dmask=False, + ): + x0 = maybe_align(x0.contiguous(), 16) + residual = maybe_align(residual.contiguous(), 16) if residual is not None else None + gamma = maybe_align(gamma.contiguous(), 16) + beta = maybe_align(beta.contiguous(), 16) if beta is not None else None + colscale = maybe_align(colscale.contiguous(), 16) if colscale is not None else None + zmat, xmat, dmask, mu, rsigma = _dropout_add_layer_norm_subset_forward( + x0, + residual, + gamma, + beta, + colscale, + x0_subset, + out_subset, + dropout_p, + epsilon, + rowscale_const, + out_numrows, + residual_in_fp32, + is_rms_norm, + ) + # Only need to save x0 if we need to compute gradient wrt colscale + x0_saved = x0 if colscale is not None else None + x_shape = (-1, *x0.shape[1:]) + ctx.save_for_backward( + xmat.view(x_shape), x0_saved, dmask, gamma, mu, rsigma, colscale, x0_subset, out_subset + ) + ctx.prenorm = prenorm + ctx.dropout_p = dropout_p + ctx.rowscale_const = rowscale_const + ctx.x0_numrows = x0.shape[:-1].numel() + ctx.has_residual = residual is not None + ctx.is_rms_norm = is_rms_norm + ctx.has_beta = beta is not None + z_shape = (-1, *x0.shape[1:]) + if not return_dmask: + return zmat.view(z_shape) if not prenorm else (zmat.view(z_shape), xmat.view(x0.shape)) + else: + z = zmat.view(z_shape) + dmask = ( + dmask.view(x0.shape) + if dropout_p > 0.0 + else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device) + ) + ctx.mark_non_differentiable(dmask) + return (z, dmask) if not prenorm else (z, xmat.view(x_shape), dmask) + + @staticmethod + def backward(ctx, dz, *args): + # assert dz.is_contiguous() + dz = maybe_align(dz.contiguous(), 16) # this happens! + dx = maybe_align(args[0].contiguous(), 16) if ctx.prenorm else None + x, x0, dmask, gamma, mu, rsigma, colscale, x0_subset, out_subset = ctx.saved_tensors + # x0 is None if colscale is None + dropout_p = ctx.dropout_p + has_residual = ctx.has_residual + dx0mat, dresidualmat, dgamma, dbeta, *rest = _dropout_add_layer_norm_subset_backward( + dz, + dx, + x, + x0, + dmask, + mu, + rsigma, + gamma, + colscale, + x0_subset, + out_subset, + dropout_p, + ctx.rowscale_const, + ctx.x0_numrows, + has_residual, + ctx.is_rms_norm, + ) + dx0 = dx0mat.view(-1, *x.shape[1:]) + dresidual = dresidualmat.view(x.shape) if dresidualmat is not None else None + dcolscale = rest[0] if colscale is not None else None + return ( + dx0, + dresidual, + dgamma, + dbeta if ctx.has_beta else None, + dcolscale, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + ) + + +class DropoutAddLayerNormParallelResidualFn(torch.autograd.Function): + @staticmethod + def forward( + ctx, + x0, + x1, + residual, + gamma0, + beta0, + gamma1, + beta1, + dropout_p, + epsilon, + residual_in_fp32=False, + prenorm=False, + is_rms_norm=False, + return_dmask=False, + ): + x0 = maybe_align(x0.contiguous(), 16) + x1 = maybe_align(x1.contiguous(), 16) if x1 is not None else None + residual = maybe_align(residual.contiguous(), 16) if residual is not None else None + gamma0 = maybe_align(gamma0.contiguous(), 16) + beta0 = maybe_align(beta0.contiguous(), 16) if beta0 is not None else None + gamma1 = maybe_align(gamma1.contiguous(), 16) if gamma1 is not None else None + beta1 = maybe_align(beta1.contiguous(), 16) if beta1 is not None else None + ( + z0mat, + z1mat, + xmat, + dmask0, + dmask1, + mu, + rsigma, + ) = _dropout_add_layer_norm_parallel_residual_forward( + x0, + x1, + residual, + gamma0, + beta0, + gamma1, + beta1, + dropout_p, + epsilon, + residual_in_fp32, + is_rms_norm, + ) + ctx.save_for_backward(xmat.view(x0.shape), dmask0, dmask1, gamma0, gamma1, mu, rsigma) + ctx.prenorm = prenorm + ctx.dropout_p = dropout_p + ctx.has_x1 = x1 is not None + ctx.has_residual = residual is not None + ctx.is_rms_norm = is_rms_norm + ctx.has_beta = beta0 is not None + z = (z0mat.view(x0.shape), z1mat.view(x0.shape) if z1mat is not None else None) + if not return_dmask: + return z if not prenorm else (*z, xmat.view(x0.shape)) + else: + dmask0 = ( + dmask0.view(x0.shape) + if dropout_p > 0.0 + else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device) + ) + dmask1 = ( + dmask1.view(x0.shape) + if dropout_p > 0.0 and x1 is not None + else torch.ones(x0.shape, dtype=torch.uint8, device=x0.device) + ) + ctx.mark_non_differentiable(dmask0) + ctx.mark_non_differentiable(dmask1) + return ( + (*z, dmask0, dmask1) if not prenorm else (*z, xmat.view(x0.shape), dmask0, dmask1) + ) + + @staticmethod + def backward(ctx, dz0, dz1, *args): + dz0 = maybe_align(dz0.contiguous(), 16) # this happens! + dz1 = maybe_align(dz1.contiguous(), 16) if dz1 is not None else None + dx = maybe_align(args[0].contiguous(), 16) if ctx.prenorm else None + x, dmask0, dmask1, gamma0, gamma1, mu, rsigma = ctx.saved_tensors + dropout_p = ctx.dropout_p + has_x1 = ctx.has_x1 + has_residual = ctx.has_residual + ( + dx0mat, + dx1mat, + dresidualmat, + dgamma0, + dbeta0, + dgamma1, + dbeta1, + ) = _dropout_add_layer_norm_parallel_residual_backward( + dz0, + dz1, + dx, + x, + dmask0, + dmask1, + mu, + rsigma, + gamma0, + gamma1, + dropout_p, + has_x1, + has_residual, + ctx.is_rms_norm, + ) + dx0 = dx0mat.view(x.shape) + dx1 = dx1mat.view(x.shape) if dx1mat is not None else None + dresidual = dresidualmat.view(x.shape) if dresidualmat is not None else None + return ( + dx0, + dx1, + dresidual, + dgamma0, + dbeta0 if ctx.has_beta else None, + dgamma1, + dbeta1 if ctx.has_beta else None, + None, + None, + None, + None, + None, + None, + ) + + +def layer_norm(x, weight, bias, epsilon): + return DropoutAddLayerNormFn.apply(x, None, weight, bias, None, None, 0.0, epsilon, False) + + +def dropout_add_layer_norm( + x0, + residual, + weight, + bias, + dropout_p, + epsilon, + rowscale=None, + layerscale=None, + prenorm=False, + residual_in_fp32=False, + return_dropout_mask=False, +): + """residual_in_fp32 only has an effect if residual is None. + Otherwise residual dtype is residual.dtype. + """ + return DropoutAddLayerNormFn.apply( + x0, + residual, + weight, + bias, + rowscale, + layerscale, + dropout_p, + epsilon, + residual_in_fp32, + prenorm, + False, + return_dropout_mask, + ) + + +def dropout_add_layer_norm_subset( + x0, + residual, + weight, + bias, + dropout_p, + epsilon, + layerscale=None, + x0_subset=None, + out_subset=None, + rowscale_const=1.0, + out_numrows=0, + prenorm=False, + residual_in_fp32=False, + return_dropout_mask=False, +): + """residual_in_fp32 only has an effect if residual is None. + Otherwise residual dtype is residual.dtype. + """ + return DropoutAddLayerNormSubsetFn.apply( + x0, + residual, + weight, + bias, + layerscale, + x0_subset, + out_subset, + dropout_p, + epsilon, + rowscale_const, + out_numrows, + residual_in_fp32, + prenorm, + False, + return_dropout_mask, + ) + + +def dropout_add_layer_norm_parallel_residual( + x0, + x1, + residual, + weight0, + bias0, + weight1, + bias1, + dropout_p, + epsilon, + prenorm=False, + residual_in_fp32=False, + return_dropout_mask=False, +): + """residual_in_fp32 only has an effect if residual is None. + Otherwise residual dtype is residual.dtype. + """ + return DropoutAddLayerNormParallelResidualFn.apply( + x0, + x1, + residual, + weight0, + bias0, + weight1, + bias1, + dropout_p, + epsilon, + residual_in_fp32, + prenorm, + False, + return_dropout_mask, + ) + + +class DropoutAddLayerNorm(torch.nn.Module): + def __init__( + self, + hidden_size, + prenorm=False, + p=0.0, + eps=1e-5, + residual_in_fp32=False, + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.prenorm = prenorm + self.p = p + self.eps = eps + self.residual_in_fp32 = residual_in_fp32 + self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs)) + self.bias = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs)) + self.reset_parameters() + + def reset_parameters(self): + init.ones_(self.weight) + init.zeros_(self.bias) + + def forward(self, x0, residual=None): + return dropout_add_layer_norm( + x0, + residual, + self.weight, + self.bias, + self.p if self.training else 0.0, + self.eps, + prenorm=self.prenorm, + residual_in_fp32=self.residual_in_fp32, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/rms_norm.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/rms_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..068348d61290e3839dd082b540d898578ba1e8e2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/rms_norm.py @@ -0,0 +1,174 @@ +# Copyright (c) 2022, Tri Dao. +# Adapted from https://github.com/NVIDIA/apex/blob/master/apex/contrib/layer_norm/layer_norm.py + +import torch +from torch.nn import init + +from flash_attn.ops.layer_norm import ( + DropoutAddLayerNormFn, + DropoutAddLayerNormParallelResidualFn, + DropoutAddLayerNormSubsetFn, +) + + +def rms_norm(x, weight, epsilon): + return DropoutAddLayerNormFn.apply( + x, None, weight, None, None, None, 0.0, epsilon, False, False, True + ) + + +def dropout_add_rms_norm( + x0, + residual, + weight, + bias, + dropout_p, + epsilon, + rowscale=None, + layerscale=None, + prenorm=False, + residual_in_fp32=False, + return_dropout_mask=False, +): + """residual_in_fp32 only has an effect if residual is None. + Otherwise residual dtype is residual.dtype. + """ + return DropoutAddLayerNormFn.apply( + x0, + residual, + weight, + bias, + rowscale, + layerscale, + dropout_p, + epsilon, + residual_in_fp32, + prenorm, + True, + return_dropout_mask, + ) + + +def dropout_add_rms_norm_subset( + x0, + residual, + weight, + bias, + dropout_p, + epsilon, + layerscale=None, + x0_subset=None, + out_subset=None, + rowscale_const=1.0, + out_numrows=0, + prenorm=False, + residual_in_fp32=False, + return_dropout_mask=False, +): + """residual_in_fp32 only has an effect if residual is None. + Otherwise residual dtype is residual.dtype. + """ + return DropoutAddLayerNormSubsetFn.apply( + x0, + residual, + weight, + bias, + layerscale, + x0_subset, + out_subset, + dropout_p, + epsilon, + rowscale_const, + out_numrows, + residual_in_fp32, + prenorm, + True, + return_dropout_mask, + ) + + +def dropout_add_rms_norm_parallel_residual( + x0, + x1, + residual, + weight0, + bias0, + weight1, + bias1, + dropout_p, + epsilon, + prenorm=False, + residual_in_fp32=False, + return_dropout_mask=False, +): + """residual_in_fp32 only has an effect if residual is None. + Otherwise residual dtype is residual.dtype. + """ + return DropoutAddLayerNormParallelResidualFn.apply( + x0, + x1, + residual, + weight0, + bias0, + weight1, + bias1, + dropout_p, + epsilon, + residual_in_fp32, + prenorm, + True, + return_dropout_mask, + ) + + +class RMSNorm(torch.nn.Module): + def __init__(self, hidden_size, eps=1e-5, device=None, dtype=None): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.eps = eps + self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs)) + self.register_parameter("bias", None) + self.reset_parameters() + + def reset_parameters(self): + init.ones_(self.weight) + + def forward(self, x): + return rms_norm(x, self.weight, self.eps) + + +class DropoutAddRMSNorm(torch.nn.Module): + def __init__( + self, + hidden_size, + prenorm=False, + p=0.0, + eps=1e-5, + residual_in_fp32=False, + device=None, + dtype=None, + ): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.prenorm = prenorm + self.p = p + self.eps = eps + self.residual_in_fp32 = residual_in_fp32 + self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs)) + self.register_parameter("bias", None) + self.reset_parameters() + + def reset_parameters(self): + init.ones_(self.weight) + + def forward(self, x0, residual=None): + return dropout_add_rms_norm( + x0, + residual, + self.weight, + None, + self.p if self.training else 0.0, + self.eps, + prenorm=self.prenorm, + residual_in_fp32=self.residual_in_fp32, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__init__.py @@ -0,0 +1 @@ + diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c9a420b2ab0067d306b83707604acf08845a2a6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/cross_entropy.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/cross_entropy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6492dcc2070b6f96414d9592fb465e6c2af2a3d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/cross_entropy.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/k_activations.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/k_activations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4be49717bdb397ba6816b325d4d536ddb37361d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/k_activations.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/layer_norm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/layer_norm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0cfc81c3dd3330d8823ce8efea8c86015594bf5a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/layer_norm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/linear.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/linear.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d37a7222430052fe6b8a7f4e0a5ff3a654b6874c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/linear.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/mlp.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/mlp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..514dd67de0d6776378818ce21f1e24d971048686 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/mlp.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/rotary.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/rotary.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f980a17a02bb0ef08a2e9e0f200be2f7be480c6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/__pycache__/rotary.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/cross_entropy.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/cross_entropy.py new file mode 100644 index 0000000000000000000000000000000000000000..1b5a415b73f236f3e05fb14b9141959559e18526 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/cross_entropy.py @@ -0,0 +1,330 @@ +# Copyright (c) 2023, Tri Dao. + +from typing import Tuple, Optional, Union + +import torch +import torch.nn.functional as F + +import triton +import triton.language as tl + +# `all_gather_into_tensor` and `reduce_scatter_tensor` are new placeholders for +# `_all_gather_base` and `_reduce_scatter_base`. They require the most recent +# version of PyTorch. The following 2 lines are for backward compatibility with +# older PyTorch. +if "all_gather_into_tensor" not in dir(torch.distributed): + torch.distributed.all_gather_into_tensor = torch.distributed._all_gather_base + + +@triton.heuristics( + { + "HAS_SMOOTHING": lambda args: args["smoothing"] > 0.0, + } +) +@triton.jit +def cross_entropy_fwd_kernel( + loss_ptr, # data ptrs + lse_ptr, + z_loss_ptr, + logits_ptr, + labels_ptr, + smoothing, + logit_scale, + lse_square_scale, + ignore_index, + total_classes, + class_start_idx, # Useful for tensor parallel when each rank only has a subset of classes + n_cols, # shapes + logits_row_stride, # strides + BLOCK_SIZE: tl.constexpr, + HAS_SMOOTHING: tl.constexpr, + # if SPLIT (e.g. tensor parallel), don't include the LSE in the loss since it's not the final LSE + SPLIT: tl.constexpr, + PRECOMPUTED_LSE: tl.constexpr, # If LSE is already computed (also no smoothing and logit_scale == 1.0) +): + row_idx = tl.program_id(0) + logits_ptr = logits_ptr + row_idx * logits_row_stride.to(tl.int64) + sum_logits = 0.0 # For smoothing + if not PRECOMPUTED_LSE: + # Statistics for online softmax + m_i = -float("inf") + l_i = 0.0 + for col_offset in range(0, n_cols, BLOCK_SIZE): + cols = col_offset + tl.arange(0, BLOCK_SIZE) + logits = tl.load(logits_ptr + cols, mask=cols < n_cols, other=-float("inf")).to( + tl.float32 + ) * logit_scale + if HAS_SMOOTHING: + sum_logits += tl.sum(tl.where(cols < n_cols, logits, 0.0)) + m_i_new = tl.maximum(m_i, tl.max(logits)) + l_i = tl.exp(m_i - m_i_new) * l_i + tl.sum(tl.exp(logits - m_i_new)) + m_i = m_i_new + lse = tl.log(l_i) + m_i + tl.store(lse_ptr + row_idx, lse) + else: + lse = tl.load(lse_ptr + row_idx) + label_idx = tl.load(labels_ptr + row_idx) + if label_idx == ignore_index: + loss = 0.0 + z_loss = 0.0 + else: + label_idx -= class_start_idx + if label_idx >= 0 and label_idx < n_cols: + logits_label = tl.load(logits_ptr + label_idx) * logit_scale + if HAS_SMOOTHING: + loss = ( + (lse if not SPLIT else 0.0) + - smoothing * sum_logits / total_classes + - (1 - smoothing) * logits_label + ) + else: + loss = (lse if not SPLIT else 0.0) - logits_label + else: + # If label is out of bounds, we set the CE loss to 0.0. But we still want the smoothing loss + if HAS_SMOOTHING: + loss = smoothing * ((lse if not SPLIT else 0.0) - sum_logits / total_classes) + else: + loss = 0.0 + if not SPLIT: + z_loss = lse_square_scale * lse * lse + loss += z_loss + else: + z_loss = 0.0 + tl.store(loss_ptr + row_idx, loss) + if not SPLIT: + tl.store(z_loss_ptr + row_idx, z_loss) + + +@triton.heuristics( + { + "HAS_SMOOTHING": lambda args: args["smoothing"] > 0.0, + } +) +@triton.jit +def cross_entropy_bwd_kernel( + dlogits_ptr, # data ptrs + dloss_ptr, + logits_ptr, + lse_ptr, + labels_ptr, + smoothing, + logit_scale, + lse_square_scale, + ignore_index, + total_classes, + class_start_idx, # Useful for tensor parallel when each rank only has a subset of classes + n_cols, # shapes + logits_row_stride, # strides + dlogits_row_stride, + dloss_row_stride, + BLOCK_SIZE: tl.constexpr, + HAS_SMOOTHING: tl.constexpr, +): + row_idx = tl.program_id(0) + col_block_idx = tl.program_id(1) + logits_ptr = logits_ptr + row_idx * logits_row_stride.to(tl.int64) + dlogits_ptr = dlogits_ptr + row_idx * dlogits_row_stride.to(tl.int64) + col_offsets = col_block_idx * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE) + label_idx = tl.load(labels_ptr + row_idx) + if label_idx != ignore_index: + dloss = tl.load(dloss_ptr + row_idx * dloss_row_stride) + else: + dloss = 0.0 + logits = tl.load(logits_ptr + col_offsets, mask=col_offsets < n_cols, other=-float("inf")).to( + tl.float32 + ) * logit_scale + lse = tl.load(lse_ptr + row_idx) + probs = tl.exp(logits - lse) + probs += 2.0 * lse_square_scale * lse * probs + label_idx -= class_start_idx + if HAS_SMOOTHING: + smooth_positive = 1.0 - smoothing + smooth_negative = smoothing / total_classes + probs = tl.where(col_offsets == label_idx, probs - smooth_positive, probs) - smooth_negative + else: + probs = tl.where(col_offsets == label_idx, probs - 1.0, probs) + tl.store(dlogits_ptr + col_offsets, (dloss * logit_scale) * probs, mask=col_offsets < n_cols) + + +class CrossEntropyLoss(torch.autograd.Function): + + @staticmethod + def forward( + ctx, + logits, + labels, + precomputed_lse=None, + smoothing=0.0, + logit_scale=1.0, + lse_square_scale=0.0, + ignore_index=-100, + inplace_backward=False, + process_group=None, + ): + # For some reason Triton generates wrong code when labels has dtype long and its address + # is not aligned to 16 bytes. The ld.global.b64 seems to load the wrong label index. + if labels.dtype == torch.long and labels.data_ptr() % 16 != 0: + labels = F.pad(labels, (0, 1))[..., :-1] + assert labels.data_ptr() % 16 == 0 + assert logit_scale > 0.0 + n_rows, n_cols = logits.shape + assert labels.shape == (n_rows,) + world_size = 1 if process_group is None else torch.distributed.get_world_size(process_group) + total_classes = world_size * n_cols + rank = 0 if process_group is None else torch.distributed.get_rank(process_group) + class_start_idx = rank * n_cols + use_precomputed_lse = precomputed_lse is not None and logit_scale == 1.0 and smoothing == 0.0 + + if logits.stride(-1) != 1: + logits = logits.contiguous() + MAX_BLOCK_SIZE = 16 * 1024 + BLOCK_SIZE = min(triton.next_power_of_2(n_cols), MAX_BLOCK_SIZE) + num_warps = ( + 4 + if BLOCK_SIZE < 2048 + else (8 if BLOCK_SIZE < 8192 else (16 if BLOCK_SIZE < 128 * 1024 else 32)) + ) + losses = torch.empty(n_rows, dtype=torch.float, device=logits.device) + if use_precomputed_lse: + assert precomputed_lse.shape == (n_rows,) + lse = precomputed_lse.contiguous() + else: + lse = torch.empty(n_rows, dtype=torch.float, device=logits.device) + z_losses = torch.empty(n_rows, dtype=torch.float, device=logits.device) + # Need this, otherwise Triton tries to launch from cuda:0 and we get + # ValueError: Pointer argument (at 0) cannot be accessed from Triton (cpu tensor?) + with torch.cuda.device(logits.device.index): + cross_entropy_fwd_kernel[(n_rows,)]( + losses, # data ptrs + lse, + z_losses, + logits, + labels, + smoothing, + logit_scale, + lse_square_scale, + ignore_index, + total_classes, + class_start_idx, + n_cols, # shapes + logits.stride(0), # strides + BLOCK_SIZE=BLOCK_SIZE, # constants + SPLIT=world_size > 1, + PRECOMPUTED_LSE=use_precomputed_lse, + num_warps=num_warps, + ) + + if world_size > 1: + # If there's no smoothing, if labels are in the vocab of this partition, losses contains + # - predicted logit, and 0 otherwise. + # If there's smoothing=0.1, for labels in the vocab of this partition, losses contains + # -0.9 * predicted logit - 0.1 * sum logit / total_classes. + # For labels not in the vocab of this partition, losses contains + # -0.1 * sum logit / total_classes. + if world_size > 1: + lse_allgather = torch.empty(world_size, n_rows, dtype=lse.dtype, device=lse.device) + torch.distributed.all_gather_into_tensor(lse_allgather, lse, group=process_group) + handle_losses = torch.distributed.all_reduce( + losses, op=torch.distributed.ReduceOp.SUM, group=process_group, async_op=True + ) + lse = torch.logsumexp(lse_allgather, dim=0) + handle_losses.wait() + # After the allreduce, if there's no smoothing, the total losses are - predicted_logit, + # we just have to add the (global) lse. + # If there's smoothing=0.1, the total losses are + # -0.9 * predicted_logit - 0.1 * sum logit / total_classes. + # Again, we just have to add the (global) lse. + losses += lse + if lse_square_scale != 0.0: + z_losses = lse_square_scale * lse.square() + z_losses.masked_fill_(labels == ignore_index, 0.0) + losses += z_losses + else: + z_losses = torch.zeros_like(losses) + losses.masked_fill_(labels == ignore_index, 0.0) + + ctx.save_for_backward(logits, lse, labels) + ctx.mark_non_differentiable(z_losses) + ctx.smoothing = smoothing + ctx.logit_scale = logit_scale + ctx.lse_square_scale = lse_square_scale + ctx.ignore_index = ignore_index + ctx.total_classes = total_classes + ctx.class_start_idx = class_start_idx + ctx.inplace_backward = inplace_backward + return losses, z_losses + + @staticmethod + def backward(ctx, grad_losses, grad_z_losses): + del grad_z_losses # z_losses are only for logging. + + logits, lse, labels = ctx.saved_tensors + dlogits = logits if ctx.inplace_backward else torch.empty_like(logits) + n_rows, n_cols = logits.shape + BLOCK_SIZE = min(triton.next_power_of_2(n_cols), 4 * 1024) + num_warps = 4 if BLOCK_SIZE < 2048 else (8 if BLOCK_SIZE < 8192 else 16) + grid = lambda META: (n_rows, triton.cdiv(n_cols, META["BLOCK_SIZE"])) # noqa + # Need this, otherwise Triton tries to launch from cuda:0 and we get + # ValueError: Pointer argument (at 0) cannot be accessed from Triton (cpu tensor?) + with torch.cuda.device(logits.device.index): + cross_entropy_bwd_kernel[grid]( + dlogits, # data ptrs + grad_losses, + logits, + lse, + labels, + ctx.smoothing, + ctx.logit_scale, + ctx.lse_square_scale, + ctx.ignore_index, + ctx.total_classes, + ctx.class_start_idx, + n_cols, # shapes + logits.stride(0), # strides + dlogits.stride(0), + grad_losses.stride(0), + BLOCK_SIZE=BLOCK_SIZE, # constants + num_warps=num_warps, + ) + return dlogits, None, None, None, None, None, None, None, None, None + + +def cross_entropy_loss( + logits: torch.Tensor, + labels: torch.Tensor, + precomputed_lse: Optional[torch.Tensor] = None, + label_smoothing: float = 0.0, + logit_scale: float = 1.0, + lse_square_scale: float = 0.0, + ignore_index=-100, + inplace_backward: bool = False, + process_group=None, +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Arguments: + logits: (batch, vocab_size) + labels: (batch,) + label_smoothing: float + logit_scale: float. Multiply logits by this scale before calculating the loss. + lse_square_scale: float. If > 0, we add lse_square_scale * lse(logits) ^ 2 to the loss. + This is also referred to as "z-loss". + ignore_index: int. If labels == ignore_index, the loss is set to 0.0. + inplace_backward: bool. If True, we do the backward pass in-place by modifying the logits. + This saves memory. + process_group: if not None, we're doing Tensor Parallel: each process is responsible for + one part of the vocab. The loss will be aggregated across processes. + Returns: + losses: (batch,), float + z_losses: (batch,), float + """ + return CrossEntropyLoss.apply( + logits, + labels, + precomputed_lse, + label_smoothing, + logit_scale, + lse_square_scale, + ignore_index, + inplace_backward, + process_group, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/k_activations.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/k_activations.py new file mode 100644 index 0000000000000000000000000000000000000000..efb83c358eb4a85d069ee340a3c83f418f9a805b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/k_activations.py @@ -0,0 +1,162 @@ +# Adapted from https://github.com/facebookresearch/xformers/blob/main/xformers/triton/k_activations.py +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import math +from enum import Enum +from typing import Optional + +import triton +import triton.language as tl + +_sqrt2pi = math.sqrt(2.0 / math.pi) +_sqrt1_2 = math.sqrt(1.0 / 2) +_gaussian_pdf_normalization = 1.0 / math.sqrt(2 * math.pi) + + +class Activation(str, Enum): + SquaredReLU = "squared_relu" + GeLU = "gelu" + GeLUApprox = "gelu_approx" + LeakyReLU = "leaky_relu" + ReLU = "relu" + + +def get_triton_activation_kernel(activation: Optional[Activation]): + return ( + { + Activation.ReLU: relu, + Activation.LeakyReLU: leaky_relu, + Activation.GeLU: gelu, + Activation.GeLUApprox: gelu_approx, + Activation.SquaredReLU: squared_relu, + }[activation] + if activation + else None + ) + + +def get_triton_activation_bwd_kernel(activation: Optional[Activation]): + return ( + { + Activation.ReLU: relu_grad, + Activation.LeakyReLU: leaky_relu_grad, + Activation.GeLU: gelu_grad, + Activation.GeLUApprox: gelu_approx_grad, + Activation.SquaredReLU: squared_relu_grad, + }[activation] + if activation + else None + ) + + +@triton.jit +def tanh(x): + # Tanh is just a scaled sigmoid + return 2 * tl.sigmoid(2 * x) - 1 + + +@triton.jit +def cosh(x): + exp_x = tl.exp(x) + return (exp_x + 1.0 / exp_x) * 0.5 + + +# a Triton implementation of the most used activations +# See for instance http://arxiv.org/abs/1606.08415 for an overview + +# ReLU +@triton.jit +def relu(x): + """ + ReLU_ activation function + + .. _ReLU: https://pytorch.org/docs/stable/generated/torch.nn.ReLU.html + """ + zero = 0.0 + return tl.where(x >= 0, x, zero.to(x.dtype)) + + +@triton.jit +def relu_grad(x): + # ReLU is different from other activations + # in that it does not require the input to retrospectively compute its gradient + # here the input is the downstream gradient, and we return the upstream gradient directly + zero = 0.0 + one = 1.0 + return tl.where(x >= 0, one.to(x.dtype), zero.to(x.dtype)) + + +@triton.jit +def squared_relu(x): + """ + Squared ReLU activation, as proposed in the Primer_ paper. + + .. _Primer: https://arxiv.org/abs/2109.08668 + """ + x_ = relu(x) + return (x_ * x_).to(x.dtype) + + +@triton.jit +def squared_relu_grad(x): + return tl.where(x >= 0, 2.0 * x, 0.0) + + +# Leaky ReLU +@triton.jit +def leaky_relu(x): + """ + LeakyReLU_ activation + + .. _LeakyReLU: https://pytorch.org/docs/stable/generated/torch.nn.LeakyReLU.html + """ + scale = 0.01 + 0.0 + scale = scale.to(x.dtype) + return tl.where(x >= 0, x, scale * x) + + +@triton.jit +def leaky_relu_grad(x): + min_grad = 0.01 + max_grad = 1 + + min_grad = min_grad.to(x.dtype) + max_grad = max_grad.to(x.dtype) + + return tl.where(x >= 0, max_grad, min_grad) + + +@triton.jit +def gelu(x): + """Gaussian Error Linear Unit (GELU)""" + return x * 0.5 * (1.0 + tl.libdevice.erf(x * _sqrt1_2)) + + +@triton.jit +def gelu_grad(x): + cdf = 0.5 * (1.0 + tl.libdevice.erf(x * _sqrt1_2)) + pdf = tl.exp(-0.5 * x * x) * _gaussian_pdf_normalization + return cdf + x * pdf + + +@triton.jit +def gelu_approx(x): + """ + GeLU_ activation - Gaussian error linear unit, with tanh approximation + + .. _GeLU: https://arxiv.org/pdf/1606.08415.pdf + """ + return 0.5 * x * (1.0 + tanh(_sqrt2pi * x * (1.0 + 0.044715 * x * x))) + + +@triton.jit +def gelu_approx_grad(x): + # CREDITS: Fast implementation proposed in + # https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/fused_bias_gelu.py#L30 + tanh_out = tanh(0.79788456 * x * (1 + 0.044715 * x * x)) + return 0.5 * x * ((1 - tanh_out * tanh_out) * (0.79788456 + 0.1070322243 * x * x)) + 0.5 * ( + 1 + tanh_out + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/layer_norm.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/layer_norm.py new file mode 100644 index 0000000000000000000000000000000000000000..192cee474b160d1876fafd14c5e3d695e8ff237f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/layer_norm.py @@ -0,0 +1,1252 @@ +# Copyright (c) 2024, Tri Dao. +# Implement dropout + residual + layer_norm / rms_norm. + +# Based on the Triton LayerNorm tutorial: https://triton-lang.org/main/getting-started/tutorials/05-layer-norm.html +# For the backward pass, we keep weight_grad and bias_grad in registers and accumulate. +# This is faster for dimensions up to 8k, but after that it's much slower due to register spilling. +# The models we train have hidden dim up to 8k anyway (e.g. Llama 70B), so this is fine. + +import math +from typing import Optional, List + +import torch +import torch.nn.functional as F +from torch import Tensor + +import triton +import triton.language as tl + +from flash_attn.utils.torch import custom_fwd, custom_bwd +from flash_attn.utils.library import triton_op + + +def maybe_contiguous_lastdim(x): + return x.contiguous() if x is not None and x.stride(-1) != 1 else x + + +def maybe_contiguous(x): + return x.contiguous() if x is not None else None + + +def triton_autotune_configs(): + # Return configs with a valid warp count for the current device + configs = [] + # Maximum threads per block is architecture-dependent in theory, but in reality all are 1024 + max_threads_per_block = 1024 + # Default to warp size 32 if not defined by device + warp_size = getattr(torch.cuda.get_device_properties(torch.cuda.current_device()), "warp_size", 32) + # Autotune for warp counts which are powers of 2 and do not exceed thread per block limit + return [triton.Config({}, num_warps=warp_count) for warp_count in [1, 2, 4, 8, 16, 32] + if warp_count * warp_size <= max_threads_per_block] + # return [triton.Config({}, num_warps=8)] + + +def layer_norm_ref( + x, + weight, + bias, + residual=None, + x1=None, + weight1=None, + bias1=None, + eps=1e-6, + dropout_p=0.0, + rowscale=None, + prenorm=False, + zero_centered_weight=False, + dropout_mask=None, + dropout_mask1=None, + upcast=False, +): + dtype = x.dtype + if upcast: + x = x.float() + weight = weight.float() + bias = bias.float() if bias is not None else None + residual = residual.float() if residual is not None else residual + x1 = x1.float() if x1 is not None else None + weight1 = weight1.float() if weight1 is not None else None + bias1 = bias1.float() if bias1 is not None else None + if zero_centered_weight: + weight = weight + 1.0 + if weight1 is not None: + weight1 = weight1 + 1.0 + if x1 is not None: + assert rowscale is None, "rowscale is not supported with parallel LayerNorm" + if rowscale is not None: + x = x * rowscale[..., None] + if dropout_p > 0.0: + if dropout_mask is not None: + x = x.masked_fill(~dropout_mask, 0.0) / (1.0 - dropout_p) + else: + x = F.dropout(x, p=dropout_p) + if x1 is not None: + if dropout_mask1 is not None: + x1 = x1.masked_fill(~dropout_mask1, 0.0) / (1.0 - dropout_p) + else: + x1 = F.dropout(x1, p=dropout_p) + if x1 is not None: + x = x + x1 + if residual is not None: + x = (x + residual).to(x.dtype) + out = F.layer_norm(x.to(weight.dtype), x.shape[-1:], weight=weight, bias=bias, eps=eps).to( + dtype + ) + if weight1 is None: + return out if not prenorm else (out, x) + else: + out1 = F.layer_norm( + x.to(weight1.dtype), x.shape[-1:], weight=weight1, bias=bias1, eps=eps + ).to(dtype) + return (out, out1) if not prenorm else (out, out1, x) + + +def rms_norm_ref( + x, + weight, + bias, + residual=None, + x1=None, + weight1=None, + bias1=None, + eps=1e-6, + dropout_p=0.0, + rowscale=None, + prenorm=False, + zero_centered_weight=False, + dropout_mask=None, + dropout_mask1=None, + upcast=False, +): + dtype = x.dtype + if upcast: + x = x.float() + weight = weight.float() + bias = bias.float() if bias is not None else None + residual = residual.float() if residual is not None else residual + x1 = x1.float() if x1 is not None else None + weight1 = weight1.float() if weight1 is not None else None + bias1 = bias1.float() if bias1 is not None else None + if zero_centered_weight: + weight = weight + 1.0 + if weight1 is not None: + weight1 = weight1 + 1.0 + if x1 is not None: + assert rowscale is None, "rowscale is not supported with parallel LayerNorm" + if rowscale is not None: + x = x * rowscale[..., None] + if dropout_p > 0.0: + if dropout_mask is not None: + x = x.masked_fill(~dropout_mask, 0.0) / (1.0 - dropout_p) + else: + x = F.dropout(x, p=dropout_p) + if x1 is not None: + if dropout_mask1 is not None: + x1 = x1.masked_fill(~dropout_mask1, 0.0) / (1.0 - dropout_p) + else: + x1 = F.dropout(x1, p=dropout_p) + if x1 is not None: + x = x + x1 + if residual is not None: + x = (x + residual).to(x.dtype) + rstd = 1 / torch.sqrt((x.square()).mean(dim=-1, keepdim=True) + eps) + out = ((x * rstd * weight) + bias if bias is not None else (x * rstd * weight)).to(dtype) + if weight1 is None: + return out if not prenorm else (out, x) + else: + out1 = ((x * rstd * weight1) + bias1 if bias1 is not None else (x * rstd * weight1)).to( + dtype + ) + return (out, out1) if not prenorm else (out, out1, x) + + +@triton.autotune( + configs=triton_autotune_configs(), + key=["N", "HAS_RESIDUAL", "STORE_RESIDUAL_OUT", "IS_RMS_NORM", "HAS_BIAS", "HAS_X1", "HAS_W1", "HAS_B1"], +) +# torch compile doesn't like triton.heuristics, so we set these manually when calling the kernel +# @triton.heuristics({"HAS_BIAS": lambda args: args["B"] is not None}) +# @triton.heuristics({"HAS_RESIDUAL": lambda args: args["RESIDUAL"] is not None}) +# @triton.heuristics({"HAS_X1": lambda args: args["X1"] is not None}) +# @triton.heuristics({"HAS_W1": lambda args: args["W1"] is not None}) +# @triton.heuristics({"HAS_B1": lambda args: args["B1"] is not None}) +@triton.jit +def _layer_norm_fwd_1pass_kernel( + X, # pointer to the input + Y, # pointer to the output + W, # pointer to the weights + B, # pointer to the biases + RESIDUAL, # pointer to the residual + X1, + W1, + B1, + Y1, + RESIDUAL_OUT, # pointer to the residual + ROWSCALE, + SEEDS, # Dropout seeds for each row + DROPOUT_MASK, + DROPOUT_MASK1, + Mean, # pointer to the mean + Rstd, # pointer to the 1/std + stride_x_row, # how much to increase the pointer when moving by 1 row + stride_y_row, + stride_res_row, + stride_res_out_row, + stride_x1_row, + stride_y1_row, + M, # number of rows in X + N, # number of columns in X + eps, # epsilon to avoid division by zero + dropout_p, # Dropout probability + zero_centered_weight, # If true, add 1.0 to the weight + IS_RMS_NORM: tl.constexpr, + BLOCK_N: tl.constexpr, + HAS_RESIDUAL: tl.constexpr, + STORE_RESIDUAL_OUT: tl.constexpr, + HAS_BIAS: tl.constexpr, + HAS_DROPOUT: tl.constexpr, + STORE_DROPOUT_MASK: tl.constexpr, + HAS_ROWSCALE: tl.constexpr, + HAS_X1: tl.constexpr, + HAS_W1: tl.constexpr, + HAS_B1: tl.constexpr, +): + # Map the program id to the row of X and Y it should compute. + row = tl.program_id(0) + X += row * stride_x_row + Y += row * stride_y_row + if HAS_RESIDUAL: + RESIDUAL += row * stride_res_row + if STORE_RESIDUAL_OUT: + RESIDUAL_OUT += row * stride_res_out_row + if HAS_X1: + X1 += row * stride_x1_row + if HAS_W1: + Y1 += row * stride_y1_row + # Compute mean and variance + cols = tl.arange(0, BLOCK_N) + x = tl.load(X + cols, mask=cols < N, other=0.0).to(tl.float32) + if HAS_ROWSCALE: + rowscale = tl.load(ROWSCALE + row).to(tl.float32) + x *= rowscale + if HAS_DROPOUT: + # Compute dropout mask + # 7 rounds is good enough, and reduces register pressure + keep_mask = tl.rand(tl.load(SEEDS + row).to(tl.uint32), cols, n_rounds=7) > dropout_p + x = tl.where(keep_mask, x / (1.0 - dropout_p), 0.0) + if STORE_DROPOUT_MASK: + tl.store(DROPOUT_MASK + row * N + cols, keep_mask, mask=cols < N) + if HAS_X1: + x1 = tl.load(X1 + cols, mask=cols < N, other=0.0).to(tl.float32) + if HAS_ROWSCALE: + rowscale = tl.load(ROWSCALE + M + row).to(tl.float32) + x1 *= rowscale + if HAS_DROPOUT: + # Compute dropout mask + # 7 rounds is good enough, and reduces register pressure + keep_mask = ( + tl.rand(tl.load(SEEDS + M + row).to(tl.uint32), cols, n_rounds=7) > dropout_p + ) + x1 = tl.where(keep_mask, x1 / (1.0 - dropout_p), 0.0) + if STORE_DROPOUT_MASK: + tl.store(DROPOUT_MASK1 + row * N + cols, keep_mask, mask=cols < N) + x += x1 + if HAS_RESIDUAL: + residual = tl.load(RESIDUAL + cols, mask=cols < N, other=0.0).to(tl.float32) + x += residual + if STORE_RESIDUAL_OUT: + tl.store(RESIDUAL_OUT + cols, x, mask=cols < N) + if not IS_RMS_NORM: + mean = tl.sum(x, axis=0) / N + tl.store(Mean + row, mean) + xbar = tl.where(cols < N, x - mean, 0.0) + var = tl.sum(xbar * xbar, axis=0) / N + else: + xbar = tl.where(cols < N, x, 0.0) + var = tl.sum(xbar * xbar, axis=0) / N + rstd = 1 / tl.sqrt(var + eps) + tl.store(Rstd + row, rstd) + # Normalize and apply linear transformation + mask = cols < N + w = tl.load(W + cols, mask=mask).to(tl.float32) + if zero_centered_weight: + w += 1.0 + if HAS_BIAS: + b = tl.load(B + cols, mask=mask).to(tl.float32) + x_hat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd + y = x_hat * w + b if HAS_BIAS else x_hat * w + # Write output + tl.store(Y + cols, y, mask=mask) + if HAS_W1: + w1 = tl.load(W1 + cols, mask=mask).to(tl.float32) + if zero_centered_weight: + w1 += 1.0 + if HAS_B1: + b1 = tl.load(B1 + cols, mask=mask).to(tl.float32) + y1 = x_hat * w1 + b1 if HAS_B1 else x_hat * w1 + tl.store(Y1 + cols, y1, mask=mask) + + +def _layer_norm_fwd( + x: Tensor, + weight: Tensor, + bias: Tensor, + eps: float, + residual: Optional[Tensor] = None, + x1: Optional[Tensor] = None, + weight1: Optional[Tensor] = None, + bias1: Optional[Tensor] = None, + dropout_p: float = 0.0, + rowscale: Optional[Tensor] = None, + out_dtype: Optional[torch.dtype] = None, + residual_dtype: Optional[torch.dtype] = None, + zero_centered_weight: bool = False, + is_rms_norm: bool = False, + return_dropout_mask: bool = False, + out: Optional[Tensor] = None, + residual_out: Optional[Tensor] = None +) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor): + # Need to wrap to handle the case where residual_out is a alias of x, which makes torch.library + # and torch.compile unhappy. Also allocate memory for out and residual_out if they are None + # so that _layer_norm_fwd_impl doesn't have to return them. + if out is None: + out = torch.empty_like(x, dtype=x.dtype if out_dtype is None else out_dtype) + if residual is not None: + residual_dtype = residual.dtype + if residual_out is None and ( + residual is not None + or (residual_dtype is not None and residual_dtype != x.dtype) + or dropout_p > 0.0 + or rowscale is not None + or x1 is not None + ): + residual_out = torch.empty_like( + x, dtype=residual_dtype if residual_dtype is not None else x.dtype + ) + else: + residual_out = None + y1, mean, rstd, seeds, dropout_mask, dropout_mask1 = _layer_norm_fwd_impl( + x, + weight, + bias, + eps, + out, + residual=residual, + x1=x1, + weight1=weight1, + bias1=bias1, + dropout_p=dropout_p, + rowscale=rowscale, + zero_centered_weight=zero_centered_weight, + is_rms_norm=is_rms_norm, + return_dropout_mask=return_dropout_mask, + residual_out=residual_out, + ) + # residual_out is None if residual is None and residual_dtype == input_dtype and dropout_p == 0.0 + if residual_out is None: + residual_out = x + return out, y1, mean, rstd, residual_out, seeds, dropout_mask, dropout_mask1 + + +# [2025-04-28] torch.library.triton_op ignores the schema argument, but here we need the schema +# since we're returning a tuple of tensors +@triton_op("flash_attn::layer_norm_fwd_impl", mutates_args={"out", "residual_out"}, + schema="(Tensor x, Tensor weight, Tensor bias, float eps, Tensor(a!) out, Tensor? residual, Tensor? x1, Tensor? weight1, Tensor? bias1, float dropout_p, Tensor? rowscale, bool zero_centered_weight, bool is_rms_norm, bool return_dropout_mask, Tensor(a!)? residual_out) -> (Tensor y1, Tensor mean, Tensor rstd, Tensor seeds, Tensor dropout_mask, Tensor dropout_mask1)") +def _layer_norm_fwd_impl( + x: Tensor, + weight: Tensor, + bias: Tensor, + eps: float, + out: Tensor, + residual: Optional[Tensor] = None, + x1: Optional[Tensor] = None, + weight1: Optional[Tensor] = None, + bias1: Optional[Tensor] = None, + dropout_p: float = 0.0, + rowscale: Optional[Tensor] = None, + zero_centered_weight: bool = False, + is_rms_norm: bool = False, + return_dropout_mask: bool = False, + residual_out: Optional[Tensor] = None +) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor): + M, N = x.shape + assert x.stride(-1) == 1 + if residual is not None: + assert residual.stride(-1) == 1 + assert residual.shape == (M, N) + assert weight.shape == (N,) + assert weight.stride(-1) == 1 + if bias is not None: + assert bias.stride(-1) == 1 + assert bias.shape == (N,) + if x1 is not None: + assert x1.shape == x.shape + assert rowscale is None + assert x1.stride(-1) == 1 + if weight1 is not None: + assert weight1.shape == (N,) + assert weight1.stride(-1) == 1 + if bias1 is not None: + assert bias1.shape == (N,) + assert bias1.stride(-1) == 1 + if rowscale is not None: + assert rowscale.is_contiguous() + assert rowscale.shape == (M,) + assert out.shape == x.shape + assert out.stride(-1) == 1 + if residual_out is not None: + assert residual_out.shape == x.shape + assert residual_out.stride(-1) == 1 + if weight1 is not None: + y1 = torch.empty_like(out) + assert y1.stride(-1) == 1 + else: + y1 = None + mean = torch.empty((M,), dtype=torch.float32, device=x.device) if not is_rms_norm else None + rstd = torch.empty((M,), dtype=torch.float32, device=x.device) + if dropout_p > 0.0: + seeds = torch.randint( + 2**32, (M if x1 is None else 2 * M,), device=x.device, dtype=torch.int64 + ) + else: + seeds = None + if return_dropout_mask and dropout_p > 0.0: + dropout_mask = torch.empty(M, N, device=x.device, dtype=torch.bool) + if x1 is not None: + dropout_mask1 = torch.empty(M, N, device=x.device, dtype=torch.bool) + else: + dropout_mask1 = None + else: + dropout_mask, dropout_mask1 = None, None + # Less than 64KB per feature: enqueue fused kernel + MAX_FUSED_SIZE = 65536 // x.element_size() + BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N)) + if N > BLOCK_N: + raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.") + with torch.cuda.device(x.device.index): + torch.library.wrap_triton(_layer_norm_fwd_1pass_kernel)[(M,)]( + x, + out, + weight, + bias, + residual, + x1, + weight1, + bias1, + y1, + residual_out, + rowscale, + seeds, + dropout_mask, + dropout_mask1, + mean, + rstd, + x.stride(0), + out.stride(0), + residual.stride(0) if residual is not None else 0, + residual_out.stride(0) if residual_out is not None else 0, + x1.stride(0) if x1 is not None else 0, + y1.stride(0) if y1 is not None else 0, + M, + N, + eps, + dropout_p, + # Passing bool make torch inductor very unhappy since it then tries to compare to int_max + int(zero_centered_weight), + is_rms_norm, + BLOCK_N, + residual is not None, + residual_out is not None, + bias is not None, + dropout_p > 0.0, + dropout_mask is not None, + rowscale is not None, + HAS_X1=x1 is not None, + HAS_W1=weight1 is not None, + HAS_B1=bias1 is not None, + ) + return y1, mean, rstd, seeds, dropout_mask, dropout_mask1 + + +@triton.autotune( + configs=triton_autotune_configs(), + key=["N", "HAS_DRESIDUAL", "STORE_DRESIDUAL", "IS_RMS_NORM", "HAS_BIAS", "HAS_DROPOUT"], +) +# torch compile doesn't like triton.heuristics, so we set these manually when calling the kernel +# @triton.heuristics({"HAS_BIAS": lambda args: args["B"] is not None}) +# @triton.heuristics({"HAS_DRESIDUAL": lambda args: args["DRESIDUAL"] is not None}) +# @triton.heuristics({"STORE_DRESIDUAL": lambda args: args["DRESIDUAL_IN"] is not None}) +# @triton.heuristics({"HAS_ROWSCALE": lambda args: args["ROWSCALE"] is not None}) +# @triton.heuristics({"HAS_DY1": lambda args: args["DY1"] is not None}) +# @triton.heuristics({"HAS_DX1": lambda args: args["DX1"] is not None}) +# @triton.heuristics({"HAS_B1": lambda args: args["DB1"] is not None}) +# @triton.heuristics({"RECOMPUTE_OUTPUT": lambda args: args["Y"] is not None}) +@triton.jit +def _layer_norm_bwd_kernel( + X, # pointer to the input + W, # pointer to the weights + B, # pointer to the biases + Y, # pointer to the output to be recomputed + DY, # pointer to the output gradient + DX, # pointer to the input gradient + DW, # pointer to the partial sum of weights gradient + DB, # pointer to the partial sum of biases gradient + DRESIDUAL, + W1, + DY1, + DX1, + DW1, + DB1, + DRESIDUAL_IN, + ROWSCALE, + SEEDS, + Mean, # pointer to the mean + Rstd, # pointer to the 1/std + stride_x_row, # how much to increase the pointer when moving by 1 row + stride_y_row, + stride_dy_row, + stride_dx_row, + stride_dres_row, + stride_dy1_row, + stride_dx1_row, + stride_dres_in_row, + M, # number of rows in X + N, # number of columns in X + eps, # epsilon to avoid division by zero + dropout_p, + zero_centered_weight, + rows_per_program, + IS_RMS_NORM: tl.constexpr, + BLOCK_N: tl.constexpr, + HAS_DRESIDUAL: tl.constexpr, + STORE_DRESIDUAL: tl.constexpr, + HAS_BIAS: tl.constexpr, + HAS_DROPOUT: tl.constexpr, + HAS_ROWSCALE: tl.constexpr, + HAS_DY1: tl.constexpr, + HAS_DX1: tl.constexpr, + HAS_B1: tl.constexpr, + RECOMPUTE_OUTPUT: tl.constexpr, +): + # Map the program id to the elements of X, DX, and DY it should compute. + row_block_id = tl.program_id(0) + row_start = row_block_id * rows_per_program + # Do not early exit if row_start >= M, because we need to write DW and DB + cols = tl.arange(0, BLOCK_N) + mask = cols < N + X += row_start * stride_x_row + if HAS_DRESIDUAL: + DRESIDUAL += row_start * stride_dres_row + if STORE_DRESIDUAL: + DRESIDUAL_IN += row_start * stride_dres_in_row + DY += row_start * stride_dy_row + DX += row_start * stride_dx_row + if HAS_DY1: + DY1 += row_start * stride_dy1_row + if HAS_DX1: + DX1 += row_start * stride_dx1_row + if RECOMPUTE_OUTPUT: + Y += row_start * stride_y_row + w = tl.load(W + cols, mask=mask).to(tl.float32) + if zero_centered_weight: + w += 1.0 + if RECOMPUTE_OUTPUT and HAS_BIAS: + b = tl.load(B + cols, mask=mask, other=0.0).to(tl.float32) + if HAS_DY1: + w1 = tl.load(W1 + cols, mask=mask).to(tl.float32) + if zero_centered_weight: + w1 += 1.0 + dw = tl.zeros((BLOCK_N,), dtype=tl.float32) + if HAS_BIAS: + db = tl.zeros((BLOCK_N,), dtype=tl.float32) + if HAS_DY1: + dw1 = tl.zeros((BLOCK_N,), dtype=tl.float32) + if HAS_B1: + db1 = tl.zeros((BLOCK_N,), dtype=tl.float32) + row_end = min((row_block_id + 1) * rows_per_program, M) + for row in range(row_start, row_end): + # Load data to SRAM + x = tl.load(X + cols, mask=mask, other=0).to(tl.float32) + dy = tl.load(DY + cols, mask=mask, other=0).to(tl.float32) + if HAS_DY1: + dy1 = tl.load(DY1 + cols, mask=mask, other=0).to(tl.float32) + if not IS_RMS_NORM: + mean = tl.load(Mean + row) + rstd = tl.load(Rstd + row) + # Compute dx + xhat = (x - mean) * rstd if not IS_RMS_NORM else x * rstd + xhat = tl.where(mask, xhat, 0.0) + if RECOMPUTE_OUTPUT: + y = xhat * w + b if HAS_BIAS else xhat * w + tl.store(Y + cols, y, mask=mask) + wdy = w * dy + dw += dy * xhat + if HAS_BIAS: + db += dy + if HAS_DY1: + wdy += w1 * dy1 + dw1 += dy1 * xhat + if HAS_B1: + db1 += dy1 + if not IS_RMS_NORM: + c1 = tl.sum(xhat * wdy, axis=0) / N + c2 = tl.sum(wdy, axis=0) / N + dx = (wdy - (xhat * c1 + c2)) * rstd + else: + c1 = tl.sum(xhat * wdy, axis=0) / N + dx = (wdy - xhat * c1) * rstd + if HAS_DRESIDUAL: + dres = tl.load(DRESIDUAL + cols, mask=mask, other=0).to(tl.float32) + dx += dres + # Write dx + if STORE_DRESIDUAL: + tl.store(DRESIDUAL_IN + cols, dx, mask=mask) + if HAS_DX1: + if HAS_DROPOUT: + keep_mask = ( + tl.rand(tl.load(SEEDS + M + row).to(tl.uint32), cols, n_rounds=7) > dropout_p + ) + dx1 = tl.where(keep_mask, dx / (1.0 - dropout_p), 0.0) + else: + dx1 = dx + tl.store(DX1 + cols, dx1, mask=mask) + if HAS_DROPOUT: + keep_mask = tl.rand(tl.load(SEEDS + row).to(tl.uint32), cols, n_rounds=7) > dropout_p + dx = tl.where(keep_mask, dx / (1.0 - dropout_p), 0.0) + if HAS_ROWSCALE: + rowscale = tl.load(ROWSCALE + row).to(tl.float32) + dx *= rowscale + tl.store(DX + cols, dx, mask=mask) + + X += stride_x_row + if HAS_DRESIDUAL: + DRESIDUAL += stride_dres_row + if STORE_DRESIDUAL: + DRESIDUAL_IN += stride_dres_in_row + if RECOMPUTE_OUTPUT: + Y += stride_y_row + DY += stride_dy_row + DX += stride_dx_row + if HAS_DY1: + DY1 += stride_dy1_row + if HAS_DX1: + DX1 += stride_dx1_row + tl.store(DW + row_block_id * N + cols, dw, mask=mask) + if HAS_BIAS: + tl.store(DB + row_block_id * N + cols, db, mask=mask) + if HAS_DY1: + tl.store(DW1 + row_block_id * N + cols, dw1, mask=mask) + if HAS_B1: + tl.store(DB1 + row_block_id * N + cols, db1, mask=mask) + + +def _layer_norm_bwd( + dy: Tensor, + x: Tensor, + weight: Tensor, + bias: Tensor, + eps: float, + mean: Tensor, + rstd: Tensor, + dresidual: Optional[Tensor] = None, + dy1: Optional[Tensor] = None, + weight1: Optional[Tensor] = None, + bias1: Optional[Tensor] = None, + seeds: Optional[Tensor] = None, + dropout_p: float = 0.0, + rowscale: Optional[Tensor] = None, + has_residual: bool = False, + has_x1: bool = False, + zero_centered_weight: bool = False, + is_rms_norm: bool = False, + x_dtype: Optional[torch.dtype] = None, + recompute_output: bool = False, +) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor): + # Need to wrap to handle the case where dresidual_in or dx1 are aliases of x, + # which makes torch.library unhappy + dx, dw, db, dresidual_in, dx1, dw1, db1, y = _layer_norm_bwd_impl( + dy, + x, + weight, + bias, + eps, + mean, + rstd, + dresidual, + dy1, + weight1, + bias1, + seeds, + dropout_p, + rowscale, + has_residual, + has_x1, + zero_centered_weight, + is_rms_norm, + x_dtype=x_dtype, + recompute_output=recompute_output, + ) + # Don't need to compute dresidual_in separately in this case + if has_residual and dx.dtype == x.dtype and dropout_p == 0.0 and rowscale is None: + dresidual_in = dx + if has_x1 and dropout_p == 0.0: + dx1 = dx + return dx, dw, db, dresidual_in, dx1, dw1, db1, y + + + +@triton_op("flash_attn::layer_norm_bwd_impl", mutates_args={}, + schema="(Tensor dy, Tensor x, Tensor weight, Tensor bias, float eps, Tensor mean, Tensor rstd, Tensor? dresidual, Tensor? dy1, Tensor? weight1, Tensor? bias1, Tensor? seeds, float dropout_p, Tensor? rowscale, bool has_residual, bool has_x1, bool zero_centered_weight, bool is_rms_norm, ScalarType? x_dtype, bool recompute_output) -> (Tensor dx, Tensor dw, Tensor db, Tensor dresidual_in, Tensor dx1, Tensor dw1, Tensor db1, Tensor y)", + allow_decomposition=False, # Don't let torch.compile trace inside + ) +def _layer_norm_bwd_impl( + dy: Tensor, + x: Tensor, + weight: Tensor, + bias: Tensor, + eps: float, + mean: Tensor, + rstd: Tensor, + dresidual: Optional[Tensor] = None, + dy1: Optional[Tensor] = None, + weight1: Optional[Tensor] = None, + bias1: Optional[Tensor] = None, + seeds: Optional[Tensor] = None, + dropout_p: float = 0.0, + rowscale: Optional[Tensor] = None, + has_residual: bool = False, + has_x1: bool = False, + zero_centered_weight: bool = False, + is_rms_norm: bool = False, + x_dtype: Optional[torch.dtype] = None, + recompute_output: bool = False, +) -> (Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor): + M, N = x.shape + assert x.stride(-1) == 1 + dy = maybe_contiguous_lastdim(dy) + assert dy.stride(-1) == 1 + assert dy.shape == (M, N) + if dresidual is not None: + dresidual = maybe_contiguous_lastdim(dresidual) + assert dresidual.stride(-1) == 1 + assert dresidual.shape == (M, N) + assert weight.shape == (N,) + assert weight.stride(-1) == 1 + if bias is not None: + assert bias.stride(-1) == 1 + assert bias.shape == (N,) + if dy1 is not None: + dy1 = maybe_contiguous_lastdim(dy1) + assert weight1 is not None + assert dy1.shape == dy.shape + assert dy1.stride(-1) == 1 + if weight1 is not None: + assert weight1.shape == (N,) + assert weight1.stride(-1) == 1 + if bias1 is not None: + assert bias1.shape == (N,) + assert bias1.stride(-1) == 1 + if seeds is not None: + assert seeds.is_contiguous() + assert seeds.shape == (M if not has_x1 else M * 2,) + if rowscale is not None: + assert rowscale.is_contiguous() + assert rowscale.shape == (M,) + # allocate output + dx = ( + torch.empty_like(x) + if x_dtype is None + else torch.empty(M, N, dtype=x_dtype, device=x.device) + ) + dresidual_in = ( + torch.empty_like(x) + if has_residual + and (dx.dtype != x.dtype or dropout_p > 0.0 or rowscale is not None or has_x1) + else None + ) + dx1 = torch.empty_like(dx) if (has_x1 and dropout_p > 0.0) else None + y = torch.empty(M, N, dtype=dy.dtype, device=dy.device) if recompute_output else None + if recompute_output: + assert weight1 is None, "recompute_output is not supported with parallel LayerNorm" + + # Less than 64KB per feature: enqueue fused kernel + MAX_FUSED_SIZE = 65536 // x.element_size() + BLOCK_N = min(MAX_FUSED_SIZE, triton.next_power_of_2(N)) + if N > BLOCK_N: + raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.") + # Increasing the multiple (e.g. 8) will allow more thread blocks to be launched and hide the + # latency of the gmem reads/writes, but will increase the time of summing up dw / db. + sm_count = torch.cuda.get_device_properties(x.device).multi_processor_count * 8 + _dw = torch.empty((sm_count, N), dtype=torch.float32, device=weight.device) + _db = ( + torch.empty((sm_count, N), dtype=torch.float32, device=bias.device) + if bias is not None + else None + ) + _dw1 = torch.empty_like(_dw) if weight1 is not None else None + _db1 = torch.empty_like(_db) if bias1 is not None else None + rows_per_program = math.ceil(M / sm_count) + grid = (sm_count,) + with torch.cuda.device(x.device.index): + torch.library.wrap_triton(_layer_norm_bwd_kernel)[grid]( + x, + weight, + bias, + y, + dy, + dx, + _dw, + _db, + dresidual, + weight1, + dy1, + dx1, + _dw1, + _db1, + dresidual_in, + rowscale, + seeds, + mean, + rstd, + x.stride(0), + 0 if not recompute_output else y.stride(0), + dy.stride(0), + dx.stride(0), + dresidual.stride(0) if dresidual is not None else 0, + dy1.stride(0) if dy1 is not None else 0, + dx1.stride(0) if dx1 is not None else 0, + dresidual_in.stride(0) if dresidual_in is not None else 0, + M, + N, + eps, + dropout_p, + # Passing bool make torch inductor very unhappy since it then tries to compare to int_max + int(zero_centered_weight), + rows_per_program, + is_rms_norm, + BLOCK_N, + dresidual is not None, + dresidual_in is not None, + bias is not None, + dropout_p > 0.0, + HAS_ROWSCALE=rowscale is not None, + HAS_DY1=dy1 is not None, + HAS_DX1=dx1 is not None, + HAS_B1=bias1 is not None, + RECOMPUTE_OUTPUT=y is not None, + ) + dw = _dw.sum(0).to(weight.dtype) + db = _db.sum(0).to(bias.dtype) if bias is not None else None + dw1 = _dw1.sum(0).to(weight1.dtype) if weight1 is not None else None + db1 = _db1.sum(0).to(bias1.dtype) if bias1 is not None else None + # dresidual_in and dx1 could be None, the wrapper will handle assigning them from dx + return dx, dw, db, dresidual_in, dx1, dw1, db1, y + + +class LayerNormFn(torch.autograd.Function): + + @staticmethod + def forward( + ctx, + x, + weight, + bias, + residual=None, + x1=None, + weight1=None, + bias1=None, + eps=1e-6, + dropout_p=0.0, + rowscale=None, + prenorm=False, + residual_in_fp32=False, + zero_centered_weight=False, + is_rms_norm=False, + return_dropout_mask=False, + out_dtype=None, + out=None, + residual_out=None + ): + x_shape_og = x.shape + # reshape input data into 2D tensor + x = maybe_contiguous_lastdim(x.reshape(-1, x.shape[-1])) + if residual is not None: + assert residual.shape == x_shape_og + residual = maybe_contiguous_lastdim(residual.reshape(-1, residual.shape[-1])) + if x1 is not None: + assert x1.shape == x_shape_og + assert rowscale is None, "rowscale is not supported with parallel LayerNorm" + x1 = maybe_contiguous_lastdim(x1.reshape(-1, x1.shape[-1])) + weight = weight.contiguous() + bias = maybe_contiguous(bias) + weight1 = maybe_contiguous(weight1) + bias1 = maybe_contiguous(bias1) + if rowscale is not None: + rowscale = rowscale.reshape(-1).contiguous() + residual_dtype = ( + residual.dtype + if residual is not None + else (torch.float32 if residual_in_fp32 else None) + ) + if out is not None: + out = out.reshape(-1, out.shape[-1]) + if residual_out is not None: + residual_out = residual_out.reshape(-1, residual_out.shape[-1]) + y, y1, mean, rstd, residual_out, seeds, dropout_mask, dropout_mask1 = _layer_norm_fwd( + x, + weight, + bias, + eps, + residual, + x1, + weight1, + bias1, + dropout_p=dropout_p, + rowscale=rowscale, + out_dtype=out_dtype, + residual_dtype=residual_dtype, + zero_centered_weight=zero_centered_weight, + is_rms_norm=is_rms_norm, + return_dropout_mask=return_dropout_mask, + out=out, + residual_out=residual_out, + ) + ctx.save_for_backward( + residual_out, weight, bias, weight1, bias1, rowscale, seeds, mean, rstd + ) + ctx.x_shape_og = x_shape_og + ctx.eps = eps + ctx.dropout_p = dropout_p + ctx.is_rms_norm = is_rms_norm + ctx.has_residual = residual is not None + ctx.has_x1 = x1 is not None + ctx.prenorm = prenorm + ctx.x_dtype = x.dtype + ctx.zero_centered_weight = zero_centered_weight + y = y.reshape(x_shape_og) + y1 = y1.reshape(x_shape_og) if y1 is not None else None + residual_out = residual_out.reshape(x_shape_og) if residual_out is not None else None + dropout_mask = dropout_mask.reshape(x_shape_og) if dropout_mask is not None else None + dropout_mask1 = dropout_mask1.reshape(x_shape_og) if dropout_mask1 is not None else None + if not return_dropout_mask: + if weight1 is None: + return y if not prenorm else (y, residual_out) + else: + return (y, y1) if not prenorm else (y, y1, residual_out) + else: + if weight1 is None: + return ( + (y, dropout_mask, dropout_mask1) + if not prenorm + else (y, residual_out, dropout_mask, dropout_mask1) + ) + else: + return ( + (y, y1, dropout_mask, dropout_mask1) + if not prenorm + else (y, y1, residual_out, dropout_mask, dropout_mask1) + ) + + @staticmethod + def backward(ctx, dy, *args): + x, weight, bias, weight1, bias1, rowscale, seeds, mean, rstd = ctx.saved_tensors + dy = dy.reshape(-1, dy.shape[-1]) + if weight1 is not None: + dy1, args = args[0], args[1:] + dy1 = dy1.reshape(-1, dy1.shape[-1]) + assert dy1.shape == x.shape + else: + dy1 = None + if ctx.prenorm: + dresidual = args[0] + dresidual = dresidual.reshape(-1, dresidual.shape[-1]) + assert dresidual.shape == x.shape + else: + dresidual = None + dx, dw, db, dresidual_in, dx1, dw1, db1, _ = _layer_norm_bwd( + dy, + x, + weight, + bias, + ctx.eps, + mean, + rstd, + dresidual, + dy1, + weight1, + bias1, + seeds, + ctx.dropout_p, + rowscale, + ctx.has_residual, + ctx.has_x1, + ctx.zero_centered_weight, + ctx.is_rms_norm, + x_dtype=ctx.x_dtype, + recompute_output=False, + ) + return ( + dx.reshape(ctx.x_shape_og), + dw, + db, + dresidual_in.reshape(ctx.x_shape_og) if ctx.has_residual else None, + dx1.reshape(ctx.x_shape_og) if dx1 is not None else None, + dw1, + db1, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + None, + ) + + +def layer_norm_fn( + x, + weight, + bias, + residual=None, + x1=None, + weight1=None, + bias1=None, + eps=1e-6, + dropout_p=0.0, + rowscale=None, + prenorm=False, + residual_in_fp32=False, + zero_centered_weight=False, + is_rms_norm=False, + return_dropout_mask=False, + out_dtype=None, + out=None, + residual_out=None +): + return LayerNormFn.apply( + x, + weight, + bias, + residual, + x1, + weight1, + bias1, + eps, + dropout_p, + rowscale, + prenorm, + residual_in_fp32, + zero_centered_weight, + is_rms_norm, + return_dropout_mask, + out_dtype, + out, + residual_out + ) + + +def rms_norm_fn( + x, + weight, + bias, + residual=None, + x1=None, + weight1=None, + bias1=None, + eps=1e-6, + dropout_p=0.0, + rowscale=None, + prenorm=False, + residual_in_fp32=False, + zero_centered_weight=False, + return_dropout_mask=False, + out_dtype=None, + out=None, + residual_out=None +): + return LayerNormFn.apply( + x, + weight, + bias, + residual, + x1, + weight1, + bias1, + eps, + dropout_p, + rowscale, + prenorm, + residual_in_fp32, + zero_centered_weight, + True, + return_dropout_mask, + out_dtype, + out, + residual_out + ) + + +class RMSNorm(torch.nn.Module): + + def __init__(self, hidden_size, eps=1e-5, dropout_p=0.0, zero_centered_weight=False, + device=None, dtype=None): + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + self.eps = eps + if dropout_p > 0.0: + self.drop = torch.nn.Dropout(dropout_p) + else: + self.drop = None + self.zero_centered_weight = zero_centered_weight + self.weight = torch.nn.Parameter(torch.empty(hidden_size, **factory_kwargs)) + self.register_parameter("bias", None) + self.reset_parameters() + + def reset_parameters(self): + if not self.zero_centered_weight: + torch.nn.init.ones_(self.weight) + else: + torch.nn.init.zeros_(self.weight) + + def forward(self, x, residual=None, prenorm=False, residual_in_fp32=False): + return rms_norm_fn( + x, + self.weight, + self.bias, + residual=residual, + eps=self.eps, + dropout_p=self.drop.p if self.drop is not None and self.training else 0.0, + prenorm=prenorm, + residual_in_fp32=residual_in_fp32, + zero_centered_weight=self.zero_centered_weight, + ) + + +class LayerNormLinearFn(torch.autograd.Function): + + @staticmethod + @custom_fwd + def forward( + ctx, + x, + norm_weight, + norm_bias, + linear_weight, + linear_bias, + residual=None, + eps=1e-6, + prenorm=False, + residual_in_fp32=False, + is_rms_norm=False, + ): + x_shape_og = x.shape + # reshape input data into 2D tensor + x = maybe_contiguous_lastdim(x.reshape(-1, x.shape[-1])) + if residual is not None: + assert residual.shape == x_shape_og + residual = maybe_contiguous_lastdim(residual.reshape(-1, residual.shape[-1])) + norm_weight = norm_weight.contiguous() + norm_bias = maybe_contiguous(norm_bias) + residual_dtype = ( + residual.dtype + if residual is not None + else (torch.float32 if residual_in_fp32 else None) + ) + y, _, mean, rstd, residual_out, *rest = _layer_norm_fwd( + x, + norm_weight, + norm_bias, + eps, + residual, + out_dtype=None if not torch.is_autocast_enabled() else torch.get_autocast_dtype("cuda"), + residual_dtype=residual_dtype, + is_rms_norm=is_rms_norm, + ) + y = y.reshape(x_shape_og) + dtype = torch.get_autocast_dtype("cuda") if torch.is_autocast_enabled() else y.dtype + linear_weight = linear_weight.to(dtype) + linear_bias = linear_bias.to(dtype) if linear_bias is not None else None + out = F.linear(y.to(linear_weight.dtype), linear_weight, linear_bias) + # We don't store y, will be recomputed in the backward pass to save memory + ctx.save_for_backward(residual_out, norm_weight, norm_bias, linear_weight, mean, rstd) + ctx.x_shape_og = x_shape_og + ctx.eps = eps + ctx.is_rms_norm = is_rms_norm + ctx.has_residual = residual is not None + ctx.prenorm = prenorm + ctx.x_dtype = x.dtype + ctx.linear_bias_is_none = linear_bias is None + return out if not prenorm else (out, residual_out.reshape(x_shape_og)) + + @staticmethod + @custom_bwd + def backward(ctx, dout, *args): + x, norm_weight, norm_bias, linear_weight, mean, rstd = ctx.saved_tensors + dout = dout.reshape(-1, dout.shape[-1]) + dy = F.linear(dout, linear_weight.t()) + dlinear_bias = None if ctx.linear_bias_is_none else dout.sum(0) + dy = maybe_contiguous_lastdim(dy) + assert dy.shape == x.shape + if ctx.prenorm: + dresidual = args[0] + dresidual = maybe_contiguous_lastdim(dresidual.reshape(-1, dresidual.shape[-1])) + assert dresidual.shape == x.shape + else: + dresidual = None + dx, dnorm_weight, dnorm_bias, dresidual_in, _, _, _, y = _layer_norm_bwd( + dy, + x, + norm_weight, + norm_bias, + ctx.eps, + mean, + rstd, + dresidual=dresidual, + has_residual=ctx.has_residual, + is_rms_norm=ctx.is_rms_norm, + x_dtype=ctx.x_dtype, + recompute_output=True, + ) + dlinear_weight = torch.einsum("bo,bi->oi", dout, y) + return ( + dx.reshape(ctx.x_shape_og), + dnorm_weight, + dnorm_bias, + dlinear_weight, + dlinear_bias, + dresidual_in.reshape(ctx.x_shape_og) if ctx.has_residual else None, + None, + None, + None, + None, + ) + + +def layer_norm_linear_fn( + x, + norm_weight, + norm_bias, + linear_weight, + linear_bias, + residual=None, + eps=1e-6, + prenorm=False, + residual_in_fp32=False, + is_rms_norm=False, +): + return LayerNormLinearFn.apply( + x, + norm_weight, + norm_bias, + linear_weight, + linear_bias, + residual, + eps, + prenorm, + residual_in_fp32, + is_rms_norm, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/linear.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/linear.py new file mode 100644 index 0000000000000000000000000000000000000000..a8966dbc345ab0e593df0124451ee7be3dae131a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/linear.py @@ -0,0 +1,594 @@ +# Adapted from https://github.com/ELS-RD/kernl/blob/main/src/kernl/implementations/linear_layer.py +# and https://github.com/openai/triton/blob/master/python/triton/ops/matmul.py +from typing import Optional + +import torch +import triton +import triton.language as tl +from triton.ops.matmul_perf_model import early_config_prune, estimate_matmul_time + +from flash_attn.ops.triton.k_activations import ( + gelu, + gelu_approx, + gelu_approx_grad, + gelu_grad, + squared_relu, + squared_relu_grad, +) + +# CREDITS: Initially inspired by the Triton tutorial on matrix multiplications + + +def init_to_zero(name): + return lambda nargs: nargs[name].zero_() + + +def get_configs_io_bound(): + configs = [] + for num_stages in [2, 3, 4, 5, 6]: + for block_m in [16, 32]: + for block_k in [32, 64]: + for block_n in [32, 64, 128, 256]: + num_warps = 2 if block_n <= 64 else 4 + configs.append( + triton.Config( + { + "BLOCK_M": block_m, + "BLOCK_N": block_n, + "BLOCK_K": block_k, + "SPLIT_K": 1, + }, + num_stages=num_stages, + num_warps=num_warps, + ) + ) + # split_k not used + # for split_k in [2, 4, 8, 16]: + # configs.append(triton.Config( + # {'BLOCK_M': block_m, 'BLOCK_N': block_n, 'BLOCK_K': block_k, 'SPLIT_K': split_k}, + # num_stages=num_stages, num_warps=num_warps, pre_hook=init_to_zero('C'))) + return configs + + +@triton.autotune( + configs=[ + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=3, num_warps=8 + ), + triton.Config( + {"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=3, num_warps=8 + ), + triton.Config( + {"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 32, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=5, num_warps=2 + ), + # good for int8 + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 128, "SPLIT_K": 1}, + num_stages=3, + num_warps=8, + ), + triton.Config( + {"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1}, + num_stages=3, + num_warps=8, + ), + triton.Config( + {"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 128, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 128, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1}, + num_stages=4, + num_warps=4, + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 32, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=5, num_warps=2 + ), + ] + + get_configs_io_bound(), + key=["CACHE_KEY_M", "CACHE_KEY_N", "CACHE_KEY_K"], + prune_configs_by={ + "early_config_prune": early_config_prune, + "perf_model": estimate_matmul_time, + "top_k": 10, + }, +) +@triton.heuristics( + { + "EVEN_K": lambda args: args["K"] % (args["BLOCK_K"] * args["SPLIT_K"]) == 0, + } +) +@triton.jit +def kernel_fwd( + C, # Pointers to matrices + ACT_INPUT, + A, + B, + bias, + # Matrix dimensions + M, + N, + K, + CACHE_KEY_M, + CACHE_KEY_N, + CACHE_KEY_K, + # The stride variables represent how much to increase the ptr by when moving by 1 + # element in a particular dimension. E.g. stride_am is how much to increase a_ptr + # by to get the element one row down (A has M rows) + stride_cm, + # stride_cn, # Assume that stride_cn == 1 + stride_am, + stride_ak, + stride_bn, + stride_bk, + # Meta-parameters + BLOCK_M: tl.constexpr, + GROUP_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLOCK_K: tl.constexpr, + # split k not used, not performant with activation, kept because early_config_prune is expecting it + SPLIT_K: tl.constexpr, + EVEN_K: tl.constexpr, + A_ROWMAJOR: tl.constexpr, + B_COLMAJOR: tl.constexpr, + BIAS: tl.constexpr, + SAVE_ACT_INPUT: tl.constexpr, + ACTIVATION: tl.constexpr, +): + + """ + Kernel for computing Out = activation(A x W + C) + - Input has shape (M, K) + - Weight has shape (K, N) + - Bias has shape (N,) + - Output has shape (M, N) + - ActInputs (optional) has shape (M, N) + 'ActInputs' optionally saves the A x W + C intermediate for backward computations + This kernel will consolidate over K + """ + + pid = tl.program_id(axis=0) + + grid_m = (M + BLOCK_M - 1) // BLOCK_M + grid_n = (N + BLOCK_N - 1) // BLOCK_N + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + + # now compute the block that each program will go through + # rm (resp. rn) denotes a range of indices + # for rows (resp. col) of C + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + # trick to avoid masking on M and N axis + ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + rk = tl.arange(0, BLOCK_K) + + if A_ROWMAJOR: + A = A + (ram[:, None] * stride_am + rk[None, :]) + else: + A = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak) + if B_COLMAJOR: + B = B + (rk[:, None] + rbn[None, :] * stride_bn) + else: + B = B + (rk[:, None] * stride_bk + rbn[None, :] * stride_bn) + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) + + for k in range(K, 0, -BLOCK_K): + if EVEN_K: + a = tl.load(A) + b = tl.load(B) + else: + a = tl.load(A, mask=rk[None, :] < k, other=0.0) + b = tl.load(B, mask=rk[:, None] < k, other=0.0) + acc += tl.dot(a, b) + + if A_ROWMAJOR: + A += BLOCK_K + else: + A += BLOCK_K * stride_ak + if B_COLMAJOR: + B += BLOCK_K + else: + B += BLOCK_K * stride_bk + + # Putting bias after the matmul (instead of before) is faster, idk why + if BIAS: + bias = tl.load(bias + rn, mask=rn < N, other=0.0).to(tl.float32) + acc += bias[None, :] + + # optional: save the activation inputs + if SAVE_ACT_INPUT: + # act_in_ptrs = ACT_INPUT + ram[:, None] * stride_cm + rbn[None, :] * stride_cn + act_in_ptrs = ACT_INPUT + ram[:, None] * stride_cm + rbn[None, :] + tl.store(act_in_ptrs, acc) + + # optional: fused activation (while the data is in shared memory) + if ACTIVATION == "gelu": + acc = gelu(acc) + elif ACTIVATION == "gelu_approx": + acc = gelu_approx(acc) + elif ACTIVATION == "squared_relu": + acc = squared_relu(acc) + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + + # write back result + # C = C + rm[:, None] * stride_cm + rn[None, :] * stride_cn + C = C + rm[:, None] * stride_cm + rn[None, :] + mask = (rm < M)[:, None] & (rn < N)[None, :] + tl.store(C, acc) + + +def triton_linear_act( + x: torch.Tensor, + weight: torch.Tensor, + bias: Optional[torch.Tensor] = None, + activation: str = "id", + save_act_input: bool = False, +) -> torch.Tensor: + """ + Compute e = activation(x @ weight.T + bias). + This wrapper kicks the `kernel_fwd` Triton kernel + :param x: input tensor + :param weight: weight matrix + :param bias: an optional bias tensor + :param activation: Activation name. Needs to be a Triton kernel. + :param act_input: an optional tensor to save the activation inputs (for backward) + :return: result tensor + """ + # if torch.is_autocast_enabled(): + # dtype = torch.get_autocast_gpu_dtype() + # x, weight, bias = [a.to(dtype=dtype) for a in [x, weight, bias]] + + assert activation in ["id", "gelu", "gelu_approx", "squared_relu"] + + batch_shape, n = x.shape[:-1], x.shape[-1] + batch_dim = batch_shape.numel() + x_reshaped = x.reshape(batch_dim, n) + + if x_reshaped.stride(0) > 1 and x_reshaped.stride(1) > 1: + x_reshaped = x_reshaped.contiguous() + if weight.stride(0) > 1 and weight.stride(1) > 1: + weight = weight.contiguous() + bias = bias.contiguous() if bias is not None else None + + assert ( + x.dtype == weight.dtype + ), f"Input and weight must have the same dtype, got {x.dtype} and {weight.dtype}" + if bias is not None: + assert ( + x.dtype == bias.dtype + ), f"Input and bias must have the same dtype, got {x.dtype} and {bias.dtype}" + assert ( + x_reshaped.shape[1] == weight.shape[1] + ), f"Incompatible dimensions: {x_reshaped.shape} - {weight.shape}" + + assert ( + bias is None or bias.shape[0] == weight.shape[0] + ), "Incompatible dimensions in between weight and bias" + + M, K = x_reshaped.shape + N, K = weight.shape + + output = torch.empty((M, N), device=x.device, dtype=x.dtype) + act_input = torch.empty_like(output) if save_act_input else None + + # 1D launch kernel where each block gets its own program. + grid = lambda META: (triton.cdiv(M, META["BLOCK_M"]) * triton.cdiv(N, META["BLOCK_N"]),) # noqa + + kernel_fwd[grid]( + output, + act_input, + x_reshaped, + weight, # data ptrs + bias if bias is not None else x, # auto skip bias if not present + M, # shapes + N, + K, + M // 32, # key for triton cache (limit number of compilations) + N // 32, + K // 32, + stride_cm=output.stride(0), # strides + # stride_cn=output.stride(1), + stride_am=x_reshaped.stride(0), + stride_ak=x_reshaped.stride(1), + stride_bk=weight.stride(1), + stride_bn=weight.stride(0), + BIAS=bias is not None, # optional fused bias + SAVE_ACT_INPUT=save_act_input, # optional save activation inputs + ACTIVATION=activation, # optional fused activation + A_ROWMAJOR=x_reshaped.stride(1) == 1, + B_COLMAJOR=weight.stride(1) == 1, + GROUP_M=8, # speed optimization: group the programs + ) + + if not save_act_input: + return output.reshape(*batch_shape, output.shape[-1]) + else: + return ( + output.reshape(*batch_shape, output.shape[-1]), + act_input.reshape(*batch_shape, act_input.shape[-1]), + ) + + +@triton.autotune( + configs=[ + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=3, num_warps=8 + ), + triton.Config( + {"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=3, num_warps=8 + ), + triton.Config( + {"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 32, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 32, "SPLIT_K": 1}, num_stages=5, num_warps=2 + ), + # good for int8 + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 256, "BLOCK_K": 128, "SPLIT_K": 1}, + num_stages=3, + num_warps=8, + ), + triton.Config( + {"BLOCK_M": 256, "BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1}, + num_stages=3, + num_warps=8, + ), + triton.Config( + {"BLOCK_M": 256, "BLOCK_N": 64, "BLOCK_K": 128, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 256, "BLOCK_K": 128, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 128, "BLOCK_K": 128, "SPLIT_K": 1}, + num_stages=4, + num_warps=4, + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 64, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 128, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 128, "BLOCK_N": 32, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=4, num_warps=4 + ), + triton.Config( + {"BLOCK_M": 64, "BLOCK_N": 32, "BLOCK_K": 64, "SPLIT_K": 1}, num_stages=5, num_warps=2 + ), + ] + + get_configs_io_bound(), + key=["CACHE_KEY_M", "CACHE_KEY_N", "CACHE_KEY_K"], + prune_configs_by={ + "early_config_prune": early_config_prune, + "perf_model": estimate_matmul_time, + "top_k": 10, + }, +) +@triton.heuristics( + { + "EVEN_K": lambda args: args["K"] % (args["BLOCK_K"] * args["SPLIT_K"]) == 0, + } +) +@triton.jit +def kernel_bwd( + C, # Pointers to matrices + ACT_INPUT, + A, + B, + # Matrix dimensions + M, + N, + K, + CACHE_KEY_M, + CACHE_KEY_N, + CACHE_KEY_K, + # The stride variables represent how much to increase the ptr by when moving by 1 + # element in a particular dimension. E.g. stride_am is how much to increase a_ptr + # by to get the element one row down (A has M rows) + stride_cm, + # stride_cn, # Assume that stride_cn == 1 + stride_am, + stride_ak, + stride_bk, + stride_bn, + # Meta-parameters + BLOCK_M: tl.constexpr, + GROUP_M: tl.constexpr, + BLOCK_N: tl.constexpr, + BLOCK_K: tl.constexpr, + # split k not used, not performant with activation, kept because early_config_prune is expecting it + SPLIT_K: tl.constexpr, + EVEN_K: tl.constexpr, + ACTIVATION: tl.constexpr, +): + + """ + Kernel for computing Out = activation(A x W + C) + - Input has shape (M, K) + - Weight has shape (K, N) + - Output has shape (M, N) + - ActInputs (optional) has shape (M, N) + 'ActInputs' optionally saves the A x W + C intermediate for backward computations + This kernel will consolidate over K + """ + + pid = tl.program_id(axis=0) + + grid_m = (M + BLOCK_M - 1) // BLOCK_M + grid_n = (N + BLOCK_N - 1) // BLOCK_N + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + + # now compute the block that each program will go through + # rm (resp. rn) denotes a range of indices + # for rows (resp. col) of C + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + # trick to avoid masking on M and N axis + ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + rk = tl.arange(0, BLOCK_K) + + A = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak) + B = B + (rk[:, None] * stride_bk + rbn[None, :] * stride_bn) + + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32) + + for k in range(K, 0, -BLOCK_K): + if EVEN_K: + a = tl.load(A) + b = tl.load(B) + else: + a = tl.load(A, mask=rk[None, :] < k, other=0.0) + b = tl.load(B, mask=rk[:, None] < k, other=0.0) + acc += tl.dot(a, b) + + A += BLOCK_K * stride_ak + B += BLOCK_K * stride_bk + + # optional: fused activation (while the data is in shared memory) + if ACTIVATION != "id": + act_in_ptrs = ACT_INPUT + ram[:, None] * stride_cm + rbn[None, :] + act_input = tl.load(act_in_ptrs).to(acc.dtype) + if ACTIVATION == "gelu": + acc *= gelu_grad(act_input) + elif ACTIVATION == "gelu_approx": + acc *= gelu_approx_grad(act_input) + elif ACTIVATION == "squared_relu": + acc *= squared_relu_grad(act_input) + + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + + # write back result + C = C + rm[:, None] * stride_cm + rn[None, :] + mask = (rm < M)[:, None] & (rn < N)[None, :] + tl.store(C, acc, mask=mask) + + +def triton_dgrad_act( + grad_output: torch.Tensor, + weight: torch.Tensor, + activation: str = "id", + act_input: Optional[torch.Tensor] = None, +) -> torch.Tensor: + """ + Compute e = activation(grad_output @ weight + bias). + This wrapper kicks the `kernel_fwd` Triton kernel + :param grad_output: input tensor + :param weight: weight matrix + :param activation: Activation name. Needs to be a Triton kernel. + :param act_input: an optional tensor to save the activation inputs (for backward) + :return: result tensor + """ + assert activation in ["id", "gelu", "gelu_approx", "squared_relu"] + + batch_shape, n = grad_output.shape[:-1], grad_output.shape[-1] + batch_dim = batch_shape.numel() + grad_output_reshaped = grad_output.reshape(batch_dim, n) + + if grad_output_reshaped.stride(0) > 1 and grad_output_reshaped.stride(1) > 1: + grad_output_reshaped = grad_output_reshaped.contiguous() + if weight.stride(0) > 1 and weight.stride(1) > 1: + weight = weight.contiguous() + + assert ( + grad_output.dtype == weight.dtype + ), f"grad_output and weight must have the same dtype, got {grad_output.dtype} and {weight.dtype}" + assert ( + grad_output_reshaped.shape[1] == weight.shape[0] + ), f"Incompatible dimensions: {grad_output_reshaped.shape} - {weight.shape}" + if activation != "id": + assert act_input is not None, f"act_input is required for activation {activation}" + + # M, N, K in bwd are different from M, N, K in fwd + M, K = grad_output_reshaped.shape + K, N = weight.shape + + grad_input = torch.empty((M, N), device=grad_output.device, dtype=grad_output.dtype) + + # 1D launch kernel where each block gets its own program. + grid = lambda META: (triton.cdiv(M, META["BLOCK_M"]) * triton.cdiv(N, META["BLOCK_N"]),) # noqa + + kernel_bwd[grid]( + grad_input, + act_input, + grad_output_reshaped, + weight, # data ptrs + M, # shapes + N, + K, + M // 32, # key for triton cache (limit number of compilations) + N // 32, + K // 32, + stride_cm=grad_input.stride(0), # strides + # stride_cn=grad_input.stride(1), + stride_am=grad_output_reshaped.stride(0), + stride_ak=grad_output_reshaped.stride(1), + stride_bk=weight.stride(0), + stride_bn=weight.stride(1), + ACTIVATION=activation, # optional fused activation + GROUP_M=8, # speed optimization: group the programs + ) + + return grad_input.reshape(*batch_shape, grad_input.shape[-1]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/mlp.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/mlp.py new file mode 100644 index 0000000000000000000000000000000000000000..059f4f8a5e174c1f4824e43d313fca18eaa799b8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/mlp.py @@ -0,0 +1,149 @@ +# The triton fused matmul + sqrelu is faster for fp16 but slower for bf16, compared +# to naive implementation. +import fused_dense_lib as fused_dense_cuda +import torch +import torch.nn as nn +import torch.nn.functional as F + +from flash_attn.utils.torch import custom_fwd, custom_bwd +from flash_attn.ops.activations import sqrelu_bwd, sqrelu_fwd +from flash_attn.ops.triton.linear import triton_dgrad_act, triton_linear_act + + +class FusedDenseSqreluDenseFunc(torch.autograd.Function): + @staticmethod + @custom_fwd + def forward(ctx, x, weight1, bias1, weight2, bias2, checkpoint_lvl=0): + """checkpoint_lvl: + 0: no recomputation in the bwd + 1: recompute gelu_out in the bwd + 2: recompute act_input and gelu_out in the bwd + """ + if torch.is_autocast_enabled(): + dtype = torch.get_autocast_gpu_dtype() + x, weight1, bias1, weight2, bias2 = [ + a.to(dtype=dtype) for a in [x, weight1, bias1, weight2, bias2] + ] + is_bf16 = x.dtype == torch.bfloat16 + assert checkpoint_lvl in [0, 1, 2] + x = x.contiguous() + weight1 = weight1.contiguous() + bias1 = bias1.contiguous() + weight2 = weight2.contiguous() + bias2 = bias2.contiguous() + batch_shape, n = x.shape[:-1], x.shape[-1] + batch_dim = batch_shape.numel() + if is_bf16: + act_input = fused_dense_cuda.linear_bias_forward( + x.reshape(batch_dim, n), weight1, bias1 + ) + output1 = sqrelu_fwd(act_input) + else: + save_act_input = checkpoint_lvl != 2 + result = triton_linear_act( + x.reshape(batch_dim, n), + weight1, + bias1, + activation="squared_relu", + save_act_input=save_act_input, + ) + if save_act_input: + output1, act_input = result + else: + output1 = result + output2 = fused_dense_cuda.linear_bias_forward(output1, weight2, bias2) + ctx.checkpoint_lvl = checkpoint_lvl + if checkpoint_lvl == 0: + ctx.save_for_backward(x, weight1, bias1, weight2, act_input, output1) + elif checkpoint_lvl == 1: + ctx.save_for_backward(x, weight1, bias1, weight2, act_input) + elif checkpoint_lvl == 2: + ctx.save_for_backward(x, weight1, bias1, weight2) + return output2.reshape(*batch_shape, output2.shape[-1]) + + @staticmethod + @custom_bwd + def backward(ctx, grad_output): + grad_output = grad_output.contiguous() + checkpoint_lvl = ctx.checkpoint_lvl + x, weight1, bias1, weight2, *rest = ctx.saved_tensors + batch_shape, n = x.shape[:-1], x.shape[-1] + batch_dim = batch_shape.numel() + is_bf16 = x.dtype == torch.bfloat16 + if checkpoint_lvl == 0: + act_input, output1 = rest + elif checkpoint_lvl == 1: + (act_input,) = rest + output1 = sqrelu_fwd(act_input) + elif checkpoint_lvl == 2: + if is_bf16: + act_input = fused_dense_cuda.linear_bias_forward( + x.reshape(batch_dim, n), weight1, bias1 + ) + output1 = sqrelu_fwd(act_input) + else: + output1, act_input = triton_linear_act( + x.reshape(batch_dim, n), + weight1, + bias1, + activation="squared_relu", + save_act_input=True, + ) + + if is_bf16: + grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1]) + grad_weight2, grad_bias2 = fused_dense_cuda.linear_bias_wgrad(output1, grad_output) + grad_output1 = grad_output @ weight2 + grad_act_input = sqrelu_bwd(grad_output1, act_input) + grad_input, grad_weight1, grad_bias1 = fused_dense_cuda.linear_bias_backward( + x.reshape(batch_dim, n), weight1, grad_act_input + ) + else: + grad_output = grad_output.reshape(batch_dim, grad_output.shape[-1]) + grad_weight2, grad_bias2 = fused_dense_cuda.linear_bias_wgrad(output1, grad_output) + grad_act_input = triton_dgrad_act( + grad_output, weight2, activation="squared_relu", act_input=act_input + ) + grad_input, grad_weight1, grad_bias1 = fused_dense_cuda.linear_bias_backward( + x.reshape(batch_dim, n), weight1, grad_act_input + ) + return grad_input.reshape_as(x), grad_weight1, grad_bias1, grad_weight2, grad_bias2, None + + +fused_dense_sqrelu_dense_function = FusedDenseSqreluDenseFunc.apply + + +class FusedDenseSqreluDense(nn.Module): + def __init__( + self, + in_features, + hidden_features=None, + out_features=None, + bias1=True, + bias2=True, + checkpoint_lvl=0, + device=None, + dtype=None, + ): + """ + checkpoint_lvl (increasing lvl means slower but more memory saving): + 0: no recomputation in the bwd + 1: recompute gelu_out in the bwd + 2: recompute gelu_in and gelu_out in the bwd + """ + assert checkpoint_lvl in [0, 1, 2] + factory_kwargs = {"device": device, "dtype": dtype} + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features * 4 + assert bias1 == True, "DenseSqreluDense module without bias is currently not supported" + assert bias2 == True, "DenseSqreluDense module without bias is currently not supported" + self.checkpoint_lvl = checkpoint_lvl + self.fc1 = nn.Linear(in_features, hidden_features, bias=bias1, **factory_kwargs) + self.fc2 = nn.Linear(hidden_features, out_features, bias=bias2, **factory_kwargs) + + def forward(self, x): + assert x.is_cuda + return fused_dense_sqrelu_dense_function( + x, self.fc1.weight, self.fc1.bias, self.fc2.weight, self.fc2.bias, self.checkpoint_lvl + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/rotary.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/rotary.py new file mode 100644 index 0000000000000000000000000000000000000000..ff4017fda3e4a6e18cf3a51b34f0fb073d8f678a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/ops/triton/rotary.py @@ -0,0 +1,185 @@ +# Copyright (c) 2025, Tri Dao. +# As of 2025-04-23, we require triton >= 3.0 + +from typing import Optional, Union + +import torch + +import triton +import triton.language as tl + + +@triton.jit +def rotary_kernel( + OUT, # Pointers to matrices + X, + COS, + SIN, + CU_SEQLENS, + SEQLEN_OFFSETS, # this could be int or a pointer + # Matrix dimensions + seqlen, + nheads, + seqlen_ro, + # strides + stride_out_batch, + stride_out_seqlen, + stride_out_nheads, + stride_out_headdim, + stride_x_batch, + stride_x_seqlen, + stride_x_nheads, + stride_x_headdim, + # Meta-parameters + # We want ROTARY_DIM to be constexpr, otherwise the triton compiler doesn't know that + # the mask is constant every 8 elements, and it will generate LDG.16 instead of LDG.128 + ROTARY_DIM: tl.constexpr, + IS_SEQLEN_OFFSETS_TENSOR: tl.constexpr, + IS_VARLEN: tl.constexpr, + INTERLEAVED: tl.constexpr, + CONJUGATE: tl.constexpr, + BLOCK_H: tl.constexpr, + BLOCK_M: tl.constexpr, +): + BLOCK_K: tl.constexpr = triton.next_power_of_2(ROTARY_DIM) + ROTARY_DIM_HALF = ROTARY_DIM // 2 + pid_head = tl.program_id(axis=0) + pid_m = tl.program_id(axis=1) + pid_batch = tl.program_id(axis=2) + + if not IS_VARLEN: + X = X + pid_batch * stride_x_batch + OUT = OUT + pid_batch * stride_out_batch + else: + start_idx = tl.load(CU_SEQLENS + pid_batch) + seqlen = tl.load(CU_SEQLENS + pid_batch + 1) - start_idx + X = X + start_idx * stride_x_seqlen + OUT = OUT + start_idx * stride_out_seqlen + + if pid_m * BLOCK_M >= seqlen: + return + + rh = pid_head * BLOCK_H + tl.arange(0, BLOCK_H) + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + if not IS_SEQLEN_OFFSETS_TENSOR: + rm_cs = rm + SEQLEN_OFFSETS + else: + rm_cs = rm + tl.load(SEQLEN_OFFSETS + pid_batch) + + rk_half = tl.arange(0, BLOCK_K // 2) + COS = COS + (rm_cs[:, None] * ROTARY_DIM_HALF + rk_half[None, :]) + SIN = SIN + (rm_cs[:, None] * ROTARY_DIM_HALF + rk_half[None, :]) + mask_cs = (rm_cs[:, None] < seqlen_ro) & (rk_half[None, :] < ROTARY_DIM_HALF) + cos = tl.load(COS, mask=mask_cs, other=1.0).to(tl.float32) + sin = tl.load(SIN, mask=mask_cs, other=0.0).to(tl.float32) + if CONJUGATE: + sin = -sin + + if not INTERLEAVED: + # Load the 1st and 2nd halves of X, do calculation, then store to 1st and 2nd halves of OUT + X = X + (rh[:, None, None] * stride_x_nheads + rm[None, :, None] * stride_x_seqlen + rk_half[None, None, :] * stride_x_headdim) + OUT = OUT + (rh[:, None, None] * stride_out_nheads + rm[None, :, None] * stride_out_seqlen + rk_half[None, None, :] * stride_out_headdim) + mask = (rh[:, None, None] < nheads) & (rm[None, :, None] < seqlen) & (rk_half[None, None, :] < ROTARY_DIM_HALF) + x0 = tl.load(X, mask=mask, other=0.0).to(tl.float32) + x1 = tl.load(X + ROTARY_DIM_HALF * stride_x_headdim, mask=mask, other=0.0,).to(tl.float32) + o0 = x0 * cos - x1 * sin + o1 = x0 * sin + x1 * cos + tl.store(OUT, o0, mask=mask) + tl.store(OUT + ROTARY_DIM_HALF * stride_out_headdim, o1, mask=mask) + else: + rk = tl.arange(0, BLOCK_K) + X = X + (rh[:, None, None] * stride_x_nheads + rm[None, :, None] * stride_x_seqlen + rk[None, None, :] * stride_x_headdim) + OUT = OUT + (rh[:, None, None] * stride_out_nheads + rm[None, :, None] * stride_out_seqlen + rk[None, None, :] * stride_out_headdim) + mask = (rh[:, None, None] < nheads) & (rm[None, :, None] < seqlen) & (rk[None, None, :] < ROTARY_DIM) + x = tl.load(X, mask=mask, other=0.0).to(tl.float32) + x0, x1 = tl.split(tl.reshape(x, [BLOCK_H, BLOCK_M, BLOCK_K // 2, 2])) + o0 = x0 * cos - x1 * sin + o1 = x0 * sin + x1 * cos + o = tl.reshape(tl.join(o0, o1), [BLOCK_H, BLOCK_M, BLOCK_K]) + tl.store(OUT, o, mask=mask) + + +def apply_rotary( + x: torch.Tensor, + cos: torch.Tensor, + sin: torch.Tensor, + seqlen_offsets: Union[int, torch.Tensor] = 0, + cu_seqlens: Optional[torch.Tensor] = None, + max_seqlen: Optional[int] = None, + interleaved=False, + inplace=False, + conjugate=False, +) -> torch.Tensor: + """ + Arguments: + x: (batch, seqlen, nheads, headdim) if cu_seqlens is None + else (total_seqlen, nheads, headdim). + cos: (seqlen_ro, rotary_dim / 2) + sin: (seqlen_ro, rotary_dim / 2) + seqlen_offsets: integer or integer tensor of size (batch,) + cu_seqlens: (batch + 1,) or None + max_seqlen: int + Returns: + y: (batch, seqlen, nheads, headdim) + """ + is_varlen = cu_seqlens is not None + if not is_varlen: + batch, seqlen, nheads, headdim = x.shape + else: + assert max_seqlen is not None, "If cu_seqlens is passed in, then max_seqlen must be passed" + total_seqlen, nheads, headdim = x.shape + batch_p_1 = cu_seqlens.shape[0] + batch = batch_p_1 - 1 + seqlen = max_seqlen + seqlen_ro, rotary_dim = cos.shape + assert sin.shape == cos.shape + rotary_dim *= 2 + assert rotary_dim <= headdim, "rotary_dim must be <= headdim" + assert headdim <= 256, "Only support headdim <= 256" + assert seqlen_ro >= seqlen, "seqlen_ro must be >= seqlen" + + cos, sin = cos.contiguous(), sin.contiguous() + if isinstance(seqlen_offsets, torch.Tensor): + assert seqlen_offsets.shape == (batch,) + assert seqlen_offsets.dtype in [torch.int32, torch.int64] + seqlen_offsets = seqlen_offsets.contiguous() + else: + assert seqlen_offsets + seqlen <= seqlen_ro + + output = torch.empty_like(x) if not inplace else x + if rotary_dim < headdim and not inplace: + output[..., rotary_dim:].copy_(x[..., rotary_dim:]) + + grid = lambda META: (triton.cdiv(nheads, META["BLOCK_H"]), triton.cdiv(seqlen, META["BLOCK_M"]), batch) # noqa + BLOCK_M = 8 if rotary_dim <= 128 else 4 + + # Need this, otherwise Triton tries to launch from cuda:0 and we get + # ValueError: Pointer argument (at 0) cannot be accessed from Triton (cpu tensor?) + with torch.cuda.device(x.device.index): + torch.library.wrap_triton(rotary_kernel)[grid]( + output, # data ptrs + x, + cos, + sin, + cu_seqlens, + seqlen_offsets, + seqlen, # shapes + nheads, + seqlen_ro, + output.stride(0) if not is_varlen else 0, # batch_strides if not varlen else 0 + output.stride(-3), # seqlen_stride or total_seqlen_stride + output.stride(-2), # nheads_stride + output.stride(-1), # headdim_stride + x.stride(0) if not is_varlen else 0, # batch_strides if not varlen else 0 + x.stride(-3), # seqlen stride or total_seqlen_stride + x.stride(-2), # nheads stride + x.stride(-1), # headdim stride + rotary_dim, + isinstance(seqlen_offsets, torch.Tensor), + is_varlen, + interleaved, + conjugate, + BLOCK_M=BLOCK_M, + BLOCK_H=2, + ) + return output diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..843a0fb8b6103a79e225e5fe4507afe98675782e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/benchmark.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/benchmark.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..473a7a70285ec43dbda1abe3ef93dfd65ba9eaf4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/benchmark.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/distributed.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/distributed.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd2d687ef0f0714ad103567fd6b1779069ed3ec4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/distributed.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/generation.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/generation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c748ddae50b8cd26493c1879dfdae731e1abfddd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/generation.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/library.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/library.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b447117ada386f81c3d6e5611742eca2c43f1a58 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/library.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/pretrained.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/pretrained.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9cde3634a08b3b8d94ab43cfa3807878c3ae986 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/pretrained.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/testing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/testing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9f7547e0c0d4b74db6755e31e5842157e88f3c2f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/testing.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/torch.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/torch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49274d015cf32ec5576bb5911bfed85451199b5c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/__pycache__/torch.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/benchmark.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/benchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..15b30405f209921189b75f7307814876350e7317 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/benchmark.py @@ -0,0 +1,268 @@ +# Copyright (c) 2023, Tri Dao. +""" Useful functions for writing test code. """ + +import torch +import torch.utils.benchmark as benchmark + + +def benchmark_forward( + fn, *inputs, repeats=10, desc="", verbose=True, amp=False, amp_dtype=torch.float16, **kwinputs +): + """Use Pytorch Benchmark on the forward pass of an arbitrary function.""" + if verbose: + print(desc, "- Forward pass") + + def amp_wrapper(*inputs, **kwinputs): + with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp): + fn(*inputs, **kwinputs) + + t = benchmark.Timer( + stmt="fn_amp(*inputs, **kwinputs)", + globals={"fn_amp": amp_wrapper, "inputs": inputs, "kwinputs": kwinputs}, + num_threads=torch.get_num_threads(), + ) + m = t.timeit(repeats) + if verbose: + print(m) + return t, m + + +def benchmark_backward( + fn, + *inputs, + grad=None, + repeats=10, + desc="", + verbose=True, + amp=False, + amp_dtype=torch.float16, + **kwinputs, +): + """Use Pytorch Benchmark on the backward pass of an arbitrary function.""" + if verbose: + print(desc, "- Backward pass") + with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp): + y = fn(*inputs, **kwinputs) + if type(y) is tuple: + y = y[0] + if grad is None: + grad = torch.randn_like(y) + else: + if grad.shape != y.shape: + raise RuntimeError("Grad shape does not match output shape") + + def f(*inputs, y, grad): + # Set .grad to None to avoid extra operation of gradient accumulation + for x in inputs: + if isinstance(x, torch.Tensor): + x.grad = None + y.backward(grad, retain_graph=True) + + t = benchmark.Timer( + stmt="f(*inputs, y=y, grad=grad)", + globals={"f": f, "inputs": inputs, "y": y, "grad": grad}, + num_threads=torch.get_num_threads(), + ) + m = t.timeit(repeats) + if verbose: + print(m) + return t, m + + +def benchmark_combined( + fn, + *inputs, + grad=None, + repeats=10, + desc="", + verbose=True, + amp=False, + amp_dtype=torch.float16, + **kwinputs, +): + """Use Pytorch Benchmark on the forward+backward pass of an arbitrary function.""" + if verbose: + print(desc, "- Forward + Backward pass") + with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp): + y = fn(*inputs, **kwinputs) + if type(y) is tuple: + y = y[0] + if grad is None: + grad = torch.randn_like(y) + else: + if grad.shape != y.shape: + raise RuntimeError("Grad shape does not match output shape") + + def f(grad, *inputs, **kwinputs): + for x in inputs: + if isinstance(x, torch.Tensor): + x.grad = None + with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp): + y = fn(*inputs, **kwinputs) + if type(y) is tuple: + y = y[0] + y.backward(grad, retain_graph=True) + + t = benchmark.Timer( + stmt="f(grad, *inputs, **kwinputs)", + globals={"f": f, "fn": fn, "inputs": inputs, "grad": grad, "kwinputs": kwinputs}, + num_threads=torch.get_num_threads(), + ) + m = t.timeit(repeats) + if verbose: + print(m) + return t, m + + +def benchmark_fwd_bwd( + fn, + *inputs, + grad=None, + repeats=10, + desc="", + verbose=True, + amp=False, + amp_dtype=torch.float16, + **kwinputs, +): + """Use Pytorch Benchmark on the forward+backward pass of an arbitrary function.""" + return ( + benchmark_forward( + fn, + *inputs, + repeats=repeats, + desc=desc, + verbose=verbose, + amp=amp, + amp_dtype=amp_dtype, + **kwinputs, + ), + benchmark_backward( + fn, + *inputs, + grad=grad, + repeats=repeats, + desc=desc, + verbose=verbose, + amp=amp, + amp_dtype=amp_dtype, + **kwinputs, + ), + ) + + +def benchmark_all( + fn, + *inputs, + grad=None, + repeats=10, + desc="", + verbose=True, + amp=False, + amp_dtype=torch.float16, + **kwinputs, +): + """Use Pytorch Benchmark on the forward+backward pass of an arbitrary function.""" + return ( + benchmark_forward( + fn, + *inputs, + repeats=repeats, + desc=desc, + verbose=verbose, + amp=amp, + amp_dtype=amp_dtype, + **kwinputs, + ), + benchmark_backward( + fn, + *inputs, + grad=grad, + repeats=repeats, + desc=desc, + verbose=verbose, + amp=amp, + amp_dtype=amp_dtype, + **kwinputs, + ), + benchmark_combined( + fn, + *inputs, + grad=grad, + repeats=repeats, + desc=desc, + verbose=verbose, + amp=amp, + amp_dtype=amp_dtype, + **kwinputs, + ), + ) + + +def pytorch_profiler( + fn, + *inputs, + trace_filename=None, + backward=False, + amp=False, + amp_dtype=torch.float16, + cpu=False, + verbose=True, + **kwinputs, +): + """Wrap benchmark functions in Pytorch profiler to see CUDA information.""" + if backward: + with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp): + out = fn(*inputs, **kwinputs) + if type(out) is tuple: + out = out[0] + g = torch.randn_like(out) + for _ in range(30): # Warm up + if backward: + for x in inputs: + if isinstance(x, torch.Tensor): + x.grad = None + with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp): + out = fn(*inputs, **kwinputs) + if type(out) is tuple: + out = out[0] + # Backward should be done outside autocast + if backward: + out.backward(g, retain_graph=True) + activities = ([torch.profiler.ProfilerActivity.CPU] if cpu else []) + [ + torch.profiler.ProfilerActivity.CUDA + ] + with torch.profiler.profile( + activities=activities, + record_shapes=True, + # profile_memory=True, + with_stack=True, + ) as prof: + if backward: + for x in inputs: + if isinstance(x, torch.Tensor): + x.grad = None + with torch.autocast(device_type="cuda", dtype=amp_dtype, enabled=amp): + out = fn(*inputs, **kwinputs) + if type(out) is tuple: + out = out[0] + if backward: + out.backward(g, retain_graph=True) + if verbose: + # print(prof.key_averages().table(sort_by="self_cuda_time_total", row_limit=50)) + print(prof.key_averages().table(row_limit=50)) + if trace_filename is not None: + prof.export_chrome_trace(trace_filename) + + +def benchmark_memory(fn, *inputs, desc="", verbose=True, **kwinputs): + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() + torch.cuda.synchronize() + fn(*inputs, **kwinputs) + torch.cuda.synchronize() + mem = torch.cuda.max_memory_allocated() / ((2**20) * 1000) + if verbose: + print(f"{desc} max memory: {mem}GB") + torch.cuda.empty_cache() + return mem diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/distributed.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..74c55279645cd0fd687584bc1b7374c8c3c73e56 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/distributed.py @@ -0,0 +1,144 @@ +from typing import Optional + +import torch +from torch import Tensor +from torch.distributed import ProcessGroup + +# `all_gather_into_tensor` and `reduce_scatter_tensor` are new placeholders for +# `_all_gather_base` and `_reduce_scatter_base`. They require the most recent +# version of PyTorch. The following 4 lines are for backward compatibility with +# older PyTorch. +if "all_gather_into_tensor" not in dir(torch.distributed): + torch.distributed.all_gather_into_tensor = torch.distributed._all_gather_base +if "reduce_scatter_tensor" not in dir(torch.distributed): + torch.distributed.reduce_scatter_tensor = torch.distributed._reduce_scatter_base + + +# Raw operation, does not support autograd, but does support async +def all_gather_raw(input_: Tensor, process_group: ProcessGroup, async_op: bool = False): + world_size = torch.distributed.get_world_size(process_group) + output = torch.empty( + world_size * input_.shape[0], *input_.shape[1:], dtype=input_.dtype, device=input_.device + ) + handle = torch.distributed.all_gather_into_tensor( + output, input_.contiguous(), group=process_group, async_op=async_op + ) + return output, handle + + +# Raw operation, does not support autograd, but does support async +def reduce_scatter_raw(input_: Tensor, process_group: ProcessGroup, async_op: bool = False): + world_size = torch.distributed.get_world_size(process_group) + assert input_.shape[0] % world_size == 0 + output = torch.empty( + input_.shape[0] // world_size, *input_.shape[1:], dtype=input_.dtype, device=input_.device + ) + handle = torch.distributed.reduce_scatter_tensor( + output, input_.contiguous(), group=process_group, async_op=async_op + ) + return output, handle + + +# Raw operation, does not support autograd, but does support async +def all_reduce_raw(input_: Tensor, process_group: ProcessGroup, async_op: bool = False): + input_ = input_.contiguous() + handle = torch.distributed.all_reduce(input_, group=process_group, async_op=async_op) + return input_, handle + + +class AllGatherFunc(torch.autograd.Function): + """Gather the input from sequence parallel region and concatenate.""" + + @staticmethod + def forward(ctx, input_: Tensor, process_group: ProcessGroup) -> Tensor: + ctx.process_group = process_group + output, _ = all_gather_raw(input_, process_group) + return output + + @staticmethod + def backward(ctx, grad_output: Tensor): + grad_input, _ = reduce_scatter_raw(grad_output, ctx.process_group) + return grad_input, None + + +# Supports autograd, but does not support async +all_gather = AllGatherFunc.apply + + +class ReduceScatterFunc(torch.autograd.Function): + """Reduce scatter the input from the sequence parallel region and concatenate.""" + + @staticmethod + def forward(ctx, input_: Tensor, process_group: ProcessGroup) -> Tensor: + ctx.process_group = process_group + output, _ = reduce_scatter_raw(input_, process_group) + return output + + @staticmethod + def backward(ctx, grad_output: Tensor): + grad_input, _ = all_gather_raw(grad_output, ctx.process_group) + return grad_input, None + + +# Supports autograd, but does not support async +reduce_scatter = ReduceScatterFunc.apply + + +class AllReduceFunc(torch.autograd.Function): + """Gather the input from sequence parallel region and concatenate.""" + + @staticmethod + def forward(ctx, input_: Tensor, process_group: ProcessGroup) -> Tensor: + ctx.process_group = process_group + output, _ = all_reduce_raw(input_, process_group) + return output + + @staticmethod + def backward(ctx, grad_output: Tensor): + return grad_output, None + + +# Supports autograd, but does not support async +all_reduce = AllReduceFunc.apply + + +def sync_shared_params(model: torch.nn.Module, process_group: ProcessGroup): + # We want to iterate over parameters with _shared_params=True in the same order, + # as different ranks might have different number of parameters (e.g., only rank 0 has bias). + pamams_shared = { + name: p for name, p in model.named_parameters() if getattr(p, "_shared_params", False) + } + for _, p in sorted(pamams_shared.items()): + with torch.no_grad(): + # Broadcast needs src to be global rank, not group rank + torch.distributed.broadcast( + p, src=torch.distributed.get_global_rank(process_group, 0), group=process_group + ) + + +# Ref: https://github.com/NVIDIA/Megatron-LM/blob/52e636888cccc41e931251c417a7181fc36de926/megatron/optimizer/optimizer.py#L256 +def allreduce_sequence_parallel_grad(model: torch.nn.Module, process_group: ProcessGroup): + # We want to iterate over parameters with _sequence_parallel=True in the same order, + # as different ranks might have different number of parameters (e.g., only rank 0 has bias). + params_seqparallel = { + name: p for name, p in model.named_parameters() if getattr(p, "_sequence_parallel", False) + } + grads = [p.grad for _, p in sorted(params_seqparallel.items())] + if grads: + with torch.no_grad(): + coalesced = torch._utils._flatten_dense_tensors(grads) + torch.distributed.all_reduce(coalesced, group=process_group) + for buf, synced in zip(grads, torch._utils._unflatten_dense_tensors(coalesced, grads)): + buf.copy_(synced) + + +def get_dim_for_local_rank(dim: int, world_size: int, local_rank: int, multiple_of: int = 1) -> int: + """Get the dim for the local rank derived from splitting dim on world_size processes. + + The split may not be even across the world_size processes. + """ + multiple = dim // multiple_of + div = multiple // world_size + mod = multiple % world_size + local_multiple = div + int(local_rank < mod) + return local_multiple * multiple_of diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/generation.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/generation.py new file mode 100644 index 0000000000000000000000000000000000000000..0d9120c386596f25b544391af10dc479cf00c822 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/generation.py @@ -0,0 +1,740 @@ +# Copyright (c) 2023, Tri Dao. +# Adapted from https://github.com/NVIDIA/Megatron-LM/blob/0bb597b42c53355a567aba2a1357cc34b9d99ddd/megatron/text_generation/forward_step.py#L31 +import gc +import time +from collections import namedtuple +from dataclasses import dataclass, field +from functools import partial +from typing import Callable, Optional, Sequence, Union + +import torch +import torch.nn.functional as F +from einops import rearrange, repeat +from torch import Tensor +from torch.profiler import ProfilerActivity, profile, record_function + +try: + from transformers.generation import GreedySearchDecoderOnlyOutput, SampleDecoderOnlyOutput +except ImportError: + GreedySearchDecoderOnlyOutput = namedtuple("GreedySearchDecoderOnlyOutput", ["sequences", "scores"]) + SampleDecoderOnlyOutput = namedtuple("SampleDecoderOnlyOutput", ["sequences", "scores"]) + + +@dataclass +class InferenceParams: + """Inference parameters that are passed to the main model in order + to efficienly calculate and store the context during inference.""" + + max_seqlen: int + max_batch_size: int + seqlen_offset: int = 0 + batch_size_offset: int = 0 + key_value_memory_dict: dict = field(default_factory=dict) + lengths_per_sample: Optional[Tensor] = None + + def reset(self, max_seqlen, max_batch_size): + self.max_seqlen = max_seqlen + self.max_batch_size = max_batch_size + self.seqlen_offset = 0 + if self.lengths_per_sample is not None: + self.lengths_per_sample.zero_() + + +# https://github.com/NVIDIA/Megatron-LM/blob/0bb597b42c53355a567aba2a1357cc34b9d99ddd/megatron/text_generation/sampling.py +# https://github.com/huggingface/transformers/blob/a44985b41cfa2de48a5e1de7f1f93b7483da25d1/src/transformers/generation/logits_process.py#L231 +def modify_logits_for_top_k_filtering(logits, top_k): + """Set the logits for none top-k values to -inf. Done in-place.""" + indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None] + logits.masked_fill_(indices_to_remove, float("-Inf")) + + +# https://github.com/NVIDIA/Megatron-LM/blob/0bb597b42c53355a567aba2a1357cc34b9d99ddd/megatron/text_generation/sampling.py +# https://github.com/huggingface/transformers/blob/a44985b41cfa2de48a5e1de7f1f93b7483da25d1/src/transformers/generation/logits_process.py#L170 +def modify_logits_for_top_p_filtering(logits, top_p): + """Set the logits for none top-p values to -inf. Done in-place.""" + if top_p <= 0.0 or top_p >= 1.0: + return + # First sort and calculate cumulative sum of probabilities. + sorted_logits, sorted_indices = torch.sort(logits, descending=False) + cumulative_probs = sorted_logits.softmax(dim=-1).cumsum(dim=-1) + # Remove tokens with cumulative top_p above the threshold (token with 0 are kept) + sorted_indices_to_remove = cumulative_probs <= (1 - top_p) + # scatter sorted tensors to original indexing + indices_to_remove = sorted_indices_to_remove.scatter( + 1, sorted_indices, sorted_indices_to_remove + ) + logits.masked_fill_(indices_to_remove, float("-inf")) + + +def sample(logits, top_k=1, top_p=0.0, temperature=1.0): + """Sample from top-k logits. + Arguments: + logits: Tensor of shape (batch_size, vocab_size) + """ + if top_k == 1: # Short-circuit for greedy decoding + return logits.argmax(dim=-1) + else: + if top_p > 0.0: + assert top_p <= 1.0, "top-p should be in (0, 1]." + if top_k > 0: + top_k = min(top_k, logits.size(-1)) # Safety check + logits_top, indices = torch.topk(logits, top_k, dim=-1) + if temperature != 1.0: + logits_top /= temperature + modify_logits_for_top_p_filtering(logits_top, top_p) + return indices[ + torch.arange(indices.shape[0], device=indices.device), + torch.multinomial(torch.softmax(logits_top, dim=-1), num_samples=1).squeeze(dim=-1), + ] + else: + # Clone so that when we modify for top_p we don't change the original logits + logits_top = logits / temperature if temperature != 1.0 else logits.clone() + modify_logits_for_top_p_filtering(logits_top, top_p) + return torch.multinomial(torch.softmax(logits_top, dim=-1), num_samples=1).squeeze( + dim=-1 + ) + + +@torch.inference_mode() +def decode( + input_ids, + model, + max_length, + top_k=1, + top_p=0.0, + temperature=1.0, + eos_token_id=None, + teacher_outputs=None, + vocab_size=None, + tensor_parallel=1, + cg=False, + enable_timing=False, +): + """Decoding, either greedy or with top-k or top-p sampling. + If top-k = 0, don't limit the number of candidates (pure sampling). + Top-k and top-p can be used together. If top_k > 0 and top_p > 0, then top-k is applied first, + then top-p. + We assume that all sequences in the same batch have the same length. + + Arguments: + input_ids: (batch, seq_len) + max_length: int + teacher_outputs (optional): (batch, seq_len). If provided, instead of sampling from the + logits, the next token is taken from the teacher_outputs. Useful for testing. + Returns: GreedySearchDecoderOnlyOutput or SampleDecoderOnlyOutput, with the following fields: + sequences: (batch, max_length) + scores: tuples of (batch, vocab_size) + """ + batch_size, seqlen_og = input_ids.shape + teacher_output_len = teacher_outputs.shape[1] if teacher_outputs is not None else 0 + if cg: + if not hasattr(model, "_decoding_cache"): + model._decoding_cache = None + model._decoding_cache = update_graph_cache( + model, + model._decoding_cache, + batch_size, + seqlen_og, + max_length, + tensor_parallel=tensor_parallel, + ) + inference_params = model._decoding_cache.inference_params + inference_params.reset(max_length, batch_size) + else: + inference_params = InferenceParams(max_seqlen=max_length, max_batch_size=batch_size) + + def get_logits(input_ids, inference_params): + decoding = inference_params.seqlen_offset > 0 + if decoding: + position_ids = torch.full( + (batch_size, 1), + inference_params.seqlen_offset, + dtype=torch.long, + device=input_ids.device, + ) + else: + position_ids = None + if not cg or not decoding: + logits = model( + input_ids, + position_ids=position_ids, + inference_params=inference_params, + num_last_tokens=1, + ).logits.squeeze(dim=1) + else: + logits = model._decoding_cache.run( + input_ids, position_ids, inference_params.seqlen_offset + ).squeeze(dim=1) + return logits[..., :vocab_size] if vocab_size is not None else logits + + def sample_tokens(logits, inference_params): + if teacher_outputs is None or teacher_output_len <= inference_params.seqlen_offset: + token = sample(logits, top_k=top_k, top_p=top_p, temperature=temperature) + else: + token = teacher_outputs[:, inference_params.seqlen_offset] + # return rearrange(token, "b -> b 1") + return token.unsqueeze(1) + + def should_stop(current_token, inference_params): + if inference_params.seqlen_offset == 0: + return False + if eos_token_id is not None and (current_token == eos_token_id).all(): + return True + if inference_params.seqlen_offset >= max_length - 1: + return True + return False + + start = torch.cuda.Event(enable_timing=enable_timing) + end = torch.cuda.Event(enable_timing=enable_timing) + + if enable_timing: + if tensor_parallel > 1: + torch.distributed.barrier() + start.record() + scores, sequences = [], [input_ids] + while not should_stop(sequences[-1], inference_params): + scores.append(get_logits(sequences[-1], inference_params)) + inference_params.seqlen_offset += sequences[-1].shape[1] + sequences.append(sample_tokens(scores[-1], inference_params)) + if enable_timing: + end.record() + if tensor_parallel > 1: + torch.distributed.barrier() + torch.cuda.synchronize() + print(f"Prompt processing + decoding time: {(start.elapsed_time(end)):.0f}ms") + output_cls = GreedySearchDecoderOnlyOutput if top_k == 1 else SampleDecoderOnlyOutput + return output_cls(sequences=torch.cat(sequences, dim=1), scores=tuple(scores)) + + +def sample_speculative(logits, logits_draft, tokens_draft, top_k=1, top_p=0.0, temperature=1.0): + """Algorithm 1 from [1] + [1] Fast Inference from Transformers via Speculative Decoding + Yaniv Leviathan, Matan Kalman, Yossi Matias + https://arxiv.org/abs/2211.17192 + + Arguments: + logits: Tensor of shape (batch_size, seqlen + 1, vocab_size) + logits_draft: Tensor of shape (batch_size, seqlen, vocab_size) + tokens_draft: Tensor of shape (batch_size, seqlen) + Return: + tokens: Tensor of shape (batch_size, seqlen + 1) + num_generated_tokens: Tensor of shape (batch_size), with value in [1, seqlen + 1]. + For each sequence in the batch, the number of valid tokens that were sampled by + speculative sampling. + """ + batch, seqlen_p_1, vocab_size = logits.shape + seqlen = seqlen_p_1 - 1 + assert logits_draft.shape == (batch, seqlen, vocab_size) + assert tokens_draft.shape == (batch, seqlen) + assert tokens_draft.dtype in [torch.int64, torch.int32] + # TODO: if top_k = 1 we can simplify things and only work with indices + if top_p > 0.0: + assert top_p <= 1.0, "top-p should be in (0, 1]." + # Clone so that when we modify for top_p we don't change the original logits + logits = logits / temperature if temperature != 1.0 else logits.clone() + logits_draft = logits_draft / temperature if temperature != 1.0 else logits_draft.clone() + if top_k > 0: + top_k = min(top_k, logits.size(-1)) # Safety check + modify_logits_for_top_k_filtering(logits, top_k) + modify_logits_for_top_k_filtering(logits_draft, top_k) + modify_logits_for_top_p_filtering(logits, top_p) + modify_logits_for_top_p_filtering(logits_draft, top_p) + probs = torch.softmax(logits, dim=-1) + probs_draft = torch.softmax(logits_draft, dim=-1) + gather = lambda probs, tokens: rearrange( + probs.gather(dim=-1, index=rearrange(tokens, "... -> ... 1")), "... 1 -> ..." + ) + # (batch, seqlen) + accepted = torch.rand(batch, seqlen, device=probs.device) * gather( + probs_draft, tokens_draft + ) <= gather(probs[:, :-1], tokens_draft) + accepted_all = accepted.all(dim=-1) + # (batch,) + first_rejected_idx = torch.where(accepted_all, seqlen, accepted.int().argmin(dim=-1)) + probs_diff = torch.clamp(probs[:, :-1] - probs_draft, min=0.0) + # torch.multinomial can deal with unnormalized probabilities + # probs_diff /= probs_diff.sum(dim=-1, keepdim=True) + resample_probs = torch.cat([probs_diff, probs[:, -1:]], dim=1) + resample_probs = rearrange( + resample_probs.gather(dim=1, index=repeat(first_rejected_idx, "b -> b 1 d", d=vocab_size)), + "b 1 d -> b d", + ) + resample = torch.multinomial(resample_probs, num_samples=1).squeeze(dim=-1) # (batch,) + tokens = F.pad(tokens_draft, (0, 1)) + tokens[:, first_rejected_idx] = resample + return tokens, first_rejected_idx + 1 + + +@torch.inference_mode() +def decode_speculative( + input_ids, + model, + model_draft, + max_length, + speculative_lookahead=3, + top_k=1, + top_p=0.0, + temperature=1.0, + eos_token_id=None, + vocab_size=None, + tensor_parallel=1, + cg=False, + enable_timing=False, + debug=False, +): + """ + TD: WIP, for my own understanding, lightly tested. Only support batch_size == 1 for now. + + Speculative decoding, either greedy or with top-k or top-p sampling. + If top-k = 0, don't limit the number of candidates (pure sampling). + Top-k and top-p can be used together. If top_k > 0 and top_p > 0, then top-k is applied first, + then top-p. + We assume that all sequences in the same batch have the same length. + + Arguments: + input_ids: (batch, seq_len) + max_length: int + Returns: GreedySearchDecoderOnlyOutput or SampleDecoderOnlyOutput, with the following fields: + sequences: (batch, max_length) + scores: tuples of (batch, vocab_size) + """ + batch_size, seqlen_og = input_ids.shape + assert batch_size == 1, "Speculative decoding implementation only supports batch_size=1" + assert eos_token_id is None, "Speculative decoding implementation doesn't support eos_token_id" + if cg: + if not hasattr(model_draft, "_decoding_cache"): + model_draft._decoding_cache = None + model_draft._decoding_cache = update_graph_cache( + model_draft, + model_draft._decoding_cache, + batch_size, + seqlen_og, + max_length, + # draft model needs to process either 1 or 2 tokens at a time + decoding_seqlens=(1, 2), + tensor_parallel=tensor_parallel, + ) + inference_params_draft = model_draft._decoding_cache.inference_params + inference_params_draft.reset(max_length, batch_size) + if not hasattr(model, "_decoding_cache"): + model._decoding_cache = None + model._decoding_cache = update_graph_cache( + model, + model._decoding_cache, + batch_size, + seqlen_og, + max_length, + decoding_seqlens=range(1, speculative_lookahead + 2), + tensor_parallel=tensor_parallel, + ) + inference_params = model._decoding_cache.inference_params + inference_params.reset(max_length, batch_size) + else: + inference_params_draft = InferenceParams(max_seqlen=max_length, max_batch_size=batch_size) + inference_params = InferenceParams(max_seqlen=max_length, max_batch_size=batch_size) + + def get_logits(input_ids, inference_params, model, num_last_tokens=1, cg=False): + decoding = inference_params.seqlen_offset > 0 + if decoding: + seqlen = input_ids.shape[1] + # if inference_params.lengths_per_sample is None: + # TODO: in the case of batched decoding where each sequence has a different length, + # we need to compute the position_ids for each sequence using lengths_per_sample + if True: + cache_seqlens = torch.full( + (input_ids.shape[0],), + inference_params.seqlen_offset, + dtype=torch.int32, + device=input_ids.device, + ) + else: + cache_seqlens = inference_params.lengths_per_sample + position_ids = cache_seqlens[:, None] + torch.arange( + seqlen, dtype=torch.long, device=input_ids.device + ) + else: + position_ids = None + if not cg or not decoding: + logits = model( + input_ids, + position_ids=position_ids, + inference_params=inference_params, + num_last_tokens=num_last_tokens, + ).logits + else: + # NOTE: careful, CUDA graph is set to have num_last_tokens=input_ids.shape[1]. + # This might not be compatible the num_last_tokens used here. + assert num_last_tokens <= input_ids.shape[1] + logits = model._decoding_cache.run( + input_ids, position_ids, inference_params.seqlen_offset + )[:, -num_last_tokens:] + return logits[..., :vocab_size] if vocab_size is not None else logits + + def sample_tokens(input_ids, get_logits_fn, inference_params, sample_fn, num_tokens=1): + """Sample `num_tokens` tokens from the model, given the previous logits. + Also return the logits of the sampled tokens. + Arguments: + input_ids: (batch, seqlen) + Return: + tokens: (batch, num_tokens) + scores: (batch, num_tokens), which contains @previous_logits and the logits of the next + (num_tokens - 1) tokens. The logits of the last token isn't computed. + """ + assert num_tokens >= 1 + sequences, scores = [input_ids], [] + for i in range(num_tokens): + scores.append(get_logits_fn(sequences[-1], inference_params)[:, -1]) + inference_params.seqlen_offset += sequences[-1].shape[1] + sequences.append(sample_fn(scores[-1]).unsqueeze(1)) + return torch.cat(sequences[1:], dim=1), torch.stack(scores, dim=1) + + sampling_kwargs = dict(top_k=top_k, top_p=top_p, temperature=temperature) + sample_fn = partial(sample, **sampling_kwargs) + get_logits_main = partial(get_logits, model=model, cg=cg) + get_logits_draft = partial(get_logits, model=model_draft, cg=cg) + sample_tokens_main = partial( + sample_tokens, + get_logits_fn=get_logits_main, + sample_fn=sample_fn, + inference_params=inference_params, + ) + sample_tokens_draft = partial( + sample_tokens, + get_logits_fn=get_logits_draft, + sample_fn=sample_fn, + inference_params=inference_params_draft, + ) + + if debug: + from transformers import AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained("gpt2") + if enable_timing: + if tensor_parallel > 1: + torch.distributed.barrier() + torch.cuda.synchronize() + start = time.time() + + sequences, scores = [input_ids], [] + num_main_model_calls = 0 + num_draft_tokens = 0 + num_accepted_tokens_history = [] + if seqlen_og >= max_length - 1: + # Don't do speculative sampling, just sample 1 token from the model + tokens, scores_new = sample_tokens_main(input_ids, num_tokens=1) + sequences.append(tokens) + scores.append(scores_new) + else: + # Sample from draft model, which produces @n_spec_tokens, and @model + # will then use to produce between 1 and 1 + @n_spec_tokens tokens. + # We want seqlen_og + 1 + @n_spec_tokens to be <= @max_length. + n_spec_tokens = min(speculative_lookahead, max_length - seqlen_og - 1) + tokens_draft, scores_draft = sample_tokens_draft(input_ids, num_tokens=n_spec_tokens) + num_draft_tokens += n_spec_tokens + if debug: + scores_draft_ref = model_draft( + torch.cat([input_ids, tokens_draft], dim=1), num_last_tokens=n_spec_tokens + 1 + ).logits + print((scores_draft - scores_draft_ref[:, :-1]).abs().max()) + + # Evaluate the draft tokens with the model + logits = get_logits_main( + torch.cat([input_ids, tokens_draft], dim=1), + inference_params, + num_last_tokens=n_spec_tokens + 1, + ) + num_main_model_calls += 1 + if debug: + logits_ref = model( + torch.cat([input_ids, tokens_draft], dim=1), num_last_tokens=n_spec_tokens + 1 + ).logits + print((logits - logits_ref).abs().max()) + # breakpoint() + tokens, num_generated_tokens = sample_speculative( + logits, scores_draft, tokens_draft, **sampling_kwargs + ) + num_accepted_tokens_history.append(num_generated_tokens - 1) + if debug: + print(tokens) + print(num_generated_tokens) + # breakpoint() + # TODO: we're using the fact that batch_size == 1 + # TODO: check eos_token_id + sequences.append(tokens[:1, : num_generated_tokens[0]]) + scores.append(logits[:1, : num_generated_tokens[0]]) + # Note that @model has not evaluated the last sampled token yet, so we'll need to pass + # that in the next time we call @model. + num_generated = num_generated_tokens[0].item() + inference_params.seqlen_offset = seqlen_og + num_generated - 1 + inference_params_draft.seqlen_offset = ( + inference_params.seqlen_offset - 1 + if num_generated > 1 + else inference_params.seqlen_offset + ) + if debug: + cur_ids = torch.cat([input_ids, sequences[-1]], dim=1) + scores_ref = model(cur_ids, num_last_tokens=num_generated_tokens[0].item() + 1).logits + print((scores[-1] - scores_ref[:, :-1]).abs().max()) + # breakpoint() + + while True: + # seqlen_offset is total length generated - 1 + if inference_params.seqlen_offset >= max_length - 1: + break + if inference_params.seqlen_offset >= max_length - 2: + # Don't do speculative sampling, just sample 1 token from the model + tokens, scores_new = sample_tokens_main(sequences[-1][:, -1:], num_tokens=1) + sequences.append(tokens) + scores.append(scores_new) + break + # Sample from draft model + n_spec_tokens = min( + speculative_lookahead, max_length - inference_params_draft.seqlen_offset - 2 + ) + # If the main model accepts all the draft tokens, plus it samples one new token, + # then at the next iteration the draft model need to evaluate the logits of the last draft + # token and the logits of the newly sampled token. So here we pass in the last 2 tokens + # of sequences[-1]. + # This exception is when the main model rejects all the draft tokens, in which case we + # will only have 1 token to pass in. + tokens_draft, scores_draft = sample_tokens_draft( + sequences[-1][:, -2:], num_tokens=n_spec_tokens + ) + num_draft_tokens += n_spec_tokens + if debug: + scores_draft_ref = model_draft( + torch.cat([cur_ids, tokens_draft], dim=1), num_last_tokens=n_spec_tokens + 1 + ).logits + print((scores_draft - scores_draft_ref[:, :-1]).abs().max()) + # breakpoint() + # Evaluate the draft tokens with the model + logits = get_logits_main( + torch.cat([sequences[-1][:, -1:], tokens_draft], dim=1), + inference_params, + num_last_tokens=n_spec_tokens + 1, + ) # (batch, n_spec_tokens + 1, vocab_size) + num_main_model_calls += 1 + if debug: + logits_ref = model( + torch.cat([cur_ids, tokens_draft], dim=1), num_last_tokens=n_spec_tokens + 1 + ).logits + print((logits - logits_ref).abs().max()) + # breakpoint() + tokens, num_generated_tokens = sample_speculative( + logits, scores_draft, tokens_draft, **sampling_kwargs + ) + num_accepted_tokens_history.append(num_generated_tokens - 1) + if debug: + print(tokens) + print(num_generated_tokens) + # breakpoint() + sequences.append(tokens[:1, : num_generated_tokens[0]]) + scores.append(logits[:1, : num_generated_tokens[0]]) + # We've evaluated 1 token from sequences[-1][:, -1:] above, plus + # num_generated_tokens[0].item() - 1 tokens from the draft model. + num_generated = num_generated_tokens[0].item() + inference_params.seqlen_offset += num_generated + inference_params_draft.seqlen_offset = ( + inference_params.seqlen_offset - 1 + if num_generated > 1 + else inference_params.seqlen_offset + ) + if debug: + cur_ids = torch.cat([cur_ids, sequences[-1]], dim=1) + scores_ref = model(cur_ids, num_last_tokens=num_generated_tokens[0].item() + 1).logits + print((scores[-1] - scores_ref[:, :-1]).abs().max()) + # breakpoint() + + if enable_timing: + if tensor_parallel > 1: + torch.distributed.barrier() + torch.cuda.synchronize() + print(f"Prompt processing + decoding time: {(time.time() - start) * 1000:.0f}ms") + print(f"Number of calls to main model: {num_main_model_calls}") + print( + f"Acceptance rate: {torch.cat(num_accepted_tokens_history).sum().item() / num_draft_tokens * 100:.2f}%" + ) + sequences = torch.cat(sequences, dim=1) + scores = torch.cat(scores, dim=1) + if debug: + scores_ref = model(sequences).logits + print((scores - scores_ref[:, seqlen_og - 1 : -1]).abs().max()) + output_cls = GreedySearchDecoderOnlyOutput if top_k == 1 else SampleDecoderOnlyOutput + return output_cls(sequences=sequences, scores=scores) + + +class GenerationMixin: + def allocate_inference_cache(self, batch_size, max_seqlen, dtype=None, **kwargs): + raise NotImplementedError + + def generate( + self, + input_ids, + max_length, + top_k=1, + top_p=0.0, + temperature=1.0, + return_dict_in_generate=False, + output_scores=False, + **kwargs, + ): + output = decode( + input_ids, self, max_length, top_k=top_k, top_p=top_p, temperature=temperature, **kwargs + ) + if not output_scores: + output.scores = None + return output if return_dict_in_generate else output.sequences + + +def allocate_inference_cache( + max_batch_size, + max_seqlen, + nheads, + headdim, + layers: Union[int, Sequence], + device, + dtype=torch.float16, +): + assert dtype in [torch.float16, torch.bfloat16, torch.float32] + kv_cache_shape = (max_batch_size, max_seqlen, 2, nheads, headdim) + if isinstance(layers, int): + layers = range(layers) + return {i: torch.empty(kv_cache_shape, device=device, dtype=dtype) for i in layers} + + +@dataclass +class DecodingCGCache: + max_batch_size: int = 0 + max_seqlen: int = 0 + device = None + dtype = None + callables: dict = field(default_factory=dict) + mempool = None + inference_params: Optional[InferenceParams] = None + run: Optional[Callable] = None + + +@torch.inference_mode() +def update_graph_cache( + model, + cache, + batch_size, + seqlen_og, + max_seqlen, + decoding_seqlens=(1,), + tensor_parallel=1, + dtype=None, + n_warmups=2, +): + if cache is None: + cache = DecodingCGCache() + param_example = next(iter(model.parameters())) + device = param_example.device + if dtype is None: + dtype = param_example.dtype + if ( + (device, dtype) != (cache.device, cache.dtype) + or batch_size > cache.max_batch_size + or max_seqlen > cache.max_seqlen + ): # Invalidate the cache + cache.callables = {} + cache.mempool = None + cache.inference_params = None + gc.collect() + cache.device, cache.dtype = device, dtype + cache.max_batch_size, cache.max_seqlen = batch_size, max_seqlen + if hasattr(model, "allocate_inference_cache"): + inf_cache = model.allocate_inference_cache(batch_size, max_seqlen, dtype) + else: + headdim = getattr( + model.config, + "head_dim", + model.config.hidden_size // model.config.num_attention_heads, + ) + inf_cache = allocate_inference_cache( + batch_size, + max_seqlen, + model.config.num_attention_heads // tensor_parallel, + headdim, + model.config.num_hidden_layers, + device, + dtype, + ) + lengths_per_sample = torch.full((batch_size,), seqlen_og, dtype=torch.int32, device=device) + cache.inference_params = InferenceParams( + max_seqlen=max_seqlen, + max_batch_size=batch_size, + seqlen_offset=seqlen_og, + key_value_memory_dict=inf_cache, + lengths_per_sample=lengths_per_sample, + ) + cache.mempool = torch.cuda.graphs.graph_pool_handle() + for decoding_seqlen in decoding_seqlens: + if (batch_size, decoding_seqlen) not in cache.callables: + cache.callables[batch_size, decoding_seqlen] = capture_graph( + model, + cache.inference_params, + batch_size, + max_seqlen, + decoding_seqlen=decoding_seqlen, + mempool=cache.mempool, + n_warmups=n_warmups, + ) + + def dispatch(input_ids, position_ids, seqlen): + batch_size, decoding_seqlen = input_ids.shape[:2] + return cache.callables[batch_size, decoding_seqlen](input_ids, position_ids, seqlen) + + cache.run = dispatch + cache.inference_params.seqlen_offset = 0 # Reset so it's not confusing + return cache + + +def capture_graph( + model, inference_params, batch_size, max_seqlen, decoding_seqlen=1, mempool=None, n_warmups=2 +): + device = next(iter(model.parameters())).device + input_ids = torch.full((batch_size, decoding_seqlen), 0, dtype=torch.long, device=device) + position_ids = torch.full((batch_size, decoding_seqlen), 0, dtype=torch.long, device=device) + seqlen_offset_og = inference_params.seqlen_offset + inference_params.seqlen_offset = max_seqlen - decoding_seqlen + inference_params.lengths_per_sample[:] = inference_params.seqlen_offset + + # Warmup before capture + s = torch.cuda.Stream() + s.wait_stream(torch.cuda.current_stream()) + with torch.cuda.stream(s): + for _ in range(n_warmups): + logits = model( + input_ids, + position_ids=position_ids, + inference_params=inference_params, + num_last_tokens=decoding_seqlen, + ).logits + s.synchronize() + # This might be needed for correctness if we run with NCCL_GRAPH_MIXING_SUPPORT=0, + # which requires that graph launch and non-captured launch to not overlap (I think, + # that's how I interpret the documentation). I'm not sure if this is required. + if torch.distributed.is_initialized(): + torch.distributed.barrier() + torch.cuda.current_stream().wait_stream(s) + # Captures the graph + # To allow capture, automatically sets a side stream as the current stream in the context + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, pool=mempool): + logits = model( + input_ids, + position_ids=position_ids, + inference_params=inference_params, + num_last_tokens=decoding_seqlen, + ).logits + + def run(new_input_ids, new_position_ids, seqlen): + inference_params.lengths_per_sample[:] = seqlen + input_ids.copy_(new_input_ids) + position_ids.copy_(new_position_ids) + graph.replay() + return logits.clone() + + inference_params.seqlen_offset = seqlen_offset_og + return run diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/library.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/library.py new file mode 100644 index 0000000000000000000000000000000000000000..05324bb01a48daf051b0fee6b8000bd16d92da9d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/library.py @@ -0,0 +1,66 @@ +# Adapted from https://github.com/pytorch/pytorch/blob/v2.7.0/torch/_library/triton.py +# The PyTorch implementation simply ignores the schema argument, we simply modify it to use schema. + +from typing import Optional, Callable, Iterable, Union + +from torch.library import custom_op, CustomOpDef +from torch._library.triton import set_wrap_triton_enabled + + +def triton_op( + name: str, + fn: Optional[Callable] = None, + /, + *, + mutates_args: Union[str, Iterable[str]], + schema: Optional[str] = None, + # If allow_decomposition=True, this matches torch.library.triton_op behavior. If set to False, + # then it behaves like torch.library.custom_op instead, which doesn't decompose the operator + # and so inductor can't trace inside. + allow_decomposition=True, +) -> Callable: + def dec(fn: Callable[..., object]) -> CustomOpDef: + def backend_fn(*args, **kwargs): # type: ignore[no-untyped-def] + # Optimization: we're passing regular Tensors into the triton kernel, so + # no need to go through HOP dispatch + with set_wrap_triton_enabled(False): + return fn(*args, **kwargs) + + result = custom_op( + name, + backend_fn, + mutates_args=mutates_args, + # This is the only difference with the PyTorch implementation + schema=schema, + ) + from torch._subclasses.functional_tensor import FunctionalTensorMode + + # We require that the user pass us a function that is make_fx traceable, + # so we can just register it as the Fake/meta kernel. + result.register_fake(fn) + + if allow_decomposition: + # We decompose the operator when FunctionalTensorMode is active. + # The goal is to decompose the operator in AOTDispatcher. + # - With torch.compile, this means that the backend (usually Inductor) + # can see a call to the triton kernel(s) and so it can directly optimize + # them by inlining them into the lowering process. + def functional_decomp( # type: ignore[no-untyped-def] + mode, op, types, args, kwargs + ): + from torch.export._trace import custom_triton_ops_decomposition_disabled + + if custom_triton_ops_decomposition_disabled(): + return mode.__torch_dispatch__(op, types, args, kwargs) + else: + with mode: + return fn(*args, **kwargs) + + result.register_torch_dispatch(FunctionalTensorMode, functional_decomp) + + return result + + if fn is None: + return dec + else: + return dec(fn) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/pretrained.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/pretrained.py new file mode 100644 index 0000000000000000000000000000000000000000..40e76bd2692335c7f474f6b6479be67eb95f8d20 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/pretrained.py @@ -0,0 +1,79 @@ +import os +from functools import partial + +import torch +from safetensors.torch import load_file as safe_load_file +from transformers.utils import ( + SAFE_WEIGHTS_INDEX_NAME, + SAFE_WEIGHTS_NAME, + WEIGHTS_INDEX_NAME, + WEIGHTS_NAME, +) +from transformers.utils.hub import cached_file, get_checkpoint_shard_files + + +def state_dict_from_pretrained(model_name, device=None, dtype=None): + # If not fp32, then we don't want to load directly to the GPU + mapped_device = "cpu" if dtype not in [torch.float32, None] else device + is_sharded = False + load_safe = False + resolved_archive_file = None + + weights_path = os.path.join(model_name, WEIGHTS_NAME) + weights_index_path = os.path.join(model_name, WEIGHTS_INDEX_NAME) + safe_weights_path = os.path.join(model_name, SAFE_WEIGHTS_NAME) + safe_weights_index_path = os.path.join(model_name, SAFE_WEIGHTS_INDEX_NAME) + + if os.path.isfile(weights_path): + resolved_archive_file = cached_file( + model_name, WEIGHTS_NAME, _raise_exceptions_for_missing_entries=False + ) + elif os.path.isfile(weights_index_path): + resolved_archive_file = cached_file( + model_name, WEIGHTS_INDEX_NAME, _raise_exceptions_for_missing_entries=False + ) + is_sharded = True + elif os.path.isfile(safe_weights_path): + resolved_archive_file = cached_file( + model_name, SAFE_WEIGHTS_NAME, _raise_exceptions_for_missing_entries=False + ) + load_safe = True + elif os.path.isfile(safe_weights_index_path): + resolved_archive_file = cached_file( + model_name, SAFE_WEIGHTS_INDEX_NAME, _raise_exceptions_for_missing_entries=False + ) + is_sharded = True + load_safe = True + else: # Try loading from HF hub instead of from local files + resolved_archive_file = cached_file(model_name, WEIGHTS_NAME, + _raise_exceptions_for_missing_entries=False) + if resolved_archive_file is None: + resolved_archive_file = cached_file(model_name, WEIGHTS_INDEX_NAME, + _raise_exceptions_for_missing_entries=False) + if resolved_archive_file is not None: + is_sharded = True + + if resolved_archive_file is None: + raise EnvironmentError(f"Model name {model_name} was not found.") + + if load_safe: + loader = partial(safe_load_file, device=mapped_device) + else: + loader = partial(torch.load, map_location=mapped_device) + + if is_sharded: + # resolved_archive_file becomes a list of files that point to the different + # checkpoint shards in this case. + resolved_archive_file, sharded_metadata = get_checkpoint_shard_files( + model_name, resolved_archive_file + ) + state_dict = {} + for sharded_file in resolved_archive_file: + state_dict.update(loader(sharded_file)) + else: + state_dict = loader(resolved_archive_file) + # Convert dtype before moving to GPU to save memory + if dtype is not None: + state_dict = {k: v.to(dtype=dtype) for k, v in state_dict.items()} + state_dict = {k: v.to(device=device) for k, v in state_dict.items()} + return state_dict diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/testing.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..339af1767c47c5ec42acccec16fb769a3133766f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/testing.py @@ -0,0 +1,349 @@ +# Copyright (c) 2025, Jay Shah, Ganesh Bikshandi, Ying Zhang, Vijay Thakkar, Pradeep Ramani, Tri Dao. +import math + +import torch +from einops import rearrange, repeat + +from padding import pad_input, unpad_input + + +def generate_random_padding_mask(max_seqlen, batch_size, device, mode="random", zero_lengths=False): + assert mode in ["full", "random", "third"] + if mode == "full": + lengths = torch.full((batch_size, 1), max_seqlen, device=device, dtype=torch.int32) + elif mode == "random": + lengths = torch.randint( + max(0 if zero_lengths else 1, max_seqlen - 20), max_seqlen + 1, (batch_size, 1), device=device + ) + elif mode == "third": + lengths = torch.randint(max_seqlen // 3, max_seqlen + 1, (batch_size, 1), device=device) + + if zero_lengths: + # Generate zero-lengths every 5 batches and the last batch. + for i in range(batch_size): + if i % 5 == 0: + lengths[i] = 0 + lengths[-1] = 0 + padding_mask = ( + repeat(torch.arange(max_seqlen, device=device), "s -> b s", b=batch_size) < lengths + ) + return padding_mask + + +def generate_qkv( + q, k, v, query_padding_mask=None, key_padding_mask=None, qv=None, kvpacked=False, qkvpacked=False, + query_unused_mask=None, key_unused_mask=None, +): + """ + Arguments: + q: (batch_size, seqlen_q, nheads, d) + k: (batch_size, seqlen_k, nheads_k, d) + v: (batch_size, seqlen_k, nheads_k, d_v) + query_padding_mask: (batch_size, seqlen), bool + key_padding_mask: (batch_size, seqlen), bool + """ + assert not (kvpacked and qkvpacked) + batch_size, seqlen_q, nheads, d = q.shape + d_v = v.shape[-1] + _, seqlen_k, nheads_k, _ = k.shape + assert k.shape == (batch_size, seqlen_k, nheads_k, d) + assert v.shape == (batch_size, seqlen_k, nheads_k, d_v) + if query_unused_mask is not None or key_unused_mask is not None: + assert not kvpacked + assert not qkvpacked + + if query_padding_mask is not None: + q_unpad, indices_q, cu_seqlens_q, max_seqlen_q, seqused_q = unpad_input( + q, query_padding_mask, query_unused_mask + ) + output_pad_fn = lambda output_unpad: pad_input( + output_unpad, indices_q, batch_size, seqlen_q + ) + qv_unpad = rearrange(qv, "b s ... -> (b s) ...")[indices_q] if qv is not None else None + else: + q_unpad = rearrange(q, "b s h d -> (b s) h d") + cu_seqlens_q = torch.arange( + 0, (batch_size + 1) * seqlen_q, step=seqlen_q, dtype=torch.int32, device=q_unpad.device + ) + seqused_q = None + max_seqlen_q = seqlen_q + output_pad_fn = lambda output_unpad: rearrange( + output_unpad, "(b s) h d -> b s h d", b=batch_size + ) + qv_unpad = rearrange(qv, "b s ... -> (b s) ...") if qv is not None else None + + if key_padding_mask is not None: + k_unpad, indices_k, cu_seqlens_k, max_seqlen_k, seqused_k = unpad_input( + k, key_padding_mask, key_unused_mask + ) + v_unpad, *rest = unpad_input(v, key_padding_mask, key_unused_mask) + else: + k_unpad = rearrange(k, "b s h d -> (b s) h d") + v_unpad = rearrange(v, "b s h d -> (b s) h d") + cu_seqlens_k = torch.arange( + 0, (batch_size + 1) * seqlen_k, step=seqlen_k, dtype=torch.int32, device=k_unpad.device + ) + seqused_k = None + max_seqlen_k = seqlen_k + + if qkvpacked: + assert (query_padding_mask == key_padding_mask).all() + assert nheads == nheads_k + qkv_unpad = torch.stack([q_unpad, k_unpad, v_unpad], dim=1) + qkv = torch.stack([q, k, v], dim=2) + if query_padding_mask is not None: + dqkv_pad_fn = lambda dqkv_unpad: pad_input(dqkv_unpad, indices_q, batch_size, seqlen_q) + else: + dqkv_pad_fn = lambda dqkv_unpad: rearrange( + dqkv_unpad, "(b s) t h d -> b s t h d", b=batch_size + ) + return ( + qkv_unpad.detach().requires_grad_(), + cu_seqlens_q, + max_seqlen_q, + qkv.detach().requires_grad_(), + output_pad_fn, + dqkv_pad_fn, + ) + elif kvpacked: + kv_unpad = torch.stack([k_unpad, v_unpad], dim=1) + kv = torch.stack([k, v], dim=2) + dq_pad_fn = output_pad_fn + if key_padding_mask is not None: + dkv_pad_fn = lambda dkv_unpad: pad_input(dkv_unpad, indices_k, batch_size, seqlen_k) + else: + dkv_pad_fn = lambda dkv_unpad: rearrange( + dkv_unpad, "(b s) t h d -> b s t h d", b=batch_size + ) + return ( + q_unpad.detach().requires_grad_(), + kv_unpad.detach().requires_grad_(), + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + q.detach().requires_grad_(), + kv.detach().requires_grad_(), + output_pad_fn, + dq_pad_fn, + dkv_pad_fn, + ) + else: + dq_pad_fn = output_pad_fn + if key_padding_mask is not None: + dk_pad_fn = lambda dk_unpad: pad_input(dk_unpad, indices_k, batch_size, seqlen_k) + else: + dk_pad_fn = lambda dk_unpad: rearrange(dk_unpad, "(b s) h d -> b s h d", b=batch_size) + return ( + q_unpad.detach().requires_grad_(), + k_unpad.detach().requires_grad_(), + v_unpad.detach().requires_grad_(), + qv_unpad.detach() if qv is not None else None, + cu_seqlens_q, + cu_seqlens_k, + seqused_q, + seqused_k, + max_seqlen_q, + max_seqlen_k, + q.detach().requires_grad_(), + k.detach().requires_grad_(), + v.detach().requires_grad_(), + qv.detach() if qv is not None else None, + output_pad_fn, + dq_pad_fn, + dk_pad_fn, + ) + + +def construct_local_mask( + seqlen_q, + seqlen_k, + window_size=(-1, -1), # -1 means infinite window size + sink_token_length=0, + query_padding_mask=None, + key_padding_mask=None, + key_leftpad=None, + device=None, +): + row_idx = rearrange(torch.arange(seqlen_q, device=device, dtype=torch.long), "s -> s 1") + col_idx = torch.arange(seqlen_k, device=device, dtype=torch.long) + if key_leftpad is not None: + key_leftpad = rearrange(key_leftpad, "b -> b 1 1 1") + col_idx = repeat(col_idx, "s -> b 1 1 s", b=key_leftpad.shape[0]) + col_idx = torch.where(col_idx >= key_leftpad, col_idx - key_leftpad, 2**32) + sk = ( + seqlen_k + if key_padding_mask is None + else rearrange(key_padding_mask.sum(-1), "b -> b 1 1 1") + ) + sq = ( + seqlen_q + if query_padding_mask is None + else rearrange(query_padding_mask.sum(-1), "b -> b 1 1 1") + ) + if window_size[0] < 0: + return col_idx > row_idx + sk - sq + window_size[1] + else: + sk = torch.full_like(col_idx, seqlen_k) if key_padding_mask is None else sk + return torch.logical_or( + col_idx > torch.minimum(row_idx + sk - sq + window_size[1], sk), + torch.logical_and(col_idx < row_idx + sk - sq - window_size[0], col_idx >= sink_token_length), + ) + + +def construct_chunk_mask( + seqlen_q, + seqlen_k, + attention_chunk, + query_padding_mask=None, + key_padding_mask=None, + key_leftpad=None, + device=None, +): + row_idx = rearrange(torch.arange(seqlen_q, device=device, dtype=torch.long), "s -> s 1") + col_idx = torch.arange(seqlen_k, device=device, dtype=torch.long) + if key_leftpad is not None: + key_leftpad = rearrange(key_leftpad, "b -> b 1 1 1") + col_idx = repeat(col_idx, "s -> b 1 1 s", b=key_leftpad.shape[0]) + col_idx = torch.where(col_idx >= key_leftpad, col_idx - key_leftpad, 2**32) + sk = ( + seqlen_k + if key_padding_mask is None + else rearrange(key_padding_mask.sum(-1), "b -> b 1 1 1") + ) + sq = ( + seqlen_q + if query_padding_mask is None + else rearrange(query_padding_mask.sum(-1), "b -> b 1 1 1") + ) + sk = torch.full_like(col_idx, seqlen_k) if key_padding_mask is None else sk + # Subtract remainder instead of divide and then multiply to take care of negative values + col_limit_left_chunk = row_idx + sk - sq - (row_idx + sk - sq) % attention_chunk + return torch.logical_or( + col_idx < col_limit_left_chunk, col_idx >= col_limit_left_chunk + attention_chunk + ) + + +def attention_ref( + q, + k, + v, + query_padding_mask=None, + key_padding_mask=None, + key_leftpad=None, + attn_bias=None, + dropout_p=0.0, + dropout_mask=None, + causal=False, + qv=None, + q_descale=None, k_descale=None, v_descale=None, + window_size=(-1, -1), # -1 means infinite window size + attention_chunk=0, + sink_token_length=0, + softcap=0.0, + upcast=True, + reorder_ops=False, + intermediate_dtype=None, +): + """ + Arguments: + q: (batch_size, seqlen_q, nheads, head_dim) + k: (batch_size, seqlen_k, nheads, head_dim) + v: (batch_size, seqlen_k, nheads, head_dim_v) + qv: (batch_size, seqlen_q, nheads, head_dim_v) + query_padding_mask: (batch_size, seqlen_q) + key_padding_mask: (batch_size, seqlen_k) + attn_bias: broadcastable to (batch_size, nheads, seqlen_q, seqlen_k) + dropout_p: float + dropout_mask: (batch_size, nheads, seqlen_q, seqlen_k) + causal: whether to apply causal masking + upcast: whether to cast all inputs to fp32, do all computation in fp32, then cast + output back to fp16/bf16. + reorder_ops: whether to change the order of operations (scaling k instead of scaling k, etc.) + without changing the math. This is to estimate the numerical error from operation + reordering. + Output: + output: (batch_size, seqlen_q, nheads, head_dim_v) + attention: (batch_size, nheads, seqlen_q, seqlen_k), softmax after dropout + """ + if causal: + window_size = (window_size[0], 0) + dtype_og = q.dtype + if upcast: + q, k, v = q.float(), k.float(), v.float() + qv = qv.float() if qv is not None else None + if q_descale is not None: + q_descale = repeat(q_descale, "b h -> b 1 (h g) 1", g=q.shape[2] // k.shape[2]) + q = (q.float() * q_descale).to(q.dtype) + qv = (qv.float() * q_descale).to(qv.dtype) if qv is not None else None + if k_descale is not None: + k = (k.float() * rearrange(k_descale, "b h -> b 1 h 1")).to(dtype=k.dtype) + if v_descale is not None: + v = (v.float() * rearrange(v_descale, "b h -> b 1 h 1")).to(dtype=v.dtype) + seqlen_q, seqlen_k = q.shape[1], k.shape[1] + k = repeat(k, "b s h d -> b s (h g) d", g=q.shape[2] // k.shape[2]) + v = repeat(v, "b s h d -> b s (h g) d", g=q.shape[2] // v.shape[2]) + d = q.shape[-1] + dv = v.shape[-1] + softmax_scale = 1.0 / math.sqrt(d if qv is None else d + dv) + if not reorder_ops: + scores = torch.einsum("bthd,bshd->bhts", q * softmax_scale, k) + else: + scores = torch.einsum("bthd,bshd->bhts", q, k * softmax_scale) + if qv is not None: + scores = scores + torch.einsum("bthd,bshd->bhts", qv * softmax_scale, v) + if softcap > 0: + scores = torch.tanh(scores / softcap) * softcap + if key_padding_mask is not None: + scores.masked_fill_(rearrange(~key_padding_mask, "b s -> b 1 1 s"), float("-inf")) + local_mask = None + if window_size[0] >= 0 or window_size[1] >= 0: + local_mask = construct_local_mask( + seqlen_q, + seqlen_k, + window_size, + sink_token_length, + query_padding_mask, + key_padding_mask, + key_leftpad=key_leftpad, + device=q.device, + ) + if attention_chunk > 0: + chunk_mask = construct_chunk_mask( + seqlen_q, + seqlen_k, + attention_chunk, + query_padding_mask, + key_padding_mask, + key_leftpad=key_leftpad, + device=q.device, + ) + local_mask = torch.logical_or(local_mask, chunk_mask) if local_mask is not None else chunk_mask + if local_mask is not None: + scores.masked_fill_(local_mask, float("-inf")) + if attn_bias is not None: + scores = scores + attn_bias + attention = torch.softmax(scores, dim=-1).to(v.dtype) + # We want to mask here so that the attention matrix doesn't have any NaNs + # Otherwise we'll get NaN in dV + if query_padding_mask is not None: + attention = attention.masked_fill(rearrange(~query_padding_mask, "b s -> b 1 s 1"), 0.0) + # Without this we might get NaN in dv + if key_padding_mask is not None: + attention = attention.masked_fill(rearrange(~key_padding_mask, "b s -> b 1 1 s"), 0.0) + # Some rows might be completely masked out so we fill them with zero instead of NaN + if local_mask is not None: + attention = attention.masked_fill(torch.all(local_mask, dim=-1, keepdim=True), 0.0) + dropout_scaling = 1.0 / (1 - dropout_p) + # attention_drop = attention.masked_fill(~dropout_mask, 0.0) * dropout_scaling + # output = torch.einsum('bhts,bshd->bthd', attention_drop , v) + if dropout_mask is not None: + attention_drop = attention.masked_fill(~dropout_mask, 0.0) + else: + attention_drop = attention + if intermediate_dtype is not None: + attention_drop = attention_drop.to(intermediate_dtype).to(attention_drop.dtype) + output = torch.einsum("bhts,bshd->bthd", attention_drop, v * dropout_scaling) + if query_padding_mask is not None: + output.masked_fill_(rearrange(~query_padding_mask, "b s -> b s 1 1"), 0.0) + return output.to(dtype=dtype_og), attention.to(dtype=dtype_og) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/torch.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/torch.py new file mode 100644 index 0000000000000000000000000000000000000000..98cbf9a274cb1513c710fb749845ae241afa758a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/_flash_attn/utils/torch.py @@ -0,0 +1,21 @@ +import torch +from typing import Callable + + +def custom_amp_decorator(dec: Callable, cuda_amp_deprecated: bool): + def decorator(*args, **kwargs): + if cuda_amp_deprecated: + kwargs["device_type"] = "cuda" + return dec(*args, **kwargs) + return decorator + + +if hasattr(torch.amp, "custom_fwd"): # type: ignore[attr-defined] + deprecated = True + from torch.amp import custom_fwd, custom_bwd # type: ignore[attr-defined] +else: + deprecated = False + from torch.cuda.amp import custom_fwd, custom_bwd + +custom_fwd = custom_amp_decorator(custom_fwd, deprecated) +custom_bwd = custom_amp_decorator(custom_bwd, deprecated) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6677db08c0dcd87f7570a3249f61cc3eabe0532a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f0d31765c32d66ca9a0a38bef4e4fe908a56fdb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/batch_fetch_results.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/batch_fetch_results.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6f33ef6353bbd3786e585b882f4b1cd315638cb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/batch_fetch_results.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/batch_submit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/batch_submit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d8833a5e39a91f154436dddaa6e779bb24615b1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/batch_submit.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/run_grid_search.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/run_grid_search.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be7f09bc4c510286b334bf2288ae085d2f0b9b10 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/run_grid_search.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/run_tasks.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/run_tasks.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..30071ee56215b9ee5e68d58eed179f5dd01b009e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/run_tasks.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/run_with_submitit.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/run_with_submitit.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c155294ac31f91a26e17bcc02c4379f44daab7a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/__pycache__/run_with_submitit.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/batch_fetch_results.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/batch_fetch_results.py new file mode 100644 index 0000000000000000000000000000000000000000..88227ac3312c13e8a88ae6e8ebd4cd44c265aedd --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/batch_fetch_results.py @@ -0,0 +1,96 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import argparse +import json +import logging +from pathlib import Path +from typing import Any, Dict + +if __name__ == "__main__": + # Get the user requests + parser = argparse.ArgumentParser( + "Collect results from a given batch of distributed results" + ) + parser.add_argument("-ck", "--checkpoint_path", required=True) + args = parser.parse_args() + + logging.getLogger().setLevel(logging.INFO) + + # Go through all the data in the given repo, try to find the end results + root = Path(args.checkpoint_path) + + # - list all the mechanisms being benchmarked + results: Dict[str, Any] = {} + + for attention in filter(lambda x: x.is_dir(), root.iterdir()): + logging.info(f"\nFound results for {attention.stem}") + task_jsons = attention.glob("*/test_eval_summary.json") + results[attention.stem] = {} + + for task in task_jsons: + task_name = task.stem.split("__")[0] + logging.info(f"Logs found for task: {task_name}") + results[attention.stem][task_name] = -1 + found_result = False + + # - collect the individual results + with open(task, "r") as result_file: + dct = json.load(result_file) + if "test_accu_mean" in dct: + found_result = True + results[attention.stem][task_name] = dct["test_accu_mean"] + + logging.info( + f"Final result found for {task_name} at epoch {dct['train_step_idx']}: " + f"{results[attention.stem][task_name]}" + ) + else: + break + + # - report an error if no result was found + if not found_result: + ERR_TAIL = 30 + + logging.warning( + f"No result found for {task_name}, showing the error log in {task.parent}" + ) + err_log = Path(task.parent).glob("*.err") + print("*****************************************************") + with open(next(err_log), "r") as err_file: + for i, line in enumerate(reversed(err_file.readlines())): + print(line, end="") + if i > ERR_TAIL: + break + print("*****************************************************") + + logging.info(f"\nCollected results: {json.dumps(results, indent=2)}") + + # - reduction: compute the average + tasks = set(t for v in results.values() for t in v.keys()) + # -- fill in the possible gaps + for att in results.keys(): + for t in tasks: + if t not in results[att].keys(): + results[att][t] = 0.0 + + # -- add the average value + for att in results.keys(): + results[att]["AVG"] = round(sum(results[att][t] for t in tasks) / len(tasks), 2) + + # - Format as an array, markdown style + tasks_sort = sorted( + set(t for v in results.values() for t in v.keys()), reverse=True + ) + print( + "{0:<20}".format("") + "".join("{0:<20} ".format(t[:10]) for t in tasks_sort) + ) + + for att in results.keys(): + print( + "{0:<20}".format(att) + + "".join("{0:<20} ".format(results[att][t]) for t in tasks_sort) + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/batch_submit.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/batch_submit.py new file mode 100644 index 0000000000000000000000000000000000000000..a3077aa62a889fe28074d54ebaabe8e6a019f583 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/batch_submit.py @@ -0,0 +1,49 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import argparse +import os +from pathlib import Path + +from xformers.benchmarks.LRA.run_tasks import Task +from xformers.components.attention import ATTENTION_REGISTRY + + +def get_default_shared_folder() -> str: + checkpoint_paths = ["/checkpoint", "/checkpoints"] + for checkpoint_path in checkpoint_paths: + if Path(checkpoint_path).is_dir(): + return checkpoint_path + + return "." + + +if __name__ == "__main__": + default_checkpoint_path = get_default_shared_folder() + + # Get the user requests + parser = argparse.ArgumentParser( + "Benchmark different attention mechanisms on various sequence lengths" + ) + parser.add_argument("-c", "--config_path", required=True) + parser.add_argument("-ck", "--checkpoint_path", required=True) + parser.add_argument( + "-a", "--attentions", nargs="+", default=list(ATTENTION_REGISTRY.keys()) + ) + parser.add_argument("-t", "--tasks", nargs="+", default=[t.value for t in Task]) + parser.add_argument( + "--partition", default="a100", type=str, help="Partition where to submit" + ) + args = parser.parse_args() + + for attention in args.attentions: + for task in args.tasks: + os.system( + "python3 run_with_submitit.py" + + f" --attention {attention} --task {task} --config {args.config_path}" + + f" --checkpoint_dir {args.checkpoint_path}/{attention}/{task}" + + f" --partition {args.partition}" + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6677db08c0dcd87f7570a3249f61cc3eabe0532a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..441e8b9119566db278a04212cbfcd63fd0b3c5f6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/__pycache__/dataset.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/__pycache__/dataset.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e26b93e72903eb9614e4d4f714b21bd44e0499be Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/__pycache__/dataset.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/__pycache__/model_wrapper.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/__pycache__/model_wrapper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bb00a1c2abb6fe03eb0f99b68183da3b5090f83 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/__pycache__/model_wrapper.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/dataset.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..cf7e003219d73cf0123476b3ad08e0b0913d2642 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/dataset.py @@ -0,0 +1,46 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +# CREDITS: Almost as-is from the Nystromformer repo +# https://github.com/mlpen/Nystromformer + +import logging +import pickle + +import torch +from torch.utils.data.dataset import Dataset + +logging.getLogger().setLevel(logging.INFO) + + +class LRADataset(Dataset): + def __init__(self, file_path, seq_len): + with open(file_path, "rb") as f: + self.examples = pickle.load(f) + + self.seq_len = seq_len + logging.info(f"Loaded {file_path}... size={len(self.examples)}") + + def __len__(self): + return len(self.examples) + + def __getitem__(self, i): + return self.create_inst(self.examples[i], self.seq_len) + + @staticmethod + def create_inst(inst, seq_len): + output = { + "input_ids_0": torch.tensor(inst["input_ids_0"], dtype=torch.long)[:seq_len] + } + output["mask_0"] = (output["input_ids_0"] != 0).float() + + if "input_ids_1" in inst: + output["input_ids_1"] = torch.tensor(inst["input_ids_1"], dtype=torch.long)[ + :seq_len + ] + output["mask_1"] = (output["input_ids_1"] != 0).float() + output["label"] = torch.tensor(inst["label"], dtype=torch.long) + return output diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/model_wrapper.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/model_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..5eb3e2ca742614755a44740b4c18463f06e206d7 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/code/model_wrapper.py @@ -0,0 +1,288 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +# CREDITS: adapted from the Nystromformer repo +# https://github.com/mlpen/Nystromformer + +from enum import Enum +from typing import Dict, Union + +import pytorch_lightning as pl +import torch +import torch.nn as nn + +from xformers.components import build_attention +from xformers.components.multi_head_dispatch import MultiHeadDispatchConfig +from xformers.factory import xFormer, xFormerConfig, xFormerEncoderConfig +from xformers.utils import generate_matching_config + +PLOutput = Dict[str, Union[float, torch.Tensor]] + + +class Pooling(str, Enum): + MEAN = "mean" + CLS = "cls" + + +def pooling(mode: Pooling): + def pool_cls(inp): + return inp[:, 0, :] + + def pool_mean(inp): + return inp.mean(dim=1) + + return {Pooling.MEAN: pool_mean, Pooling.CLS: pool_cls}[mode] + + +def append_cls(inp, mask, vocab_size): + batch_size = inp.size(0) + cls_id = ( + (vocab_size - 1) * torch.ones(batch_size, dtype=torch.long, device=inp.device) + ).long() + cls_mask = torch.ones(batch_size, dtype=torch.float, device=mask.device) + inp = torch.cat([cls_id[:, None], inp[:, :-1]], dim=-1) + mask = torch.cat([cls_mask[:, None], mask[:, :-1]], dim=-1) + return inp, mask + + +def patch_model_config(config, attention_name): + # Rebuild a specific config out of generic + extra params + commons = config["common"] + try: + extra_attention_settings = config["extra_settings"]["attention"][attention_name] + except KeyError: + extra_attention_settings = None + + for bc in config["xformer"]: + bc["dim_model"] = commons["dim_model"] + bc["position_encoding_config"].update(commons) + bc["feedforward_config"].update(commons) + bc["multi_head_config"].update(commons) + bc["multi_head_config"]["attention"].update(commons) + bc["multi_head_config"]["attention"]["name"] = attention_name + bc["multi_head_config"]["attention"]["dim_head"] = ( + commons["dim_model"] / commons["num_heads"] + ) + if extra_attention_settings is not None: + bc["multi_head_config"]["attention"].update(extra_attention_settings) + + bc["multi_head_config"] = generate_matching_config( + bc["multi_head_config"], MultiHeadDispatchConfig + ) + bc["multi_head_config"].attention = build_attention( + bc["multi_head_config"].attention + ) + bc = generate_matching_config(bc, xFormerEncoderConfig) + + return config + + +class SCHead(nn.Module): + def __init__(self, config, dim_embedding, dim_mlp): + super().__init__() + self.pooling = pooling(Pooling(config["pooling_mode"])) + + self.mlpblock = nn.Sequential( + nn.Linear(dim_embedding, dim_mlp), + nn.ReLU(), + nn.Linear(dim_mlp, config["common"]["num_classes"]), + ) + + def forward(self, inp: torch.Tensor): + seq_score = self.mlpblock(self.pooling(inp)) + return seq_score + + +class SCHeadDual(nn.Module): + def __init__(self, config, dim_embedding, dim_mlp): + super().__init__() + self.pooling = pooling(Pooling(config["pooling_mode"])) + + self.mlpblock = nn.Sequential( + nn.Linear( + dim_embedding * 4, + dim_mlp, + ), + nn.ReLU(), + nn.Linear(dim_mlp, config["common"]["num_classes"]), + ) + + def forward(self, inp_0: torch.Tensor, inp_1: torch.Tensor): + X_0 = self.pooling(inp_0) + X_1 = self.pooling(inp_1) + seq_score = self.mlpblock(torch.cat([X_0, X_1, X_0 * X_1, X_0 - X_1], dim=-1)) + return seq_score + + +class ModelTrunk(pl.LightningModule): + def __init__(self, config, model_name): + super().__init__() + + config_model = config["model"] + self.config_training = config["training"] + + self.enable_amp = config["training"]["mixed_precision"] + self.pooling_mode = Pooling(config_model["pooling_mode"]) + self.vocab_size = config_model["common"]["vocab_size"] + + # Rebuild a specific config out of generic + extra params + self.config_model = patch_model_config(config_model, model_name) + self.model = xFormer.from_config(xFormerConfig(config_model["xformer"])) + self.norm = nn.LayerNorm(self.config_model["common"]["dim_model"]) + + ff_config = self.config_model["xformer"][0]["feedforward_config"] + self.dim_mlp = ( + self.config_model["common"]["dim_model"] + * ff_config["hidden_layer_multiplier"] + ) + + def training_step( # type: ignore + self, batch: Dict[str, torch.Tensor], batch_idx: int + ) -> PLOutput: + outputs = self(**batch) + self.logger.log_metrics({f"train_{k}": v for k, v in outputs.items()}) # type: ignore + self.log("train_accu", outputs["accu"], sync_dist=True) + return outputs + + def training_epoch_end(self, outputs): + logs = self.eval_epoch_end(outputs) + self.log("train_accu_mean", logs["accu"], sync_dist=True) + + def configure_optimizers(self): + optimizer = torch.optim.AdamW( + self.parameters(), + lr=self.config_training["learning_rate"], + betas=(0.9, 0.999), + eps=1e-6, + weight_decay=self.config_training["weight_decay"], + ) + + lr_scheduler = torch.optim.lr_scheduler.OneCycleLR( + optimizer=optimizer, + max_lr=self.config_training["learning_rate"], + pct_start=self.config_training["warmup"] + / self.config_training["num_train_steps"], + anneal_strategy=self.config_training["lr_decay"], + total_steps=self.config_training["num_train_steps"], + ) + + return [optimizer], [lr_scheduler] + + def eval_step(self, batch: Dict[str, torch.Tensor], batch_idx: int) -> PLOutput: + outputs = self(**batch) + return outputs + + def eval_epoch_end(self, outputs, prefix: str = "train"): + logs = {} + counts = torch.tensor([x["count"] for x in outputs]).float() + logs["count"] = counts.sum() + for k in ("accu", "loss"): + logs[k] = (torch.tensor([x[k] for x in outputs]) * counts).sum() / logs[ + "count" + ] + self.log(f"{prefix}_{k}_mean", logs[k], sync_dist=True) + return logs + + def validation_step( # type: ignore + self, batch: Dict[str, torch.Tensor], batch_idx: int + ) -> PLOutput: + outputs = self.eval_step(batch, batch_idx) + self.logger.log_metrics({f"val_{k}": v for k, v in outputs.items()}) # type: ignore + self.log("val_accu", outputs["accu"], sync_dist=True, prog_bar=True) + return outputs + + def validation_epoch_end(self, outputs): + self.eval_epoch_end(outputs, prefix="val") + + def test_step( # type: ignore + self, batch: Dict[str, torch.Tensor], batch_idx: int + ) -> PLOutput: + return self.eval_step(batch, batch_idx) + + def test_epoch_end(self, outputs): + self.eval_epoch_end(outputs, prefix="test") + + +class ModelForSC(ModelTrunk): + def __init__(self, config, model_name): + # Setup trunk + super().__init__(config, model_name) + + self.seq_classifer = SCHead( + self.config_model, + dim_embedding=self.config_model["common"]["dim_model"], + dim_mlp=self.dim_mlp, + ) + + def forward( # type: ignore + self, input_ids_0: torch.Tensor, mask_0: torch.Tensor, label: torch.Tensor + ): + + if self.pooling_mode == Pooling.CLS: + input_ids_0, mask_0 = append_cls(input_ids_0, mask_0, self.vocab_size) + + token_out = self.norm( + self.model(input_ids_0, encoder_input_mask=mask_0) + ) * mask_0.unsqueeze(-1) + + seq_scores = self.seq_classifer(token_out) + + seq_loss = torch.nn.CrossEntropyLoss(reduction="none")(seq_scores, label) + seq_accu = (seq_scores.argmax(dim=-1) == label).to(torch.float32) + outputs = { + "loss": seq_loss.mean(), + "accu": seq_accu.mean(), + "count": label.size(0), + } + + return outputs + + +class ModelForSCDual(ModelTrunk): + def __init__(self, config, model_name): + # Setup trunk + super().__init__(config, model_name) + + self.seq_classifer = SCHeadDual( + self.config_model, + dim_embedding=self.config_model["common"]["dim_model"], + dim_mlp=self.dim_mlp, + ) + + def forward( # type: ignore + self, + input_ids_0: torch.Tensor, + input_ids_1: torch.Tensor, + mask_0: torch.Tensor, + mask_1: torch.Tensor, + label: torch.Tensor, + ): + + mask_0, mask_1 = mask_0.long(), mask_1.long() + + if self.pooling_mode == Pooling.CLS: + input_ids_0, mask_0 = append_cls(input_ids_0, mask_0, self.vocab_size) + input_ids_1, mask_1 = append_cls(input_ids_1, mask_1, self.vocab_size) + + # Concatenate the two inputs into one batch + input_ids = torch.cat([input_ids_0, input_ids_1], dim=0) + masks = torch.cat([mask_0, mask_1], dim=0) + + tokens_out = self.norm( + self.model(input_ids, encoder_input_mask=masks) + ) * masks.unsqueeze(-1) + + seq_scores = self.seq_classifer(*torch.chunk(tokens_out, 2, dim=0)) + + seq_loss = torch.nn.CrossEntropyLoss(reduction="none")(seq_scores, label) + seq_accu = (seq_scores.argmax(dim=-1) == label).to(torch.float32) + outputs = { + "loss": seq_loss.mean(), + "accu": seq_accu.mean(), + "count": label.size(0), + } + + return outputs diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/run_grid_search.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/run_grid_search.py new file mode 100644 index 0000000000000000000000000000000000000000..825ae8fb8d6e059354c5740e9c70ea00d9fa9b1b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/run_grid_search.py @@ -0,0 +1,148 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import itertools +import os +import uuid +from datetime import date +from pathlib import Path +from typing import Dict, Iterable + +import submitit + +from xformers.benchmarks.LRA.run_with_submitit import ( + get_init_file, + get_shared_folder, + parse_args, + Trainer, +) + + +def grid_parameters(grid: Dict): + """ + Yield all combinations of parameters in the grid (as a dict) + """ + grid_copy = dict(grid) + # Turn single value in an Iterable + for k in grid_copy: + if not isinstance(grid_copy[k], Iterable): + grid_copy[k] = [grid_copy[k]] + for p in itertools.product(*grid_copy.values()): + yield dict(zip(grid.keys(), p)) + + +def grid_search(args): + if args.checkpoint_dir == "": + args.checkpoint_dir = get_shared_folder() / "%j" + + date_curr = date.today().strftime("%m-%d-%Y") + orig_check_dir = os.path.join(args.checkpoint_dir, date_curr) + + # Create the executor + # Note that the folder will depend on the job_id, to easily track experiments + executor = submitit.AutoExecutor( + folder=get_shared_folder() / "%j", slurm_max_num_timeout=30 + ) + num_gpus_per_node = args.ngpus + nodes = args.nodes + args.world_size = args.nodes * args.ngpus + partition = args.partition + + executor.update_parameters( + gpus_per_node=num_gpus_per_node, + tasks_per_node=num_gpus_per_node, # one task per GPU + cpus_per_task=10, + nodes=nodes, + timeout_min=60 * 72, + slurm_signal_delay_s=120, + slurm_partition=partition, + ) + executor.update_parameters(name="lra") + + if args.task == "text": + grid_meta = { + "training:learning_rate": ( + [1e-4, 2e-4, 3e-4, 5e-5], + lambda val: f"lr{val}", + ), + "training:warmup": ([3000, 8000], lambda val: f"warmup{val}"), + "training:seed": ([1234, 32, 1994], lambda val: f"seed{val}"), + "training:weight_decay": ([0.02, 0.05, 0.01], lambda val: f"wd{val}"), + "model:pooling_model": (["cls"], lambda val: f"pool-{val}"), + "model:common:dropout": ([0, 0.05], lambda val: f"drop{val}"), + } + elif args.task == "retrieval": + grid_meta = { + "training:learning_rate": ([1e-4, 3e-4], lambda val: f"lr{val}"), + "training:warmup": ([2000, 8000], lambda val: f"warmup{val}"), + "training:seed": ([4096, 1234, 3, 15, 5], lambda val: f"seed{val}"), + "training:weight_decay": ([0.01, 0], lambda val: f"wd{val}"), + "model:pooling_model": (["cls"], lambda val: f"pool-{val}"), + "model:common:dropout": ([0], lambda val: f"drop{val}"), + } + elif args.task == "listops": + grid_meta = { + "training:learning_rate": ( + [1e-4, 2e-4, 3e-4, 5e-5], + lambda val: f"lr{val}", + ), + "training:warmup": ([3000, 2000], lambda val: f"warmup{val}"), + "training:seed": ( + [ + 1234, + ], + lambda val: f"seed{val}", + ), + "training:weight_decay": ([0.02, 0.05, 0, 1], lambda val: f"wd{val}"), + "model:pooling_model": (["cls"], lambda val: f"pool-{val}"), + "model:common:dropout": ([0], lambda val: f"drop{val}"), + } + else: + grid_meta = { + "training:learning_rate": ([1e-4, 5e-5], lambda val: f"lr{val}"), + "training:warmup": ([8000], lambda val: f"warmup{val}"), + "training:seed": ([1234, 4321, 3], lambda val: f"seed{val}"), + "training:weight_decay": ([0.01], lambda val: f"wd{val}"), + "model:pooling_model": (["cls"], lambda val: f"pool-{val}"), + "model:common:dropout": ([0.1], lambda val: f"drop{val}"), + } + + grid = {k: v[0] for k, v in grid_meta.items()} + save_key = {k: v[1] for k, v in grid_meta.items()} + + hyper_parameters = list(grid_parameters(grid)) + jobs = [] + + for i, grid_data in enumerate(hyper_parameters): + + args.sweep_parameters = grid_data + run_name = f"{args.attention}" + # run_name = "paper_config" + for k, v in grid_data.items(): + run_name += "prenorm-" + save_key[k](v) + args.checkpoint_dir = os.path.join( + orig_check_dir, f"{args.task}", "logs", run_name + ) + Path(args.checkpoint_dir).mkdir(parents=True, exist_ok=True) + args.tb_dir = os.path.join(orig_check_dir, f"{args.task}", "tb", run_name) + Path(args.tb_dir).mkdir(parents=True, exist_ok=True) + + # Chronos needs a different job name each time + executor.update_parameters(name=f"lra_{args.task}_{i:02d}_{uuid.uuid4().hex}") + + args.dist_url = get_init_file().as_uri() + args.temp_file = str(get_init_file()) + + trainer = Trainer(args) + job = executor.submit(trainer) + jobs.append(job) + print(f"Run {i:02d} submitted with train cfg: {args}") + print(f"Submitted jobs ids: {','.join([str(job.job_id) for job in jobs])}") + + +if __name__ == "__main__": + args = parse_args() + grid_search(args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/run_tasks.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/run_tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..25fea8a50045b818a3822997cd1b756164d1ce64 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/run_tasks.py @@ -0,0 +1,302 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import argparse +import json +import logging +import os +from enum import Enum +from pathlib import Path +from typing import cast, Dict, Tuple + +import pytorch_lightning as pl +import torch +import torch.nn as nn +from fvcore.nn import flop_count_str, FlopCountAnalysis +from pytorch_lightning.callbacks import ModelCheckpoint, TQDMProgressBar +from pytorch_lightning.loggers import TensorBoardLogger +from pytorch_lightning.strategies import DDPStrategy +from torch.utils.data import DataLoader + +from xformers.benchmarks.LRA.code.dataset import LRADataset +from xformers.benchmarks.LRA.code.model_wrapper import ModelForSC, ModelForSCDual +from xformers.components.attention import ATTENTION_REGISTRY + + +class Task(str, Enum): + Retrieval = "retrieval" + ListOps = "listops" + Image = "image" + PathfinderBaseline = "pathfinder32-curv_baseline" + PathfinderContour9 = "pathfinder32-curv_contour_length_9" + PathfinderContour14 = "pathfinder32-curv_contour_length_14" + Text = "text" + + +def load_config(path: str) -> Dict: + with open(Path(path).absolute(), "r") as fileio: + config = json.load(fileio) + + # Duplicate the pathfinder configs + config["pathfinder32-curv_baseline"] = config["pathfinder32"] + config["pathfinder32-curv_contour_length_9"] = config["pathfinder32"] + config["pathfinder32-curv_contour_length_14"] = config["pathfinder32"] + return config + + +def build_model(args: argparse.Namespace, config: Dict) -> nn.Module: + task = args.task + attention_name = args.attention + + model = cast( + pl.LightningModule, + ( + ModelForSCDual(config[f"{task}"], attention_name) + if task == Task.Retrieval + else ModelForSC(config[f"{task}"], attention_name) + ), + ) + + logging.info(model) + summary = pl.utilities.model_summary.LayerSummary(model) + logging.info(f"num_parameter: {summary.num_parameters // 1e3 / 1e3}M") + + with torch.no_grad(): + # Check the flops + seq_len = config[f"{task}"]["model"]["common"]["seq_len"] + x = torch.rand(1, seq_len).long() + mask = torch.rand(1, seq_len).long() + indices = torch.rand(1, seq_len).long() + flops = FlopCountAnalysis(model.model, (x, mask, indices)) + logging.info(f"complexity: {round(flops.total()/1e9, 3)} GFlops") + logging.info(flop_count_str(flops)) + + return model + + +def get_arg_parser(): + parser = argparse.ArgumentParser() + parser.add_argument( + "--attention", + type=str, + help=f"Attention mechanism to chose, among {list(ATTENTION_REGISTRY.keys())}. \ + A list can be passed to test several mechanisms in sequence", + dest="attention", + required=True, + ) + parser.add_argument( + "--task", + type=Task, + help=f"Task to chose, among {[t.value for t in Task]}.", + dest="task", + required=True, + ) + parser.add_argument( + "--skip_train", + type=bool, + help="Whether to skip training, and test an existing model", + dest="skip_train", + default=False, + ) + parser.add_argument( + "--config", + type=str, + help="Path to the config being used", + dest="config", + default="./config.json", + ) + parser.add_argument( + "--checkpoint_dir", + type=str, + help="Path to the checkpoint directory", + dest="checkpoint_dir", + default=f"/checkpoints/{os.getenv('USER')}/xformers", + ) + parser.add_argument( + "--checkpoint_path", + type=str, + help="Path to checkpoint", + ) + parser.add_argument( + "--debug", + help="Make it easier to debug a possible issue", + dest="debug", + default=False, + action="store_true", + ) + parser.add_argument( + "--world_size", + help="Number of GPUs used", + dest="world_size", + type=int, + default=1, + ) + parser.add_argument( + "--sweep_parameters", + help="Rewrite some hyperparameters in the config", + dest="sweep_parameters", + type=dict, + default=None, + ) + return parser + + +def setup_log(args, attention_name, task) -> Tuple[str, TensorBoardLogger]: + experiment_name = f"{task}__{attention_name}" + logger = TensorBoardLogger( + save_dir=args.checkpoint_dir, + name="", # remove lightning_logs subdirectory + version=experiment_name, + ) + log_dir = os.path.join(logger._save_dir, experiment_name) + return log_dir, logger + + +def rewrite_hyper(config, rewrites): + def replace(config_dict, k, v): + if len(k.split(":")) == 1: + config_dict[k] = v + return + first_key = k.split(":")[0] + assert first_key in config_dict, first_key + k = k[len(first_key) + 1 :] + replace(config_dict[first_key], k, v) + + for k, v in rewrites.items(): + replace(config, k, v) + return config + + +def build_dataloaders( + args: argparse.Namespace, + config_training: Dict, + num_workers: int = 4, +) -> Dict[str, DataLoader]: + datasets = {} + for component in ("train", "dev", "test"): + datasets[component] = LRADataset( + file_path=f"datasets/{args.task}.{component}.pickle", + seq_len=config_training["seq_len"], + ) + + # Gradient accumulation + accumu_steps = config_training["gradient_accumulation"] + logging.info(f"accumu_steps={accumu_steps}") + + # Batch size + per_gpu_batch_size = ( + config_training["batch_size"] // args.world_size // accumu_steps + ) + logging.warning( + f"Requested batch size: {config_training['batch_size']}. Given world\ + size and grad accumulation, per-gpu batch is\ + {per_gpu_batch_size}" + ) + + dataloaders = { + k: DataLoader( + v, + batch_size=per_gpu_batch_size, + shuffle=False, + pin_memory=True, + num_workers=num_workers, + ) + for k, v in datasets.items() + } + return dataloaders + + +def get_eval_summary(trainer: pl.Trainer) -> Dict[str, float]: + eval_summary: Dict[str, float] = {"train_step_idx": trainer.global_step} + for k, v in trainer.callback_metrics.items(): + eval_summary[k] = v.item() + return eval_summary + + +class BasicProgressBar(TQDMProgressBar): + def get_metrics(self, trainer, model): + items = super().get_metrics(trainer, model) + items.pop("v_num", None) + return items + + +def benchmark(args): + log_dir, logger = setup_log(args, f"{args.attention}", f"{args.task}") + args.logger = logger + + config = load_config(args.config) + + config_task = config[f"{args.task}"] + if args.sweep_parameters is not None: + logging.info("Replacing hyperparameters") + rewrite_hyper(config_task, args.sweep_parameters) + + config_training = config_task["training"] + config_training["seq_len"] = config_task["model"]["common"]["seq_len"] + logging.info(f"Learning rate: {config_training['learning_rate']}") + + pl.seed_everything(config_training.get("seed", 0)) + dataloaders = build_dataloaders(args, config_training) + + model = build_model(args, config) + + progress_bar = BasicProgressBar() + checkpoint_callback = ModelCheckpoint( + monitor="val_accu", + mode="max", + dirpath=args.checkpoint_dir, + filename="{epoch}-{val_accu:.2f}", + every_n_train_steps=config_training["eval_frequency"], + ) + + trainer = pl.Trainer( + accelerator="gpu", + strategy=( + DDPStrategy(find_unused_parameters=args.debug) + if not args.skip_train + else None + ), + accumulate_grad_batches=config_training["gradient_accumulation"], + callbacks=[progress_bar, checkpoint_callback], + detect_anomaly=args.debug, + deterministic=True, + gpus=args.world_size, + limit_val_batches=config_training["num_eval_steps"], + logger=logger, + max_steps=config_training["num_train_steps"], + num_sanity_val_steps=int(not args.skip_train), + precision=16 if config_training["mixed_precision"] else 32, + val_check_interval=config_training["eval_frequency"] + / float(len(dataloaders["train"])), + ) + + if not args.skip_train: + trainer.fit( + model, + train_dataloaders=dataloaders["train"], + val_dataloaders=dataloaders["dev"], + ) + ckpt_path = checkpoint_callback.best_model_path + else: + ckpt_path = args.checkpoint_path + + trainer.test( + model, + dataloaders=dataloaders["test"], + ckpt_path=ckpt_path, + ) + eval_summary = get_eval_summary(trainer) + with open(os.path.join(log_dir, "test_eval_summary.json"), "w") as f: + logging.info(f"Saving test results at {f.name}") + json.dump(eval_summary, f) + + +if __name__ == "__main__": + parser = get_arg_parser() + args = parser.parse_args() + if args.skip_train and args.checkpoint_path is None: + raise parser.error("Must provide --checkpoint_path if --skip_train=True") + benchmark(args) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/run_with_submitit.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/run_with_submitit.py new file mode 100644 index 0000000000000000000000000000000000000000..6fefdd1f54ff7a3c312f8010913dc3955805b539 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/LRA/run_with_submitit.py @@ -0,0 +1,153 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +""" +A script to run multinode training with submitit. +Almost copy-paste from https://github.com/facebookresearch/deit/blob/main/run_with_submitit.py +""" + +import argparse +import os +import uuid +from pathlib import Path + +import submitit + +from xformers.benchmarks.LRA.run_tasks import benchmark, get_arg_parser + + +def parse_args(): + parser = argparse.ArgumentParser( + "Submitit for LRA", parents=[get_arg_parser()], add_help=False + ) + parser.add_argument( + "--ngpus", default=1, type=int, help="Number of gpus to request on each node" + ) + parser.add_argument( + "--nodes", default=1, type=int, help="Number of nodes to request" + ) + parser.add_argument("--timeout", default=2800, type=int, help="Duration of the job") + + parser.add_argument( + "--partition", default="a100", type=str, help="Partition where to submit" + ) + parser.add_argument( + "--use_volta32", action="store_true", help="Big models? Use this" + ) + parser.add_argument( + "--enforce_host_memory", action="store_true", help="Use if the host OOMs" + ) + + parser.add_argument( + "--comment", + default="", + type=str, + help="Comment to pass to scheduler, e.g. priority message", + ) + return parser.parse_args() + + +def get_shared_folder() -> Path: + user = os.getenv("USER") + checkpoint_paths = ["/checkpoint", "/checkpoints"] + for checkpoint_path in checkpoint_paths: + if Path(checkpoint_path).is_dir(): + p = Path(f"{checkpoint_path}/{user}/xformers/submitit") + p.mkdir(exist_ok=True, parents=True) + return p + raise RuntimeError(f"No shared folder available - considering {checkpoint_paths}") + + +def get_init_file(): + # Init file must not exist, but it's parent dir must exist. + os.makedirs(str(get_shared_folder()), exist_ok=True) + init_file = get_shared_folder() / f"{uuid.uuid4().hex}_init" + if init_file.exists(): + os.remove(str(init_file)) + return init_file + + +class Trainer: + def __init__(self, args): + self.args = args + + def __call__(self): + self._setup_gpu_args() + benchmark(self.args) + + def checkpoint(self): + self.args.dist_url = get_init_file().as_uri() + print("Requeuing ", self.args) + empty_trainer = type(self)(self.args) + return submitit.helpers.DelayedSubmission(empty_trainer) + + def _setup_gpu_args(self): + job_env = submitit.JobEnvironment() + self.args.checkpoint_dir = Path( + str(self.args.checkpoint_dir).replace("%j", str(job_env.job_id)) + ) + self.args.gpu = job_env.local_rank + self.args.rank = job_env.global_rank + self.args.world_size = job_env.num_tasks + print(f"Process group: {job_env.num_tasks} tasks, rank: {job_env.global_rank}") + + +def main(): + args = parse_args() + if args.checkpoint_dir == "": + args.checkpoint_dir = get_shared_folder() / "%j" + Path(args.checkpoint_dir).mkdir(parents=True, exist_ok=True) + executor = submitit.AutoExecutor( + folder=args.checkpoint_dir, slurm_max_num_timeout=30 + ) + + num_gpus_per_node = args.ngpus + nodes = args.nodes + timeout_min = args.timeout + args.world_size = args.nodes * args.ngpus + + partition = args.partition + + kwargs = { + "gpus_per_node": num_gpus_per_node, + "tasks_per_node": num_gpus_per_node, # one task per GPU + "cpus_per_task": 10, + "nodes": nodes, + "timeout_min": timeout_min, # max is 60 * 72 + # Below are cluster dependent parameters + "slurm_partition": partition, + "slurm_signal_delay_s": 120, + } + + if args.enforce_host_memory: + kwargs["mem_gb"] = (40 * num_gpus_per_node,) + + if args.use_volta32: + kwargs["slurm_constraint"] = "volta32gb" + + if args.comment: + kwargs["slurm_comment"] = args.comment + + executor.update_parameters( + **kwargs, + ) + + executor.update_parameters(name="lra") + + args.dist_url = get_init_file().as_uri() + args.temp_file = str(get_init_file()) + + trainer = Trainer(args) + job = executor.submit(trainer) + + print(f"Submitted job_id: {job.job_id}") + print(f"Logs and checkpoints will be saved at: {args.checkpoint_dir}") + with open(Path(f"{args.checkpoint_dir}") / Path("jobs.txt"), "a") as jobfile: + jobfile.write(f"{job.job_id}\n") + + +if __name__ == "__main__": + main() diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6677db08c0dcd87f7570a3249f61cc3eabe0532a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50cc7b784e67826e4c0f1f65912589525ce47cd3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_attn_decoding.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_attn_decoding.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df30a874e55eebf4559029af7fba0d14e48a7b42 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_attn_decoding.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_core.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b4c2958b0e45c0333fddc9b096203ee35d2acae Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_core.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_indexing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_indexing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13a2cdf09cd8ba8327184edece2d0b43299a180f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_indexing.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_mem_eff_attention.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_mem_eff_attention.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7cd4890027b9cc893111087a25286758bf907d81 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_mem_eff_attention.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_merge_attentions.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_merge_attentions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1484c282dfcfe31e4237db6dd4a850249056a85 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_merge_attentions.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_nystrom_utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_nystrom_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b06a3bceccfc8a73eef2909f8bf5772905a935f2 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_nystrom_utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_revnet.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_revnet.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..417d7b483deed8657c787bf4ae3af03e6b77ce0c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_revnet.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_sddmm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_sddmm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a656310643df790a75ea603a0ad2e339c2567058 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_sddmm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_sequence_parallel_fused.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_sequence_parallel_fused.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75a594beee7b563bef5aeb083fbe4beeb1913437 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_sequence_parallel_fused.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_sp24.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_sp24.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..434d4a40857bd688cd64ff0d41b2069f76422b52 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_sp24.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_swiglu.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_swiglu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..423e8062945b823785524df40d4e52db5c37fa00 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_swiglu.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_tiled_matmul.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_tiled_matmul.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94931f5467312838abb65fe4b75931e08289ddba Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/benchmark_tiled_matmul.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c716dd9cc9a3bd7b2bdd09d0ff5f9534edf4321d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_attn_decoding.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_attn_decoding.py new file mode 100644 index 0000000000000000000000000000000000000000..30ef3abee4b7a1a860ffaf30c35c397e82b45673 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_attn_decoding.py @@ -0,0 +1,472 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +# Run with --omit-baselines to skip slow baselines. +# See other CLI arguments in benchmark_main_helper in utils.py. + +import sys +from typing import Any, Dict, Type + +import pytest +import torch + +import xformers.ops as xops +from xformers.attn_bias_utils import create_attn_bias +from xformers.benchmarks.utils import benchmark_main_helper2, NotSupportedInputError + +min_run_time = 0.5 +device = torch.device("cuda") + + +CASES = [ + dict( + B=max(1, 2 ** (16 - i)), + Mq=1, + Mkv=2**i, + Hq=16, + Hkv=hkv, + K=128, + attn_bias_type=xops.fmha.attn_bias.BlockDiagonalCausalWithOffsetPaddedKeysMask, + ) + for i in range(8, 18) + for hkv in (1, 2) +] + + +def quantize_kv_int4(k: torch.Tensor, num_groups: int = 1) -> torch.Tensor: + """ + Auxiliary int4 row quantization function used for benchmarking and tests. + Matches the behaviour of torch.ops.llama_cpp.dequantize_int4_cache - + quantization parameters (scale and offset) of each row along the last + dimension of the tensor are assumed to be packed into two float16 values + at the beginning of the row. + """ + # Scale and shift are such that quantization linearly maps int4 values range [0..15] + # to input values range min(k)..max(k) individually for every row + k = k.reshape(*k.shape[:-1], num_groups, k.shape[-1] // num_groups) + # print(f"k_reshape = {k.shape}") + max_vals = torch.max(k, dim=-1, keepdim=True).values + min_vals = torch.min(k, dim=-1, keepdim=True).values + scale_k: torch.Tensor = (max_vals - min_vals) / 15 + # print(f"scale_k_shape = {scale_k.shape}") + + shift_k = torch.min(k, dim=-1, keepdim=True).values + scale_k = scale_k.to(torch.float16) + shift_k = shift_k.to(torch.float16) + in_bytes = ((k - shift_k.expand(k.shape)) / scale_k.expand(k.shape)) + 0.5 + in_bytes = in_bytes.to(torch.uint8) + in_int4 = in_bytes & 0xF + in_int4_packed = in_int4[..., ::2] + (in_int4[..., 1::2] << 4) + scale_shift = torch.concat( + [scale_k.view(torch.uint8), shift_k.view(torch.uint8)], dim=-1 + ) + k_quant = torch.concat( + [ + scale_shift.flatten(start_dim=-2), + in_int4_packed.flatten(start_dim=-2), + ], + dim=-1, + ).view(torch.int16) + return k_quant + + +class AttentionDecodingBase: + OP: Any = None + + def __init__( + self, + B: int, + Mq: int, + Mkv: int, + Hq: int, + Hkv: int, + K: int, + bw: bool, + attn_bias_type, + ) -> None: + dtype = torch.float16 + torch.manual_seed(10) + self.sub_label = ( + f"B={B} Mq={Mq} Mkv={Mkv} Hq={Hq} Hkv={Hkv} K={K} TotalBytes=" + f"{((B * Mkv * Hkv * K * 2) + (B * Mq * Hq * K) + (B * Mq * Hq * K)) * 2}" + ) + self.label = "attn_decoding" + self.shapes = (B, Mq, Mkv, Hq, Hkv, K) + + assert Hkv <= Hq + assert Hq % Hkv == 0 + self.q = torch.randn( + [B, Mq, Hkv, Hq // Hkv, K], device="cuda", dtype=dtype, requires_grad=bw + ) + self.k = torch.randn( + [B, Mkv, Hkv, 1, K], device="cuda", dtype=dtype, requires_grad=bw + ).expand(-1, -1, -1, Hq // Hkv, -1) + self.v = torch.randn( + [B, Mkv, Hkv, 1, K], device="cuda", dtype=dtype, requires_grad=bw + ).expand(-1, -1, -1, Hq // Hkv, -1) + + if Hq == Hkv: + self.q = self.q[:, :, :, 0] + self.k = self.k[:, :, :, 0] + self.v = self.v[:, :, :, 0] + if Hkv == 1: + self.q = self.q[:, :, 0] + self.k = self.k[:, :, 0] + self.v = self.v[:, :, 0] + + self.attn_bias = create_attn_bias( + attn_bias_type, + batch_size=B, + num_heads=Hq, + num_heads_groups=Hq // Hkv, + q_len=Mq, + kv_len=Mkv, + dtype=dtype, + device=device, + requires_grad=False, + fmt="BMHK", + op=self.OP, + ) + + if isinstance( + self.attn_bias, + xops.fmha.attn_bias.BlockDiagonalCausalWithOffsetPaddedKeysMask, + ): + self.q = self.q.view(1, -1, *self.q.shape[2:]) + self.k = self.k.view(1, -1, *self.k.shape[2:]) + self.v = self.v.view(1, -1, *self.v.shape[2:]) + + if hasattr(self.OP, "not_supported_reasons"): + inp = xops.fmha.Inputs( + query=self.q, key=self.k, value=self.v, attn_bias=self.attn_bias + ) + not_supported_reasons = self.OP.not_supported_reasons(inp) + if not_supported_reasons: + raise NotSupportedInputError(not_supported_reasons) + + def get_inputs(self): + inp = xops.fmha.Inputs( + query=self.q, key=self.k, value=self.v, attn_bias=self.attn_bias + ) + return inp + + def fw(self) -> None: + try: + xops.memory_efficient_attention_forward( + self.q, self.k, self.v, op=self.OP, attn_bias=self.attn_bias + ) + except (RuntimeError, ValueError) as e: + print(f"Runtime error: {e}") + + +class AttentionDecodingCUTLASS(AttentionDecodingBase): + OP = xops.fmha.cutlass.FwOp + + +class AttentionDecodingCK(AttentionDecodingBase): + OP = xops.fmha.ck.FwOp + + def __init__( + self, + B: int, + Mq: int, + Mkv: int, + Hq: int, + Hkv: int, + K: int, + bw: bool, + attn_bias_type, + ) -> None: + dtype = torch.float16 + torch.manual_seed(10) + self.sub_label = ( + f"B={B} Mq={Mq} Mkv={Mkv} Hq={Hq} Hkv={Hkv} K={K} TotalBytes=" + f"{((B * Mkv * Hkv * K * 2) + (B * Mq * Hq * K) + (B * Mq * Hq * K)) * 2}" + ) + self.label = "attn_decoding" + self.shapes = (B, Mq, Mkv, Hq, Hkv, K) + + assert Hkv <= Hq + assert Hq % Hkv == 0 + self.q = torch.randn( + [B, Mq, Hkv, Hq // Hkv, K], device="cuda", dtype=dtype, requires_grad=bw + ) + self.k = torch.randn( + [B, Mkv, Hkv, 1, K], device="cuda", dtype=dtype, requires_grad=bw + ).expand(-1, -1, -1, Hq // Hkv, -1) + self.v = torch.randn( + [B, Mkv, Hkv, 1, K], device="cuda", dtype=dtype, requires_grad=bw + ).expand(-1, -1, -1, Hq // Hkv, -1) + + if Hq == Hkv: + self.q = self.q[:, :, :, 0] + self.k = self.k[:, :, :, 0] + self.v = self.v[:, :, :, 0] + + self.attn_bias = create_attn_bias( + attn_bias_type, + batch_size=B, + num_heads=Hq, + num_heads_groups=Hq // Hkv, + q_len=Mq, + kv_len=Mkv, + dtype=dtype, + device=device, + requires_grad=False, + fmt="BMHK", + op=self.OP, + ) + + if isinstance( + self.attn_bias, + xops.fmha.attn_bias.BlockDiagonalCausalWithOffsetPaddedKeysMask, + ): + self.q = self.q.view(1, -1, *self.q.shape[2:]) + self.k = self.k.view(1, -1, *self.k.shape[2:]) + self.v = self.v.view(1, -1, *self.v.shape[2:]) + + if hasattr(self.OP, "not_supported_reasons"): + inp = xops.fmha.Inputs( + query=self.q, key=self.k, value=self.v, attn_bias=self.attn_bias + ) + not_supported_reasons = self.OP.not_supported_reasons(inp) + if not_supported_reasons: + raise NotSupportedInputError(not_supported_reasons) + + +class AttentionDecodingCKDecoder(AttentionDecodingBase): + OP = xops.fmha.ck_decoder.FwOp + + +class AttentionDecodingSplitKV(AttentionDecodingBase): + OP = xops.fmha.triton_splitk.FwOp + + +class AttentionDecodingCKSplitKV(AttentionDecodingBase): + OP = xops.fmha.ck_splitk.FwOp + + +class AttentionDecodingSplitInt4KV(AttentionDecodingBase): + OP = xops.fmha.triton_splitk.FwOp + + def __init__( + self, + B: int, + Mq: int, + Mkv: int, + Hq: int, + Hkv: int, + K: int, + bw: bool, + attn_bias_type, + ) -> None: + # super(AttentionDecodingSplitInt4KV, self).__init__(B, Mq, Mkv, Hq, Hkv, K, bw, attn_bias_type) + dtype = torch.float16 + torch.manual_seed(10) + self.sub_label = ( + f"B={B} Mq={Mq} Mkv={Mkv} Hq={Hq} Hkv={Hkv} K={K} TotalBytes=" + f"{((B * Mkv * Hkv * K * 2) + (B * Mq * Hq * K) + (B * Mq * Hq * K)) * 2}" + ) + self.label = "attn_decoding" + self.shapes = (B, Mq, Mkv, Hq, Hkv, K) + + assert Hkv <= Hq + assert Hq % Hkv == 0 + self.q = torch.randn( + [B, Mq, Hkv, Hq // Hkv, K], device="cuda", dtype=dtype, requires_grad=bw + ) + self.k = torch.randn( + [B, Mkv, Hkv, 1, K], device="cuda", dtype=dtype, requires_grad=bw + ) + self.v = torch.randn( + [B, Mkv, Hkv, 1, K], device="cuda", dtype=dtype, requires_grad=bw + ) + + num_groups = 1 + self.k = ( + quantize_kv_int4(self.k, num_groups=num_groups) + .contiguous() + .view(torch.int32) + ).expand(-1, -1, -1, Hq // Hkv, -1) + self.v = ( + quantize_kv_int4(self.v, num_groups=num_groups) + .contiguous() + .view(torch.int32) + ).expand(-1, -1, -1, Hq // Hkv, -1) + + if Hq == Hkv: + self.q = self.q[:, :, :, 0] + self.k = self.k[:, :, :, 0] + self.v = self.v[:, :, :, 0] + if Hkv == 1: + self.q = self.q[:, :, 0] + self.k = self.k[:, :, 0] + self.v = self.v[:, :, 0] + + self.attn_bias = create_attn_bias( + attn_bias_type, + batch_size=B, + num_heads=Hq, + num_heads_groups=Hq // Hkv, + q_len=Mq, + kv_len=Mkv, + dtype=dtype, + device=device, + requires_grad=False, + fmt="BMHK", + op=self.OP, + ) + + if isinstance( + self.attn_bias, + xops.fmha.attn_bias.BlockDiagonalCausalWithOffsetPaddedKeysMask, + ): + self.q = self.q.view(1, -1, *self.q.shape[2:]) + self.k = self.k.view(1, -1, *self.k.shape[2:]) + self.v = self.v.view(1, -1, *self.v.shape[2:]) + + if hasattr(self.OP, "not_supported_reasons"): + inp = xops.fmha.Inputs( + query=self.q, key=self.k, value=self.v, attn_bias=self.attn_bias + ) + not_supported_reasons = self.OP.not_supported_reasons(inp) + if not_supported_reasons: + raise NotSupportedInputError(not_supported_reasons) + + +class AttentionDecodingPyTorchRepeat(AttentionDecodingBase): + def fw(self) -> None: + B, Mq, Mkv, Hq, Hkv, K = self.shapes + scale = 1 / K**0.5 + q = self.q.reshape([B, Mq, -1, K]).permute(0, 2, 1, 3) + k = self.k.reshape([B, Mkv, -1, K]).permute(0, 2, 1, 3) + v = self.v.reshape([B, Mkv, -1, K]).permute(0, 2, 1, 3) + attn = (q @ k.transpose(-1, -2) * scale).softmax(-1) + return attn @ v + + +BENCHMARKS: Dict[str, Type[AttentionDecodingBase]] = { + "pytorch": AttentionDecodingPyTorchRepeat, +} + +if torch.version.cuda: + BENCHMARKS["cutlass"] = AttentionDecodingCUTLASS + +if torch.version.hip: + BENCHMARKS.update( + { + "ck": AttentionDecodingCK, + "ck-decoder": AttentionDecodingCKDecoder, + "ck_splitK": AttentionDecodingCKSplitKV, + } + ) + + +if (sys.version_info.major, sys.version_info.minor) >= (3, 9): + BENCHMARKS["triton_splitK"] = AttentionDecodingSplitKV + BENCHMARKS["triton_int4KV"] = AttentionDecodingSplitInt4KV + +try: + import flash_attn + + class AttentionDecodingFlashAttention(AttentionDecodingBase): + def fw(self) -> None: + q, k, v = self.q, self.k, self.v + if q.ndim == 5: + B, Mq, H1, H2, K = q.shape + B, Mkv, H1, H2, K = k.shape + q = q.reshape([B, Mq, H1 * H2, K]) + k = k[:, :, :, 0] + v = v[:, :, :, 0] + return flash_attn.flash_attn_func(q, k, v) + + BENCHMARKS[f"flash-attention@{flash_attn.__version__}"] = ( + AttentionDecodingFlashAttention + ) +except ImportError: + pass + + +TEST_CASES = [ + dict( + B=max(1, 2 ** (16 - i)), + Mq=1, + Mkv=2**i, + Hq=16, + Hkv=hkv, + K=128, + attn_bias_type=None, + ) + for i in range(8, 18) + for hkv in range(1, 3) +] + [ + dict(B=i, Mq=1, Mkv=4097, Hq=8, Hkv=1, K=128, attn_bias_type=None) + for i in [2, 4, 8, 16, 32, 64, 128] +] + + +def get_benchmark_names(): + decoder_names = list(BENCHMARKS.keys()) + decoder_names.remove("pytorch") + return decoder_names + + +# tests to verify correctness of each decoder implementation +@pytest.mark.parametrize( + "name, case", + [(name, case) for name in get_benchmark_names() for case in TEST_CASES], +) +def test_flash_attention_decoder(name, case): + baseline = AttentionDecodingPyTorchRepeat( + case["B"], + case["Mq"], + case["Mkv"], + case["Hq"], + case["Hkv"], + case["K"], + False, + case["attn_bias_type"], + ) + if name == "ck-decoder" and case["Mkv"] >= 2**14: + pytest.skip("ck-decoder does not support Mkv >= 16K") + + baseline_out = baseline.fw() + inputs = baseline.get_inputs() + decoder = BENCHMARKS[name] + + assert name in ["ck-decoder", "ck_splitK", "ck", "triton_splitK", "triton_int4KV"] + decoder_output, ctx = decoder.OP.apply(inputs, False) + + q, k, v = inputs.get_qkv_in_bmghk() + B, M, G, H, Kq = q.shape + mqa_swap_seqlen_head = False + if k.shape[3] > 1 and k.stride(3) == 0 and v.stride(3) == 0: + mqa_swap_seqlen_head = True + if mqa_swap_seqlen_head: + decoder_output = ( + decoder_output.reshape(B, -1, M, Kq).transpose(1, 2).contiguous() + ) + else: + decoder_output = decoder_output.reshape(B, H * G, -1, Kq).contiguous() + + decoder_output = decoder_output.transpose(2, 1).contiguous() + torch.testing.assert_close(decoder_output, baseline_out, atol=1e-2, rtol=0) + + +def main() -> None: + """ + run performance benchmark + """ + benchmark_main_helper2( + "attn_decoding", + fw=True, + cases=CASES, + functions=BENCHMARKS, + min_run_time=min_run_time, + ) + + +if __name__ == "__main__": + main() # pragma: no cover diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_core.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_core.py new file mode 100644 index 0000000000000000000000000000000000000000..0837eebf2dabc60455bc74c4d7d42f6259443331 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_core.py @@ -0,0 +1,261 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import itertools + +import torch +from torch.utils import benchmark + +from xformers.components.attention.core import ( + _create_random_sparsity, + _matmul_with_mask, + _softmax, + bmm, + SparseCS, +) + +MIN_RUN_TIME = 1 +SHAPES = [[8, 8], [256, 1024], [128, 256]] +SPARSITIES = [0.5, 0.8, 0.9, 0.95, 0.99] + + +def bench_sddmm(): + min_run_time = MIN_RUN_TIME + SPARSITIES = [0.95, 0.98, 0.99, 0.995, 0.999] + + device = torch.device("cuda") + results = [] + + for B, M, K in zip(*SHAPES): + a = torch.rand(B, M, K, device=device) + b = torch.rand(B, M, K, device=device) + + for backend, prob in itertools.product( + ["coo_pytorch", "csr_sputnik", "csr_ge"], SPARSITIES + ): + mask = _create_random_sparsity(torch.ones(B, M, M, dtype=torch.bool), prob) + aa = a + bb = b + if "csr" in backend: + mask = SparseCS(mask, device) + aa = a + bb = b + row_indices = mask.row_indices + row_offsets = mask.row_offsets + column_indices = mask.column_indices + if "_ge" in backend: + fn = torch.ops.xformers.csr_sddmm + else: + fn = torch.ops.xformers.sddmm_sputnik + fn_str = "fn(a, b, row_indices, row_offsets, column_indices)" + else: + mask = mask.to_sparse().to(device) + _, row_offsets, column_indices = mask.indices().int().unbind() + row_offsets = row_offsets.contiguous() + column_indices = column_indices.contiguous() + row_indices = row_offsets + + bb = b.transpose(-2, -1) + fn = _matmul_with_mask + fn_str = "fn(a, b, mask)" + + results.append( + benchmark.Timer( + stmt=fn_str, + globals={ + "a": aa, + "b": bb, + "mask": mask, + "row_indices": row_indices, + "row_offsets": row_offsets, + "column_indices": column_indices, + "fn": fn, + }, + label="sddmm", + sub_label=f"sparsity {backend}: {prob:0.4f}", + description=f"B={B}, M={M}, K={K}", + ).blocked_autorange(min_run_time=min_run_time) + ) + + compare = benchmark.Compare(results) + compare.print() + + +def bench_matmul_with_mask(): + min_run_time = MIN_RUN_TIME + prob = 0.9 + device = torch.device("cuda") + results = [] + + for B, M, K in zip(*SHAPES): + a = torch.rand(B, M, K, device=device) + b = torch.rand(B, K, M, device=device) + mask = torch.rand(B, M, M, device=device) > prob + + results.extend( + [ + benchmark.Timer( + stmt="_matmul_with_mask(a, b, mask)", + globals={ + "a": a, + "b": b, + "mask": None, + "_matmul_with_mask": _matmul_with_mask, + }, + label="matmul_with_mask", + sub_label="dense", + description=f"B={B}, M={M}, K={K}", + ).blocked_autorange(min_run_time=min_run_time), + benchmark.Timer( + stmt="_matmul_with_mask(a, b, mask)", + globals={ + "a": a, + "b": b, + "mask": mask, + "_matmul_with_mask": _matmul_with_mask, + }, + label="matmul_with_mask", + sub_label="dense with masking", + description=f"B={B}, M={M}, K={K}", + ).blocked_autorange(min_run_time=min_run_time), + ] + ) + for sputnik, prob in itertools.product([False, True], SPARSITIES): + mask = _create_random_sparsity( + torch.ones(B, M, M, dtype=torch.bool, device=device), prob + ) + aa = a + bb = b + if sputnik: + mask = SparseCS(mask, device) + aa = a + bb = b.transpose(-2, -1).contiguous().transpose(-2, -1) + else: + mask = mask.to_sparse() + results.append( + benchmark.Timer( + stmt="_matmul_with_mask(a, b, mask)", + globals={ + "a": aa, + "b": bb, + "mask": mask, + "_matmul_with_mask": _matmul_with_mask, + }, + label="matmul_with_mask", + sub_label=f"sparsity {'sputnik' if sputnik else 'pytorch'}: {prob:0.2f}", + description=f"B={B}, M={M}, K={K}", + ).blocked_autorange(min_run_time=min_run_time) + ) + + compare = benchmark.Compare(results) + compare.print() + + +def bench_softmax(): + min_run_time = MIN_RUN_TIME + prob = 0.9 + device = torch.device("cuda") + results = [] + + for B, M, K in zip(*SHAPES): + a = torch.rand(B, M, M, device=device) + a[a < prob] = 0 + + results.extend( + [ + benchmark.Timer( + stmt="_softmax(a)", + globals={ + "a": a, + "_softmax": _softmax, + }, + label="softmax", + sub_label="dense", + description=f"B={B}, M={M}, K={K}", + ).blocked_autorange(min_run_time=min_run_time), + ] + ) + for sputnik, prob in itertools.product([False, True], SPARSITIES): + a = _create_random_sparsity(torch.rand(B, M, M, device=device), prob) + if sputnik: + a = SparseCS(a, device) + else: + a = a.to_sparse() + results.append( + benchmark.Timer( + stmt="_softmax(a)", + globals={ + "a": a, + "_softmax": _softmax, + }, + label="softmax", + sub_label=f"sparsity {'sputnik' if sputnik else 'pytorch'}: {prob:0.2f}", + description=f"B={B}, M={M}, K={K}", + ).blocked_autorange(min_run_time=min_run_time) + ) + + compare = benchmark.Compare(results) + compare.print() + + +def bench_bmm(): + min_run_time = MIN_RUN_TIME + prob = 0.9 + device = torch.device("cuda") + results = [] + + for B, M, K in zip(*SHAPES): + a = torch.rand(B, M, M, device=device) + a[a < prob] = 0 + b = torch.rand(B, M, K, device=device) + + results.extend( + [ + benchmark.Timer( + stmt="bmm(a, b)", + globals={ + "a": a, + "b": b, + "bmm": bmm, + }, + label="bmm", + sub_label="dense", + description=f"B={B}, M={M}, K={K}", + ).blocked_autorange(min_run_time=min_run_time), + ] + ) + for sputnik, prob in itertools.product([False, True], SPARSITIES): + a = _create_random_sparsity(torch.rand(B, M, M, device=device), prob) + bb = b + if sputnik: + a = SparseCS(a, device) + bb = b + else: + a = a.to_sparse() + results.append( + benchmark.Timer( + stmt="bmm(a, b)", + globals={ + "a": a, + "b": bb, + "bmm": bmm, + }, + label="bmm", + sub_label=f"sparsity {'sputnik' if sputnik else 'pytorch'}: {prob:0.2f}", + description=f"B={B}, M={M}, K={K}", + ).blocked_autorange(min_run_time=min_run_time) + ) + + compare = benchmark.Compare(results) + compare.print() + + +if torch.version.hip: + print("This benchmark could not be done on ROCM!") +else: + bench_sddmm() + bench_matmul_with_mask() + bench_softmax() + bench_bmm() diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_indexing.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..0eba49933b099ed069eb1f41df2e795bacf72843 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_indexing.py @@ -0,0 +1,191 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import random + +import torch + +import xformers.ops as xops +from utils import benchmark_main_helper2, DTYPE2STR, product_dict + +min_run_time = 0.2 +device = torch.device("cuda") + +CASES_IADD = list( + product_dict( + shape=[ + (int(48 * 0.6), 48, 1, 257 * 1536), + (int(48 * 0.6), 48, 257, 1536), + ], + scaling=[False, True], + dtype=[torch.half], + ) +) + list( + product_dict( + shape=[ + # Format: [B_src, B_inp, M, D] + (int(192 * 0.6), 192, 50, 1536), + (int(48 * 257 * 0.6), 257 * 48, 1, 1536), + (int(192 * 50 * 0.6), 192 * 50, 1, 1536), + (int(16 * 257 * 0.6), 48 * 257, 1, 1536), + ], + scaling=[False], + dtype=[torch.half], + ) +) + +CASES_ISELECT = list( + product_dict( + batches=[((48, 257), (50, 192))], + D=[1536], + keep_ratio=[0.6], + dtype=[torch.half], + ) +) + + +class ScaledIndexAddBenchmark: + def __init__(self, dtype, scaling: bool, shape, bw: bool) -> None: + B_src, B_out, M, D = shape + torch.manual_seed(B_out + B_src) + dtype_str = DTYPE2STR.get(dtype, dtype) + self.sub_label = f"{dtype_str} B_src={B_src}, B_out={B_out}, M={M}, D={D} s={'Y' if scaling else 'N'}" + self.label = "scaled_index_add" + self.alpha = 0.73 + + self.inp = torch.randn( + [B_out, M, D], device="cuda", dtype=dtype, requires_grad=bw + ) + self.src = torch.randn( + [B_src, M, D], device="cuda", dtype=dtype, requires_grad=bw + ) + self.scaling = ( + torch.randn([D], device="cuda", dtype=dtype, requires_grad=bw) + if scaling + else None + ) + self.index = torch.tensor( + [i for i in range(self.src.shape[0])], dtype=torch.int64, device="cuda" + ) + self.grad = torch.randn([B_out, M, D], device="cuda", dtype=dtype) + self.out = torch.Tensor() + + def fw(self) -> None: + self.out = xops.scaled_index_add( + input=self.inp.clone(), + index=self.index, + source=self.src, + scaling=self.scaling, + alpha=self.alpha, + ) + + def bw(self): + self.inp.grad = None + self.src.grad = None + if self.scaling is not None: + self.scaling.grad = None + self.out.backward(self.grad, retain_graph=True) + + +class ScaledIndexAddBenchmarkBaseline(ScaledIndexAddBenchmark): + def fw(self) -> None: + src_scaled = self.src + if self.scaling is not None: + src_scaled * self.scaling.unsqueeze(0).unsqueeze(0) + self.out = self.inp.index_add( + dim=0, + source=src_scaled, + index=self.index, + alpha=self.alpha, + ) + + +class IndexSelectBenchmark: + def __init__(self, dtype, batches, D, keep_ratio, bw: bool) -> None: + dtype_str = DTYPE2STR.get(dtype, dtype) + self.sub_label = f"{dtype_str} D={D} batches={batches} keep={keep_ratio}" + self.label = "index_select" + + indices = [] + sources = [] + for B, seqlen in batches: + index = [i for i in range(B)] + random.Random(B).shuffle(index) + indices.append( + torch.zeros( + index[int(keep_ratio * B)], + dtype=torch.int64, + device="cuda", + ) + ) + source_i = torch.randn( + [B, seqlen * D], dtype=dtype, device="cuda", requires_grad=bw + ) + sources.append(source_i) + self.indices, self.sources = indices, sources + self.out = torch.Tensor() + + def fw(self) -> None: + self.out = xops.index_select_cat(self.sources, self.indices) + + def bw(self): + for src in self.sources: + src.grad = None + self.out.backward(self.out, retain_graph=True) + + +class IndexSelectBenchmarkBaseline(IndexSelectBenchmark): + def fw(self) -> None: + self.out = torch.cat( + [s[i].flatten() for s, i in zip(self.sources, self.indices)], dim=0 + ) + + +benchmark_main_helper2( + "scaled_index_add_fw", + fw=True, + functions={ + "xformers": ScaledIndexAddBenchmark, + "pytorch": ScaledIndexAddBenchmarkBaseline, + }, + cases=CASES_IADD, + min_run_time=min_run_time, +) + +benchmark_main_helper2( + "scaled_index_add_fwbw", + fw=True, + bw=True, + functions={ + "xformers": ScaledIndexAddBenchmark, + "pytorch": ScaledIndexAddBenchmarkBaseline, + }, + cases=CASES_IADD, + min_run_time=min_run_time, +) + +benchmark_main_helper2( + "index_select_fw", + fw=True, + functions={ + "xformers": IndexSelectBenchmark, + "pytorch": IndexSelectBenchmarkBaseline, + }, + cases=CASES_ISELECT, + min_run_time=min_run_time, +) + +benchmark_main_helper2( + "index_select_fwbw", + fw=True, + bw=True, + functions={ + "xformers": IndexSelectBenchmark, + "pytorch": IndexSelectBenchmarkBaseline, + }, + cases=CASES_ISELECT, + min_run_time=min_run_time, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_mem_eff_attention.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_mem_eff_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..2f489fce925e819695d9bbaa062195f354cf08f3 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_mem_eff_attention.py @@ -0,0 +1,373 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import itertools +import random +from functools import partial + +import torch + +import xformers.ops +import xformers.ops.fmha as fmha +from torch.utils import benchmark +from xformers.attn_bias_utils import create_attn_bias, ref_attention +from xformers.benchmarks.utils import benchmark_main_helper, create_argparser + +torch.backends.cuda.matmul.allow_tf32 = False + +min_run_time = 0.5 +device = torch.device("cuda") + +NUM_THREADS = [1] if device.type == "cuda" else [1, 40] +VISION_SHAPES = [ + # ViT + (384, 197, 1, 88), + (384, 197, 1, 80), + (384, 197, 1, 64), + (1024, 197, 1, 88), + (1024, 197, 1, 80), + (1024, 197, 1, 64), + # ViT-Huge + (32 * 16, 197, 1, 80), + (32, 197, 16, 80), + (32, 197, 16, 64), + (32, 197, 16, 128), + # ViT-Giant + (16 * 16, 197, 1, 88), + (16, 197, 16, 88), + (16, 197, 16, 64), + (16, 197, 16, 128), + # FB models + (1024, 82, 8, 64), + (150, 256, 16, 64), + (64, 256, 12, 64), + # Stable diffusion (https://github.com/huggingface/diffusers/pull/532) + (1, 4096, 16, 40), # 512x512 + (1, 16384, 16, 40), # 1024x1024 + (1, 4096, 16, 80), + (1, 16384, 16, 80), + # + bs4 + (4, 4096, 16, 40), + (4, 16384, 16, 40), + (4, 4096, 16, 80), + (4, 16384, 16, 80), + # ParlAI model + (256, 4096, 16, 64), + # Zetta B M H K + (8, 2048, 20, 128), +] + +LLM_SHAPES = [ + # LLaMa 70b - mp=8/16 + *sorted(itertools.product([1, 2], [2048, 4096, 8192], [4, 8], [128])), + *sorted( + itertools.product([16], [128, 512, 1024], [16], [16, 32, 64, 128, 160, 256]) + ), +] + + +OPS = [ + (xformers.ops.fmha.cutlass.FwOp, xformers.ops.fmha.cutlass.BwOp), + (xformers.ops.fmha.flash.FwOp, xformers.ops.fmha.flash.BwOp), + (xformers.ops.fmha.flash3.FwOp, xformers.ops.fmha.flash3.BwOp), + (xformers.ops.fmha.ck.FwOp, xformers.ops.fmha.ck.BwOp), +] + + +def product_dict(**kwargs): + keys = kwargs.keys() + vals = kwargs.values() + for instance in itertools.product(*vals): + yield dict(zip(keys, instance)) + + +VISION_CASES, LLM_CASES = [ + list( + product_dict( + shape_q=SHAPES, + num_threads=NUM_THREADS, + dropout_p=[0.0], + attn_bias_cfg=[(type(None), False)], + dtype=[torch.half], + ) + ) + for SHAPES in (VISION_SHAPES, LLM_SHAPES) +] + +# Add more cases with some variations +for c in VISION_CASES.copy(): + c = c.copy() + c.update( + random.Random(str(c["shape_q"])).choice( + [ + {"dropout_p": 0.3}, + {"attn_bias_cfg": (torch.Tensor, False)}, + {"attn_bias_cfg": (torch.Tensor, True)}, + {"dtype": torch.bfloat16}, + {"dtype": torch.float}, + ] + ) + ) + VISION_CASES.append(c) + + +LLM_CASE_UPDATES = [ + {"attn_bias_cfg": (torch.Tensor, True)}, + {"attn_bias_cfg": (xformers.ops.LowerTriangularMask, False)}, + *[ + { + "attn_bias_cfg": ( + xformers.ops.fmha.attn_bias.BlockDiagonalCausalWithOffsetPaddedKeysMask, + False, + ), + "Hkv": Hkv, + "dtype": torch.bfloat16, + } + for Hkv in [1, 2] + ], +] + +for c in LLM_CASES.copy(): + for update in LLM_CASE_UPDATES: + c = c.copy() + c.update(update) + LLM_CASES.append(c) + +CASES = VISION_CASES + LLM_CASES + + +def create_tensors(shape_q, Hkv, dtype, requires_grad=False, packed=True): + stacked_shape = list(shape_q) # B, M, H, K + Hq = shape_q[2] + stacked_dim = 2 if packed else 0 + stacked_shape.insert(stacked_dim, 3) + qkv = torch.rand( + stacked_shape, device=device, dtype=dtype, requires_grad=requires_grad + ) + q = torch.rand(shape_q, device=device, dtype=dtype, requires_grad=requires_grad) + shape_kv = (shape_q[0], shape_q[1], Hkv, shape_q[3]) + k = ( + torch.rand(shape_kv, device=device, dtype=dtype, requires_grad=requires_grad) + .reshape(shape_q[0], shape_q[1], 1, Hkv, shape_q[3]) + .expand(shape_q[0], shape_q[1], Hq // Hkv, Hkv, shape_q[3]) + .reshape(shape_q) + ) + v = ( + torch.rand(shape_kv, device=device, dtype=dtype, requires_grad=requires_grad) + .reshape(shape_q[0], shape_q[1], 1, Hkv, shape_q[3]) + .expand(shape_q[0], shape_q[1], Hq // Hkv, Hkv, shape_q[3]) + .reshape(shape_q) + ) + + return qkv, q, k, v + + +def mem_eff_attention_fw( + shape_q, + num_threads: int, + attn_bias_cfg, + dropout_p, + dtype, + packed=True, + Hkv=None, +): + B, M, Hq, K = shape_q + Hkv = Hkv or Hq + _, q, k, v = create_tensors( + shape_q, + Hkv, + dtype, + requires_grad=False, + packed=packed, + ) + attn_bias_type, attn_bias_requires_grad = attn_bias_cfg + if attn_bias_requires_grad: + return + + dtype_str = { + torch.bfloat16: "b16", + torch.half: "f16", + torch.float: "f32", + }[dtype] + sub_label = ( + f"{dtype_str} {B}-{M}-{Hq}-{Hkv}-{K}, p={dropout_p}, " + f"BiasT={attn_bias_type.__name__}" + ) + + has_run = False + for fw_op, bw_op in OPS: + bias = create_attn_bias( + attn_bias_type, + batch_size=B, + num_heads=Hq, + num_heads_groups=Hq // Hkv, + q_len=M, + kv_len=M, + dtype=dtype, + device=device, + requires_grad=attn_bias_requires_grad, + fmt="BMHK", + op=fw_op, + ) + inp = fmha.Inputs(query=q, key=k, value=v, attn_bias=bias, p=dropout_p) + if isinstance( + bias, + ( + fmha.attn_bias.BlockDiagonalMask, + fmha.attn_bias.BlockDiagonalCausalWithOffsetPaddedKeysMask, + ), + ): + q, k, v = [x.reshape([1, -1, *x.shape[2:]]) for x in [q, k, v]] + if not fw_op.supports(inp): + continue + + yield benchmark.Timer( + stmt="fn(q, k, v, attn_bias, p)", + globals={ + "q": q, + "k": k, + "v": v, + "attn_bias": inp.attn_bias, + "p": dropout_p, + "fn": partial( + xformers.ops.memory_efficient_attention, op=(fw_op, bw_op) + ), + }, + label=f"attention (attn_bias={attn_bias_type})", + description=fw_op.NAME, + sub_label=sub_label, + num_threads=num_threads, + ) + has_run = True + + if not has_run: + return + + yield benchmark.Timer( + stmt="fn(q, k, v, attn_bias, p)", + globals={ + "q": q, + "k": k, + "v": v, + "attn_bias": inp.attn_bias, + "p": dropout_p, + "fn": ref_attention, + }, + label=f"attention (attn_bias={attn_bias_type})", + description="eager", + sub_label=sub_label, + num_threads=num_threads, + ) + + +def mem_eff_attention_bw( + shape_q, num_threads: int, attn_bias_cfg, dropout_p, dtype, Hkv=None +): + B, M, Hq, K = shape_q + Hkv = Hkv or Hq + _, q, k, v = create_tensors( + shape_q, + Hkv, + dtype, + requires_grad=True, + ) + + attn_bias_type, attn_bias_requires_grad = attn_bias_cfg + + dtype_str = { + torch.bfloat16: "b16", + torch.half: "f16", + torch.float: "f32", + }[dtype] + sub_label = ( + f"{dtype_str} {B}-{M}-{Hq}-{Hkv}-{K}, p={dropout_p}, " + f"BiasT={attn_bias_type.__name__}, BiasGrad={attn_bias_requires_grad}" + ) + + has_run = False + for fw_op, bw_op in OPS: + bias = create_attn_bias( + attn_bias_type, + batch_size=B, + num_heads=Hq, + num_heads_groups=Hq // Hkv, + q_len=M, + kv_len=M, + dtype=dtype, + device=device, + requires_grad=attn_bias_requires_grad, + fmt="BMHK", + op=bw_op, + ) + inp = fmha.Inputs(query=q, key=k, value=v, attn_bias=bias, p=dropout_p) + + if not fw_op.supports(inp) or not bw_op.supports(inp): + continue + has_run = True + out = xformers.ops.memory_efficient_attention( + inp.query, inp.key, inp.value, inp.attn_bias, inp.p, op=(fw_op, bw_op) + ) + grad_benchmark = torch.ones_like(q) + + yield benchmark.Timer( + stmt="out.backward(grad, retain_graph=True)", + globals={ + "out": out, + "grad": grad_benchmark, + }, + label=f"attention backward (attn_bias={attn_bias_type})", + description=bw_op.NAME, + sub_label=sub_label, + num_threads=num_threads, + ) + del out + + if not has_run: + return + yield benchmark.Timer( + stmt="out.backward(grad, retain_graph=True)", + globals={ + "out": ref_attention(q, k, v, inp.attn_bias, dropout_p), + "grad": grad_benchmark, + }, + label=f"attention backward (attn_bias={attn_bias_type})", + description="vanilla", + sub_label=sub_label, + num_threads=num_threads, + ) + + +def main(): + arg_parser = create_argparser() + arg_parser.add_argument( + "--omit-forward", + action="store_true", + help="Do not run forward benchmarks", + ) + arg_parser.add_argument( + "--omit-backward", + action="store_true", + help="Do not run backward benchmarks", + ) + args = arg_parser.parse_args() + if not args.omit_forward: + benchmark_main_helper( + mem_eff_attention_fw, + CASES, + arg_parser=arg_parser, + min_run_time=min_run_time, + ) + if not args.omit_backward: + benchmark_main_helper( + mem_eff_attention_bw, + CASES, + arg_parser=arg_parser, + min_run_time=min_run_time, + ) + + +if __name__ == "__main__": + main() diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_merge_attentions.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_merge_attentions.py new file mode 100644 index 0000000000000000000000000000000000000000..d89561ae5ea30580b654bfd8e0879e83ce4bed54 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_merge_attentions.py @@ -0,0 +1,92 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import torch + +from xformers.ops import fmha +from xformers.utils import do_bench_cudagraph + + +def _merge_attentions_varargs_ref(attn_split, lse_split): + """ + attn_split: list of [B, M, (G,) H, Kq] + lse_split: list of [B, (G,) H, M] + """ + attn_split = torch.stack(attn_split) + lse_split = torch.stack(lse_split) + + lse_split = lse_split[..., None].moveaxis(4, 2) # [split_k, B, M, G, H, 1] + + lse_max, _ = torch.max(lse_split, dim=0) # [B, M, G, H, 1] + sumexp_normalized = torch.exp(lse_split - lse_max) # [split_k, B, M, G, H, 1] + denominator = sumexp_normalized.sum(dim=0) # [B, M, G, H, 1] + numerator = (sumexp_normalized * attn_split).sum(dim=0) # [B, M, G, H, K] + + attn_out = numerator / denominator # [B, M_ceil, G, H, Kq] + lse_out = lse_max + torch.log(denominator) + lse_out = lse_out.squeeze(4).permute(0, 2, 3, 1) # [B, G, H, M] + + return attn_out, lse_out + + +def benchmark_merge_attentions_backward(split_k, B, M, G, N_H_L, D_H, dtype): + """ + Benchmark backward pass for merge_attentions. Assumes "varargs" path, + i.e. LSE and attention of chunks are provided as two lists of tensors, and not as two stacked tensors. + """ + + bench_stream = torch.cuda.Stream() + with torch.cuda.stream(bench_stream): + + attn_split = [ + torch.randn( + [B, M, G, N_H_L, D_H], dtype=dtype, device="cuda", requires_grad=True + ) + for _ in range(split_k) + ] + lse_split = [ + torch.randn( + [B, G, N_H_L, M], dtype=dtype, device="cuda", requires_grad=True + ) + for _ in range(split_k) + ] + + attn_out_ref, lse_out_ref = _merge_attentions_varargs_ref(attn_split, lse_split) + out_grad = torch.randn_like(attn_out_ref) + attn_out_ref.backward(out_grad, retain_graph=True) + t_ms_ref = do_bench_cudagraph( + lambda: attn_out_ref.backward(out_grad, retain_graph=True) + ) + + for x in attn_split + lse_split: + x.detach_() + x.requires_grad_(True) + + attn_out, lse_out = fmha.merge_attentions(attn_split, lse_split) + attn_out.backward(out_grad, retain_graph=True) + t_ms = do_bench_cudagraph( + lambda: attn_out.backward(out_grad, retain_graph=True) + ) + + print( + f"{split_k=}, {B=}, {M=}, {G=}, {N_H_L=}, {D_H=}, {dtype=}. " + f"Baseline: {t_ms_ref * 1e3:.2f}us, " + f"Triton: {t_ms * 1e3:.2f}us, {t_ms_ref/t_ms:.1f}x faster" + ) + + +def main(): + G = 2 + N_H_L = 8 + D_H = 128 + dtype = torch.float32 + for split_k in [2, 4, 8, 16]: + for B in [1, 32, 128]: + for M in [1, 32, 512]: + benchmark_merge_attentions_backward(split_k, B, M, G, N_H_L, D_H, dtype) + + +if __name__ == "__main__": + main() diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_nystrom_utils.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_nystrom_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c85b0345683a9cc6077a3fb4d25bb50cbdffeead --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_nystrom_utils.py @@ -0,0 +1,101 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Callable + +import torch +from torch.utils import benchmark + +from xformers.components.attention.utils import iterative_pinv + +MIN_RUN_TIME = 1 +SHAPES = [[8, 8], [256, 1024], [128, 256]] +SPARSITIES = [0.5, 0.8, 0.9, 0.95, 0.99] + + +def bench_inverse(inverse_fn: Callable[[torch.Tensor], torch.Tensor]): + min_run_time = MIN_RUN_TIME + prob = 0.9 + device = torch.device("cuda") + results = [] + + for B, M, K in zip(*SHAPES): + a = torch.rand(B, M, M, device=device) + a[a < prob] = 0 + a = torch.softmax(a, dim=-1) + + results.extend( + [ + benchmark.Timer( + stmt=f"{inverse_fn.__name__}(a)", + globals={ + "a": a, + f"{inverse_fn.__name__}": inverse_fn, + }, + label=f"{inverse_fn.__name__}", + sub_label="dense", + description=f"B={B}, M={M}, K={K}", + ).blocked_autorange(min_run_time=min_run_time), + ] + ) + for prob in SPARSITIES: + a = torch.rand(B, M, M, device=device) + a[a < prob] = 0 + a = a.to_sparse() + results.append( + benchmark.Timer( + stmt=f"{inverse_fn.__name__}(a)", + globals={ + "a": a, + f"{inverse_fn.__name__}": inverse_fn, + }, + label=f"{inverse_fn.__name__}", + sub_label=f"sparsity: {prob:0.2f}", + description=f"B={B}, M={M}, K={K}", + ).blocked_autorange(min_run_time=min_run_time) + ) + + compare = benchmark.Compare(results) + compare.print() + + +def iterative_pinv_analysis( + identity_tolerance: float = 1e-1, + pinv_tolerance: float = 5e-1, + max_iters: int = 30, + plot: bool = True, +): + + for i in range(1, 10): + B, M = 1, 2**i + a = torch.rand(B, M, M) + a = torch.softmax(a, dim=-1) + + for n_iter in range(1, max_iters + 1): + result = iterative_pinv(a, n_iter=n_iter) + expected = torch.linalg.pinv(a) + + result_identity = torch.matmul(a, result) + identity = torch.eye(M) + + # Default is frobenius norm. + identity_error = torch.linalg.norm(identity - result_identity, dim=(-2, -1)) + inverse_error = torch.linalg.norm(expected - result, dim=(-2, -1)) + + if (identity_error < identity_tolerance).all() or n_iter == max_iters: + print( + f"Size {M}, n_iters {n_iter}: \n\t \ + Final Error from Identity: {identity_error.item()} \n\t \ + Final Error from linalg.pinv {inverse_error.item()}" + ) + break + + +if torch.version.hip: + print("This benchmark could not be done on ROCM!") +else: + iterative_pinv_analysis() + bench_inverse(iterative_pinv) + bench_inverse(torch.linalg.pinv) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_revnet.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_revnet.py new file mode 100644 index 0000000000000000000000000000000000000000..8a21b80feea34070c1a48b30ac41caee2844b4c9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_revnet.py @@ -0,0 +1,83 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +from typing import Any, Dict + +import torch +import triton + +from xformers.benchmarks.utils import pretty_plot, pretty_print, TestCase +from xformers.components.reversible import ReversibleSequence + +SHAPES = [(16384, 32), (2048, 256), (128, 4096)] + +DEPTH = [4, 32, 256] + + +def bench_revnet(backward: bool): + device = torch.device("cuda") + bw = "+bw" if backward else "" + + for dtype in [torch.float16, torch.float32]: + results: Dict[str, Any] = {} + + for B, K in SHAPES: + for depth in DEPTH: + f = torch.nn.Linear(K, K).to(device=device, dtype=dtype) + g = torch.nn.Linear(K, K).to(device=device, dtype=dtype) + revseq = ReversibleSequence( + torch.nn.ModuleList([torch.nn.ModuleList([f, g])] * depth) + ) + revseq = revseq.to(device=device, dtype=dtype) + + a = torch.rand( + 1, B, K, device=device, dtype=dtype, requires_grad=backward + ) + b = torch.rand( + 1, B, K * 2, device=device, dtype=dtype, requires_grad=backward + ) + + def normal_step(): + y = a + for _ in range(depth): + y = y + f(y) + y = y + g(y) + if backward: + torch.norm(y).backward() + return y + + def reversible_step(): + y = revseq(b) + if backward: + torch.norm(y).backward() + return y + + for testcase in [ + TestCase(normal_step, f"residual - fw{bw}"), + TestCase(reversible_step, f"reversible - fw{bw}"), + ]: + time = triton.testing.do_bench(testcase.function)[0] + key = f"Batch={B}, Features={K}, Depth={depth}" + if key not in results: + results[key] = {} + + results[key][testcase.name] = f"{time:.2f}" + + pretty_print( + results, + title=f"\n --- Type: {dtype} --- ", + units="runtime in ms, lower is better", + ) + pretty_plot( + results, + title=f"RevNet-FW{bw}-{dtype}", + units="runtime in ms, lower is better", + dash_key="torch", + ) + + +for bw in [False, True]: + bench_revnet(bw) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_sddmm.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_sddmm.py new file mode 100644 index 0000000000000000000000000000000000000000..8a3bc0eb58b426cccbc9113ddc69117ab2e9438a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_sddmm.py @@ -0,0 +1,120 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import itertools + +import torch +from torch.utils import benchmark + +from xformers.components.attention._sputnik_sparse import _csr_to_coo +from xformers.components.attention.core import _create_random_sparsity, SparseCS + +MIN_RUN_TIME = 0.2 + + +def _get_fn(backend): + if backend == "csr_ge": + fn = torch.ops.xformers.csr_sddmm + elif backend == "csr_sputnik": + fn = torch.ops.xformers.sddmm_sputnik + elif backend == "coo_ge": + + def fn(a, b, row_indices, row_offsets, column_indices): + row_coo, _ = _csr_to_coo( + a.shape[-2], b.shape[-2], row_offsets, column_indices + ) + return torch.ops.xformers.coo_sddmm( + a, b, row_indices, row_coo, column_indices + ) + + elif backend == "csr_to_coo": + + def fn(a, b, row_indices, row_offsets, column_indices): + row_coo, _ = _csr_to_coo( + a.shape[-2], b.shape[-2], row_offsets, column_indices + ) + return row_coo + + return fn + + +def bench_sddmm(configs): + min_run_time = MIN_RUN_TIME + + device = torch.device("cuda") + results = [] + + for (B, M, K), prob in configs: + a = torch.rand(B, M, K, device=device) + b = torch.rand(B, M, K, device=device) + + mask = _create_random_sparsity( + torch.ones(1, M, M, dtype=torch.bool), prob, divisible_by=16 + ) + aa = a + bb = b + mask = SparseCS(mask, device) + row_indices = mask.row_indices + row_offsets = mask.row_offsets + column_indices = mask.column_indices + + for backend in ["csr_sputnik", "csr_ge", "coo_ge", "csr_to_coo"]: + + fn_str = "fn(a, b, row_indices, row_offsets, column_indices)" + fn = _get_fn(backend) + + results.append( + benchmark.Timer( + stmt=fn_str, + globals={ + "a": aa, + "b": bb, + "mask": mask, + "row_indices": row_indices, + "row_offsets": row_offsets, + "column_indices": column_indices, + "fn": fn, + }, + label="sddmm", + sub_label=f"B={B:>4d}, M={M:>4d}, K={K:>3d}, prob={prob:0.4f}", + description=backend, + ).blocked_autorange(min_run_time=min_run_time) + ) + + compare = benchmark.Compare(results) + compare.print() + return results + + +# batch size 32, for different layers +SWIN_T_SIZES = [(96, 3136, 32), (192, 784, 32), (384, 196, 32), (768, 49, 32)] +swin_t_config = list(zip(SWIN_T_SIZES, (0.9844, 0.9375, 0.75, 0.0))) + +# some random values +BASIC_SIZES = [(32, 1024, 32), (32, 1024, 128), (8, 4096, 32), (8, 4096, 128)] +SPARSITIES = [0.90, 0.93, 0.95, 0.97, 0.98, 0.99, 0.995, 0.999] +basic_config = list(itertools.product(BASIC_SIZES, SPARSITIES)) + +# batch size 32 here +vit_sizes = [ + (192, 785, 64), # deit_small_patch8_224 + (192, 197, 64), # deit_small_patch16_224 + (384, 785, 64), # deit_base_patch8_224 + (384, 197, 64), # deit_base_patch16_224 +] +SPARSITIES = [0.70, 0.80, 0.85, 0.90, 0.93, 0.95, 0.97] +vit_config = list(itertools.product(vit_sizes, SPARSITIES)) + +results = [] + +if torch.version.hip: + print("This benchmark could not be done on ROCM!") +else: + print("Swin Transformer") + results += bench_sddmm(swin_t_config) + print("ViT") + results += bench_sddmm(vit_config) + print("Basic cases") + results += bench_sddmm(basic_config) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_sequence_parallel_fused.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_sequence_parallel_fused.py new file mode 100644 index 0000000000000000000000000000000000000000..cd0d646a53917524a9855e5977b827eb1ee5420e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_sequence_parallel_fused.py @@ -0,0 +1,473 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import argparse +import contextlib +import dataclasses +import enum +import multiprocessing +import os +import random +from collections import deque +from statistics import mean, stdev +from typing import Callable + +import torch + +# torch._C._set_print_stack_traces_on_fatal_signal(True) + + +@dataclasses.dataclass +class Scenario: + # The number of tokens, i.e., the batch size times the sequence length + num_samples: int + # The per-sample features outside of the MHA/FFN block, and inside of it + outer_dim: int + inner_dim: int + # Simulate this many matmuls during the all-gather step + num_ag_matrices: int + + +class Step(enum.Enum): + AllGather = "ag" + ReduceScatter = "rs" + + def __str__(self): + return self.value + + +@dataclasses.dataclass +class Bench: + ag: Callable[[], None] + rs: Callable[[], None] + + def __getitem__(self, step: Step): + if step is Step.AllGather: + return self.ag + elif step is Step.ReduceScatter: + return self.rs + else: + raise KeyError(f"{step}") + + +LLAMA_07B_SLEN = 4096 +LLAMA_07B_D = 4096 + +LLAMA_70B_SLEN = 2048 +LLAMA_70B_D = 8192 + + +def round_up_to_nearest_multiple(n: int, m: int) -> int: + return m * ((n + m - 1) // m) + + +def llama_07B_MHA(world_size: int) -> Scenario: + batch_size = 8 + return Scenario( + num_samples=batch_size * LLAMA_07B_SLEN, + outer_dim=LLAMA_07B_D, + inner_dim=LLAMA_07B_D // world_size, + num_ag_matrices=3, + ) + + +def llama_07B_FFN(world_size: int) -> Scenario: + batch_size = 8 + return Scenario( + num_samples=batch_size * LLAMA_07B_SLEN, + outer_dim=LLAMA_07B_D, + inner_dim=round_up_to_nearest_multiple(2 * (4 * LLAMA_07B_D) // 3, 256) + // world_size, + num_ag_matrices=2, + ) + + +def llama_70B_MHA(world_size: int) -> Scenario: + batch_size = world_size + return Scenario( + num_samples=batch_size * LLAMA_70B_SLEN, + outer_dim=LLAMA_70B_D, + inner_dim=LLAMA_70B_D // world_size, + num_ag_matrices=3, + ) + + +def llama_70B_FFN(world_size: int) -> Scenario: + batch_size = world_size + return Scenario( + num_samples=batch_size * LLAMA_70B_SLEN, + outer_dim=LLAMA_70B_D, + inner_dim=round_up_to_nearest_multiple(2 * (4 * LLAMA_70B_D) // 3, 256) + // world_size, + num_ag_matrices=2, + ) + + +SCENARIOS = { + "llama_07B_MHA": llama_07B_MHA, + "llama_07B_FFN": llama_07B_FFN, + "llama_70B_MHA": llama_70B_MHA, + "llama_70B_FFN": llama_70B_FFN, +} + +DTYPES = { + "bfloat16": torch.bfloat16, +} + + +def run_one_rank( + my_rank, + world_size, + scenario_name, + step, + dtype_str, + num_rounds, + num_warmup_iters, + num_bench_iters, + profile, + conn_from_prev, + conn_to_next, +): + print(f"RANK {my_rank} started") + + torch.cuda.set_device(my_rank) + my_device = torch.device(f"cuda:{my_rank}") + + os.environ["RANK"] = f"{my_rank}" + os.environ["WORLD_SIZE"] = f"{world_size}" + os.environ["MASTER_ADDR"] = "localhost" + os.environ["MASTER_PORT"] = "29500" + torch.distributed.init_process_group(backend="nccl", init_method="env://") + + subgroup = torch.distributed.new_group() + subgroup_nowait = torch.distributed.new_group() + subgroup_nowait_nomemcpy = torch.distributed.new_group() + + scenario = SCENARIOS[scenario_name](world_size) + if step is Step.AllGather: + M = scenario.num_samples + N = scenario.inner_dim + K = scenario.outer_dim + num_matrices = scenario.num_ag_matrices + elif step is Step.ReduceScatter: + M = scenario.num_samples + N = scenario.outer_dim + K = scenario.inner_dim + num_matrices = 1 + + dtype = DTYPES[dtype_str] + + scattered_input = torch.randn((M // world_size, K), dtype=dtype, device=my_device) + gathered_input = torch.randn((M, K), dtype=dtype, device=my_device) + weights = [ + torch.randn((K, N), dtype=dtype, device=my_device) for _ in range(num_matrices) + ] + gathered_outputs = [ + torch.randn((M, N), dtype=dtype, device=my_device) for _ in range(num_matrices) + ] + scattered_outputs = [ + torch.randn((M // world_size, N), dtype=dtype, device=my_device) + for _ in range(num_matrices) + ] + + gathered_outputs_nccl_reference = [ + torch.randn((M, N), dtype=dtype, device=my_device) for _ in range(num_matrices) + ] + gathered_outputs_fused = [ + torch.randn((M, N), dtype=dtype, device=my_device) for _ in range(num_matrices) + ] + scattered_outputs_nccl_reference = [ + torch.randn((M // world_size, N), dtype=dtype, device=my_device) + for _ in range(num_matrices) + ] + scattered_outputs_fused = [ + torch.randn((M // world_size, N), dtype=dtype, device=my_device) + for _ in range(num_matrices) + ] + + def run_compute_lower_bound_ag(): + for w, go in zip(weights, gathered_outputs): + torch.matmul(gathered_input, w, out=go) + + def run_compute_lower_bound_rs(): + for w, go, so in zip(weights, gathered_outputs, scattered_outputs): + torch.matmul(gathered_input, w, out=go) + torch.sum(go.view((world_size, M // world_size, N)), dim=0, out=so) + + def run_comms_lower_bound_ag(): + torch.distributed.all_gather_into_tensor(gathered_input, scattered_input) + + def run_comms_lower_bound_rs(): + for so, go in zip(scattered_outputs, gathered_outputs): + torch.distributed.reduce_scatter_tensor(so, go) + + def run_nccl_reference_ag(): + torch.distributed.all_gather_into_tensor(gathered_input, scattered_input) + for w, go in zip(weights, gathered_outputs_nccl_reference): + torch.matmul(gathered_input, w, out=go) + + def run_nccl_reference_rs(): + for w, go, so in zip( + weights, gathered_outputs, scattered_outputs_nccl_reference + ): + torch.matmul(gathered_input, w, out=go) + torch.distributed.reduce_scatter_tensor(so, go) + + def run_fused_ag(): + nonlocal gathered_outputs_fused + from xformers.ops import fused_allgather_and_linear + + gathered_outputs_fused = fused_allgather_and_linear( + scattered_input, + [w.t() for w in weights], + group=subgroup, + timeout_s=10, + ) + + def run_fused_rs(): + nonlocal scattered_outputs_fused + from xformers.ops import fused_linear_and_reducescatter + + scattered_outputs_fused = fused_linear_and_reducescatter( + gathered_input, + [w.t() for w in weights], + group=subgroup, + timeout_s=10, + ) + + def run_fused_nowait_ag(): + nonlocal gathered_outputs_fused + from xformers.ops import fused_allgather_and_linear + + gathered_outputs_fused = fused_allgather_and_linear( + scattered_input, + [w.t() for w in weights], + group=subgroup_nowait, + _wait=False, + timeout_s=10, + ) + + def run_fused_nowait_rs(): + nonlocal scattered_outputs_fused + from xformers.ops import fused_linear_and_reducescatter + + scattered_outputs_fused = fused_linear_and_reducescatter( + gathered_input, + [w.t() for w in weights], + group=subgroup_nowait, + _wait=False, + timeout_s=10, + ) + + def run_fused_nowait_nomemcpy_ag(): + nonlocal gathered_outputs_fused + from xformers.ops import fused_allgather_and_linear + + gathered_outputs_fused = fused_allgather_and_linear( + scattered_input, + [w.t() for w in weights], + group=subgroup_nowait_nomemcpy, + _wait=False, + _memcpy=False, + timeout_s=10, + ) + + def run_fused_nowait_nomemcpy_rs(): + nonlocal scattered_outputs_fused + from xformers.ops import fused_linear_and_reducescatter + + scattered_outputs_fused = fused_linear_and_reducescatter( + gathered_input, + [w.t() for w in weights], + group=subgroup_nowait_nomemcpy, + _wait=False, + _memcpy=False, + timeout_s=10, + ) + + print(f"Sizes: ({world_size}x{M // world_size})x({num_matrices}x{N})x{K}") + + if step is Step.AllGather: + run_nccl_reference_ag() + run_fused_ag() + if my_rank == 0: + print("fused:") + print( + "Are equal? " + + " ".join( + str(torch.equal(ref, fus)) + for ref, fus in zip( + gathered_outputs_nccl_reference, gathered_outputs_fused + ) + ) + ) + print( + "Are allclose? " + + " ".join( + str(torch.allclose(ref, fus)) + for ref, fus in zip( + gathered_outputs_nccl_reference, gathered_outputs_fused + ) + ) + ) + + elif step is Step.ReduceScatter: + run_nccl_reference_rs() + run_fused_rs() + if my_rank == 0: + print("fused:") + print( + "Are equal? " + + " ".join( + str(torch.equal(ref, fus)) + for ref, fus in zip( + scattered_outputs_nccl_reference, scattered_outputs_fused + ) + ) + ) + print( + "Are allclose? " + + " ".join( + str(torch.allclose(ref, fus)) + for ref, fus in zip( + scattered_outputs_nccl_reference, scattered_outputs_fused + ) + ) + ) + + # The above checks might still return False for, e.g., bfloat16 because they + # have too little tolerance for its lower precision. This method, OTOH, uses + # variable tolerances based on dtype. + # for ref, fus in zip(gathered_outputs_nccl_reference, gathered_outputs_fused): + # torch.testing.assert_close(ref, fus) + # for ref, fus in zip(scattered_outputs_nccl_reference, scattered_outputs_fused): + # torch.testing.assert_close(ref, fus) + + all_benchs = { + "compute_lower_bound": Bench( + ag=run_compute_lower_bound_ag, rs=run_compute_lower_bound_rs + ), + "comms_lower_bound": Bench( + ag=run_comms_lower_bound_ag, rs=run_comms_lower_bound_rs + ), + "nccl_reference": Bench(ag=run_nccl_reference_ag, rs=run_nccl_reference_rs), + "fused": Bench(ag=run_fused_ag, rs=run_fused_rs), + "fused_nowait": Bench(ag=run_fused_nowait_ag, rs=run_fused_nowait_rs), + "fused_nowait_nomemcpy": Bench( + ag=run_fused_nowait_nomemcpy_ag, rs=run_fused_nowait_nomemcpy_rs + ), + } + + unused_events = deque( + tuple(torch.cuda.Event(enable_timing=my_rank == 0) for _ in range(2)) + for f in range(len(all_benchs)) + ) + used_events = deque() + + timings = {} + + gen = random.Random(42) + + if profile: + profiler = torch.profiler.profile() + else: + profiler = contextlib.nullcontext() + + with profiler as p: + for method in gen.sample( + list(all_benchs), + k=num_rounds * len(all_benchs), + counts=[num_rounds] * len(all_benchs), + ): + fun = all_benchs[method][step] + + if unused_events: + start_ev, end_ev = unused_events.popleft() + else: + old_method, start_ev, end_ev = used_events.popleft() + end_ev.synchronize() + if my_rank == 0: + timings.setdefault(old_method, []).append( + start_ev.elapsed_time(end_ev) / num_bench_iters + ) + + for _ in range(num_warmup_iters): + fun() + start_ev.record() + for _ in range(num_bench_iters): + fun() + end_ev.record() + + used_events.append((method, start_ev, end_ev)) + + torch.cuda.synchronize() + + if profile: + p.export_chrome_trace(f"fusion_trace_{my_rank}.json") + + if my_rank == 0: + for method, start_ev, end_ev in used_events: + timings.setdefault(method, []).append( + start_ev.elapsed_time(end_ev) / num_bench_iters + ) + + for method in all_benchs: + print( + f"{method} = {mean(timings[method]):g}ms (+/- {stdev(timings[method]):g})" + ) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("scenario", choices=SCENARIOS.keys()) + parser.add_argument("step", choices=list(Step), type=Step) + parser.add_argument("--world-size", type=int, default=8) + parser.add_argument("--dtype", choices=DTYPES.keys(), default="bfloat16") + parser.add_argument("--num-rounds", type=int, default=20) + parser.add_argument("--num-warmup-iters", type=int, default=5) + parser.add_argument("--num-bench-iters", type=int, default=50) + parser.add_argument("--profile", action="store_true") + args = parser.parse_args() + + conns_from_prev = [None] * args.world_size + conns_to_next = [None] * args.world_size + for rank in range(args.world_size): + end1, end2 = multiprocessing.get_context("spawn").Pipe(duplex=True) + conns_to_next[rank] = end1 + conns_from_prev[(rank + 1) % args.world_size] = end2 + + processes = [] + for rank in range(args.world_size): + p = multiprocessing.get_context("spawn").Process( + target=run_one_rank, + args=( + rank, + args.world_size, + args.scenario, + args.step, + args.dtype, + args.num_rounds, + args.num_warmup_iters, + args.num_bench_iters, + args.profile, + conns_from_prev[rank], + conns_to_next[rank], + ), + daemon=True, + ) + p.start() + processes.append(p) + + print("LAUNCHED") + + for rank, p in enumerate(processes): + p.join() + print(f"Rank {rank} exited with {p.exitcode}") + + print("JOINED") + + +if __name__ == "__main__": + main() diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_sp24.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_sp24.py new file mode 100644 index 0000000000000000000000000000000000000000..6b9d0dd5e7cf80247554731d7f731f5e68a0b24a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_sp24.py @@ -0,0 +1,178 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +from typing import Tuple + +import torch +import torch.nn.functional as F + +import xformers.ops as xops +from torch import nn +from utils import benchmark_main_helper2, DTYPE2STR, product_dict + +min_run_time = 0.5 +device = torch.device("cuda") + +CASES = list( + product_dict( + B_in_hidden_out_ft=[ + (2048 * 8, 2048, 2048 * 3, 2048), + (2048, 5120, 5120 * 3, 5120), # 13b + (1024, 8192, 8192 * 3, 8192), # 30b + (2048, 8192, 8192 * 3, 8192), # 30b + (2048 * 2, 8192, 8192 * 3, 8192), # 30b + # DINO ViT-L: lg + sm crops (patch16) + (64 * 2 * (14 * 14 + 1) + 64 * 8 * (6 * 6 + 1), 1024, 1024 * 4, 1024), + # DINO ViT-g: lg + sm crops (patch16) + ( + 12 * 2 * (16 * 16 + 1 + 11) + 12 * 8 * (7 * 7 + 1 + 11), + 1536, + 1536 * 4, + 1536, + ), + ], + dtype=[torch.half], + bias=[False], + ) +) + + +class Mlp(nn.Module): + LINEAR_CLS = nn.Linear + + def __init__( + self, B_in_hidden_out_ft: Tuple[int, int, int, int], dtype, bias: bool, bw: bool + ) -> None: + B, in_ft, hid_ft, out_ft = B_in_hidden_out_ft + super().__init__() + self.label = "mlp" + self.sub_label = ( + f"{DTYPE2STR[dtype]} ({B},{in_ft},{hid_ft},{out_ft}){' b' if bias else ''}" + ) + self.fc1 = self.LINEAR_CLS(in_ft, hid_ft, bias=bias) + self.act = nn.GELU() + self.fc2 = self.LINEAR_CLS(hid_ft, out_ft, bias=bias) + self.grad = torch.randn([B, out_ft], device="cuda", dtype=dtype) + self.input = torch.randn( + [B, in_ft], device="cuda", dtype=dtype, requires_grad=True + ) + self.out = self.input + self.to("cuda").to(dtype) + + def fw(self): + x = self.input + x = self.fc1(x) + x = self.act(x) + x = self.fc2(x) + self.out = x + + def bw(self): + self.out.backward(self.grad, retain_graph=True) + + +class MlpDenseMask(Mlp): + def fw(self): + x = self.input + x = self.fc1(x) + + mask = torch.ops.xformers.sparse24_largest_mask_2d(x) + x = mask * x + + x = self.act(x) + x = self.fc2(x) + self.out = x + + +class MlpAct24(Mlp): + def fw(self): + x = self.input + x = self.fc1(x) + + x = xops.sparsify24(x) + + x = self.act(x) + x = self.fc2(x) + self.out = x + + +class LinearW24(torch.nn.Linear): + def forward(self, input: torch.Tensor) -> torch.Tensor: + w_sparse = xops.sparsify24( + self.weight, + gradient="24dense", + backend="cusparselt", + ) + return F.linear(input, w_sparse, self.bias) + + +class MlpW24(Mlp): + LINEAR_CLS = LinearW24 + + +class MicrobenchmarkBase: + def __init__( + self, B_in_hidden_out_ft: Tuple[int, int, int, int], dtype, bias: bool, bw: bool + ) -> None: + B, in_ft, hid_ft, out_ft = B_in_hidden_out_ft + super().__init__() + self.label = "mlp" + self.sub_label = ( + f"{DTYPE2STR[dtype]} ({B},{in_ft},{hid_ft},{out_ft}){' b' if bias else ''}" + ) + self.input = torch.randn( + [B, in_ft], device="cuda", dtype=dtype, requires_grad=True + ) + self.input_colMajor = self.input.t().contiguous().t() + self.input_sp = xops.sparsify24(self.input) + + def bw(self) -> None: + return None + + +class MicrobenchmarkSparsify24(MicrobenchmarkBase): + def fw(self) -> torch.Tensor: + xops.sparsify24(self.input) + return self.input + + +class MicrobenchmarkSp24ApplyDense(MicrobenchmarkBase): + def fw(self) -> torch.Tensor: + xops.sparsify24_like(self.input, pattern=self.input_sp, out_dense=True) + return self.input + + +class MicrobenchmarkSp24ApplyDenseT(MicrobenchmarkBase): + def fw(self) -> torch.Tensor: + xops.sparsify24_like(self.input_colMajor, pattern=self.input_sp, out_dense=True) + return self.input + + +class MicrobenchmarkInputClone(MicrobenchmarkBase): + def fw(self) -> torch.Tensor: + self.input.clone() + return self.input + + +functions = { + "act24": MlpAct24, + "dense": Mlp, + "w24": MlpW24, + "s24_inp_sparsify24": MicrobenchmarkSparsify24, + "s24_inp_apply_dense": MicrobenchmarkSp24ApplyDense, + "s24_inp_apply_dense_t": MicrobenchmarkSp24ApplyDenseT, + "s24_inp_clone": MicrobenchmarkInputClone, +} +benchmark_main_helper2( + "sp24_fw", fw=True, cases=CASES, functions=functions, min_run_time=min_run_time +) +benchmark_main_helper2( + "sp24_fwbw", + fw=True, + bw=True, + cases=CASES, + functions=functions, + min_run_time=min_run_time, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_swiglu.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_swiglu.py new file mode 100644 index 0000000000000000000000000000000000000000..e6cb180151de640ccf519d40028180e5e07709b1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_swiglu.py @@ -0,0 +1,163 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import itertools +from contextlib import nullcontext +from functools import partial +from typing import Any + +import torch + +import xformers.ops.swiglu_op as xsw +from torch.utils import benchmark +from xformers.benchmarks.utils import benchmark_main_helper + +min_run_time = 0.5 +device = torch.device("cuda") + +SHAPES = [ + # Format: [inp.shape[0], inp.shape[1], hidden.shape[1]] + # ViT-Giant + (9456, 1536, 2736), + (4440, 1536, 2736), + (4728, 1536, 2736), + # Some smaller shapes as well + (4728, 1536, 1024), + # GPT-3 (small) + (32768, 2048, 5632), + # Chinchilla + (32768, 8192, 22016), +] + + +# OP = xsw._SwiGLUDecomposedOp +# OP = xsw.SwiGLUFusedOp +OP = xsw.SwiGLUPackedFusedOp + + +def product_dict(**kwargs): + keys = kwargs.keys() + vals = kwargs.values() + for instance in itertools.product(*vals): + yield dict(zip(keys, instance)) + + +CASES = list( + product_dict( + shape=SHAPES, + dtype=[torch.bfloat16, torch.half, "autocast_half"], + bias=[True, False], + ) +) + +DTYPE2STR = { + torch.bfloat16: "b16 ", + torch.half: "f16 ", + "autocast_half": "f16.ac", +} + + +def benchmark_swiglu(shape, dtype, bias: bool): + if dtype == "autocast_half": + inp_dtype, model_dtype, autocast = torch.float, torch.float, True + else: + inp_dtype, model_dtype, autocast = dtype, dtype, False + + x = torch.randn(shape[:2], device=device, dtype=inp_dtype) + module = ( + xsw.SwiGLU(in_features=shape[1], hidden_features=shape[2], bias=bias) + .to(device) + .to(model_dtype) + ) + + dtype_str = DTYPE2STR.get(dtype, dtype) + bstr = "bias" if bias else "nobi" + sub_label = f"{dtype_str} B={shape[0]}, I={shape[1]}, H={shape[2]} {bstr}" + + params = module._ordered_params() + + PREFIX = 'with torch.autocast("cuda", dtype=torch.half):\n ' if autocast else "" + yield benchmark.Timer( + stmt=f"{PREFIX}fn(x, *args)", + globals={ + "x": x, + "args": params, + "fn": partial(xsw.swiglu, op=OP), + }, + label="swiglu_fw", + description=OP.NAME, + sub_label=sub_label, + ) + yield benchmark.Timer( + stmt=f"{PREFIX}fn(x, *args)", + globals={ + "x": x, + "args": params, + "fn": partial(xsw.swiglu, op=xsw.SwiGLUEagerOp), + }, + label="swiglu_fw", + description="eager", + sub_label=sub_label, + ) + + +def benchmark_swiglu_bw(shape, dtype, bias: bool): + if dtype == "autocast_half": + inp_dtype, model_dtype = torch.float, torch.float + cm: Any = partial(torch.amp.autocast, "cuda", enabled=True, dtype=torch.float16) + else: + inp_dtype, model_dtype = dtype, dtype + cm = nullcontext + + x = torch.randn(shape[:2], device=device, dtype=inp_dtype) + x.requires_grad_() + module = ( + xsw.SwiGLU(in_features=shape[1], hidden_features=shape[2], bias=bias) + .to(device) + .to(model_dtype) + ) + + dtype_str = DTYPE2STR.get(dtype, dtype) + bstr = "bias" if bias else "nobi" + sub_label = f"{dtype_str} B={shape[0]}, I={shape[1]}, H={shape[2]} {bstr}" + + params = module._ordered_params() + with cm(): + out = xsw.swiglu(x, *params, op=OP) + grad = torch.zeros_like(out) + + yield benchmark.Timer( + stmt="out.backward(grad, retain_graph=True)", + globals={ + "out": out, + "grad": grad, + }, + label="swiglu_bw", + description=OP.NAME, + sub_label=sub_label, + ) + del out + + with cm(): + out = xsw.swiglu(x, *params, op=xsw.SwiGLUEagerOp) + + yield benchmark.Timer( + stmt="out.backward(grad, retain_graph=True)", + globals={ + "out": out, + "grad": grad, + }, + label="swiglu_bw", + description="eager", + sub_label=sub_label, + ) + + +if torch.version.hip: + print("This benchmark could not be done on ROCM!") +else: + benchmark_main_helper(benchmark_swiglu, CASES, min_run_time=min_run_time) + benchmark_main_helper(benchmark_swiglu_bw, CASES, min_run_time=min_run_time) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_tiled_matmul.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_tiled_matmul.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ca26c3987c0320f6fc323300c501d745f9b438 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/benchmark_tiled_matmul.py @@ -0,0 +1,122 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import itertools + +import torch +from torch.utils import benchmark + +from xformers.benchmarks.utils import benchmark_main_helper, DTYPE2STR +from xformers.ops.tiled_matmul import tiled_matmul + +min_run_time = 5 + + +SHAPES = { + "llama1_65b_mha_fwd": ([16384], [1024] * 3, [8192]), + "llama1_65b_mha_bwd_input": ([16384], [8192], [1024] * 3), + "llama1_65b_mha_bwd_weight": ([8192], [1024] * 3, [16384]), + "llama1_65b_ffn_fwd": ([16384], [2752] * 2, [8192]), + "llama1_65b_ffn_bwd_input": ([16384], [8192], [2752] * 2), + "llama1_65b_ffn_bwd_weight": ([8192], [2752] * 2, [16384]), + "llama2_150b_mha_fwd": ([16384], [1536, 128, 128], [12288]), + "llama2_150b_mha_bwd_input": ([16384], [12288], [1536, 128, 128]), + "llama2_150b_mha_bwd_weight": ([12288], [1536, 128, 128], [16384]), + "llama2_150b_ffn_fwd": ([16384], [4096] * 2, [12288]), + "llama2_150b_ffn_bwd_input": ([16384], [12288], [4096] * 2), + "llama2_150b_ffn_bwd_weight": ([12288], [4096] * 2, [16384]), +} + + +def product_dict(**kwargs): + keys = kwargs.keys() + vals = kwargs.values() + for instance in itertools.product(*vals): + yield dict(zip(keys, instance)) + + +CASES = list( + product_dict( + shape_name=SHAPES.keys(), + dtype=[ + # torch.float32, + torch.bfloat16, + # torch.float16, + ], + ) +) + + +def matmul_per_tile(a, b): + c = [] + for n in range(len(a)): + c.append([]) + for m in range(len(b[0])): + c[-1].append( + sum([torch.matmul(a[n][k], b[k][m]) for k in range(len(a[0]))]) + ) + return c + + +def benchmark_tiled_matmul(shape_name, dtype): + ms, ns, ks = SHAPES[shape_name] + m, n, k = sum(ms), sum(ns), sum(ks) + + a = torch.randn((m, k), device="cuda", dtype=dtype) + b = torch.randn((k, n), device="cuda", dtype=dtype) + + a_tiles = [[y.clone() for y in x.split(ks, dim=1)] for x in a.split(ms, dim=0)] + b_tiles = [[y.clone() for y in x.split(ns, dim=1)] for x in b.split(ks, dim=0)] + + dtype_str = DTYPE2STR.get(dtype, dtype) + sub_label = ( + f"{dtype_str} {shape_name} " + f"M={'+'.join(f'{m}' for m in ms)} " + f"N={'+'.join(f'{n}' for n in ns)} " + f"K={'+'.join(f'{k}' for k in ks)}" + ) + + # Warmup (maybe not needed?) + torch.mm(a, b) + matmul_per_tile(a_tiles, b_tiles) + tiled_matmul(a_tiles, b_tiles) + + yield benchmark.Timer( + stmt="fn(a, b)", + globals={ + "a": a, + "b": b, + "fn": torch.mm, + }, + label="tiled_matmul", + description="pytorch_fused", + sub_label=sub_label, + ) + yield benchmark.Timer( + stmt="fn(a, b)", + globals={ + "a": a_tiles, + "b": b_tiles, + "fn": matmul_per_tile, + }, + label="tiled_matmul", + description="pytorch_tiled", + sub_label=sub_label, + ) + yield benchmark.Timer( + stmt="fn(a, b)", + globals={ + "a": a_tiles, + "b": b_tiles, + "fn": tiled_matmul, + }, + label="tiled_matmul", + description="xformers_tiled", + sub_label=sub_label, + ) + + +benchmark_main_helper(benchmark_tiled_matmul, CASES, min_run_time=min_run_time) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/utils.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4d31db0d6b1c6e1becd914fd9fdce3dff7a9121e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/benchmarks/utils.py @@ -0,0 +1,767 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import argparse +import contextlib +import copy +import csv +import functools +import glob +import itertools +import logging +import math +import os +import tempfile +from collections import defaultdict, namedtuple +from dataclasses import replace +from typing import Any, Dict, Generator, Iterator, List, Set, Tuple + +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +import seaborn as sns +import torch +import tqdm +from torch.utils import benchmark + +sns.set() + +TestCase = namedtuple("TestCase", ["function", "name"]) + + +class NotSupportedInputError(Exception): + pass + + +_triton_is_available = torch.cuda.is_available() +if _triton_is_available: + try: + import triton + except ImportError as e: + logging.warning(f"Triton is not available: {e}.\nbench_functions") + _triton_is_available = False + + +def get_func_name(fn): + if isinstance(fn, functools.partial): + return fn.func.__name__ + return fn.__name__ + + +def pretty_print(results, title, units) -> None: + """Printout the contents of a dict as a human-readable and Markdown compatible array""" + print(title) + header = " Units: {:<45}".format(units) + print("| " + header + "|" + "".join("{0:<20}|".format(k) for k in results.keys())) + + offset = len(header) + print( + "|-{}|".format("-" * offset) + + "".join("{}|".format("-" * 20) for _ in results.keys()) + ) + + workloads: Dict[str, Any] = {k: [] for v in results.values() for k in v.keys()} + for v in results.values(): + for k in v.keys(): + workloads[k].append(v[k]) + + for k, w in workloads.items(): + print( + "| {0:<{offset}}|".format(k, offset=offset) + + "".join("{:<20}|".format(v) for v in w) + ) + + print("") + + +def pretty_plot( + results, title, units: str, filename=None, dash_key="", legend_loc="lower right" +): + """Graph out the contents of a dict. + Dash key means that if the result label has this key, then it will be displayed with a dash + """ + + if not filename: + filename = title + ".png" + + # Sanitize the filename + filename = ( + filename.replace(" ", "_").replace("/", "_").replace("-", "_").replace(":", "") + ) + + # Gather all the results in "collumns" + workloads: Dict[str, Any] = {k: [] for v in results.values() for k in v.keys()} + for v in results.values(): + for k in v.keys(): + workloads[k].append(float(v[k])) + + # Make sure that the plot is big enough + f = plt.figure() + f.set_figwidth(6) + f.set_figheight(6) + + # Display the collections + for k, v in workloads.items(): + if dash_key and dash_key in k: + plt.plot(list(results.keys()), v, "--") + else: + plt.plot(list(results.keys()), v) + + plt.title(title) + plt.legend(list(workloads.keys()), loc=legend_loc) + plt.ylabel(units) + plt.xticks(rotation=45) + + plt.savefig(filename, bbox_inches="tight") + plt.close(f) + + +if _triton_is_available: + + def bench_functions( + test_cases: List[TestCase], shapes, metric_transform, unit, title="" + ): + device = torch.device("cuda") + + for dtype in [torch.bfloat16, torch.float16, torch.float32]: + results: Dict[str, Any] = {} + + for B, M, K in shapes: + a = torch.rand(B, M, K, device=device, dtype=dtype, requires_grad=True) + + for testcase in test_cases: + time = triton.testing.do_bench(lambda: testcase.function(a))[0] + + metric = metric_transform(a, time) + + key = f"B={B}, M={M}, K={K}" + if key not in results: + results[key] = {} + + results[key][testcase.name] = f"{metric:.1f}" + + pretty_print( + results, + title=" ------------- Type: {} ------------- ".format(dtype), + units=unit, + ) + pretty_plot(results, title + str(dtype), unit, dash_key="pytorch") + + +def pretty_barplot(results, title, units: str, filename=None, dash_key=""): + """Graph out the contents of a dict. + Dash key means that if the result label has this key, then it will be displayed with a dash + """ + + if not filename: + filename = title + ".png" + + # Sanitize the filename + filename = ( + filename.replace(" ", "_").replace("/", "_").replace("-", "_").replace(":", "") + ) + + xlabels = list(results.keys()) + # Gather all the results in "collumns" + workloads: Dict[str, Any] = {k: [] for v in results.values() for k in v.keys()} + for v in results.values(): + for k in v.keys(): + workloads[k].append(float(v[k])) + + options = list(workloads.keys()) + group_len = len(options) + for key in workloads.keys(): + num_groups = len(workloads[key]) + break + group_width = group_len + 1 + + # Make sure that the plot is big enough + f = plt.figure() + f.set_figwidth(6) + f.set_figheight(6) + + for idx in range(group_len): + option = options[idx] + values = workloads[option] + xloc = np.arange(1 + idx, group_width * num_groups, group_width) + plt.bar(xloc, values, width=1, edgecolor="black") + + plt.title(title) + plt.legend(list(workloads.keys()), loc="upper right") + plt.ylabel(units) + + ax = plt.gca() + xticks_loc = np.arange( + 1 + (group_len - 1) / 2.0, group_width * num_groups, group_width + ) + ax.set_xticks(xticks_loc, xlabels) + plt.xticks(rotation=45) + + plt.setp(ax.xaxis.get_majorticklabels(), ha="right") + ax.set_axisbelow(True) + ax.yaxis.grid(color="gray", linestyle="dashed") + ax.xaxis.grid(color="gray", linestyle="dashed") + + plt.savefig(filename, bbox_inches="tight") + plt.close(f) + + +def rmf(filename: str) -> None: + """Remove a file like rm -f.""" + try: + os.remove(filename) + except FileNotFoundError: + pass + + +@contextlib.contextmanager +def temp_files_ctx(num: int) -> Generator: + """A context to get tempfiles and ensure they are cleaned up.""" + files = [tempfile.mkstemp()[1] for _ in range(num)] + + yield tuple(files) + + # temp files could have been removed, so we use rmf. + for name in files: + rmf(name) + + +META_ALGORITHM = "algorithm" +BASELINE_DESCRIPTIONS = ["eager", "vanilla", "pytorch"] + + +# Serialize/unserialize to CSV +# We could use pkl, but resort to CSV for readability +def _benchmark_results_from_csv(filename: str) -> List[Tuple[Dict[str, Any], Any]]: + parts = os.path.basename(filename).split(".") + env = "" + description = "" + if len(parts) == 3: + env = parts[1] + description = parts[0] + + data = [] + with open(filename, "r") as csvfile: + reader = csv.DictReader(csvfile) + for row in reader: + if description != "" and row["description"] not in BASELINE_DESCRIPTIONS: + row["description"] = description + task_spec = benchmark.utils.common.TaskSpec( + stmt="", + setup="", + global_setup="", + label=row["label"], + sub_label=row["sub_label"], + description=row["description"], + env=env, + num_threads=int(row["num_threads"]), + ) + measurement = benchmark.utils.common.Measurement( + number_per_run=1, + raw_times=[float(row["runtime_us"]) / (1000.0 * 1000)], + task_spec=task_spec, + ) + measurement.mem_use = float(row["mem_use_mb"]) # type: ignore + data.append( + ( + { + META_ALGORITHM: ( + row["algorithm"] if row["algorithm"] != "" else None + ), + }, + measurement, + ) + ) + return data + + +def _benchmark_results_to_csv( + filename: str, results: List[Tuple[Dict[str, Any], Any]] +) -> None: + data = [ + { + "sub_label": r.task_spec.sub_label, + "label": r.task_spec.label, + "num_threads": r.task_spec.num_threads, + "algorithm": metadata.get(META_ALGORITHM, ""), + "description": ( + r.task_spec.description + if r.task_spec.description in BASELINE_DESCRIPTIONS + else "" + ), + "runtime_us": int(1000 * 1000 * r.mean), + "mem_use_mb": r.mem_use, + } + for metadata, r in results + ] + with open(filename, "w+", newline="") as csvfile: + writer = csv.DictWriter(csvfile, fieldnames=list(data[0].keys())) + writer.writeheader() + for d in data: + writer.writerow(d) + + +def _finalize_results(results: List[Tuple[Dict[str, Any], Any]]) -> List[Any]: + """ + Returns a `benchmark.Compare` object, except that if we have runs + with different algorithms, we also add the algorithm name + in the column titles + """ + all_algorithms: Set[str] = set() + all_description: Set[str] = set() + for metadata, r in results: + algo = metadata.get(META_ALGORITHM, None) + if algo is not None: + all_algorithms.add(algo) + all_description.add(r.task_spec.description) + display_algo = len(all_algorithms) > 1 + display_descr = len(all_description) > 1 + + display_results = [] + for metadata, r in results: + algo = metadata.get(META_ALGORITHM, None) + if algo is None: + display_results.append(r) + else: + r = copy.copy(r) + description = "" + if display_descr: + description = r.task_spec.description + if display_algo: + if display_descr: + description += "[" + description += algo + if display_descr: + description += "]" + r.task_spec = replace(r.task_spec, description=description) + display_results.append(r) + return display_results + + +def _render_bar_plot(results: List[Any], store_results_folder: str) -> None: + if not results: + return + runtime: Dict[str, Dict[str, float]] = defaultdict(dict) + memory_usage: Dict[str, Dict[str, float]] = defaultdict(dict) + all_descriptions: List[str] = [] + for r in results: + # Hacky: use a list to preserve order + if r.task_spec.description not in all_descriptions: + if r.task_spec.description in BASELINE_DESCRIPTIONS: + all_descriptions.insert(0, r.task_spec.description) + else: + all_descriptions.append(r.task_spec.description) + runtime[r.task_spec.sub_label][r.task_spec.description] = r.mean + memory_usage[r.task_spec.sub_label][r.task_spec.description] = r.mem_use + all_data_mem: List[Any] = [] + all_data_run: List[Any] = [] + for key, runtime_values in runtime.items(): + memory_values = memory_usage[key] + denom = memory_values.get(all_descriptions[0], math.inf) + if denom == 0: + all_data_mem.append([key] + [0] * len(all_descriptions)) + else: + all_data_mem.append( + [key] + [memory_values.get(d, 0) / denom for d in all_descriptions] + ) + all_data_run.append( + [key] + + [ + runtime_values.get(all_descriptions[0], 0) + / runtime_values.get(d, math.inf) + for d in all_descriptions + ] + ) + if all_descriptions[0] == "": + all_descriptions[0] = "baseline" + else: + all_descriptions[0] = f"{all_descriptions[0]} (baseline)" + + for data, filename, title in [ + (all_data_mem, "mem.png", "Memory usage (vs baseline, lower is better)"), + ( + all_data_run, + "runtime.png", + "Runtime speedup (vs baseline, higher is better)", + ), + ]: + df = pd.DataFrame(data, columns=["Configuration"] + all_descriptions) + df.plot( + x="Configuration", + kind="bar", + stacked=False, + title=title, + ) + plt.tight_layout() + filename_full = os.path.join(store_results_folder, filename) + plt.savefig(filename_full) + print(f"Saved plot: {filename_full}") + + +def create_argparser() -> argparse.ArgumentParser: + """ + Create CLI argument parser. + """ + parser = argparse.ArgumentParser() + parser.add_argument( + "--fn", default=None, type=str, help="Only benchmark this function" + ) + parser.add_argument( + "--label", default=None, type=str, help="Store results to a file" + ) + parser.add_argument( + "--fail_if_regression", + action="store_true", + help="Enabled in CI to check against performance regressions", + ) + parser.add_argument( + "--compare", + default=None, + type=str, + help="Compare to previously stored benchmarks (coma separated)", + ) + parser.add_argument( + "--omit-baselines", + action="store_true", + help="Do not run the (potentially slow) baselines", + ) + parser.add_argument( + "--quiet", + action="store_true", + help="Skip intermediate results and progress bar", + ) + return parser + + +def benchmark_main_helper( + benchmark_fn, cases: List[Dict[str, Any]], arg_parser=None, **kwargs +) -> None: + """ + Helper function to run benchmarks. + Supports loading previous results for comparison, and saving current results to file. + """ + arg_parser = arg_parser or create_argparser() + args = arg_parser.parse_args() + + if args.fn is not None and args.fn != get_func_name(benchmark_fn): + print(f'Skipping benchmark "{get_func_name(benchmark_fn)}"') + return + benchmark_run_and_compare( + benchmark_fn=benchmark_fn, + cases=cases, + optimized_label="optimized" if args.label is None else args.label, + fail_if_regression=args.fail_if_regression, + compare=args.compare.split(",") if args.compare is not None else [], + quiet=args.quiet, + omit_baselines=args.omit_baselines, + **kwargs, + ) + + +def benchmark_run_and_compare( + benchmark_fn, + cases: List[Dict[str, Any]], + compare: List[str], + omit_baselines: bool = False, + fail_if_regression: bool = False, + quiet: bool = False, + optimized_label: str = "optimized", + *, + min_run_time: float = 2.0, + atol_s: float = 30e-6, + rtol: float = 0.05, +) -> None: + SKIP_VANILLA_TASKS_IF_ALREADY_DONE = True + results_compare_to = [] + results = [] + + store_results_folder = os.path.expanduser( + os.path.join( + os.environ.get( + "XFORMERS_BENCHMARKS_CACHE", + os.path.join("~", ".cache", "xformers", "benchmarks"), + ), + get_func_name(benchmark_fn), + ) + ) + + try: + env = ( + torch.cuda.get_device_name(torch.cuda.current_device()) + .replace(" ", "_") + .replace("-", "_") + .replace(".", "_") + .replace("/", "_") + ) + except (RuntimeError, AssertionError): # No GPU + env = "cpu" + assert ( + "." not in optimized_label + ), f"label=`{optimized_label}` should not contain dots" + assert "." not in env, f"env=`{env}` should not contain dots" + + os.makedirs(store_results_folder, exist_ok=True) + + # Load runs that we want to compare to + skip_vanilla_tasks = set() + for cmp_name in compare: + name_with_env = cmp_name if "." in cmp_name else f"{cmp_name}.*" + for filename in glob.glob( + os.path.join(store_results_folder, f"{name_with_env}.csv") + ): + loaded = _benchmark_results_from_csv(filename) + for m, r in loaded: + if m.get(META_ALGORITHM) is not None: + m[META_ALGORITHM] = m[META_ALGORITHM].partition("@")[0] + if r.task_spec.env == env and SKIP_VANILLA_TASKS_IF_ALREADY_DONE: + skip_vanilla_tasks.add( + (r.task_spec.sub_label, r.task_spec.num_threads) + ) + results_compare_to += loaded + + if not quiet: + pbar = tqdm.tqdm(cases, leave=False) + cases = pbar + for case in cases: + if quiet: + print(str(case)) + else: + pbar.write(f"====== {str(case)} ======") + try: + benchmarks_generator = benchmark_fn(**case) + except NotImplementedError: + # pbar.write(f"Skipped (NotImplementedError)") + continue + except RuntimeError as e: + if not _is_oom_error(e): + raise + if not quiet: + pbar.write("Skipped (OOM)") + continue + + name = None + try: + torch.cuda.synchronize() + torch.cuda.reset_peak_memory_stats() + mem_begin = torch.cuda.max_memory_allocated() / 2**20 + + for benchmark_object in benchmarks_generator: + memory = math.inf + try: + + is_optimized = ( + benchmark_object._task_spec.description + not in BASELINE_DESCRIPTIONS + ) + metadata = {} + if is_optimized: + metadata[META_ALGORITHM] = ( + benchmark_object._task_spec.description + ) + benchmark_object._task_spec = replace( + benchmark_object._task_spec, description=optimized_label + ) + elif ( + omit_baselines + or ( + benchmark_object._task_spec.sub_label, + benchmark_object._task_spec.num_threads, + ) + in skip_vanilla_tasks + ): + continue + + torch.cuda.synchronize() + benchmark_object._task_spec = replace( + benchmark_object._task_spec, env=env + ) + measurement = benchmark_object.blocked_autorange( + min_run_time=min_run_time + ) + torch.cuda.synchronize() + results.append((metadata, measurement)) + name = measurement.task_spec.description + memory = torch.cuda.max_memory_allocated() / 2**20 - mem_begin + measurement.mem_use = memory + + torch.cuda.reset_peak_memory_stats() + mem_begin = torch.cuda.max_memory_allocated() / 2**20 + except RuntimeError as e: + if not _is_oom_error(e): + raise + if not quiet: + pbar.write("Skipped (OOM)") + finally: + del benchmark_object + if not quiet: + pbar.write(f"{name}: memory used: {memory} MB") + except RuntimeError as e: + if not _is_oom_error(e): + raise + if not quiet: + pbar.write("Skipped (OOM)") + # Display results for benchmarks we just calculated + if name is not None and not quiet: + + def matches_current(r): + return ( + r[1].task_spec.sub_label == results[-1][1].task_spec.sub_label + and r[1].task_spec.label == results[-1][1].task_spec.label + ) + + pbar.write( + str( + benchmark.Compare( + _finalize_results( + list(filter(matches_current, results)) + + list(filter(matches_current, results_compare_to)) + ) + ) + ) + ) + + results_for_print = _finalize_results(results + results_compare_to) + benchmark.Compare(results_for_print).print() + _render_bar_plot(results_for_print, store_results_folder) + + # Save runs to a file + if results and optimized_label is not None: + write_to_path = os.path.join( + store_results_folder, f"{optimized_label}.{env}.csv" + ) + _benchmark_results_to_csv(write_to_path, results) + print(f"Saved results to {write_to_path}") + + if fail_if_regression: + _fail_if_regressions( + results, reference=results_compare_to, atol_s=atol_s, rtol=rtol + ) + + +def _is_oom_error(e): + return isinstance( + e, (torch.cuda.OutOfMemoryError, triton.runtime.autotuner.OutOfResources) + ) + + +def _fail_if_regressions( + results: List[Any], reference: List[Any], atol_s: float, rtol: float +) -> None: + def get_measurement_id(r): + return ( + r[0].get(META_ALGORITHM, "").partition("@")[0], + r[1].task_spec.label, + r[1].task_spec.sub_label, + r[1].task_spec.env, + ) + + id_to_result = {} + for r in results: + id_to_result[get_measurement_id(r)] = r[1] + + num_better = 0 + num_worse = 0 + num_nochange = 0 + num_unk = 0 + reference_set = set() + for ref in reference: + if ref[1].task_spec.description in BASELINE_DESCRIPTIONS: + continue + benchmark_id = get_measurement_id(ref) + if benchmark_id in reference_set: + raise ValueError(f"Duplicate benchmark in reference for {benchmark_id}") + reference_set.add(benchmark_id) + if benchmark_id not in id_to_result: + num_unk += 1 + continue + res = id_to_result[benchmark_id] + # If significative change + if abs(ref[1].mean - res.mean) - rtol * ref[1].mean > atol_s: + is_now_better = res.mean < ref[1].mean + if is_now_better: + num_better += 1 + else: + num_worse += 1 + cmp = "IMPROVED" if is_now_better else "REGRESS " + print(cmp, benchmark_id, f"ref={ref[1].mean}", f"now={res.mean}") + else: + num_nochange += 1 + + print("Regression test summary:") + print(f" Better : {num_better}") + print(f" No change: {num_nochange}") + print(f" Worse : {num_worse}") + if num_unk > 0: + print(f" (no ref) : {num_unk}") + benchmarks_run = num_better + num_nochange + num_worse + if num_worse > 1: + raise RuntimeError("At least one benchmark regressed!") + elif num_unk == benchmarks_run: + raise RuntimeError("No reference found") + elif benchmarks_run == 0: + raise RuntimeError("No benchmark was run") + + +def benchmark_main_helper2( + name: str, + functions, + fw: bool = False, + bw: bool = False, + cuda_graph: bool = True, + **kwargs, +) -> None: + assert fw or bw + + def handle_case(**case) -> Iterator[benchmark.Timer]: + for k, benchmark_cls in functions.items(): + try: + benchmark_object = benchmark_cls(**case, bw=bw) + except NotSupportedInputError: + continue + label = benchmark_object.label + label += "fw" if fw else "" + label += "bw" if bw else "" + + def run_one(): + if fw: + benchmark_object.fw() + if bw: + benchmark_object.bw() + + if cuda_graph: + run_one() + g = torch.cuda.CUDAGraph() + with torch.cuda.graph(g): + run_one() + + def run_one(): + g.replay() + + yield benchmark.Timer( + stmt="fn()", + globals={ + "fn": run_one, + }, + label=label, + description=k, + sub_label=benchmark_object.sub_label, + ) + + handle_case.__name__ = name + benchmark_main_helper(handle_case, **kwargs) + + +def product_dict(**kwargs): + keys = kwargs.keys() + vals = kwargs.values() + for instance in itertools.product(*vals): + yield dict(zip(keys, instance)) + + +DTYPE2STR = { + torch.bfloat16: "b16", + torch.half: "f16", + torch.float32: "f32", +} diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..18251a787e422b01c9ecb628c7e9b9080b4ffd70 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/__init__.py @@ -0,0 +1,32 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import warnings +from pathlib import Path + +from xformers.utils import import_all_modules + +from .attention import Attention, build_attention # noqa +from .input_projection import InputProjection, InputProjectionConfig # noqa +from .residual import ( # noqa + NormalizationType, + PostNorm, + PreNorm, + RequiresWrappedInputs, + Residual, + ResidualNormStyle, +) + +warnings.warn( + "xformers.components is deprecated and is not maintained anymore. " + "It might be removed in a future version of xFormers ", + FutureWarning, + stacklevel=2, +) + + +# automatically import any Python files in the directory +import_all_modules(str(Path(__file__).parent), "xformers.components") diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ce54cb69425c279cd5d302981d318fc13221c87 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/__pycache__/input_projection.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/__pycache__/input_projection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31e78b887344cc710685ec2638e8026a837e1b2d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/__pycache__/input_projection.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/__pycache__/residual.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/__pycache__/residual.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e34b4408fdb8e1f1641c034ae9c57fd27dfaa97 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/__pycache__/residual.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ff72d3598c46f1c9ebe48f96a98cc05b03814762 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__init__.py @@ -0,0 +1,110 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import logging +from pathlib import Path +from typing import Any, Callable, Dict, Set, Union + +import torch + +from xformers.utils import ( + generate_matching_config, + get_registry_decorator, + import_all_modules, +) + +from ._sputnik_sparse import SparseCS +from .attention_mask import AttentionMask +from .base import Attention, AttentionConfig # noqa + +logger = logging.getLogger("xformers") + + +# CREDITS: Classy Vision registry mechanism + +ATTENTION_REGISTRY: Dict[str, Any] = {} +ATTENTION_CLASS_NAMES: Set[str] = set() + +# Arbitrary threshold for now, +# in between dense and sparse matrix algorithms for the attention mechanism +_DENSITY_THRESHOLD = 0.30 # noqa # from the sputnik paper, vs. +_USE_SPUTNIK = True + + +def build_attention(config: Union[Dict[str, Any], AttentionConfig]): + """Builds an attention from a config. + + This assumes a 'name' key in the config which is used to determine what + attention class to instantiate. For instance, a config `{"name": "my_attention", + "foo": "bar"}` will find a class that was registered as "my_attention" + (see :func:`register_attention`) and call .from_config on it.""" + + if not isinstance(config, AttentionConfig): + try: + config_instance = generate_matching_config( + config, ATTENTION_REGISTRY[config["name"]].config + ) + except KeyError as e: + name = config["name"] + logger.warning(f"{name} not available among {ATTENTION_REGISTRY.keys()}") + raise e + else: + config_instance = config + + return ATTENTION_REGISTRY[config_instance.name].constructor.from_config( + config_instance + ) + + +"""Registers an Attention subclass. + + This decorator allows xFormers to instantiate a subclass of Attention + from a configuration file, even if the class itself is not part of the + xFormers library. To use it, apply this decorator to an Attention + subclass, like this: + + .. code-block:: python + + @dataclass + class MyConfig: + ... + + @register_attention('my_attention', MyConfig) + class MyAttention(Attention): + ... + + To instantiate an attention from a configuration file, see :func:`build_attention`.""" +register_attention: Callable[[str, Any], Callable[[Any], Any]] = get_registry_decorator( + ATTENTION_REGISTRY, ATTENTION_CLASS_NAMES, Attention, AttentionConfig +) + + +def maybe_sparsify(matrix) -> Any: + # Sparsify if that makes sense + if torch.count_nonzero(matrix).item() / matrix.numel() > _DENSITY_THRESHOLD: + # If not sparse, then AttentionMask is the reference type + return AttentionMask.from_bool(matrix) + + return sparsify(matrix) + + +def sparsify(matrix): + if _USE_SPUTNIK: + return SparseCS(matrix) + return matrix.to_sparse() + + +from .scaled_dot_product import ScaledDotProduct # noqa + +__all__ = [ + "ScaledDotProduct", + "Attention", + "AttentionMask", + "build_attention", + "register_attention", +] + +# automatically import any Python files in the directory +import_all_modules(str(Path(__file__).parent), "xformers.components.attention") diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c0f1696c9e953905277907fa32378616f483d38 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/_sputnik_sparse.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/_sputnik_sparse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40b56335d9f903ebb4626c5c3e04882659b81101 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/_sputnik_sparse.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/attention_mask.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/attention_mask.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efbb587cc19a1403ec255acf08708c7b0cb857a1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/attention_mask.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/attention_patterns.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/attention_patterns.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc29311eae646dc4f0b372c18451d8b31e0882cd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/attention_patterns.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/base.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..795e25489a454e8e2c54fc627de00e502cecf070 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/base.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/core.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16505633fc6f280bf0b5befeaba8c347e067e473 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/core.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/fourier_mix.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/fourier_mix.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82798f4ed0d7c6b5c5b444782784341716028fe0 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/fourier_mix.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/scaled_dot_product.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/scaled_dot_product.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cecc8e178c3bdf2b7bfd2b899a0502f47ebca04c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/scaled_dot_product.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/sparsity_config.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/sparsity_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..253ffcbed66fdbd756b79ca71bc07249cb8123a6 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/sparsity_config.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d65bf560ecbe9abb6d1d7da31846767411c1fd3 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/_sputnik_sparse.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/_sputnik_sparse.py new file mode 100644 index 0000000000000000000000000000000000000000..d6b92d75cd81511256377dc493215b66acb25364 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/_sputnik_sparse.py @@ -0,0 +1,121 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import torch + +from xformers.ops import masked_matmul +from xformers.sparse import SparseCSRTensor + +# TODO: this is here for BC +from xformers.sparse.utils import _csr_to_coo, _dense_to_sparse # noqa: F401 + + +class SparseCS: + def __init__(self, matrix, device=None): + if device is None: + device = torch.device("cpu") + if matrix.ndim == 2: + matrix = matrix[None] + assert matrix.ndim == 3 + self._mat = SparseCSRTensor.from_dense(matrix).to(device) + + @property + def device(self): + return self._mat.device + + @property + def ndim(self): + return self._mat.ndim + + @property + def dtype(self): + return self._mat.dtype + + @property + def is_sparse(self): + return True + + @property + def shape(self): + return self._mat.shape[1:] + + @property + def values(self): + return self._mat.values() + + @property + def row_indices(self): + return self._mat._csr_row_indices + + @property + def column_indices(self): + return self._mat._csr_column_indices + + @property + def row_offsets(self): + return self._mat._csr_row_offsets + + @property + def _transp_info(self): + return self._mat._csr_transp_info + + @classmethod + def wrap( + cls, shape, values, row_indices, row_offsets, column_indices, _transp_info + ): + matrix = cls.__new__(cls) + _shape = (values.shape[0],) + shape + csr_matrix = SparseCSRTensor._wrap( + _shape, values, row_indices, row_offsets, column_indices, _transp_info + ) + matrix._mat = csr_matrix + return matrix + + @classmethod + def _wrap(cls, csr_matrix): + assert isinstance(csr_matrix, SparseCSRTensor) + matrix = cls.__new__(cls) + matrix._mat = csr_matrix + return matrix + + def __mul__(self, other): + assert isinstance(other, (int, float)) + return type(self)._wrap(self._mat * other) + + def __add__(self, other): + assert isinstance(other, type(self)) + return type(self)._wrap(self._mat + other._mat) + + def matmul_with_mask(self, a, b): + return type(self)._wrap(masked_matmul(a, b, self._mat)) + + def softmax(self): + out = torch.nn.functional.softmax(self._mat, -1) + return type(self)._wrap(out) + + def spmm(self, b): + out = torch.bmm(self._mat, b) + return out + + def transpose(self): + out = torch.transpose(self._mat, -2, -1) + return type(self)._wrap(out) + + def to(self, device): + assert isinstance(device, torch.device) + out = self._mat.to(device) + return type(self)._wrap(out) + + def to_dense(self): + return self._mat.to_dense() + + def logical_and(self, other: torch.Tensor): + assert not isinstance(other, SparseCS) + out = torch.logical_and(self._mat, other) + return type(self)._wrap(out) + + def __and__(self, other): + return self.logical_and(other) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/attention_mask.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/attention_mask.py new file mode 100644 index 0000000000000000000000000000000000000000..7006e97aa9eb710f4029d709f87c1f83a316254b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/attention_mask.py @@ -0,0 +1,143 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +from typing import Optional, Type, TypeVar + +import torch + +Self = TypeVar("Self", bound="AttentionMask") + + +class AttentionMask: + """ + Holds an attention mask, along with a couple of helpers and attributes. + + .. note: this is an additive mask, meaning that coefficients which should be computed hold the '0.' value, + and coefficients which should be skipped hold the '-inf' value. Any other value is possible if the purpose + is to bias the attention computation for instance + + .. note: the attention mask dimensions are expected to be `[batch, to_sequence, from_sequence]`, + `[to_sequence, from_sequence]`, or anything broadcastable in between + """ + + def __init__(self, additive_mask: torch.Tensor, is_causal: bool = False): + assert additive_mask.is_floating_point(), additive_mask.dtype + assert not additive_mask.requires_grad + + if additive_mask.ndim == 2: + additive_mask = additive_mask.unsqueeze(0) + + self.values = additive_mask + self.is_causal = is_causal + self.seq_len = additive_mask.shape[1] + self.to_seq_len = additive_mask.shape[0] + + def to_bool(self) -> torch.Tensor: + """ + .. warning: we assume here that True implies that the value should be computed + """ + return self.values != float("-inf") + + @classmethod + def from_bool(cls: Type[Self], x: torch.Tensor) -> Self: + """ + Create an AttentionMask given a boolean pattern. + .. warning: we assume here that True implies that the value should be computed + """ + assert x.dtype == torch.bool + + additive_mask = torch.empty_like(x, dtype=torch.float, device=x.device) + additive_mask.masked_fill_(x, 0.0) + additive_mask.masked_fill_(~x, float("-inf")) + + return cls(additive_mask) + + @classmethod + def from_multiplicative(cls: Type[Self], x: torch.Tensor) -> Self: + """ + Create an AttentionMask given a multiplicative attention mask. + """ + assert not x.dtype == torch.bool + + additive_mask = torch.empty_like(x, dtype=torch.float, device=x.device) + x = x.bool() + + additive_mask.masked_fill_(x, 0.0) + additive_mask.masked_fill_(~x, float("-inf")) + + return cls(additive_mask) + + @classmethod + def make_causal( + cls: Type[Self], + seq_len: int, + to_seq_len: Optional[int] = None, + device: Optional[torch.device] = None, + dtype: Optional[torch.dtype] = None, + ) -> Self: + if not to_seq_len: + to_seq_len = seq_len + + additive_mask = torch.triu( + torch.ones(seq_len, to_seq_len, device=device, dtype=dtype) * float("-inf"), + diagonal=1, + ) + return cls(additive_mask=additive_mask, is_causal=True) + + def make_crop( + self, seq_len: int, to_seq_len: Optional[int] = None + ) -> "AttentionMask": + """ + Return a cropped attention mask, whose underlying tensor is a view of this one + """ + + if not to_seq_len: + to_seq_len = seq_len + + return AttentionMask( + self.values[:, :seq_len, :to_seq_len], is_causal=self.is_causal + ) + + def __repr__(self): + return f"AttentionMask - causal {self.is_causal} - mask " + str(self.values) + + @property + def device(self): + return self.values.device + + @property + def is_sparse(self): + return False + + @property + def ndim(self): + return len(self.values.shape) + + @property + def dtype(self): + return self.values.dtype + + @property + def shape(self): + return self.values.shape + + def __add__(self, other): + return AttentionMask(self.values + other.values, is_causal=False) + + def to( + self, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None + ) -> "AttentionMask": + assert device is None or isinstance(device, torch.device) + assert dtype is None or isinstance(dtype, torch.dtype) + assert device is not None or dtype is not None + + # Noop if we don't need to create another instance + if ((device and device == self.device) or not device) and ( + (dtype and dtype == self.dtype) or not dtype + ): + return self + + return AttentionMask(self.values.to(device=device, dtype=dtype), self.is_causal) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/attention_patterns.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/attention_patterns.py new file mode 100644 index 0000000000000000000000000000000000000000..9c817debb926a27e32aedcaa728f777f812f313c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/attention_patterns.py @@ -0,0 +1,295 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import math +from typing import List + +import numpy as np +import torch + +from xformers.components.attention.sparsity_config import ( + BigBirdSparsityConfig, + BSLongformerSparsityConfig, + FixedSparsityConfig, + VariableSparsityConfig, +) + + +# generic nd cases +def _generate_nd_grid(*sizes): + coords = [torch.arange(s) for s in sizes] + return torch.meshgrid(*coords) + + +def local_nd_distance(*sizes, p=2.0, weights=None): + if weights is None: + weights = (1,) * len(sizes) + assert len(sizes) == len(weights) + grid = _generate_nd_grid(*sizes) + grid = [i.flatten() * w for i, w in zip(grid, weights)] + grid = torch.stack(grid, dim=1).float() + d = torch.cdist(grid, grid, p=p) + return d + + +def local_nd_gaussian_distribution(*sizes, sigma=1): + d = local_nd_distance(*sizes, p=2.0) ** 2 + d = torch.exp(-0.5 * sigma ** (-2.0) * d) + return d + + +def local_nd_pattern(*sizes, distance, p=2.0): + d = local_nd_distance(*sizes, p=p) + return d < distance + + +def axial_nd_pattern(*sizes): + # axial is a special case with p=0 and distance=2 + d = local_nd_distance(*sizes, p=0) + return d < 2 + + +def random_pattern_from_probability_matrix(dist_matrix, nnz): + att = torch.zeros_like(dist_matrix, dtype=torch.bool) + # PyTorch multinomial wrongly doesn't support sampling when number of categories + # is > 2^24, arguing that it's because it's the max representable consecutive element + # in fp32 and that the kernels use float32. This is actually not true, and the kernels + # should work fine if double tensor is passed on CPU. This is a bug that was introduced + # in https://github.com/pytorch/pytorch/commit/bf04c2ca2f591d98ce57816f0ef0cd20a21bbf66 + # when unifying the checks between CPU and CUDA. For now, just fall-back to numpy + if dist_matrix.numel() > 2**24: + dist_matrix = dist_matrix.double() + dist_matrix /= dist_matrix.sum() + idxs = np.random.choice( + dist_matrix.numel(), nnz, p=dist_matrix.flatten(), replace=False + ) + idxs = torch.as_tensor(idxs) + else: + idxs = torch.multinomial(dist_matrix.flatten(), nnz, replacement=False) + att.view(-1)[idxs] = True + return att + + +def global_token_pattern(attention_query_mask: torch.Tensor) -> torch.Tensor: + assert attention_query_mask.ndim == 1 + assert attention_query_mask.dtype == torch.bool + attention_query_mask = attention_query_mask[None, :] + mask = attention_query_mask | attention_query_mask.transpose(1, 0) + return mask + + +def random_pattern(attn_size: int, sparsity: float) -> torch.Tensor: + assert 0 < sparsity < 1 + mask = torch.rand(attn_size, attn_size) > sparsity + return mask + + +# 1d-specific cases +def local_1d_pattern(attn_size: int, window_size: int) -> torch.Tensor: + assert ( + window_size % 2 == 1 + ), "The window size is assumed to be odd (counts self-attention + 2 wings)" + h_win_size = window_size // 2 + 1 + return local_nd_pattern(attn_size, distance=h_win_size, p=1.0) + + +def causal_1d_pattern(attn_size: int) -> torch.Tensor: + mask = torch.tril(torch.ones(attn_size, attn_size, dtype=torch.bool)) + return mask + + +# 2d-specific cases +def horizontal_axial_2d_distance(H, W, p=2.0): + d = local_nd_distance(H, W, p=p, weights=(1, 0)) + return d + + +def vertical_axial_2d_distance(H, W, p=2.0): + d = local_nd_distance(H, W, p=p, weights=(0, 1)) + return d + + +def local_2d_distance(H, W, p=2.0): + return local_nd_distance(H, W, p=p) + + +def local_2d_gausian_distribution(H, W, sigma=1): + return local_nd_gaussian_distribution(H, W, sigma=sigma) + + +def local_2d_pattern(H, W, distance, p=2.0): + return local_nd_pattern(H, W, distance=distance, p=p) + + +def axial_2d_pattern(H, W): + return axial_nd_pattern(H, W) + + +def swin_attention_pattern(H, W, window_size, shift_size=0): + assert H % window_size == 0 + assert W % window_size == 0 + assert 0 <= shift_size < window_size, "shift_size must in 0-window_size" + + # input grid + i, j = _generate_nd_grid(H, W) + i, j = i + 0.5, j + 0.5 + + # anchors grid + # if shift is present, add extra element to the grid + # to account for the uneven partitioning + extra = int(shift_size % window_size != 0) + grid_h = H // window_size + extra + grid_w = W // window_size + extra + + ii, jj = _generate_nd_grid(grid_h, grid_w) + # convert shift to be compatible with the paper representation + s = (-shift_size) % window_size + offset = window_size / 2 - s + ii = ii * window_size + offset + jj = jj * window_size + offset + + input_coords = torch.stack([i.flatten(), j.flatten()], 1).float() + anchors_coords = torch.stack([ii.flatten(), jj.flatten()], 1).float() + + anchor_id = torch.cdist(input_coords, anchors_coords, p=2).argmin(1) + mask = anchor_id[:, None] == anchor_id[None, :] + return mask + + +def dilated_2d_pattern(H, W, k=2): + """ + Returns a 2d pattern that samples 1 every k elements in the attention mask. + Can be seen as a form of downsampling, where every pixel attends to a downsampled + version of the input. + """ + d_h = local_nd_distance(H, W, p=1, weights=(1, 0)) + d_w = local_nd_distance(H, W, p=1, weights=(0, 1)) + d = (d_h.floor() % k == 0) & (d_w.floor() % k == 0) + return d + + +# Block sparse utils +def block_sparsify_tensor(x, mask, block_size): + """ + Block sparsify a tensor, given a mask and block size + """ + ret = torch.empty( + (x.size(0), mask.sum(), block_size, block_size), dtype=x.dtype, device=x.device + ) + + for idx, (h, i, j) in enumerate(zip(*mask.nonzero(as_tuple=True))): + ret[:, idx, :, :] = x[ + :, + h, + i * block_size : (i + 1) * block_size, + j * block_size : (j + 1) * block_size, + ] + return ret + + +def pattern_to_layout(mask: torch.Tensor, block_size: int) -> torch.Tensor: + r""" + Given a mask pattern and blocksize, return the corresponding layout + which makes sure that all the positives in the mask are covered + """ + assert mask.ndim >= 2, "We're expecting [Heads, Seq, Seq] or [Seq, Seq]" + _should_squeeze = False + + if mask.ndim == 2: + mask = mask.unsqueeze(0) + _should_squeeze = True + + assert ( + mask.shape[1] % block_size == 0 and mask.shape[2] % block_size == 0 + ), "We're only handling masks divisible by block_size" + + # Now mark the mask + layout = torch.nn.functional.max_pool2d( + mask.to(torch.float), kernel_size=block_size, stride=block_size + ) + layout = layout.to(torch.long) + + if _should_squeeze: + layout.squeeze_(0) + + return layout + + +def alibi_pattern(threshold: float, mask_shape: torch.Size) -> torch.Tensor: + r""" + Use the additive bias computation from ALiBi_ to generate a mask. + Note that this mask can in turn be used to generate a blocksparse attention computation layout + + .. note: mask_shape is expected to hold the [heads, seq, seq] dimensions + + .. _ALiBi: https://arxiv.org/pdf/2108.12409.pdf + """ + + # CREDITS: code snippet from Ofir Press, one of the authors + + def get_slopes(n: int): + def get_slopes_power_of_2(n: int) -> List[float]: + start = 2 ** (-(2 ** -(math.log2(n) - 3))) + ratio = start + return [start * ratio**i for i in range(n)] + + # In the paper, we only train models that have 2^a heads for some a. This function has + # some good properties that only occur when the input is a power of 2. To maintain that even + # when the number of heads is not a power of 2, we use this workaround. + if math.log2(n).is_integer(): + return get_slopes_power_of_2(n) + else: + closest_power_of_2 = 2 ** math.floor(math.log2(n)) + return ( + get_slopes_power_of_2(closest_power_of_2) + + get_slopes(2 * closest_power_of_2)[0::2][: n - closest_power_of_2] + ) + + maxpos = mask_shape[1] + attn_heads = mask_shape[0] + slopes = torch.Tensor(get_slopes(attn_heads)) + + # In the next line, the part after the * is what constructs the diagonal matrix + # (right matrix in Figure 3 in the paper). + # If you run it you'll see that it doesn't exactly print out the same matrix as we have in Figure 3, + # but one where all rows are identical. + # This works because the softmax operation is invariant to translation, + # and our bias functions are always linear. + alibi = slopes.unsqueeze(1).unsqueeze(1) * torch.arange(maxpos).unsqueeze( + 0 + ).unsqueeze(0).expand(attn_heads, -1, -1) + alibi = alibi.view(attn_heads, 1, maxpos) + + # Now threshold arbitrarily, report the mask + return alibi < threshold + + +def quick_fixed_layout(num_heads: int, block_size: int, seq_len: int): + config = FixedSparsityConfig(num_heads=num_heads, block_size=block_size) + return config.make_layout(seq_len) + + +def quick_variable_layout(num_heads: int, block_size: int, seq_len: int): + config = VariableSparsityConfig(num_heads=num_heads, block_size=block_size) + return config.make_layout(seq_len) + + +def quick_bigbird_layout(num_heads: int, block_size: int, seq_len: int): + config = BigBirdSparsityConfig(num_heads=num_heads, block_size=block_size) + return config.make_layout(seq_len) + + +def quick_bslongformer_layout(num_heads: int, block_size: int, seq_len: int): + config = BSLongformerSparsityConfig(num_heads=num_heads, block_size=block_size) + return config.make_layout(seq_len) + + +def layout_to_pattern(layout: torch.Tensor, block_size: int): + r""" + create a pattern of shape [heads, seq, seq] out of a blocksparse + layout of shape [heads, seq/block_size, seq/block_size] + """ + return torch.kron(layout, torch.ones(block_size, block_size)) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/base.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/base.py new file mode 100644 index 0000000000000000000000000000000000000000..848deb8a050cc7564dc617da5c0a16ec2520e6ee --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/base.py @@ -0,0 +1,95 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +from abc import ABCMeta, abstractmethod +from dataclasses import asdict, dataclass +from typing import Optional, Type, TypeVar + +import torch +import torch.nn as nn + +from xformers._deprecation_warning import deprecated_function +from xformers.components.attention import AttentionMask + + +@dataclass +class AttentionConfig: + """Parameters required for all Attentions. + Can accept and store extra parameters. + """ + + name: str # the registered name for this attention mechanism + dropout: float # dropout probability + + +Self = TypeVar("Self", bound="Attention") + + +# Define the common interface, every attention block needs to derive from it +class Attention(nn.Module, metaclass=ABCMeta): + r"""The base Attention mechanism, which is typically a sub-part of the multi-head attention""" + + _causal_mask: Optional[AttentionMask] = None + + @abstractmethod + def __init__(self, dropout: Optional[float] = None, *args, **kwargs): + super().__init__() + deprecated_function(self) + + # Requires the inputs to be projected + self.requires_input_projection = True + + # Whether the head dimension needs to be present (if not it can be folded into the batch dimension) + self.requires_head_dimension = False + + # key padding mask and attention mask must be passed in as separate arguments instead of a merged attention mask + self.requires_separate_masks = False + + # Requires that K and Q have the same sequence length + self.requires_same_k_q_dimensions = False + + # Whether the attention owns the single head/multihead mechanism + # so that the MHA wrapper should skip it + self.requires_skip_multi_head = False + + # This attention requires a context length which is squared, often due to 2D pooling + self.requires_squared_context = False + + # Whether this attention mechanism supports attention masks + self.supports_attention_mask = True + self.supports_key_padding_mask = False + + @classmethod + def from_config(cls: Type[Self], config: AttentionConfig) -> Self: + # Generate the class inputs from the config + fields = asdict(config) + + # Skip all Nones so that default values are used + fields = {k: v for k, v in fields.items() if v is not None} + + return cls(**fields) + + @abstractmethod + def forward( + self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, *args, **kwargs + ) -> torch.Tensor: + raise NotImplementedError + + @staticmethod + def _maybe_pad_sequence(x: torch.Tensor, mask: torch.Tensor): + """ + If the sequence is shorter than the mask, return a padded view + """ + if x.shape[-2] != mask.shape[-1]: + assert x.shape[-2] < mask.shape[-1], ( + "Sequence is bigger than the provided mask, cannot infer what to do with it." + " Please update your attention mask" + ) + + pad_size = (0, 0, 0, mask.shape[-1] - x.shape[-2], 0, 0) + return torch.nn.functional.pad(x, pad_size, mode="constant", value=0.0) + + return x diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/core.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/core.py new file mode 100644 index 0000000000000000000000000000000000000000..3e80e917dc2ce10d54e95f4d31934751f7889295 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/core.py @@ -0,0 +1,248 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import logging +import math +from contextlib import nullcontext +from typing import Optional, Union + +import torch + +from xformers import _has_cpp_library +from xformers.components.attention.attention_mask import AttentionMask + +if _has_cpp_library: + from ._sputnik_sparse import SparseCS + +logger = logging.getLogger("xformers") + + +def _create_random_sparsity(matrix, sparsity, divisible_by=4): + assert matrix.ndim == 3 + keep = torch.rand_like(matrix[0], dtype=torch.float32) > sparsity + nonzero = torch.nonzero(keep) + nnz = nonzero.shape[0] + # NOTE: need to make it a multiple of 4 for sputnik + nonzero = nonzero[: (nnz - nnz % divisible_by)] + i, j = nonzero.unbind(1) + output = torch.zeros_like(matrix) + bdim = torch.arange(matrix.shape[0], device=matrix.device)[:, None] + output[bdim, i, j] = matrix[bdim, i, j] + return output + + +def _broadcast_batch(mask, batch_size): + if mask.ndim == 3: + return mask + assert mask.ndim == 2 + + mask = mask.coalesce() + values = mask.values() + indices = mask.indices() + nnz = len(values) + # strategy: repeat the indices and append the extra batch dimension to the indices + indices = indices.repeat(1, batch_size) + # now create the batch indices + batch_indices = torch.arange(batch_size, device=indices.device) + batch_indices = batch_indices[:, None].expand(batch_size, nnz).flatten() + + # put them together + indices = torch.cat([batch_indices[None, :], indices], dim=0) + + # now repeat the values + values = values.repeat(batch_size) + + size = (batch_size,) + mask.shape + + return torch.sparse_coo_tensor(indices, values, size) + + +def _matmul_with_mask( + a: torch.Tensor, + b: torch.Tensor, + mask: Optional[Union[torch.Tensor, "SparseCS"]], +) -> torch.Tensor: + if mask is None: + return a @ b + + if _has_cpp_library and mask.dtype == torch.bool: + if isinstance(mask, SparseCS): + return mask.matmul_with_mask(a, b) + if mask.is_sparse: + # perform broadcasting if needed + mask = _broadcast_batch(mask, a.shape[0]) + + # coalesced is not implemented for bool tensors, so need to cast + mask = mask.to(dtype=a.dtype) # type: ignore # mypy is missing the catch above + + return torch.ops.xformers.matmul_with_mask(a, b, mask) + + # Non optimized codepath + if _has_cpp_library: + assert not isinstance(mask, SparseCS) + + att = a @ b + if mask.dtype == torch.bool: + assert not isinstance(mask, SparseCS) + if mask.ndim == 2: + mask = mask.unsqueeze(0).expand(att.shape[0], -1, -1) + # mask is presumed false == ignore + att[~mask] = float("-inf") + else: + # mask is presumed additive + # repeat if batch sizes don't match + if ( + not isinstance(mask, SparseCS) + and mask.ndim == 3 + and mask.shape[0] != att.shape[0] + and (att.shape[0] % mask.shape[0]) == 0 + ): + repeat_factor = att.shape[0] // mask.shape[0] + mask = mask.repeat([repeat_factor, 1, 1]) + logger.info("Mismatched batch dimensions for mask, repeating mask.") + att += mask # type: ignore + return att + + +def _softmax(a: torch.Tensor, causal: bool = False) -> torch.Tensor: + if _has_cpp_library and isinstance(a, SparseCS): + return a.softmax() + + if a.is_sparse: + return torch.sparse.softmax(a, dim=a.ndim - 1) + + return torch.softmax(a, dim=a.ndim - 1) + + +if _has_cpp_library: + + class SparseBMM(torch.autograd.Function): + @staticmethod + def forward(ctx, a, b): + a = a.coalesce() + r = torch.bmm(a, b) + ctx.save_for_backward(a, b) + return r + + @staticmethod + def backward(ctx, grad): + a, b = ctx.saved_tensors + + # gradients w.r.t. a + ga = None + if ctx.needs_input_grad[0]: + ga = torch.ops.xformers.matmul_with_mask(grad, b.transpose(-2, -1), a) + + # gradients w.r.t. b + gb = None + if ctx.needs_input_grad[1]: + gb = a.transpose(1, 2).bmm(grad) + + return ga, gb + + def _sparse_bmm(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + """ + Batch matrix multiply between a sparse matrix and a dense matrix + """ + assert a.ndim == b.ndim == 3 + assert a.shape[0] == b.shape[0] + assert a.shape[2] == b.shape[1] + return SparseBMM.apply(a, b) + + +def bmm(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + if _has_cpp_library: + if isinstance(a, SparseCS): + return a.spmm(b) + if a.is_sparse: + return _sparse_bmm(a, b) + return a @ b + + +def _apply_dropout(att, dropout): + if dropout is None: + return att + + # Dropout chokes on sparse tensors + if _has_cpp_library: + if isinstance(att, SparseCS): + values = att.values.clone() + values = dropout(values) + att = SparseCS.wrap( + att.shape, + values, + att.row_indices, + att.row_offsets, + att.column_indices, + att._transp_info, + ) + elif att.is_sparse: + att = att.coalesce() + values = att.values().clone() # protect against in-place dropout + values = dropout(values) + att = torch.sparse_coo_tensor(att.indices(), values, att.shape) + else: + # Simple dense case + att = dropout(att) + + return att + + # Non optimized vanilla dropout + att = dropout(att) + return att + + +def scaled_query_key_softmax( + q: torch.Tensor, + k: torch.Tensor, + att_mask: Optional[Union[AttentionMask, "SparseCS", torch.Tensor]], +) -> torch.Tensor: + # TODO assume we have (N, S, hs) instead of (B, nh, S, hs), with N = B x nh + # this is needed due to limitations in sparse_bmm for now + + # Self-attend: (N, S, hs) x (N, hs, S) -> (N, S, S) + q = q / math.sqrt(k.size(-1)) + + # Matmul with mask + if att_mask is not None and isinstance(att_mask, AttentionMask): + # Additive mask + mask: Optional[Union[SparseCS, torch.Tensor]] = att_mask.values + else: + mask = att_mask + + att = _matmul_with_mask(q, k.transpose(-2, -1), mask) + + # Softmax to get the attention probabilities + is_causal = isinstance(att_mask, AttentionMask) and att_mask.is_causal + att = _softmax(att, causal=is_causal) + return att + + +def scaled_dot_product_attention( + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + att_mask: Optional[Union[AttentionMask, "SparseCS", torch.Tensor]], + dropout: Optional[torch.nn.Module] = None, +) -> torch.Tensor: + autocast_disabled = ( + _has_cpp_library + and isinstance(att_mask, SparseCS) + or (att_mask is not None and att_mask.is_sparse) + ) + with torch.amp.autocast("cuda", enabled=False) if autocast_disabled else nullcontext(): # type: ignore + if autocast_disabled: + q, k, v = q.float(), k.float(), v.float() + + att = scaled_query_key_softmax(q, k, att_mask=att_mask) + + # Optional dropout, could be part of the masking in the future + att = _apply_dropout(att, dropout) + + # Get to the predicted values, for all heads + # y = att @ v # (N, S, S) x (N, S, hs) -> (N, S, hs) + y = bmm(att, v) + return y diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/fourier_mix.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/fourier_mix.py new file mode 100644 index 0000000000000000000000000000000000000000..ad32591f2b794c48ee7a0908685b309bf6cc977d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/fourier_mix.py @@ -0,0 +1,35 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch.amp import autocast + +from xformers.components.attention import Attention, AttentionConfig, register_attention + + +@register_attention("fourier_mix", AttentionConfig) +class FourierMix(Attention): + def __init__(self, dropout: float, *_, **__): + """ + FFT-based pseudo-attention mechanism, from + " + "FNet: Mixing Tokens with Fourier Transforms" + Lee-Thorp et al., 2021, https://arxiv.org/pdf/2105.03824.pdf + """ + super().__init__() + self.attn_drop = torch.nn.Dropout(dropout, inplace=False) + + # Properties specific to this attention mechanism + self.supports_attention_mask = False + self.requires_input_projection = False + + def forward(self, q: torch.Tensor, *_, **__): + # Guard against autocast / fp16, not supported by torch.fft.fft2 + with autocast("cuda", enabled=False): + att = torch.fft.fft2(q).real + + att = self.attn_drop(att) + + return att diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/scaled_dot_product.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/scaled_dot_product.py new file mode 100644 index 0000000000000000000000000000000000000000..16fd32ab7f236673846dc2fafad9643265c6986d --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/scaled_dot_product.py @@ -0,0 +1,134 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import logging +from dataclasses import dataclass +from typing import Optional, Union + +import torch +from torch import nn + +from xformers.components.attention import ( + Attention, + AttentionConfig, + AttentionMask, + register_attention, +) +from xformers.components.attention.core import scaled_dot_product_attention + +logger = logging.getLogger("xformers") + + +@dataclass +class ScaledDotProductConfig(AttentionConfig): + causal: Optional[bool] + seq_len: Optional[int] + to_seq_len: Optional[int] + + +@register_attention("scaled_dot_product", ScaledDotProductConfig) +class ScaledDotProduct(Attention): + r""" + Implementing the Scaled Dot-Product attention proposed in + `Attention is all you need`_, Vaswani et al. + + .. _`Attention is all you need`: https://arxiv.org/abs/1706.03762v5 + """ + + mask: Optional[AttentionMask] + + def __init__( + self, + dropout: float = 0.0, + causal: bool = False, + seq_len: Optional[int] = None, + to_seq_len: Optional[int] = None, + *args, + **kwargs, + ): + super().__init__() + + self.attn_drop = nn.Dropout(dropout, inplace=False) + self.causal = causal + self.seq_len = seq_len + + if causal and seq_len is not None: + self.mask = AttentionMask.make_causal(seq_len, to_seq_len) + else: + self.mask = None + + # Properties specific to this attention mechanism + self.supports_attention_mask = True + self.supports_key_padding_mask = False + + def forward( + self, + q: torch.Tensor, + k: torch.Tensor, + v: torch.Tensor, + att_mask: Optional[Union[AttentionMask, torch.Tensor]] = None, + *args, + **kwargs, + ) -> torch.Tensor: + r""" + att_mask A 2D or 3D mask which ignores attention at certain positions. + + - If the mask is boolean, a value of True will keep the value, + while a value of False will mask the value. + + Key padding masks (dimension: batch x sequence length) and attention masks + (dimension: sequence length x sequence length OR batch x sequence length x sequence length) + can be combined and passed in here. Method maybe_merge_masks provided in the utils can be + used for that merging. + + - If the mask has the float type, then an additive mask is expected (masked values are -inf) + + """ + + # Convenience, create an attention mask if a tensor was passed + if att_mask is not None and isinstance(att_mask, torch.Tensor): + # By default we don't know of the causality, and a check would be expensive + att_mask = ( + AttentionMask.from_bool(att_mask) + if att_mask.dtype == torch.bool + else AttentionMask(att_mask, is_causal=False) + ) + + # Handle a possibly deferred causal mask handling + mask = self.mask + if self.causal and self.mask is None: + mask = AttentionMask.make_causal( + seq_len=q.shape[-2], + to_seq_len=q.shape[-2], + device=q.device, + dtype=q.dtype, + ) + + # Merge the optional causal mask and the user-provided mask + if mask is not None: + mask = mask.to(dtype=q.dtype, device=q.device) + + att_mask = att_mask + mask if att_mask is not None else mask + + # Try to handle a case where the sequence is smaller than the mask + if ( + att_mask is not None + and q.shape[-2] == k.shape[-2] + and q.shape[-2] < att_mask.shape[1] + ): + if isinstance(att_mask, AttentionMask): + att_mask = att_mask.make_crop(seq_len=q.shape[-2]) + else: + logger.error( + "Mismatching sparse attention mask and sequence length." + + " Please pad the inputs or adjust the attention mask" + ) + raise NotImplementedError + + # Attend: (B x nh, S, hs) x (B x nh, hs, S) -> (B x nh, S, S) + y = scaled_dot_product_attention( + q=q, k=k, v=v, att_mask=att_mask, dropout=self.attn_drop + ) + return y diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/sparsity_config.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/sparsity_config.py new file mode 100644 index 0000000000000000000000000000000000000000..727a7ff70a4fbcd1f70206719f6c14bd15b84c06 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/sparsity_config.py @@ -0,0 +1,812 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. +""" +The code has been adopted from DeepSpeed +(https://github.com/microsoft/DeepSpeed/blob/master/deepspeed/ops/sparse_attention/sparsity_config.py) +""" + +import random + +import torch + + +class SparsityConfig: + """Abstract Configuration class to store `sparsity configuration of a self attention layer`. + It contains shared property of different block-sparse sparsity patterns. However, each class + needs to extend it based on required property and functionality. + """ + + def __init__(self, num_heads, block_size=16, different_layout_per_head=False): + """Initialize the Sparsity Pattern Config. + Arguments: + num_heads: required: an integer determining number of attention heads of the layer. + block_size: optional: an integer determining the block size. Current implementation of + sparse self-attention is based on blocked sparse matrices. In which this parameter + defines size of such blocks, `Block X Block`. + different_layout_per_head: optional: a boolean determining if each head should be + assigned a different sparsity layout; default is false and this will be satisfied + based on availability. + """ + + self.num_heads = num_heads + self.block_size = block_size + self.different_layout_per_head = different_layout_per_head + self.num_layout_heads = num_heads if different_layout_per_head else 1 + + def setup_layout(self, seq_len): + """Create layout tensor for the given sequence length + Arguments: + seq_len: required: an integer determining number of attention heads of the layer. + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) for sparsity layout + of all head; initialized with zero + """ + + if seq_len % self.block_size != 0: + raise ValueError( + f"Sequence Length, {seq_len}, needs to be dividable by Block size {self.block_size}!" + ) + num_blocks = seq_len // self.block_size + # TODO Currently we allocate layout per head; needs to be updated if heads share a single layout. + layout = torch.zeros( + (self.num_heads, num_blocks, num_blocks), dtype=torch.int64 + ) + return layout + + def check_and_propagate_first_head_layout(self, layout): + """If all heads require same sparsity layout, it propagate first head layout to all heads + Arguments: + layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing + sparsity layout of all head; may not be completely set at this step + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity + layout of all head + """ + + if not self.different_layout_per_head: + layout[1 : self.num_heads, :, :] = layout[0, :, :] + return layout + + +class DenseSparsityConfig(SparsityConfig): + """Configuration class to store `Dense` configuration. + In reality, this is not sparse and all blocks are used. We keep it for the sake of comparison and + comprehension. + """ + + def __init__(self, num_heads, block_size=16, different_layout_per_head=False): + """Initialize the Dense Sparsity Pattern Config. + In reality, this is not sparse and all blocks are used. We keep it for the sake of comparison + and comprehension. + Arguments: + num_heads: required: an integer determining number of attention heads of the layer. + block_size: optional: an integer determining the block size. Current implementation of + sparse self-attention is based on blocked sparse matrices. In which this parameter + defines size of such blocks, `Block X Block`. + different_layout_per_head: optional: this is just for the sake of consistency with + other sparsity formats; can ignore it for DenseSparsityConfig + """ + + super().__init__(num_heads, block_size, different_layout_per_head) + + def make_layout(self, seq_len): + """Set 1 to all blocks of the layout meanins the pattern is dense; not sparse. + Arguments: + seq_len: required: an integer determining the underling sequence length; + must be <= max sequence length + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity + layout of all head; for dense everything is 1 + """ + + layout = self.setup_layout(seq_len) + layout[:, :, :] = 1 + return layout + + +class FixedSparsityConfig(SparsityConfig): + """Configuration class to store `Fixed` sparsity configuration. + For more details about this sparsity config, please see `Generative Modeling with + Sparse Transformers`: https://arxiv.org/abs/1904.10509; this has been customized. + This class extends parent class of `SparsityConfig` and customizes it for `Fixed` sparsity. + """ + + def __init__( + self, + num_heads, + block_size=16, + different_layout_per_head=False, + num_local_blocks=4, + num_global_blocks=1, + attention="bidirectional", + horizontal_global_attention=False, + num_different_global_patterns=1, + ): + """Initialize `Fixed` Sparsity Pattern Config. + For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial + Arguments: + num_heads: required: an integer determining number of attention heads of the layer. + block_size: optional: an integer determining the block size. Current implementation of + sparse self-attention is based on blocked sparse matrices. In which this parameter + defines size of such blocks, `Block X Block`. + different_layout_per_head: optional: a boolean determining if each head should be + assigned a different sparsity layout; default is false and this will be satisfied + based on availability. + num_local_blocks: optional: an integer determining the number of blocks in local attention + window. + num_global_blocks: optional: an integer determining how many consecutive blocks in a local + window is used as the representative of the window for global attention. + attention: optional: a string determining attention type. Attention can be `unidirectional`, + such as autoregressive models, in which tokens attend only to tokens appear before them + in the context. Considering that, the upper triangular of attention matrix is empty as + above figure. Or it can be `bidirectional`, such as BERT, in which tokens can attend to + any other tokens before or after them. Then, the upper triangular part of the attention + matrix is mirror of the lower triangular in the above figure. + horizontal_global_attention: optional: a boolean determining if blocks that are global + representative of a local window, also attend to all other blocks. This is valid only if + attention type is `bidirectional`. Looking at the attention matrix, that means global + attention not only includes the vertical blocks, but also horizontal blocks. + num_different_global_patterns: optional: an integer determining number of different global + attentions layouts. While global attention can be fixed by which block/s are representative + of any local window, since there are multi-heads, each head can use a different global representative. + For example, with 4 blocks local window and global attention size of 1 block, we can have 4 different + versions in which the first, Second, third, or forth block of each local window can be global + representative of that window. This parameter determines how many of such patterns we want. + Of course, there is a limitation based on num_local_blocks and num_global_blocks. + """ + + super().__init__(num_heads, block_size, different_layout_per_head) + + self.num_local_blocks = num_local_blocks + + if num_local_blocks % num_global_blocks != 0: + raise ValueError( + f"""Number of blocks in a local window, {num_local_blocks}, + must be dividable by number of global blocks, {num_global_blocks}!""" + ) + self.num_global_blocks = num_global_blocks + + if attention != "unidirectional" and attention != "bidirectional": + raise NotImplementedError( + 'only "uni/bi-directional" attentions are supported for now!' + ) + self.attention = attention + + if attention != "bidirectional" and horizontal_global_attention: + raise ValueError( + 'only "bi-directional" attentions can support horizontal global attention!' + ) + self.horizontal_global_attention = horizontal_global_attention + + if num_different_global_patterns > 1 and not different_layout_per_head: + raise ValueError( + """Number of different layouts cannot be more than one when you have set a single layout + for all heads! Set different_layout_per_head to True.""" + ) + if num_different_global_patterns > (num_local_blocks // num_global_blocks): + raise ValueError( + f"""Number of layout versions (num_different_global_patterns), {num_different_global_patterns}, + cannot be larger than number of local window blocks divided by number of global blocks, + {num_local_blocks} / {num_global_blocks} = {num_local_blocks//num_global_blocks}!""" + ) + self.num_different_global_patterns = num_different_global_patterns + + def set_local_layout(self, h, layout): + """Sets local attention layout used by the given head in the sparse attention. + Arguments: + h: required: an integer determining head index + layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing + sparsity layout of all head; may not be completely set at this step + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity + layout of all head in which local layout is set + """ + + num_blocks = layout.shape[1] + for i in range(0, num_blocks, self.num_local_blocks): + end = min(i + self.num_local_blocks, num_blocks) + for row in range(i, end): + for col in range( + i, (row + 1 if self.attention == "unidirectional" else end) + ): + layout[h, row, col] = 1 + return layout + + def set_global_layout(self, h, layout): + """Sets global attention layout used by the given head in the sparse attention. + Currently we set global blocks starting from the last block of a local window to the first one. + That means if a local window consists of 4 blocks and global attention size is one block, we use + block #4 in each local window as global. If we have different layout per head, then other heads + will get #3, #2, and #1. And if we have more heads (and different layout has set) than num of global + attentions, multiple head may have same global attentions. + Note) if horizontal_global_attention is set, global blocks will be set both horizontally and + vertically. + Arguments: + h: required: an integer determining head index + layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing + sparsity layout of all head; may not be completely set at this step + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity + layout of all head in which global layout is set + """ + + num_blocks = layout.shape[1] + first_global_block_idx = ( + self.num_local_blocks + - (1 + h % self.num_different_global_patterns) * self.num_global_blocks + ) + + # set all global blocks except the last one if (in last local window) + end = num_blocks - (num_blocks % self.num_local_blocks) + for i in range(first_global_block_idx, end, self.num_local_blocks): + + # vertical global attention + first_row = 0 if self.attention == "bidirectional" else i + # (((i // self.num_local_blocks) + 1) * self.num_local_blocks) + # if (first_row < num_blocks): + layout[h, first_row:, i : i + self.num_global_blocks] = 1 + + # horizontal global attention; only in bidirectional attention + if self.horizontal_global_attention: + layout[h, i : i + self.num_global_blocks, :] = 1 + + # set last global blocks; handle possible short last local window + if end < num_blocks: + start = min( + end + first_global_block_idx, num_blocks - self.num_global_blocks + ) + end = start + self.num_global_blocks + + # vertical global attention + first_row = 0 if self.attention == "bidirectional" else start + # (((start // self.num_local_blocks) + 1) * self.num_local_blocks) + # if (first_row < num_blocks): + layout[h, first_row:, start:end] = 1 + + # horizontal global attention + if self.horizontal_global_attention: + layout[h, start:end, :] = 1 + return layout + + def make_layout(self, seq_len): + """Generates `Fixed` sparsity layout used by each head in the sparse attention. + Arguments: + seq_len: required: an integer determining number of attention heads of the layer. + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing `Fixed` + sparsity layout of all head + """ + + layout = self.setup_layout(seq_len) + for h in range(0, self.num_layout_heads): + layout = self.set_local_layout(h, layout) + layout = self.set_global_layout(h, layout) + + layout = self.check_and_propagate_first_head_layout(layout) + return layout + + +class VariableSparsityConfig(SparsityConfig): + """Configuration class to store `Variable` sparsity configuration. + This layout is an extension of FixedSparsityConfig in which: + - user can set random layout; default value is zero means no random block + - user can provide a list of local block sizes + - user can provide a list of global block indices. + For more details about `Fixed` sparsity config, please see `Generative Modeling with + Sparse Transformers`: https://arxiv.org/abs/1904.10509; this has been customized. + This class extends parent class of `SparsityConfig` and customizes it for `Fixed` sparsity. + """ + + def __init__( + self, + num_heads, + block_size=16, + different_layout_per_head=False, + num_random_blocks=0, + local_window_blocks=[4], + global_block_indices=[0], + global_block_end_indices=None, + attention="bidirectional", + horizontal_global_attention=False, + ): + """Initialize `Variable` Sparsity Pattern Config. + For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial + Arguments: + num_heads: required: an integer determining number of attention heads of the layer. + block_size: optional: an integer determining the block size. Current implementation of sparse + self-attention is based on blocked sparse matrices. In which this parameter defines + size of such blocks, `Block X Block`. + different_layout_per_head: optional: a boolean determining if each head should be assigned a + different sparsity layout; default is false and this will be satisfied based on + availability. Currently this sparsity config can only assign single layout to all heads; + needs to be extended for different layout per head. + num_random_blocks: optional: an integer determining the number of random blocks in each block row. + local_window_blocks: optional: a list of integers determining the number of blocks in each + local attention window. It assumes first number determines # of blocks in the first local + window, second the second window, ..., and the last number determines the number of blocks + in the remaining local windows. + global_block_indices: optional: a list of integers determining which blocks are considered + as global attention. Given indices, determine the blocks that all other token blocks + attend to and they attend to all other token blocks. Default value is only index 0. + Notice that if global_block_end_indices parameter is set, this parameter is used as + starting index of each global window. + global_block_end_indices: optional: a list of integers determining end indices of global + window blocks. By default this is not used. But if it is set, it must have the same size + of global_block_indices parameter, and combining this two parameters, for each index i, + blocks from global_block_indices[i] to global_block_end_indices[i] (exclusive) are + considered as global attention. + attention: optional: a string determining attention type. Attention can be `unidirectional`, + such as autoregressive models, in which tokens attend only to tokens appear before them + in the context. Considering that, the upper triangular of attention matrix is empty as + above figure. Or it can be `bidirectional`, such as BERT, in which tokens can attend to + any other tokens before or after them. Then, the upper triangular part of the attention + matrix is mirror of the lower triangular in the above figure. + horizontal_global_attention: optional: a boolean determining if blocks that are global + representative of a local window, also attend to all other blocks. This is valid only if + attention type is `bidirectional`. Looking at the attention matrix, that means global + attention not only includes the vertical blocks, but also horizontal blocks. + """ + + super().__init__(num_heads, block_size, different_layout_per_head) + + self.num_random_blocks = num_random_blocks + self.local_window_blocks = local_window_blocks + self.global_block_indices = global_block_indices + + if global_block_end_indices is not None: + if len(global_block_indices) != len(global_block_end_indices): + raise ValueError( + f"""Global block start indices length, {len(global_block_indices)}, must be same as + global block end indices length, {len(global_block_end_indices)}!""" + ) + for _, (start_idx, end_idx) in enumerate( + zip(global_block_indices, global_block_end_indices) + ): + if start_idx >= end_idx: + raise ValueError( + f"""Global block start index, {start_idx}, must be smaller than global block end + index, {end_idx}!""" + ) + self.global_block_end_indices = global_block_end_indices + + if attention != "unidirectional" and attention != "bidirectional": + raise NotImplementedError( + 'only "uni/bi-directional" attentions are supported for now!' + ) + self.attention = attention + + if attention != "bidirectional" and horizontal_global_attention: + raise ValueError( + 'only "bi-directional" attentions can support horizontal global attention!' + ) + self.horizontal_global_attention = horizontal_global_attention + + def set_random_layout(self, h, layout): + """Sets random attention layout used by the given head in the sparse attention. + Note) By default, it assumes there will be a unique random block layout for all heads; unless + `different_layout_per_head` parameter is set in which each head can have a different random + layout. + Arguments: + h: required: an integer determining head index + layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing + sparsity layout of all head; may not be completely set at this step + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity + layout of all head in which random layout is set + """ + + num_blocks = layout.shape[1] + if num_blocks < self.num_random_blocks: + raise ValueError( + f"""Number of random blocks, {self.num_random_blocks}, must be smaller than overall number + of blocks in a row, {num_blocks}!""" + ) + for row in range(0, num_blocks): + rnd_cols = random.sample(range(0, num_blocks), self.num_random_blocks) + layout[h, row, rnd_cols] = 1 + return layout + + def set_local_layout(self, h, layout): + """Sets local attention layout used by the given head in the sparse attention. + Arguments: + h: required: an integer determining head index + layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing + sparsity layout of all head; may not be completely set at this step + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity + layout of all head in which local layout is set + """ + + num_blocks = layout.shape[1] + start_block_idx = 0 + end_block_idx = 0 + for block_size in self.local_window_blocks: + end_block_idx += block_size + end_block_idx = min(end_block_idx, num_blocks) + for row in range(start_block_idx, end_block_idx): + for col in range( + start_block_idx, + (row + 1 if self.attention == "unidirectional" else end_block_idx), + ): + layout[h, row, col] = 1 + start_block_idx += block_size + + # if there is any remaining not attended part, use the lats local window block size as local + # window for the remaining applicable local windows + for i in range(start_block_idx, num_blocks, block_size): + end_block_idx = min(i + block_size, num_blocks) + for row in range(i, end_block_idx): + for col in range( + i, + (row + 1 if self.attention == "unidirectional" else end_block_idx), + ): + layout[h, row, col] = 1 + return layout + + def set_global_layout(self, h, layout): + """Sets global attention layout used by the given head in the sparse attention. + Arguments: + h: required: an integer determining head index + layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing + sparsity layout of all head; may not be completely set at this step + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity + layout of all head in which global layout is set + """ + + num_blocks = layout.shape[1] + if self.global_block_end_indices is None: + for idx in self.global_block_indices: + # if global block idx is in the range of the sequence blocks + if idx < num_blocks: + # global rows + if self.horizontal_global_attention: + layout[h, idx, :] = 1 + + # global columns + first_row = 0 if self.attention == "bidirectional" else idx + layout[h, first_row:, idx] = 1 + else: + for _, (start_idx, end_idx) in enumerate( + zip(self.global_block_indices, self.global_block_end_indices) + ): + # if global block idx is in the range of the sequence blocks + if start_idx < num_blocks: + end_idx = min(end_idx, num_blocks) + # global rows + if self.horizontal_global_attention: + layout[h, start_idx:end_idx, :] = 1 + + # global columns + first_row = 0 if self.attention == "bidirectional" else start_idx + layout[h, first_row:, start_idx:end_idx] = 1 + return layout + + def make_layout(self, seq_len): + """Generates `Variable` sparsity layout used by each head in the sparse attention. + Arguments: + seq_len: required: an integer determining number of attention heads of the layer. + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing `Variable` + sparsity layout of all head + """ + + layout = self.setup_layout(seq_len) + for h in range(0, self.num_layout_heads): + layout = self.set_random_layout(h, layout) + layout = self.set_local_layout(h, layout) + layout = self.set_global_layout(h, layout) + + layout = self.check_and_propagate_first_head_layout(layout) + return layout + + +class BigBirdSparsityConfig(SparsityConfig): + """Configuration class to store `BigBird` sparsity configuration. + For more details about this sparsity config, please see `Big Bird: Transformers for + Longer Sequences`: https://arxiv.org/pdf/2007.14062.pdf + This class extends parent class of `SparsityConfig` and customizes it for `BigBird` sparsity. + """ + + def __init__( + self, + num_heads, + block_size=16, + different_layout_per_head=False, + num_random_blocks=1, + num_sliding_window_blocks=3, + num_global_blocks=1, + attention="bidirectional", + ): + """Initialize the BigBird Sparsity Pattern Config. + For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial + Arguments: + num_heads: required: an integer determining number of attention heads of the layer. + block_size: optional: an integer determining the block size. Current implementation of + sparse self-attention is based on blocked sparse matrices. In which this parameter + defines size of such blocks, `Block X Block`. + different_layout_per_head: optional: a boolean determining if each head should be assigned + a different sparsity layout; default is false and this will be satisfied based on + availability. + num_random_blocks: optional: an integer determining the number of random blocks in each + block row. + num_sliding_window_blocks: optional: an integer determining the number of blocks in sliding + local attention window. + num_global_blocks: optional: an integer determining how many consecutive blocks, starting + from index 0, are considered as global attention. Global block tokens will be attended + by all other block tokens and will attend to all other block tokens as well. + attention: optional: a string determining attention type. Attention can be `unidirectional`, + such as autoregressive models, in which tokens attend only to tokens appear before them + in the context. Considering that, the upper triangular of attention matrix is empty as + above figure. Or it can be `bidirectional`, such as BERT, in which tokens can attend to + any other tokens before or after them. Then, the upper triangular part of the attention + matrix is mirror of the lower triangular in the above figure. + """ + + super().__init__(num_heads, block_size, different_layout_per_head) + + self.num_random_blocks = num_random_blocks + self.num_sliding_window_blocks = num_sliding_window_blocks + self.num_global_blocks = num_global_blocks + + if attention != "unidirectional" and attention != "bidirectional": + raise NotImplementedError( + 'only "uni/bi-directional" attentions are supported for now!' + ) + self.attention = attention + + def set_random_layout(self, h, layout): + """Sets random attention layout used by the given head in the sparse attention. + Note) By default, it assumes there will be a unique random block layout for all heads; unless + `different_layout_per_head` parameter is set in which each head can have a different random layout. + Arguments: + h: required: an integer determining head index + layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing + sparsity layout of all head; may not be completely set at this step + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity + layout of all head in which random layout is set + """ + + num_blocks = layout.shape[1] + if num_blocks < self.num_random_blocks: + raise ValueError( + f"""Number of random blocks, {self.num_random_blocks}, must be smaller than overall number + of blocks in a row, {num_blocks}!""" + ) + + for row in range(0, num_blocks): + sample_range = ( + range(0, num_blocks) + if self.attention == "bidirectional" + else range(0, row + 1) + ) + rnd_cols = random.sample(sample_range, self.num_random_blocks) + layout[h, row, rnd_cols] = 1 + return layout + + def set_sliding_window_layout(self, h, layout): + """Sets sliding local attention layout used by the given head in the sparse attention. + Arguments: + h: required: an integer determining head index + layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing + sparsity layout of all head; may not be completely set at this step + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity + layout of all head in which local sliding window layout is set + """ + + num_blocks = layout.shape[1] + if num_blocks < self.num_sliding_window_blocks: + raise ValueError( + f"""Number of sliding window blocks, {self.num_sliding_window_blocks}, must be smaller than + overall number of blocks in a row, {num_blocks}!""" + ) + + w = self.num_sliding_window_blocks // 2 + for row in range(0, num_blocks): + start = max(0, row - w) + end = min(row + w + 1, num_blocks) + layout[h, row, start:end] = 1 + return layout + + def set_global_layout_itc(self, h, layout): + """Sets global attention layout used by the given head in the sparse attention. + Arguments: + h: required: an integer determining head index + layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing + sparsity layout of all head; may not be completely set at this step + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout + of all head in which global layout is set + """ + + num_blocks = layout.shape[1] + if num_blocks < self.num_global_blocks: + raise ValueError( + f"""Number of global blocks, {self.num_global_blocks}, must be smaller than overall number + of blocks in a row, {num_blocks}!""" + ) + + # global rows + layout[h, 0 : self.num_global_blocks, :] = 1 + + # global columns + layout[h, :, 0 : self.num_global_blocks] = 1 + + if self.attention == "unidirectional": + # zero out anything attending to the future + layout = torch.tril(layout) + + return layout + + def make_layout(self, seq_len): + """Generates `BigBird` sparsity layout used by each head in the sparse attention. + Arguments: + seq_len: required: an integer determining number of attention heads of the layer. + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing `BigBird` + sparsity layout of all head + """ + + layout = self.setup_layout(seq_len) + for h in range(0, self.num_layout_heads): + layout = self.set_random_layout(h, layout) + layout = self.set_sliding_window_layout(h, layout) + layout = self.set_global_layout_itc(h, layout) + + layout = self.check_and_propagate_first_head_layout(layout) + return layout + + +class BSLongformerSparsityConfig(SparsityConfig): + """Configuration class to store edited `Longformer` sparsity configuration. + Note) this is a block-sparse version of the Longformer which is slightly different than original + Longformer; which is element-wise sparsity. + For more details about this sparsity config, please see `Longformer: + The Long-Document Transformer`: https://arxiv.org/pdf/2004.05150.pdf + This class extends parent class of `SparsityConfig` and customizes it for `Longformer` sparsity. + """ + + def __init__( + self, + num_heads, + block_size=16, + different_layout_per_head=False, + num_sliding_window_blocks=3, + global_block_indices=[0], + global_block_end_indices=None, + attention="bidirectional", + ): + """Initialize the edited `Longformer` Sparsity Pattern Config. + For usage example please see, TODO DeepSpeed Sparse Transformer Tutorial + Arguments: + num_heads: required: an integer determining number of attention heads of the layer. + block_size: optional: an integer determining the block size. Current implementation of sparse + self-attention is based on blocked sparse matrices. In which this parameter defines size + of such blocks, `Block X Block`. + different_layout_per_head: optional: a boolean determining if each head should be assigned a + different sparsity layout; default is false and this will be satisfied based on + availability. + num_sliding_window_blocks: optional: an integer determining the number of blocks in sliding + local attention window. + global_block_indices: optional: a list of integers determining which blocks are considered + as global attention. Given indices, determine the blocks that all other token blocks + attend to and they attend to all other token blocks. Default value is only index 0. + Notice that if global_block_end_indices parameter is set, this parameter is used as + starting index of each global window. + global_block_end_indices: optional: a list of integers determining end indices of global + window blocks. By default this is not used. But if it is set, it must have the same size + of global_block_indices parameter, and combining this two parameters, for each index i, + blocks from global_block_indices[i] to global_block_end_indices[i] (exclusive) are + considered as global attention. + attention: optional: a string determining attention type. Attention can be `unidirectional`, + such as autoregressive models, in which tokens attend only to tokens appear before them + in the context. Considering that, the upper triangular of attention matrix is empty as + above figure. Or it can be `bidirectional`, such as BERT, in which tokens can attend to + any other tokens before or after them. Then, the upper triangular part of the attention + matrix is mirror of the lower triangular in the above figure. + """ + + super().__init__(num_heads, block_size, different_layout_per_head) + + self.num_sliding_window_blocks = num_sliding_window_blocks + self.global_block_indices = global_block_indices + self.attention = attention + + if global_block_end_indices is not None: + if len(global_block_indices) != len(global_block_end_indices): + raise ValueError( + f"""Global block start indices length, {len(global_block_indices)}, must be same as + global block end indices length, {len(global_block_end_indices)}!""" + ) + for _, (start_idx, end_idx) in enumerate( + zip(global_block_indices, global_block_end_indices) + ): + if start_idx >= end_idx: + raise ValueError( + f"""Global block start index, {start_idx}, must be smaller than global block end + index, {end_idx}!""" + ) + self.global_block_end_indices = global_block_end_indices + + def set_sliding_window_layout(self, h, layout): + """Sets sliding local attention layout used by the given head in the sparse attention. + Arguments: + h: required: an integer determining head index + layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing + sparsity layout of all head; may not be completely set at this step + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity layout + of all head in which local sliding window layout is set + """ + + num_blocks = layout.shape[1] + if num_blocks < self.num_sliding_window_blocks: + raise ValueError( + f"""Number of sliding window blocks, {self.num_sliding_window_blocks}, must be smaller + than overall number of blocks in a row, {num_blocks}!""" + ) + + w = self.num_sliding_window_blocks // 2 + for row in range(0, num_blocks): + start = max(0, row - w) + end = min(row + w + 1, num_blocks) + layout[h, row, start:end] = 1 + return layout + + def set_global_layout(self, h, layout): + """Sets global attention layout used by the given head in the sparse attention. + Arguments: + h: required: an integer determining head index + layout: required: a tensor of dimension (num_heads, num_blocks, num_blocks) containing + sparsity layout of all head; may not be completely set at this step + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing sparsity + layout of all head in which global layout is set + """ + + num_blocks = layout.shape[1] + if self.global_block_end_indices is None: + for idx in self.global_block_indices: + # if global block idx is in the range of the sequence blocks + if idx < num_blocks: + # global rows + layout[h, idx, :] = 1 + + # global columns + layout[h, :, idx] = 1 + else: + for _, (start_idx, end_idx) in enumerate( + zip(self.global_block_indices, self.global_block_end_indices) + ): + # if global block idx is in the range of the sequence blocks + if start_idx < num_blocks: + end_idx = min(end_idx, num_blocks) + # global rows + layout[h, start_idx:end_idx, :] = 1 + + # global columns + layout[h, :, start_idx:end_idx] = 1 + if self.attention == "unidirectional": + layout = torch.tril(layout) + return layout + + def make_layout(self, seq_len): + """Generates edited `Longformer` sparsity layout used by each head in the sparse attention. + Arguments: + seq_len: required: an integer determining number of attention heads of the layer. + Return: + layout: a tensor of dimension (num_heads, num_blocks, num_blocks) containing `BSLongformer` + sparsity layout of all head + """ + + layout = self.setup_layout(seq_len) + for h in range(0, self.num_layout_heads): + layout = self.set_sliding_window_layout(h, layout) + layout = self.set_global_layout(h, layout) + + layout = self.check_and_propagate_first_head_layout(layout) + return layout diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/utils.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d6bb06a1acf4f1884442e6dd5a6c238e0a6f641e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/attention/utils.py @@ -0,0 +1,108 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +from typing import Optional + +import torch + + +# Reshapes key padding mask from (batch_size, src_len) -> (batch_size * num_heads 1, src_len) +def reshape_key_padding_mask( + key_padding_mask: torch.Tensor, batched_dim: int +) -> torch.Tensor: + assert key_padding_mask.ndim == 2 + batch_size, src_len = key_padding_mask.size() + num_heads = batched_dim // batch_size + return _reshape_key_padding_mask(key_padding_mask, batch_size, src_len, num_heads) + + +def _reshape_key_padding_mask( + key_padding_mask: torch.Tensor, batch_size: int, src_len: int, num_heads: int +) -> torch.Tensor: + assert key_padding_mask.shape == (batch_size, src_len) + key_padding_mask = ( + key_padding_mask.view(batch_size, 1, 1, src_len) + .expand(-1, num_heads, -1, -1) + .reshape(batch_size * num_heads, 1, src_len) + ) + return key_padding_mask + + +# Combine the attention mask and key padding mask into a single mask +# Taken from https://github.com/pytorch/pytorch/blob/master/torch/nn/functional.py +# Additive masking not yet supported +def maybe_merge_masks( + att_mask: Optional[torch.Tensor], + key_padding_mask: Optional[torch.Tensor], + batch_size: int, + src_len: int, + num_heads: int, + tgt_len: Optional[int] = None, +) -> Optional[torch.Tensor]: + if tgt_len is None: + tgt_len = src_len + if key_padding_mask is not None: + assert key_padding_mask.shape == (batch_size, src_len) + key_padding_mask = _reshape_key_padding_mask( + key_padding_mask, batch_size, src_len, num_heads + ) + if att_mask is None: + # make sure dimensions of key padding mask are the same as those expected for att_mask + att_mask = key_padding_mask.expand(-1, tgt_len, -1) + # Assumption is that False means to mask. + elif att_mask.dtype == torch.bool: + att_mask = att_mask.logical_and(key_padding_mask) + else: + att_mask = att_mask.masked_fill(~key_padding_mask, float("-inf")) + + return att_mask + + +# Assumes that matrix passed in has had softmax applied to it. +def iterative_pinv(softmax_mat: torch.Tensor, n_iter=6, pinverse_original_init=False): + """ + Computing the Moore-Penrose inverse. + Use an iterative method from (Razavi et al. 2014) to approximate the Moore-Penrose inverse via efficient + matrix-matrix multiplications. + """ + + i = torch.eye( + softmax_mat.size(-1), device=softmax_mat.device, dtype=softmax_mat.dtype + ) + k = softmax_mat + + # The entries of K are positive and ||K||_{\infty} = 1 due to softmax + if pinverse_original_init: + # This original implementation is more conservative to compute coefficient of Z_0. + v = 1 / torch.max(torch.sum(k, dim=-2)) * k.transpose(-1, -2) + else: + # This is the exact coefficient computation, 1 / ||K||_1, of initialization of Z_0, leading to faster + # convergence. + v = ( + 1 + / torch.max(torch.sum(k, dim=-2), dim=-1).values[:, None, None] + * k.transpose(-1, -2) + ) + + for _ in range(n_iter): + kv = torch.matmul(k, v) + v = torch.matmul( + 0.25 * v, + 13 * i - torch.matmul(kv, 15 * i - torch.matmul(kv, 7 * i - kv)), + ) + return v + + +def bool_mask_to_additive( + mask: torch.Tensor, dtype: Optional[torch.dtype] = torch.float32 +) -> torch.Tensor: + assert ( + mask.dtype == torch.bool + ), "This util is meant to convert in between bool masks and additive ones" + + mask_ = torch.zeros_like(mask, dtype=dtype) + mask_[~mask] = float("-inf") + return mask_ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/input_projection.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/input_projection.py new file mode 100644 index 0000000000000000000000000000000000000000..a77d1d4eaf16f7cd42cfdd579f5b1837ae6dc425 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/input_projection.py @@ -0,0 +1,102 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +# CREDITS: Inspired by https://github.com/pytorch/text/blob/master/torchtext/nn/modules/multiheadattention.py +# and the MultiHeadAttention implementation from PyTorch + + +import logging +from dataclasses import dataclass +from typing import Optional, Tuple + +import torch +from torch import nn + +from xformers._deprecation_warning import deprecated_function + +logger = logging.getLogger("xformers") + + +@dataclass +class InputProjectionConfig: + in_features: int + out_features: int + bias: bool + + +class InputProjection(nn.Module): + """ + Handle all the input projections in one go, opportunistically fuse some operations. + """ + + def __init__( + self, + query_proj_params: InputProjectionConfig, + key_proj_params: Optional[InputProjectionConfig], + value_proj_params: Optional[InputProjectionConfig], + use_separate_proj_weight: bool = True, + ): + + super().__init__() + deprecated_function(self) + + self.out_features = query_proj_params.out_features + + # Each input gets a separate projection + self.q_proj = nn.Linear( + query_proj_params.in_features, + query_proj_params.out_features, + query_proj_params.bias, + ) + + if key_proj_params is not None: + self.k_proj = nn.Linear( + key_proj_params.in_features, + key_proj_params.out_features, + key_proj_params.bias, + ) + else: + logger.info( + "No Key projection parameters were passed, assuming that the weights" + + " are shared with the query projection" + ) + self.k_proj = self.q_proj + + if value_proj_params is not None: + self.v_proj = nn.Linear( + value_proj_params.in_features, + value_proj_params.out_features, + value_proj_params.bias, + ) + else: + logger.info( + "No Value projection parameters were passed, assuming that the weights" + + " are shared with the query projection" + ) + self.v_proj = self.q_proj + + if not use_separate_proj_weight: + # Compute optimization used at times, share the parameters in between Q/K/V + with torch.no_grad(): + self.k_proj.weight = self.q_proj.weight + self.v_proj.weight = self.q_proj.weight + + def forward( + self, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + # One projection per input tensor + + # NOTE: Would it make sense to catch self attention + shared weights, to skip a projection step ? + + q, k, v = map( + lambda fn, x: fn(x), + [self.q_proj, self.k_proj, self.v_proj], + [query, key, value], + ) + + return q, k, v diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/components/residual.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/residual.py new file mode 100644 index 0000000000000000000000000000000000000000..ce635abfa157c0e5b776c2dc6f2569ea0485e57f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/components/residual.py @@ -0,0 +1,192 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +from collections import namedtuple +from enum import Enum +from typing import List, Optional, Tuple + +import torch +import torch.nn as nn + +from xformers._deprecation_warning import deprecated_function + + +class ResidualNormStyle(str, Enum): + """Support different residual path and norm styles. + See "On Layer Normalization in the Transformer Architecture", + Xiong et al., https://arxiv.org/pdf/2002.04745v1.pdf + """ + + Pre = "pre" + Post = "post" + DeepNorm = "deepnorm" + + +class NormalizationType(str, Enum): + LayerNorm = "layernorm" + Skip = "skip" + # TODO: BatchNorm = "batchnorm" + # TODO: GroupNorm = "groupnorm" + + +def get_normalization_layer(normalization_type: NormalizationType): + class Skip(nn.Module): + def __init__(self, *_, **__) -> None: + super().__init__() + deprecated_function(self) + + def forward(self, x: torch.Tensor, **_): + return x + + return { + NormalizationType.LayerNorm: nn.LayerNorm, + NormalizationType.Skip: Skip, + }[normalization_type] + + +class RequiresWrappedInputs: + """Used to mark, through inheritance, + the fact that this class will require inputs to be passed as a single list""" + + pass + + +# CREDITS: the following is inspired by FastAI's Transformer implementation +class Residual(nn.Module, RequiresWrappedInputs): + """ + Object-oriented handling of the residual path + + This supports scaling of the residual path, as proposed by DeepNet_ + .. _DeepNet: https://arxiv.org/pdf/2203.00555v1.pdf + + .. Note: the wrapped layers must accept all the inputs as a single list + """ + + def __init__(self, layer: nn.Module, scale: Optional[float] = None): + super().__init__() + deprecated_function(self) + self.layer = layer + self.scale = scale + + # PreNorm and PostNorm require all the tensors to be passed as a list + self.wrap_inputs = isinstance(layer, RequiresWrappedInputs) + + def forward(self, inputs: List[torch.Tensor], **kwargs): + if self.scale is not None: + residue = inputs[0] * self.scale + else: + residue = inputs[0] + + if self.wrap_inputs: + return residue + self.layer(inputs=inputs, **kwargs) + + else: + return residue + self.layer(*inputs, **kwargs) + + +class PreNorm(nn.Module, RequiresWrappedInputs): + """Adds a normalization before computing attention + + ..Note: If a list of inputs is passed, all of them get normalized""" + + def __init__( + self, + d_norm: int, + sublayer: nn.Module, + normalization: NormalizationType, + use_triton: bool = True, + ): + + super().__init__() + deprecated_function(self) + self.norm = get_normalization_layer(normalization)(d_norm) + + self.sublayer = sublayer + self.wrap_inputs = isinstance(sublayer, RequiresWrappedInputs) + + def forward(self, inputs: List[torch.Tensor], **kwargs): + assert len(inputs) > 0 + + # Perf improvement: if the inputs are all the same, only norm once + ids = [id(x) for x in inputs] + if ids.count(ids[0]) == len(ids): + # The same tensor is passed multiple times + x_norm = self.norm(inputs[0]) + inputs_normed = [x_norm for _ in inputs] + else: + # The inputs differ, norm them all + inputs_normed = [self.norm(x_) for x_ in inputs] + + if self.wrap_inputs: + return self.sublayer(inputs=inputs_normed, **kwargs) + else: + return self.sublayer(*inputs_normed, **kwargs) + + +class PostNorm(nn.Module, RequiresWrappedInputs): + """Adds LayerNorm after computing attention""" + + def __init__( + self, + d_norm: int, + sublayer: nn.Module, + normalization: NormalizationType, + use_triton: bool = True, + ): + super().__init__() + deprecated_function(self) + self.norm = get_normalization_layer(normalization)(d_norm) + + self.sublayer = sublayer + self.wrap_inputs = isinstance(sublayer, RequiresWrappedInputs) + + def forward(self, inputs: List[torch.Tensor], **kwargs): + if self.wrap_inputs: + x = self.sublayer(inputs=inputs, **kwargs) + else: + x = self.sublayer(*inputs, **kwargs) + return self.norm(x) + + +DeepNormCoefficients = namedtuple("DeepNormCoefficients", ["alpha", "beta"]) + + +def get_deepnorm_coefficients( + encoder_layers: int, decoder_layers: int +) -> Tuple[Optional[DeepNormCoefficients], Optional[DeepNormCoefficients]]: + """ + See DeepNet_. + + Returns alpha and beta depending on the number of encoder and decoder layers, + first tuple is for the encoder and second for the decoder + + .. _DeepNet: https://arxiv.org/pdf/2203.00555v1.pdf + """ + + N = encoder_layers + M = decoder_layers + + if decoder_layers == 0: + # Encoder only + return ( + DeepNormCoefficients(alpha=(2 * N) ** 0.25, beta=(8 * N) ** -0.25), + None, + ) + + elif encoder_layers == 0: + # Decoder only + return None, DeepNormCoefficients(alpha=(2 * M) ** 0.25, beta=(8 * M) ** -0.25) + else: + # Encoder/decoder + encoder_coeffs = DeepNormCoefficients( + alpha=0.81 * ((N**4) * M) ** 0.0625, beta=0.87 * ((N**4) * M) ** -0.0625 + ) + + decoder_coeffs = DeepNormCoefficients( + alpha=(3 * M) ** 0.25, beta=(12 * M) ** -0.25 + ) + + return (encoder_coeffs, decoder_coeffs) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/flash_attn_3/_C.so b/tool_server/.venv/lib/python3.12/site-packages/xformers/flash_attn_3/_C.so new file mode 100644 index 0000000000000000000000000000000000000000..999c8a8c31ac0d3635ff4df7f7d189b1e8dbd44a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/flash_attn_3/_C.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2503d3c6784edec23e6a05df5a4fb4692750238ac471a3d17899aa4b82c9c192 +size 336631128 diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/flash_attn_3/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/flash_attn_3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6677db08c0dcd87f7570a3249f61cc3eabe0532a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/flash_attn_3/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/flash_attn_3/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/flash_attn_3/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3174b8604668877f8d6aeadd3ae10b9d1ae0b372 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/flash_attn_3/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..24d847b7220849e305ecc91c3ccacc49870a07a0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__init__.py @@ -0,0 +1,128 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import torch + +from .fmha import ( + AttentionBias, + AttentionOp, + AttentionOpBase, + LowerTriangularMask, + memory_efficient_attention, + memory_efficient_attention_backward, + memory_efficient_attention_forward, + memory_efficient_attention_forward_requires_grad, + MemoryEfficientAttentionCkOp, + MemoryEfficientAttentionCutlassFwdFlashBwOp, + MemoryEfficientAttentionCutlassOp, + MemoryEfficientAttentionFlashAttentionOp, + MemoryEfficientAttentionSplitKCkOp, +) +from .indexing import index_select_cat, scaled_index_add +from .modpar_layers import ColumnParallelLinear, RowParallelLinear +from .rmsnorm import RMSNorm +from .rope_padded import rope_padded +from .seqpar import sequence_parallel_leading_matmul, sequence_parallel_trailing_matmul +from .sequence_parallel_fused_ops import ( + fused_allgather_and_anything, + fused_allgather_and_linear, + fused_anything_and_reducescatter, + fused_linear_and_reducescatter, +) +from .sp24 import Sparse24Tensor, sparsify24, sparsify24_like +from .swiglu_op import ( + SwiGLU, + swiglu, + SwiGLUEagerOp, + SwiGLUFusedOp, + SwiGLUOp, + SwiGLUOpDispatch, + SwiGLUPackedFusedOp, +) +from .tiled_matmul import tiled_matmul +from .unbind import get_stack_strides, stack_or_none, unbind + +# BW compatibility +AttentionMask = AttentionBias + + +def masked_matmul(a, b, mask=None): + if torch.overrides.has_torch_function((a, b, mask)): + return torch.overrides.handle_torch_function( + masked_matmul, (a, b, mask), a, b, mask + ) + + att = a @ b + + if mask is None: + return att + + if mask.dtype == torch.bool: + if mask.ndim == 2: + mask = mask.unsqueeze(0).expand(att.shape[0], -1, -1) + # mask is presumed false == ignore + att[~mask] = float("-inf") + else: + # mask is presumed additive + att += mask + return att + + +__all__ = [ + # fmha + "AttentionBias", + "AttentionMask", + "AttentionOp", + "AttentionOpBase", + "LowerTriangularMask", + "MemoryEfficientAttentionCutlassFwdFlashBwOp", + "MemoryEfficientAttentionCutlassOp", + "MemoryEfficientAttentionFlashAttentionOp", + "MemoryEfficientAttentionCkOp", + "MemoryEfficientAttentionSplitKCkOp", + "memory_efficient_attention", + "memory_efficient_attention_backward", + "memory_efficient_attention_forward", + "memory_efficient_attention_forward_requires_grad", + # indexing + "index_select_cat", + "scaled_index_add", + # modpar_layers + "ColumnParallelLinear", + "RowParallelLinear", + # rmsnorm + "RMSNorm", + # rope_padded + "rope_padded", + # seqpar + "sequence_parallel_leading_matmul", + "sequence_parallel_trailing_matmul", + # sequence_parallel_fused_ops + "fused_allgather_and_anything", + "fused_allgather_and_linear", + "fused_anything_and_reducescatter", + "fused_linear_and_reducescatter", + # swiglu_op + "SwiGLU", + "SwiGLUEagerOp", + "SwiGLUFusedOp", + "SwiGLUOp", + "SwiGLUOpDispatch", + "SwiGLUPackedFusedOp", + "swiglu", + # tiled_matmul + "tiled_matmul", + # unbind + "get_stack_strides", + "stack_or_none", + "unbind", + # sp24 + "sparsify24", + "sparsify24_like", + "Sparse24Tensor", + # . + "masked_matmul", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a9c67d56fe9baa10e27c3be026ca048067a8c9c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/common.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..62b6a47e2b6536c449ae4ed5d23028c00bb233b4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/common.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/differentiable_collectives.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/differentiable_collectives.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f72a801ff1f38a2722bef7728c8fbfc46b201c22 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/differentiable_collectives.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/indexing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/indexing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b912cc0761d64623e9e4d41522ee442da4843d1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/indexing.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/modpar_layers.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/modpar_layers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d58e1756923456b22f9e129aac155a76e6fc90ad Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/modpar_layers.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/rmsnorm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/rmsnorm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36c9f987f11a10b9e3d19fe3a5b1f43036865b69 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/rmsnorm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/rope_padded.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/rope_padded.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b275604035d5f89faee43c2e4ad9506ceb2c8ac5 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/rope_padded.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/seqpar.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/seqpar.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eaa927ffc357e161c67879ae19078e0126cc6a1b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/seqpar.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/sequence_parallel_fused_ops.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/sequence_parallel_fused_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcde47411d7e205803408a1b72361cfebc933f8e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/sequence_parallel_fused_ops.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/sp24.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/sp24.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..461127985022614e44453454e8cc711e3c69bc24 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/sp24.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/swiglu_op.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/swiglu_op.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02796595ee831f4e935b7e1c0985e8a365d6646e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/swiglu_op.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/tiled_matmul.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/tiled_matmul.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fefe9925fa1ab7badc31dea56b3a7d5da1ca454 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/tiled_matmul.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/tree_attention.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/tree_attention.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37d9c7a0e05fa82f1387ffc208e46171c79c2e3a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/tree_attention.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/unbind.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/unbind.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58d274d6087b11ed4e929c4941b3bdfb0b40c032 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/__pycache__/unbind.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0a8ab8e0f6ebcc23b8aa5eaa5dfad7dd70c8acee --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__init__.py @@ -0,0 +1,19 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +# One reason this module is called `_triton` instead of just `triton` is this: +# https://github.com/openai/triton/commit/c6040bcbd8a046785462481b2830b3fff5fc4aab + +from typing import TYPE_CHECKING + +import xformers + +if TYPE_CHECKING or xformers._is_triton_available(): + from .k_index_select_cat import index_select_cat_bwd, index_select_cat_fwd + from .k_scaled_index_add import scaled_index_add_bwd, scaled_index_add_fwd +else: + index_select_cat_fwd = index_select_cat_bwd = None + scaled_index_add_fwd = scaled_index_add_bwd = None diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9af8f9b1d7fcd05f7307eb7106d12c72e9fc75be Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/k_index_select_cat.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/k_index_select_cat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b2f19173d5f64d74ed54fd7acb302c3ff138d95 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/k_index_select_cat.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/k_scaled_index_add.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/k_scaled_index_add.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..742f2d7c4ac158ad554f592ffdde6ae1db46857c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/k_scaled_index_add.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/matmul_perf_model.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/matmul_perf_model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f4a4ce09c65e9d9f91f3cc6bda1c1aa18fd2f45b Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/matmul_perf_model.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/rmsnorm_kernels.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/rmsnorm_kernels.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..048b7b60c5ad7c14c317b22b309dcbd52a8b04af Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/rmsnorm_kernels.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/rope_padded_kernels.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/rope_padded_kernels.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0de48bc1c2c1b736d4fd6e731d52e4470296537c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/rope_padded_kernels.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/tiled_matmul_kernels.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/tiled_matmul_kernels.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..01d253fe1612f594e2c1efd1765dd1c5d9dbc15d Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/__pycache__/tiled_matmul_kernels.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/k_index_select_cat.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/k_index_select_cat.py new file mode 100644 index 0000000000000000000000000000000000000000..d34c32c326d98be702ee7ff3109364a3738fa8c8 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/k_index_select_cat.py @@ -0,0 +1,184 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import triton +import triton.language as tl + + +@triton.jit +def index_select_cat_fwd_kernel( + output_ptr, # *Pointer* to output tensor. + source_ptr, # *Pointer* to source tensor. + index_ptr, # *Pointer* to index tensor. + num_indices, + num_cols, + stride0, # Stride information of source tensor. + stride1, + BLOCK_SIZE_INDEX: tl.constexpr, # Number of indices each program should process. + BLOCK_SIZE_COL: tl.constexpr, # Number of cols each program should process. +): + pid0 = tl.program_id(axis=0) # We use 2D launch grid + pid1 = tl.program_id(axis=1) + + indices = pid0 * BLOCK_SIZE_INDEX + tl.arange(0, BLOCK_SIZE_INDEX) + rows = tl.load(index_ptr + indices, mask=(indices < num_indices)) + cols = pid1 * BLOCK_SIZE_COL + tl.arange(0, BLOCK_SIZE_COL) + + source_offsets = source_ptr + rows[:, None] * stride0 + cols[None, :] * stride1 + mask = (indices[:, None] < num_indices) & (cols[None, :] < num_cols) + output = tl.load(source_offsets, mask=mask) + + output_offsets = output_ptr + indices[:, None] * stride0 + cols[None, :] * stride1 + tl.store(output_offsets, output, mask=mask) + + +def index_select_cat_fwd( + output: torch.Tensor, + source: torch.Tensor, + index: torch.Tensor, +): + if not (source.is_cuda and index.is_cuda): + raise ValueError("The index tensor and the source tensor must be of type CUDA!") + + if not source.ndim == 2: + raise ValueError(f"Expected 2-dimensional tensor, got {source.ndim}.") + if not index.ndim == 1: + raise ValueError(f"Expected 1-dimensional tensor, got {index.ndim}.") + + num_rows, num_cols = source.shape + num_indices = index.shape[0] + + if not num_indices < num_rows: + raise ValueError( + "The number of indices cannot exceed the number of rows in the source matrix." + ) + + stride0, stride1 = source.stride(0), source.stride(1) + + def grid(meta): + return ( + triton.cdiv(num_indices, meta["BLOCK_SIZE_INDEX"]), + triton.cdiv(num_cols, meta["BLOCK_SIZE_COL"]), + ) + + index_select_cat_fwd_kernel[grid]( + output, + source, + index, + num_indices, + num_cols, + stride0, + stride1, + BLOCK_SIZE_INDEX=1, + BLOCK_SIZE_COL=512, + ) + + return output + + +@triton.jit +def index_select_cat_bwd_kernel( + grad_source_ptr, # *Pointer* to grad_source tensor. + index_ptr, # *Pointer* to index tensor. + grad_output_ptr, # *Pointer* to grad_output tensor. + num_rows, + num_indices, + num_cols, + stride0, # Stride information of input and source tensor. + stride1, + BLOCK_SIZE_INDEX: tl.constexpr, # Number of indices each program should process. + BLOCK_SIZE_COL: tl.constexpr, # Number of cols each program should process. +): + pid0 = tl.program_id(axis=0) # We use 3D launch grid + pid1 = tl.program_id(axis=1) + + cols = pid1 * BLOCK_SIZE_COL + tl.arange(0, BLOCK_SIZE_COL) + + # load grad_output + grad_output_indices = pid0 * BLOCK_SIZE_INDEX + tl.arange(0, BLOCK_SIZE_INDEX) + grad_output_offsets = ( + grad_output_ptr + + grad_output_indices[:, None] * stride0 + + cols[None, :] * stride1 + ) + grad_output_mask = (grad_output_indices[:, None] < num_indices) & ( + cols[None, :] < num_cols + ) + grad_output = tl.load(grad_output_offsets, mask=grad_output_mask).to(tl.float32) + + # select indices from grad_source + grad_source_indices = tl.load( + index_ptr + grad_output_indices, mask=(grad_output_indices < num_indices) + ) + grad_source_offsets = ( + grad_source_ptr + + grad_source_indices[:, None] * stride0 + + cols[None, :] * stride1 + ) + + # compute scaled index add and save + tl.store(grad_source_offsets, grad_output, mask=grad_output_mask) + + +def index_select_cat_bwd( + grad_source: torch.Tensor, + index: torch.Tensor, + grad_output: torch.Tensor, +): + if not (grad_source.is_cuda and grad_output.is_cuda): + raise ValueError("The grad_source and grad_output tensor must be of type CUDA!") + + if not (grad_source.ndim == 2 and grad_output.ndim == 2): + raise ValueError( + f"The grad_source and grad_output must be three-dimensional " + f"(got {grad_source.ndim} and {grad_output.ndim})!" + ) + if not grad_source.shape[1] == grad_output.shape[1]: + raise ValueError( + f"The number of elements along dimension 1 of grad_source and grad_output must be the same " + f"(got {grad_source.shape[1]} and {grad_output.shape[1]})" + ) + + num_rows, num_cols = grad_source.shape + num_indices, num_cols = grad_output.shape + if not num_rows >= num_indices: + raise ValueError( + f"The number of elements along dimension 0 of grad_source must be larger than that of grad_output " + f"(got {num_rows} and {num_indices})!" + ) + if not index.shape[0] == num_indices: + raise ValueError( + f"The number of indices and the number of elements along dimension 0 of grad_output must match " + f"(got {index.shape[0]} and {num_indices})!" + ) + + stride0, stride1 = grad_source.stride(0), grad_source.stride(1) + if not (grad_output.stride(0) == stride0 and grad_output.stride(1) == stride1): + raise ValueError( + f"The strides of the grad_source and grad_output tensors must match " + f"(got {stride0} vs. {grad_output.stride(0)}, {stride1} vs. {grad_output.stride(1)})!" + ) + + def grid(meta): + return ( + triton.cdiv(num_indices, meta["BLOCK_SIZE_INDEX"]), + triton.cdiv(num_cols, meta["BLOCK_SIZE_COL"]), + ) + + index_select_cat_bwd_kernel[grid]( + grad_source, + index, + grad_output, + num_rows, + num_indices, + num_cols, + grad_source.stride(0), + grad_source.stride(1), + BLOCK_SIZE_INDEX=1, + BLOCK_SIZE_COL=512, + ) + + return diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/k_scaled_index_add.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/k_scaled_index_add.py new file mode 100644 index 0000000000000000000000000000000000000000..ab1fd96cf1fe1cdc11bb3526e3a7e511071cd966 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/k_scaled_index_add.py @@ -0,0 +1,365 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Optional + +import torch +import triton +import triton.language as tl + + +@triton.jit +def scaled_index_add_fwd_kernel( + input_ptr, # *Pointer* to input tensor. + index_ptr, # *Pointer* to index tensor. + source_ptr, # *Pointer* to source tensor. + scaling_ptr, # *Pointer* to the scaling tensor. + alpha, + num_inp_indices, + num_src_indices, + num_rows, + num_cols, + stride0, # Stride information of input and source tensor. + stride1, + stride2, + BLOCK_SIZE_INDEX: tl.constexpr, # Number of indices each program should process. + BLOCK_SIZE_ROW: tl.constexpr, # Number of rows each program should process. + BLOCK_SIZE_COL: tl.constexpr, # Number of cols each program should process. + HAS_SCALING: tl.constexpr, # Boolean indicating if the scaling factor is present. +): + pid0 = tl.program_id(axis=0) # We use 3D launch grid + pid1 = tl.program_id(axis=1) + pid2 = tl.program_id(axis=2) + + rows = pid1 * BLOCK_SIZE_ROW + tl.arange(0, BLOCK_SIZE_ROW) + cols = pid2 * BLOCK_SIZE_COL + tl.arange(0, BLOCK_SIZE_COL) + + # load source + source_indices = pid0 * BLOCK_SIZE_INDEX + tl.arange(0, BLOCK_SIZE_INDEX) + source_offsets = ( + source_ptr + + source_indices[:, None, None] * stride0 + + rows[None, :, None] * stride1 + + cols[None, None, :] * stride2 + ) + source_mask = ( + (source_indices[:, None, None] < num_src_indices) + & (rows[None, :, None] < num_rows) + & (cols[None, None, :] < num_cols) + ) + source = tl.load(source_offsets, mask=source_mask).to(tl.float32) + + # load input + input_indices = tl.load( + index_ptr + source_indices, mask=(source_indices < num_src_indices) + ) + input_offsets = ( + input_ptr + + input_indices[:, None, None] * stride0 + + rows[None, :, None] * stride1 + + cols[None, None, :] * stride2 + ) + x = tl.load(input_offsets, mask=source_mask).to(tl.float32) + + # compute scaled index add and save + if HAS_SCALING: + scaling = tl.load( + scaling_ptr + cols[None, None, :] * stride2, + mask=(cols[None, None, :] < num_cols), + ).to(tl.float32) + tl.store(input_offsets, x + alpha * scaling * source, mask=source_mask) + else: + tl.store(input_offsets, x + alpha * source, mask=source_mask) + + +def scaled_index_add_fwd( + x: torch.Tensor, + index: torch.Tensor, + source: torch.Tensor, + scaling: Optional[torch.Tensor], + alpha: float, +): + if not (x.is_cuda and index.is_cuda and source.is_cuda): + raise ValueError( + "The input tensor, the index tensor and the source tensor must be of type CUDA!" + ) + + if not (x.ndim == 3 and source.ndim == 3): + raise ValueError( + f"The input and source must be three-dimensional (got {x.ndim} and {source.ndim})!" + ) + if not x.shape[1] == source.shape[1]: + raise ValueError( + f"The number of elements along dimension 1 of the input and source must be the same " + f"(got {x.shape[1], } and {source.shape[1], })!" + ) + if not x.shape[2] == source.shape[2]: + raise ValueError( + f"The number of elements along dimension 2 of the input and source must be the same " + f"(got {x.shape[2], } and {source.shape[2], })!" + ) + + num_inp_indices, num_rows, num_cols = x.shape + num_src_indices, num_rows, num_cols = source.shape + if not num_inp_indices >= num_src_indices: + raise ValueError( + f"The number of elements along dimension 0 of the input must be larger than that of source " + f"(got {num_inp_indices} and {num_src_indices})!" + ) + if not index.shape[0] == num_src_indices: + raise ValueError( + f"The number of indices and source tensors must match (got {len(index)} and {len(source)})!" + ) + + stride0, stride1, stride2 = x.stride(0), x.stride(1), x.stride(2) + if not ( + source.stride(0) == stride0 + and source.stride(1) == stride1 + and source.stride(2) == stride2 + ): + raise ValueError( + f"The strides of the source and input tensors must match (got {source.stride(0)} vs. {stride0}, " + f"{source.stride(1)} vs. {stride1}, {source.stride(2)} vs. {stride2})!" + ) + + if scaling is None: + HAS_SCALING = False + else: + HAS_SCALING = True + if not scaling.is_cuda: + raise ValueError("The scaling tensor must be of type CUDA!") + if not (scaling.ndim == 1 and scaling.numel() == num_cols): + raise ValueError( + f"The scaling tensor must be a 1-dimensional tensor (got {scaling.ndim}) and its size " + f"must be equal to the size of dimension 2 of source (got {scaling.numel()} vs. {num_cols})." + ) + if not scaling.stride(0) == stride2: + raise ValueError( + f"The stride of scaling must match the stride2 of input (got {scaling.stride(0)} vs. {stride2})" + ) + + if not index.ndim == 1: + raise ValueError(f"The index must be one-dimensional (got {index.ndim})!") + + def grid(meta): + return ( + triton.cdiv(num_src_indices, meta["BLOCK_SIZE_INDEX"]), + triton.cdiv(num_rows, meta["BLOCK_SIZE_ROW"]), + triton.cdiv(num_cols, meta["BLOCK_SIZE_COL"]), + ) + + scaled_index_add_fwd_kernel[grid]( + x, + index, + source, + scaling, + alpha, + num_inp_indices, + num_src_indices, + num_rows, + num_cols, + x.stride(0), + x.stride(1), + x.stride(2), + BLOCK_SIZE_INDEX=1, + BLOCK_SIZE_ROW=1, + BLOCK_SIZE_COL=512, + HAS_SCALING=HAS_SCALING, + ) + + return + + +@triton.jit +def scaled_index_add_bwd_kernel( + grad_output_ptr, # *Pointer* to input tensor. + grad_source_ptr, # *Pointer* to index tensor. + grad_scaling_ptr, # *Pointer* to source tensor. + source_ptr, # *Pointer* to the source tensor. + scaling_ptr, # *Pointer* to the scaling tensor. + index_ptr, + alpha, + num_inp_indices, + num_src_indices, + num_rows, + num_cols, + stride0, # Stride information of input and source tensor. + stride1, + stride2, + BLOCK_SIZE_INDEX: tl.constexpr, # Number of indices each program should process. + BLOCK_SIZE_ROW: tl.constexpr, # Number of rows each program should process. + BLOCK_SIZE_COL: tl.constexpr, # Number of cols each program should process. + HAS_SCALING: tl.constexpr, # Boolean indicating if the scaling factor is present. +): + pid0 = tl.program_id(axis=0) # We use 3D launch grid + pid1 = tl.program_id(axis=1) + pid2 = tl.program_id(axis=2) + + rows = pid1 * BLOCK_SIZE_ROW + tl.arange(0, BLOCK_SIZE_ROW) + cols = pid2 * BLOCK_SIZE_COL + tl.arange(0, BLOCK_SIZE_COL) + + # load source + source_indices = pid0 * BLOCK_SIZE_INDEX + tl.arange(0, BLOCK_SIZE_INDEX) + source_offsets = ( + source_ptr + + source_indices[:, None, None] * stride0 + + rows[None, :, None] * stride1 + + cols[None, None, :] * stride2 + ) + source_mask = ( + (source_indices[:, None, None] < num_src_indices) + & (rows[None, :, None] < num_rows) + & (cols[None, None, :] < num_cols) + ) + source = tl.load(source_offsets, mask=source_mask).to(tl.float32) + + # load grad_output + grad_output_indices = tl.load( + index_ptr + source_indices, mask=(source_indices < num_src_indices) + ) + grad_output_offsets = ( + grad_output_ptr + + grad_output_indices * stride0 + + rows[None, :, None] * stride1 + + cols[None, None, :] * stride2 + ) + grad_output = tl.load(grad_output_offsets, mask=source_mask).to(tl.float32) + + # compute gradient + grad_source_offsets = ( + grad_source_ptr + + source_indices[:, None, None] * stride0 + + rows[None, :, None] * stride1 + + cols[None, None, :] * stride2 + ) + if HAS_SCALING: + scaling = tl.load( + scaling_ptr + cols[None, None, :] * stride2, + mask=(cols[None, None, :] < num_cols), + ).to(tl.float32) + + tl.store(grad_source_offsets, alpha * grad_output * scaling, mask=source_mask) + + grad_scaling_offsets = ( + grad_scaling_ptr + + source_indices[:, None, None] * stride0 + + rows[None, :, None] * stride1 + + cols[None, None, :] * stride2 + ) + tl.store(grad_scaling_offsets, alpha * grad_output * source, mask=source_mask) + else: + tl.store(grad_source_offsets, alpha * grad_output, mask=source_mask) + + +def scaled_index_add_bwd( + grad_output: torch.Tensor, + grad_source: torch.Tensor, + grad_scaling: Optional[torch.Tensor], + source: torch.Tensor, + scaling: Optional[torch.Tensor], + index: torch.Tensor, + alpha: float, +): + if not (grad_output.is_cuda and grad_source.is_cuda): + raise ValueError( + "The grad_output tensor and grad_source tensor must be of type CUDA!" + ) + + if not (grad_output.ndim == 3 and source.ndim == 3): + raise ValueError( + f"The input and source must be three-dimensional (got {grad_output.ndim} and {source.ndim})!" + ) + + if not grad_output.shape[1] == source.shape[1]: + raise ValueError( + f"The number of elements along dimension 1 of the input and source must be the same " + f"(got {grad_output.shape[1], } and {source.shape[1], })!" + ) + if not grad_output.shape[2] == source.shape[2]: + raise ValueError( + f"The number of elements along dimension 2 of the input and source must be the same " + f"(got {grad_output.shape[2], } and {source.shape[2], })!" + ) + + num_inp_indices, num_rows, num_cols = grad_output.shape + num_src_indices, num_rows, num_cols = source.shape + if not num_inp_indices >= num_src_indices: + raise ValueError( + f"The number of elements along dimension 0 of the input must be larger than that of source " + f"(got {num_inp_indices} and {num_src_indices})!" + ) + + stride0, stride1, stride2 = source.stride(0), source.stride(1), source.stride(2) + if not ( + grad_output.stride(0) == stride0 + and grad_output.stride(1) == stride1 + and grad_output.stride(2) == stride2 + ): + raise ValueError( + f"The strides of grad_output and source must match " + f"(got {grad_output.stride(0)} vs {stride0}, {grad_output.stride(1)} vs {stride1}, " + f"{grad_output.stride(2)} vs {stride2})!" + ) + if not ( + grad_source.stride(0) == stride0 + and grad_source.stride(1) == stride1 + and grad_source.stride(2) == stride2 + ): + raise ValueError( + f"The strides of grad_source and source must match " + f"(got {grad_source.stride(0)} vs {stride0}, {grad_source.stride(1)} vs {stride1}, " + f"{grad_source.stride(2)} vs {stride2})!" + ) + + if scaling is not None and grad_scaling is not None: + HAS_SCALING = True + if not grad_scaling.is_cuda: + raise ValueError("The scaling tensor must be of type CUDA!") + if not ( + grad_scaling.stride(0) == stride0 + and grad_scaling.stride(1) == stride1 + and grad_scaling.stride(2) == stride2 + ): + raise ValueError( + f"The strides of grad_scaling and source must match " + f"(got {grad_scaling.stride(0)} vs {stride0}, {grad_scaling.stride(1)} vs {stride1}, " + f"{grad_scaling.stride(2)} vs {stride2})!" + ) + if not scaling.stride(0) == stride2: + raise ValueError( + f"The stride of scaling must match stride2 of source (got {scaling.stride(0)} vs. {stride2})!" + ) + else: + HAS_SCALING = False + + def grid(meta): + return ( + triton.cdiv(num_src_indices, meta["BLOCK_SIZE_INDEX"]), + triton.cdiv(num_rows, meta["BLOCK_SIZE_ROW"]), + triton.cdiv(num_cols, meta["BLOCK_SIZE_COL"]), + ) + + scaled_index_add_bwd_kernel[grid]( + grad_output, + grad_source, + grad_scaling, + source, + scaling, + index, + alpha, + num_inp_indices, + num_src_indices, + num_rows, + num_cols, + stride0, + stride1, + stride2, + BLOCK_SIZE_INDEX=1, + BLOCK_SIZE_ROW=1, + BLOCK_SIZE_COL=512, + HAS_SCALING=HAS_SCALING, + ) + + return diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/matmul_perf_model.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/matmul_perf_model.py new file mode 100644 index 0000000000000000000000000000000000000000..6ab6bacc1b0697997beb5cb6cfb802a2ea80cee0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/matmul_perf_model.py @@ -0,0 +1,250 @@ +# Source: https://github.com/triton-lang/kernels/blob/main/kernels/matmul_perf_model.py +# License: MIT from triton-lang/kernels +""" +MIT License + +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. +""" + +# @lint-ignore-every LICENSELINT + +# flake8: noqa +# pyre-ignore-all-errors +# fmt: off +import functools +import heapq + +import torch +from triton import cdiv +from triton.runtime import driver +from triton.testing import ( + get_dram_gbps, + get_max_simd_tflops, + get_max_tensorcore_tflops, + nvsmi, +) + + +@functools.lru_cache() +def get_clock_rate_in_khz(): + try: + return nvsmi(["clocks.max.sm"])[0] * 1e3 + except FileNotFoundError: + import pynvml + + pynvml.nvmlInit() + handle = pynvml.nvmlDeviceGetHandleByIndex(0) + return pynvml.nvmlDeviceGetMaxClockInfo(handle, pynvml.NVML_CLOCK_SM) * 1e3 + + +def get_tensorcore_tflops(device, num_ctas, num_warps, dtype): + """return compute throughput in TOPS""" + total_warps = num_ctas * min(num_warps, 4) + num_subcores = ( + driver.active.utils.get_device_properties(device)["multiprocessor_count"] * 4 + ) # on recent GPUs + tflops = ( + min(num_subcores, total_warps) + / num_subcores + * get_max_tensorcore_tflops(dtype, get_clock_rate_in_khz(), device) + ) + return tflops + + +def get_simd_tflops(device, num_ctas, num_warps, dtype): + """return compute throughput in TOPS""" + total_warps = num_ctas * min(num_warps, 4) + num_subcores = ( + driver.active.utils.get_device_properties(device)["multiprocessor_count"] * 4 + ) # on recent GPUs + tflops = ( + min(num_subcores, total_warps) + / num_subcores + * get_max_simd_tflops(dtype, get_clock_rate_in_khz(), device) + ) + return tflops + + +def get_tflops(device, num_ctas, num_warps, dtype): + capability = torch.cuda.get_device_capability(device) + if capability[0] < 8 and dtype == torch.float32: + return get_simd_tflops(device, num_ctas, num_warps, dtype) + return get_tensorcore_tflops(device, num_ctas, num_warps, dtype) + + +def estimate_matmul_time( + # backend, device, + num_warps, + num_stages, # + A, + B, + C, # + M, + N, + K, # + BLOCK_M, + BLOCK_N, + BLOCK_K, + SPLIT_K, # + debug=False, + **kwargs, # +): + """return estimated running time in ms + = max(compute, loading) + store""" + device = torch.cuda.current_device() + dtype = A.dtype + dtsize = A.element_size() + + num_cta_m = cdiv(M, BLOCK_M) + num_cta_n = cdiv(N, BLOCK_N) + num_cta_k = SPLIT_K + num_ctas = num_cta_m * num_cta_n * num_cta_k + + # If the input is smaller than the block size + M, N = max(M, BLOCK_M), max(N, BLOCK_N) + + # time to compute + total_ops = 2 * M * N * K / (1024 * 1024 * 1024) # GOPS + tput = get_tflops(device, num_ctas, num_warps, dtype) + compute_ms = total_ops / tput + + # time to load data + num_sm = driver.active.utils.get_device_properties(device)["multiprocessor_count"] + active_cta_ratio = min(1, num_ctas / num_sm) + active_cta_ratio_bw1 = min( + 1, num_ctas / 32 + ) # 32 active ctas are enough to saturate + active_cta_ratio_bw2 = max( + min(1, (num_ctas - 32) / (108 - 32)), 0 + ) # 32-108, remaining 5% + dram_bw = get_dram_gbps(device) * ( + active_cta_ratio_bw1 * 0.95 + active_cta_ratio_bw2 * 0.05 + ) # in GB/s + l2_bw = dram_bw * 4 # rough estimation (should be 4.7 for A100?) + # assume 80% of (following) loads are in L2 cache + load_a_dram = M * K * dtsize * (1 + 0.2 * (num_cta_n - 1)) + load_a_l2 = M * K * dtsize * 0.8 * (num_cta_n - 1) + load_b_dram = N * K * dtsize * (1 + 0.2 * (num_cta_m - 1)) + load_b_l2 = N * K * dtsize * 0.8 * (num_cta_m - 1) + # total + total_dram = (load_a_dram + load_b_dram) / (1024 * 1024) # MB + total_l2 = (load_a_l2 + load_b_l2) / (1024 * 1024) + # loading time in ms + load_ms = total_dram / dram_bw + total_l2 / l2_bw + + # estimate storing time + store_bw = dram_bw * 0.6 # :o + store_c_dram = M * N * dtsize * SPLIT_K / (1024 * 1024) # MB + if SPLIT_K == 1: + store_ms = store_c_dram / store_bw + else: + reduce_bw = store_bw + store_ms = store_c_dram / reduce_bw + # c.zero_() + zero_ms = M * N * 2 / (1024 * 1024) / store_bw + store_ms += zero_ms + + total_time_ms = max(compute_ms, load_ms) + store_ms + if debug: + print( + f"Total time: {total_time_ms}ms, compute time: {compute_ms}ms, " + f"loading time: {load_ms}ms, store time: {store_ms}ms, " + f"Activate CTAs: {active_cta_ratio*100}%" + ) + return total_time_ms + + +def early_config_prune(configs, named_args, **kwargs): + device = torch.cuda.current_device() + capability = torch.cuda.get_device_capability() + # BLOCK_M, BLOCK_N, BLOCK_K, SPLIT_K, num_warps, num_stages + dtsize = named_args["A"].element_size() + dtype = named_args["A"].dtype + + # 1. make sure we have enough smem + pruned_configs = [] + for config in configs: + kw = config.kwargs + BLOCK_M, BLOCK_N, BLOCK_K, num_stages = ( + kw["BLOCK_M"], + kw["BLOCK_N"], + kw["BLOCK_K"], + config.num_stages, + ) + + max_shared_memory = driver.active.utils.get_device_properties(device)[ + "max_shared_mem" + ] + required_shared_memory = (BLOCK_M + BLOCK_N) * BLOCK_K * num_stages * dtsize + if required_shared_memory <= max_shared_memory: + pruned_configs.append(config) + configs = pruned_configs + + # Some dtypes do not allow atomic_add + if dtype not in [torch.float16, torch.float32]: + configs = [config for config in configs if config.kwargs["SPLIT_K"] == 1] + + # group configs by (BLOCK_M,_N,_K, SPLIT_K, num_warps) + configs_map = {} + for config in configs: + kw = config.kwargs + BLOCK_M, BLOCK_N, BLOCK_K, SPLIT_K, num_warps, num_stages = ( + kw["BLOCK_M"], + kw["BLOCK_N"], + kw["BLOCK_K"], + kw["SPLIT_K"], + config.num_warps, + config.num_stages, + ) + + key = (BLOCK_M, BLOCK_N, BLOCK_K, SPLIT_K, num_warps) + if key in configs_map: + configs_map[key].append((config, num_stages)) + else: + configs_map[key] = [(config, num_stages)] + + pruned_configs = [] + for k, v in configs_map.items(): + BLOCK_M, BLOCK_N, BLOCK_K, SPLIT_K, num_warps = k + if capability[0] >= 8: + # compute cycles (only works for ampere GPUs) + mmas = BLOCK_M * BLOCK_N * BLOCK_K / (16 * 8 * 16) + mma_cycles = mmas / min(4, num_warps) * 8 + + ldgsts_latency = 300 # Does this matter? + optimal_num_stages = ldgsts_latency / mma_cycles + + # nearest stages, prefer large #stages + nearest = heapq.nsmallest( + 2, + v, + key=lambda x: ( + 10 + abs(x[1] - optimal_num_stages) + if (x[1] - optimal_num_stages) < 0 + else x[1] - optimal_num_stages + ), + ) + + for n in nearest: + pruned_configs.append(n[0]) + else: # Volta & Turing only supports num_stages <= 2 + random_config = v[0][0] + random_config.num_stages = 2 + pruned_configs.append(random_config) + return pruned_configs diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/rmsnorm_kernels.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/rmsnorm_kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..54812aba551489d53287ccdf3f39ec60ee0eb9de --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/rmsnorm_kernels.py @@ -0,0 +1,159 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. +import torch +import triton +import triton.language as tl + +from xformers.triton.importing import libdevice_find + +rsqrt = libdevice_find("rsqrt") + + +@triton.jit +def _rms_norm_kernel( + x_ptr, + h1_ptr, + w_ptr, + eps, + stride, + N_COLS: tl.constexpr, + BLOCK_SIZE: tl.constexpr, + INCLUDE_WEIGHT: tl.constexpr, +): + row = tl.program_id(0).to(tl.int64) + x_ptr += row * stride + h1_ptr += row * stride + + _mean = tl.zeros([BLOCK_SIZE], dtype=tl.float32) + for offset in range(0, N_COLS, BLOCK_SIZE): + cols = offset + tl.arange(0, BLOCK_SIZE) + a = tl.load( + x_ptr + cols, mask=cols < N_COLS, other=0.0, eviction_policy="evict_last" + ).to(tl.float32) + _mean += a * a + rstd = rsqrt((tl.sum(_mean, axis=0) / N_COLS) + eps) + for offset in range(0, N_COLS, BLOCK_SIZE): + cols = offset + tl.arange(0, BLOCK_SIZE) + mask = cols < N_COLS + a = tl.load( + x_ptr + cols, mask=mask, other=0.0, eviction_policy="evict_first" + ).to(tl.float32) + if INCLUDE_WEIGHT: + w = tl.load(w_ptr + cols, mask=mask) + tl.store(h1_ptr + cols, a * rstd * w, mask=mask) + else: + tl.store(h1_ptr + cols, a * rstd, mask=mask) + + +@triton.jit +def _rms_norm_add_kernel( + x_ptr, + y_ptr, + h1_ptr, + w_ptr, + eps, + stride, + N_COLS: tl.constexpr, + BLOCK_SIZE: tl.constexpr, + INCLUDE_WEIGHT: tl.constexpr, +): + row = tl.program_id(0) + x_ptr += row * stride + y_ptr += row * stride + h1_ptr += row * stride + + _mean = tl.zeros([BLOCK_SIZE], dtype=tl.float32) + for offset in range(0, N_COLS, BLOCK_SIZE): + cols = offset + tl.arange(0, BLOCK_SIZE) + mask = cols < N_COLS + ax = tl.load( + x_ptr + cols, mask=mask, other=0.0, eviction_policy="evict_last" + ).to(tl.float32) + ay = tl.load( + y_ptr + cols, mask=mask, other=0.0, eviction_policy="evict_first" + ).to(tl.float32) + a = ax + ay + tl.store(x_ptr + cols, a, mask=mask) + _mean += a * a + rstd = rsqrt((tl.sum(_mean, axis=0) / N_COLS) + eps) + for offset in range(0, N_COLS, BLOCK_SIZE): + cols = offset + tl.arange(0, BLOCK_SIZE) + mask = cols < N_COLS + a = tl.load( + x_ptr + cols, mask=mask, other=0.0, eviction_policy="evict_first" + ).to(tl.float32) + if INCLUDE_WEIGHT: + w = tl.load(w_ptr + cols, mask=mask) + tl.store(h1_ptr + cols, a * rstd * w, mask=mask) + else: + tl.store(h1_ptr + cols, a * rstd, mask=mask) + + +def _rms_norm_forward(x, attn_norm_weights, eps): + if not x.is_contiguous(): + raise ValueError("data must be contiguous") + if attn_norm_weights is not None: + if not attn_norm_weights.is_contiguous(): + raise ValueError("weights must be contiguous") + out = torch.empty_like(x) + x_arg = x.reshape(-1, x.shape[-1]) + M, N = x_arg.shape + # Less than 64KB per feature: enqueue fused kernel + MAX_FUSED_SIZE = 65536 // x.element_size() + BLOCK_SIZE = min(MAX_FUSED_SIZE, triton.next_power_of_2(N)) + BLOCK_SIZE = max(BLOCK_SIZE, 128) + BLOCK_SIZE = min(BLOCK_SIZE, 8192) + # heuristics for number of warps + num_warps = min(max(BLOCK_SIZE // 256, 1), 8) + with torch.cuda.device(x.device): + _rms_norm_kernel[(M,)]( + x_arg, + out, + attn_norm_weights, + eps, + x_arg.stride(0), + N, + BLOCK_SIZE=BLOCK_SIZE, + num_warps=num_warps, + INCLUDE_WEIGHT=attn_norm_weights is not None, + ) + return out + + +def _rms_norm_add_forward(x, y, attn_norm_weights, eps): + # x, y contiguous of same shape [..., n] + # output of same shape, normed over the last dim. + if not x.is_contiguous(): + raise ValueError("x must be contiguous") + if not y.is_contiguous(): + raise ValueError("y must be contiguous") + if attn_norm_weights is not None: + if not attn_norm_weights.is_contiguous(): + raise ValueError("weights must be contiguous") + out = torch.empty_like(x) + x_arg = x.reshape(-1, x.shape[-1]) + y_arg = y.reshape(-1, x.shape[-1]) + M, N = x_arg.shape + # Less than 64KB per feature: enqueue fused kernel + MAX_FUSED_SIZE = 65536 // x.element_size() + BLOCK_SIZE = min(MAX_FUSED_SIZE, triton.next_power_of_2(N)) + BLOCK_SIZE = max(BLOCK_SIZE, 128) + BLOCK_SIZE = min(BLOCK_SIZE, 8192) + # heuristics for number of warps + num_warps = min(max(BLOCK_SIZE // 256, 1), 8) + with torch.cuda.device(x.device): + _rms_norm_add_kernel[(M,)]( + x_arg, + y_arg, + out, + attn_norm_weights, + eps, + x_arg.stride(0), + N, + BLOCK_SIZE=BLOCK_SIZE, + num_warps=num_warps, + INCLUDE_WEIGHT=attn_norm_weights is not None, + ) + return out diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/rope_padded_kernels.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/rope_padded_kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..28977608300ed42dfd957c2fe9249efcb4bf0ea5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/rope_padded_kernels.py @@ -0,0 +1,222 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. +import triton # type: ignore +import triton.language as tl # type: ignore + +from xformers.triton.importing import libdevice_find + +pow = libdevice_find("pow") + + +@triton.jit +def _rope_padded_kernel( + xq, + xk, + xv, + out_q, + cache_k, + cache_v, + seqstartq, + seqstartk, + seqlenk, + theta, + linear_scale, + use_dynamic_scaling: tl.constexpr, + dynamic_old_context_len: tl.constexpr, + dynamic_scale_factor: tl.constexpr, + dynamic_low_freq_factor: tl.constexpr, + dynamic_high_freq_factor: tl.constexpr, + first_seqpos, + seqpos, + k_start: tl.constexpr, + v_start: tl.constexpr, + n_groups, + dim: tl.constexpr, # dimension of each head + stride_xqM, + stride_xqG, + stride_xqH, + stride_xkM, + stride_xkG, + stride_xkH, + stride_xvM, + stride_xvG, + stride_xvH, + stride_cachekM, + stride_cachekG, + stride_cachekH, + stride_cachevM, + stride_cachevG, + stride_cachevH, + stride_seqstartq, + stride_seqstartk, + stride_seqlenk, + stride_outqM, + stride_outqG, + stride_outqH, + stride_seqpos, + internal_dtype: tl.constexpr, + # If True, seqstartq and seqstartk are not used but rather we + # assume that every batch element has the same number of + # queries (i.e. num_queries := tl.num_programs(1) ) + # and the same cache space cache_padding_length. + # Always False when called below. + const_batch_strides: tl.constexpr, + # If const_batch_strides==True, the common cache length for each batch element. + # (Only the first seqlenk[i] elements are actually in use, and only the last + # num_queries of those are actually written to.) + cache_padding_length, + # offset added to all values in seqlenk before using them. + # Always 0 when called below. + seqlenk_shift: tl.constexpr, + BLOCK_SIZE: tl.constexpr, + adjacents: tl.constexpr, +): + """ + Each letter in this diagram is a whole row of length dim. + + INPUT xq xk xv + + head_dim ─► + + batch qqqqqq kk vv + │ qqqqqq kk vv + ▼ qqqqqq kk vv + + head_idx: (goes across all heads of all 3 inputs) + ▲ ▲ ▲ ▲ ▲ ▲ + │ │ │ │ │ │ + │ │ + 0 k_start │v_start │n_total_heads + │ │ + │ │ + k_start v_start + + Output is to out_q (same shape as xq), an xk-shaped part + of cache_k and an xv-shaped part of cache_v + """ + query_pos_in_batch_elt = tl.program_id(0) + batch_elt = tl.program_id(1) + group_head_idx = tl.program_id(2) + group_idx = group_head_idx % n_groups + head_idx = group_head_idx // n_groups + + if internal_dtype == "f32": + theta = theta.to(tl.float32) + elif internal_dtype == "f64": + theta = theta.to(tl.float64) + + if const_batch_strides: + query_pos = query_pos_in_batch_elt + tl.num_programs(1) * batch_elt + end_query_pos = tl.num_programs(1) * (batch_elt + 1) + else: + query_pos = query_pos_in_batch_elt + tl.load( + seqstartq + batch_elt * stride_seqstartq + ) + end_query_pos = tl.load(seqstartq + (batch_elt + 1) * stride_seqstartq) + if query_pos >= end_query_pos: + return + + is_q = head_idx < k_start + is_v = head_idx >= v_start + + xq += query_pos * stride_xqM + head_idx * stride_xqH + group_idx * stride_xqG + out_q += ( + query_pos * stride_outqM + head_idx * stride_outqH + group_idx * stride_outqG + ) + + if const_batch_strides: + cache_start = cache_padding_length * batch_elt + else: + cache_start = tl.load(seqstartk + batch_elt * stride_seqstartk) + end_of_batch_elt_cache = ( + cache_start + tl.load(seqlenk + batch_elt * stride_seqlenk) + seqlenk_shift + ) + + cache_pos = end_of_batch_elt_cache - (end_query_pos - query_pos) + if seqpos is not None: + seq_pos = tl.load(seqpos + query_pos * stride_seqpos) + else: + seq_pos = cache_pos - cache_start + if first_seqpos is not None: + seq_pos += tl.load(first_seqpos + batch_elt * stride_seqpos) + cache_k += ( + (head_idx - k_start) * stride_cachekH + + cache_pos * stride_cachekM + + group_idx * stride_cachekG + ) + xk += ( + query_pos * stride_xkM + + (head_idx - k_start) * stride_xkH + + group_idx * stride_xkG + ) + in_qk = tl.where(is_q, xq, xk) + out_qk = tl.where(is_q, out_q, cache_k) + + cache_v += ( + (head_idx - v_start) * stride_cachevH + + cache_pos * stride_cachevM + + group_idx * stride_cachevG + ) + xv += ( + query_pos * stride_xvM + + (head_idx - v_start) * stride_xvH + + group_idx * stride_xvG + ) + + out = tl.where(is_v, cache_v, out_qk) + x_in = tl.where(is_v, xv, in_qk) + + for offset in range(0, dim // 2, BLOCK_SIZE // 2): + c = tl.arange(0, BLOCK_SIZE // 2) + powers = (offset + c) * 2.0 + if adjacents: + cols_re = (offset + c) * 2 + cols_im = cols_re + 1 + else: + cols_re = offset + c + cols_im = cols_re + dim // 2 + + mask = cols_im < dim + + re_x = tl.load(x_in + cols_re, mask=mask) + im_x = tl.load(x_in + cols_im, mask=mask) + # freqs = seq_pos / (theta ** (powers / dim)) + freqs = pow(theta, powers / (-dim)) + + if use_dynamic_scaling: + lo_freq_wavelen = dynamic_old_context_len / dynamic_low_freq_factor + hi_freq_wavelen = dynamic_old_context_len / dynamic_high_freq_factor + + wavelens = 6.28318530718 / freqs # 2*pi + is_low_freq = wavelens > lo_freq_wavelen + freqs = tl.where(is_low_freq, freqs / dynamic_scale_factor, freqs) + + is_mid_freq = hi_freq_wavelen < wavelens and wavelens <= lo_freq_wavelen + + smooth = (dynamic_old_context_len / wavelens - dynamic_low_freq_factor) / ( + dynamic_high_freq_factor - dynamic_low_freq_factor + ) + freqs = tl.where( + is_mid_freq, + (1 - smooth) * freqs / dynamic_scale_factor + smooth * freqs, + freqs, + ) + + freqs = seq_pos * freqs / linear_scale + sines = tl.sin(freqs) + cosines = tl.cos(freqs) + re_out = re_x * cosines - im_x * sines + im_out = im_x * cosines + re_x * sines + + re_out_ = tl.where(is_v, re_x, re_out) + im_out_ = tl.where(is_v, im_x, im_out) + if internal_dtype == "f64": + if re_x.dtype == tl.bfloat16: + # triton 2.0.0 crashes if you try to convert + # float64 directly to bfloat16, so make an intermediate step. + re_out_ = re_out_.to(tl.float32) + im_out_ = im_out_.to(tl.float32) + tl.store(out + cols_re, re_out_, mask=mask) + tl.store(out + cols_im, im_out_, mask=mask) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/tiled_matmul_kernels.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/tiled_matmul_kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..7fc1171db92cf13488bbe405a9e7d4014c0325fe --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/_triton/tiled_matmul_kernels.py @@ -0,0 +1,436 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import itertools +from typing import List, Tuple + +import torch +import triton +import triton.language as tl + +from xformers.ops._triton.matmul_perf_model import ( + early_config_prune, + estimate_matmul_time, +) + + +def init_to_zero(*names): + def result(nargs): + for name in names: + nargs[name].zero_() + + return result + + +def gen_config( + block_m: int, + block_n: int, + block_k: int, + stages: int, + warps: int, + split_k: int = 1, + group_m: int = 8, +) -> triton.Config: + """A more compact way to define a triton.Config, so it fits on one line""" + + return triton.Config( + { + "BLOCK_M": block_m, + "BLOCK_N": block_n, + "BLOCK_K": block_k, + "SPLIT_K": split_k, + "GROUP_M": group_m, + }, + num_stages=stages, + num_warps=warps, + pre_hook=( + init_to_zero(*[f"C{i+1}{j+1}" for i in range(3) for j in range(3)]) + if split_k > 1 + else init_to_zero() + ), + ) + + +BASIC_MATMUL_CONFIGS = [ + gen_config(block_m=128, block_n=256, block_k=32, stages=3, warps=8), + gen_config(block_m=256, block_n=128, block_k=32, stages=3, warps=8), + gen_config(block_m=256, block_n=64, block_k=32, stages=4, warps=4), + gen_config(block_m=64, block_n=256, block_k=32, stages=4, warps=4), + gen_config(block_m=128, block_n=128, block_k=32, stages=4, warps=4), + gen_config(block_m=128, block_n=64, block_k=32, stages=4, warps=4), + gen_config(block_m=64, block_n=128, block_k=32, stages=4, warps=4), + gen_config(block_m=128, block_n=32, block_k=32, stages=4, warps=4), + gen_config(block_m=64, block_n=32, block_k=32, stages=5, warps=2), +] + + +INT8_MATMUL_CONFIGS = [ + gen_config(block_m=128, block_n=256, block_k=128, stages=3, warps=8), + gen_config(block_m=256, block_n=128, block_k=128, stages=3, warps=8), + gen_config(block_m=256, block_n=64, block_k=128, stages=4, warps=4), + gen_config(block_m=64, block_n=256, block_k=128, stages=4, warps=4), + gen_config(block_m=128, block_n=128, block_k=128, stages=4, warps=4), + gen_config(block_m=128, block_n=64, block_k=64, stages=4, warps=4), + gen_config(block_m=64, block_n=128, block_k=64, stages=4, warps=4), + gen_config(block_m=128, block_n=32, block_k=64, stages=4, warps=4), + gen_config(block_m=64, block_n=32, block_k=64, stages=5, warps=2), +] + + +IO_BOUND_MATMUL_CONFIGS_STAGES = [2, 3, 4, 5, 6] +IO_BOUND_MATMUL_CONFIGS_BLOCK_M = [16, 32] +IO_BOUND_MATMUL_CONFIGS_BLOCK_K = [32, 64] +IO_BOUND_MATMUL_CONFIGS_BLOCK_N = [32, 64, 128, 256] +IO_BOUND_MATMUL_CONFIGS_SPLIT_K = [1, 2, 4, 8, 16] + + +IO_BOUND_MATMUL_CONFIGS = [ + gen_config( + block_m=block_m, + block_n=block_n, + block_k=block_k, + stages=stages, + warps=2 if block_n <= 64 else 4, + split_k=split_k, + ) + for stages, block_m, block_k, block_n, split_k in itertools.product( + IO_BOUND_MATMUL_CONFIGS_STAGES, + IO_BOUND_MATMUL_CONFIGS_BLOCK_M, + IO_BOUND_MATMUL_CONFIGS_BLOCK_K, + IO_BOUND_MATMUL_CONFIGS_BLOCK_N, + IO_BOUND_MATMUL_CONFIGS_SPLIT_K, + ) +] + + +TRITON_CONFIGS = BASIC_MATMUL_CONFIGS + INT8_MATMUL_CONFIGS + IO_BOUND_MATMUL_CONFIGS + + +def our_estimate_matmul_time( + A11, B11, C11, M1, M2, M3, N1, N2, N3, K1, K2, K3, **kwargs +): + """Call into Triton's upstream cost model, with the right args + + The upstream function expects arguments to have certain names. Since we + renamed a few of them in our implementation, we rename them back. + + At the time of writing (July 2023) the arguments that Triton expects are: + M, N, K, A, B, C, BLOCK_M, BLOCK_N, BLOCK_K, SPLIT_K, num_warps, num_stages. + + """ + return estimate_matmul_time( + M=M1 + M2 + M3, N=N1 + N2 + N3, K=K1 + K2 + K3, A=A11, B=B11, C=C11, **kwargs + ) + + +def our_early_config_prune(config, named_args, **kwargs): + new_named_args = named_args.copy() + new_named_args["M"] = named_args["M1"] + named_args["M2"] + named_args["M3"] + new_named_args["N"] = named_args["N1"] + named_args["N2"] + named_args["N3"] + new_named_args["K"] = named_args["K1"] + named_args["K2"] + named_args["K3"] + new_named_args["A"] = named_args["A11"] + new_named_args["B"] = named_args["B11"] + new_named_args["C"] = named_args["C11"] + return early_config_prune(config, new_named_args, **kwargs) + + +@triton.autotune( + configs=TRITON_CONFIGS, + key=["M1", "M2", "M3", "N1", "N2", "N3", "K1", "K2", "K3"], + prune_configs_by={ + "early_config_prune": our_early_config_prune, + "perf_model": our_estimate_matmul_time, + "top_k": 10, + }, +) +@triton.heuristics( + { + "EVEN_K": lambda args: all( + k % (args["BLOCK_K"] * args["SPLIT_K"]) == 0 + for k in [args["K1"], args["K2"], args["K3"]] + ), + } +) +@triton.jit() +def _xformers_tiled_matmul_kernel( + A11, + A12, + A13, + A21, + A22, + A23, + A31, + A32, + A33, + B11, + B12, + B13, + B21, + B22, + B23, + B31, + B32, + B33, + C11, + C12, + C13, + C21, + C22, + C23, + C31, + C32, + C33, + M1, + M2, + M3, + N1, + N2, + N3, + K1, + K2, + K3, + stride_am1, + stride_am2, + stride_am3, + stride_ak1, + stride_ak2, + stride_ak3, + stride_bk1, + stride_bk2, + stride_bk3, + stride_bn1, + stride_bn2, + stride_bn3, + stride_cm1, + stride_cm2, + stride_cm3, + stride_cn1, + stride_cn2, + stride_cn3, + BLOCK_M: tl.constexpr, # DO NOT CHANGE NAME: MUST MATCH PERF MODEL + BLOCK_N: tl.constexpr, # DO NOT CHANGE NAME: MUST MATCH PERF MODEL + BLOCK_K: tl.constexpr, # DO NOT CHANGE NAME: MUST MATCH PERF MODEL + GROUP_M: tl.constexpr, + SPLIT_K: tl.constexpr, # DO NOT CHANGE NAME: MUST MATCH PERF MODEL + EVEN_K: tl.constexpr, + ACC_TYPE: tl.constexpr, +): + # matrix multiplication + pid = tl.program_id(0) + pid_k = tl.program_id(1) + grid_m1 = tl.cdiv(M1, BLOCK_M) + grid_m2 = tl.cdiv(M2, BLOCK_M) + grid_m3 = tl.cdiv(M3, BLOCK_M) + grid_n1 = tl.cdiv(N1, BLOCK_N) + grid_n2 = tl.cdiv(N2, BLOCK_N) + grid_n3 = tl.cdiv(N3, BLOCK_N) + grid_m = grid_m1 + grid_m2 + grid_m3 + grid_n = grid_n1 + grid_n2 + grid_n3 + + # re-order program ID for better L2 performance + width = GROUP_M * grid_n + group_id = pid // width + group_size = min(grid_m - group_id * GROUP_M, GROUP_M) + pid_m = group_id * GROUP_M + (pid % group_size) + pid_n = (pid % width) // (group_size) + + # We use tl.where to circumvent a regression in alignment auto-detection: + # https://github.com/openai/triton/issues/1784 + + A1 = tl.where(pid_m < grid_m1, A11, tl.where(pid_m < grid_m1 + grid_m2, A21, A31)) + A2 = tl.where(pid_m < grid_m1, A12, tl.where(pid_m < grid_m1 + grid_m2, A22, A32)) + A3 = tl.where(pid_m < grid_m1, A13, tl.where(pid_m < grid_m1 + grid_m2, A23, A33)) + B1 = tl.where(pid_n < grid_n1, B11, tl.where(pid_n < grid_n1 + grid_n2, B12, B13)) + B2 = tl.where(pid_n < grid_n1, B21, tl.where(pid_n < grid_n1 + grid_n2, B22, B23)) + B3 = tl.where(pid_n < grid_n1, B31, tl.where(pid_n < grid_n1 + grid_n2, B32, B33)) + C = tl.where( + pid_m < grid_m1, + tl.where(pid_n < grid_n1, C11, tl.where(pid_n < grid_n1 + grid_n2, C12, C13)), + tl.where( + pid_m < grid_m1 + grid_m2, + tl.where( + pid_n < grid_n1, C21, tl.where(pid_n < grid_n1 + grid_n2, C22, C23) + ), + tl.where( + pid_n < grid_n1, C31, tl.where(pid_n < grid_n1 + grid_n2, C32, C33) + ), + ), + ) + M = tl.where(pid_m < grid_m1, M1, tl.where(pid_m < grid_m1 + grid_m2, M2, M3)) + N = tl.where(pid_n < grid_n1, N1, tl.where(pid_n < grid_n1 + grid_n2, N2, N3)) + stride_ak = tl.where( + pid_m < grid_m1, + stride_ak1, + tl.where(pid_m < grid_m1 + grid_m2, stride_ak2, stride_ak3), + ) + stride_bk = tl.where( + pid_n < grid_n1, + stride_bk1, + tl.where(pid_n < grid_n1 + grid_n2, stride_bk2, stride_bk3), + ) + stride_cn = tl.where( + pid_m < grid_m1, + stride_cn1, + tl.where(pid_m < grid_m1 + grid_m2, stride_cn2, stride_cn3), + ) + stride_cm = tl.where( + pid_n < grid_n1, + stride_cm1, + tl.where(pid_n < grid_n1 + grid_n2, stride_cm2, stride_cm3), + ) + pid_m = tl.where( + pid_m < grid_m1, + pid_m, + tl.where(pid_m < grid_m1 + grid_m2, pid_m - grid_m1, pid_m - grid_m1 - grid_m2), + ) + pid_n = tl.where( + pid_n < grid_n1, + pid_n, + tl.where(pid_n < grid_n1 + grid_n2, pid_n - grid_n1, pid_n - grid_n1 - grid_n2), + ) + + # do matrix multiplication + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + ram = tl.max_contiguous(tl.multiple_of(rm % M, BLOCK_M), BLOCK_M) + rbn = tl.max_contiguous(tl.multiple_of(rn % N, BLOCK_N), BLOCK_N) + # pointers + acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=ACC_TYPE) + grid_k1 = tl.cdiv(K1, BLOCK_K) + grid_k2 = tl.cdiv(K2, BLOCK_K) + grid_k3 = tl.cdiv(K3, BLOCK_K) + for tile in range(pid_k, grid_k1 + grid_k2 + grid_k3, SPLIT_K): + A = tl.where(tile < grid_k1, A1, tl.where(tile < grid_k1 + grid_k2, A2, A3)) + B = tl.where(tile < grid_k1, B1, tl.where(tile < grid_k1 + grid_k2, B2, B3)) + K = tl.where(tile < grid_k1, K1, tl.where(tile < grid_k1 + grid_k2, K2, K3)) + stride_am = tl.where( + tile < grid_k1, + stride_am1, + tl.where(tile < grid_k1 + grid_k2, stride_am2, stride_am3), + ) + stride_bn = tl.where( + tile < grid_k1, + stride_bn1, + tl.where(tile < grid_k1 + grid_k2, stride_bn2, stride_bn3), + ) + my_tile = tl.where( + tile < grid_k1, + tile, + tl.where( + tile < grid_k1 + grid_k2, tile - grid_k1, tile - grid_k1 - grid_k2 + ), + ) + rk = my_tile * BLOCK_K + tl.arange(0, BLOCK_K) + Ain = A + (ram[:, None] * stride_am + rk[None, :] * stride_ak) + Bin = B + (rk[:, None] * stride_bk + rbn[None, :] * stride_bn) + if EVEN_K: + a = tl.load(Ain) + b = tl.load(Bin) + else: + a = tl.load(Ain, mask=rk[None, :] < K, other=0.0) + b = tl.load(Bin, mask=rk[:, None] < K, other=0.0) + acc += tl.dot(a, b, allow_tf32=False) + acc = acc.to(C.dtype.element_ty) + # rematerialize rm and rn to save registers + rm = pid_m * BLOCK_M + tl.arange(0, BLOCK_M) + rn = pid_n * BLOCK_N + tl.arange(0, BLOCK_N) + C = C + (rm[:, None] * stride_cm + rn[None, :] * stride_cn) + mask = (rm < M)[:, None] & (rn < N)[None, :] + # handles write-back with reduction-splitting + if SPLIT_K == 1: + tl.store(C, acc, mask=mask) + else: + tl.atomic_add(C, acc, mask=mask) + + +def _check_row_or_column(row_or_col_type, row_or_col_idx, tensor_name, dim_name, vals): + assert len(vals) > 0 + for pos, val in enumerate(vals[1:]): + assert val == vals[0], ( + f"the tensors on {row_or_col_type} {row_or_col_idx} of the {tensor_name} " + f"must all have the same stride along the {dim_name} dimension, got " + f"{vals[0]} at position 0 and {val} at position {pos + 1}" + ) + return vals[0] + + +def _get_strides( + ts: List[List[torch.Tensor]], tensor_name, dim_0_name, dim_1_name +) -> Tuple[List[int], List[int]]: + strides_0 = [ + _check_row_or_column( + "column", idx, tensor_name, dim_0_name, [y.stride(0) for y in x] + ) + for idx, x in enumerate(zip(*ts)) + ] + strides_1 = [ + _check_row_or_column( + "row", idx, tensor_name, dim_1_name, [y.stride(1) for y in x] + ) + for idx, x in enumerate(ts) + ] + assert all(s == 1 for s in strides_0) or all(s == 1 for s in strides_1) + while len(strides_0) < 3: + strides_0.append(1 if strides_0[0] == 1 else 0) + while len(strides_1) < 3: + strides_1.append(1 if strides_1[0] == 1 else 0) + return strides_0, strides_1 + + +def _launch_triton_matmul( + a: List[List[torch.Tensor]], + b: List[List[torch.Tensor]], + c: List[List[torch.Tensor]], + ms: List[int], + ns: List[int], + ks: List[int], +) -> None: + strides_am, strides_ak = _get_strides(a, "first operand", "m", "k") + strides_bk, strides_bn = _get_strides(b, "second operand", "k", "n") + strides_cm, strides_cn = _get_strides(c, "output", "m", "n") + + # accumulator types + ACC_TYPE = ( + tl.float32 + if c[0][0].dtype in [torch.float16, torch.bfloat16, torch.float32] + else tl.int32 + ) + + # launch kernel + def grid(META): + return ( + sum(triton.cdiv(m, META["BLOCK_M"]) for m in ms) + * sum(triton.cdiv(n, META["BLOCK_N"]) for n in ns), + META["SPLIT_K"], + ) + + _xformers_tiled_matmul_kernel[grid]( + *[ + a[min(i, len(a) - 1)][min(j, len(a[0]) - 1)] + for i in range(3) + for j in range(3) + ], + *[ + b[min(i, len(b) - 1)][min(j, len(b[0]) - 1)] + for i in range(3) + for j in range(3) + ], + *[ + c[min(i, len(c) - 1)][min(j, len(c[0]) - 1)] + for i in range(3) + for j in range(3) + ], + *[ms[i] if len(ms) > i else 0 for i in range(3)], + *[ns[i] if len(ns) > i else 0 for i in range(3)], + *[ks[i] if len(ks) > i else 0 for i in range(3)], + *strides_am, + *strides_ak, + *strides_bk, + *strides_bn, + *strides_cm, + *strides_cn, + ACC_TYPE=ACC_TYPE, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/common.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/common.py new file mode 100644 index 0000000000000000000000000000000000000000..f31fde7332be7e2156fad13406fb5df773f11427 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/common.py @@ -0,0 +1,64 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Any, Dict, List, Type, TypeVar + +import torch + + +def get_operator(library: str, name: str): + def no_such_operator(*args, **kwargs): + raise RuntimeError( + f"No such operator {library}::{name} - did you forget to build xformers with `python setup.py develop`?" + ) + + try: + return getattr(getattr(torch.ops, library), name) + except (RuntimeError, AttributeError): + return no_such_operator + + +def get_xformers_operator(name: str): + return get_operator("xformers", name) + + +class BaseOperator: + OPERATOR: Any + NAME: str + OPERATOR_CATEGORY: str + + @classmethod + def is_available(cls) -> bool: + # cls.OPERATOR can be either a kernel or a Triton Autotuner object, which doesn't have __name__ + if ( + cls.OPERATOR is None + or getattr(cls.OPERATOR, "__name__", "") == "no_such_operator" + ): + return False + return True + + +OPERATORS_REGISTRY: List[Type[BaseOperator]] = [] +FUNC_TO_XFORMERS_OPERATOR: Dict[Any, Type[BaseOperator]] = {} + +ClsT = TypeVar("ClsT") + + +def register_operator(cls: ClsT) -> ClsT: + global OPERATORS_REGISTRY, FUNC_TO_XFORMERS_OPERATOR + OPERATORS_REGISTRY.append(cls) # type: ignore + FUNC_TO_XFORMERS_OPERATOR[cls.OPERATOR] = cls # type: ignore + return cls + + +# post-2.0, avoids a warning +# (`torch.Tensor.storage` will also be deleted in the future) +_GET_TENSOR_STORAGE = getattr(torch.Tensor, "untyped_storage", None) +if _GET_TENSOR_STORAGE is None: # pre-2.0, `untyped_storage` didn't exist + _GET_TENSOR_STORAGE = torch.Tensor.storage + + +def _get_storage_base(x: torch.Tensor) -> int: + return _GET_TENSOR_STORAGE(x).data_ptr() # type: ignore diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/differentiable_collectives.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/differentiable_collectives.py new file mode 100644 index 0000000000000000000000000000000000000000..9d87629dd1611fca3ef98eb7a91b3ffa7b11aec1 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/differentiable_collectives.py @@ -0,0 +1,174 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +from typing import Optional, Tuple + +import torch +import torch.distributed + + +def all_reduce( + x: torch.Tensor, *, process_group: torch.distributed.ProcessGroup +) -> None: + mp_size = process_group.size() + if mp_size == 1: + return + + torch.distributed.all_reduce( + tensor=x, op=torch.distributed.ReduceOp.SUM, group=process_group + ) + + +def gather_along_first_dim_async( + input_: torch.Tensor, *, process_group: torch.distributed.ProcessGroup +) -> Tuple[torch.Tensor, Optional[torch.distributed.Work]]: + mp_size = process_group.size() + if mp_size == 1: + return input_, None + + output = input_.new_empty((input_.shape[0] * mp_size,) + input_.shape[1:]) + handle = torch.distributed.all_gather_into_tensor( + output_tensor=output, + input_tensor=input_, + group=process_group, + async_op=True, + ) + + return output, handle + + +def reduce_scatter_along_first_dim_async( + input_: torch.Tensor, *, process_group: torch.distributed.ProcessGroup +) -> Tuple[torch.Tensor, Optional[torch.distributed.Work]]: + mp_size = process_group.size() + if mp_size == 1: + return input_, None + + assert input_.shape[0] % mp_size == 0 + output = input_.new_empty((input_.shape[0] // mp_size,) + input_.shape[1:]) + handle = torch.distributed.reduce_scatter_tensor( + output=output, + input=input_, + op=torch.distributed.ReduceOp.SUM, + group=process_group, + async_op=True, + ) + + return output, handle + + +def gather_along_first_dim( + input_: torch.Tensor, *, process_group: torch.distributed.ProcessGroup +) -> torch.Tensor: + output, handle = gather_along_first_dim_async(input_, process_group=process_group) + if handle is not None: + handle.wait() + return output + + +def reduce_scatter_along_first_dim( + input_: torch.Tensor, *, process_group: torch.distributed.ProcessGroup +) -> torch.Tensor: + output, handle = reduce_scatter_along_first_dim_async( + input_, process_group=process_group + ) + if handle is not None: + handle.wait() + return output + + +class _CopyToModelParallelRegion(torch.autograd.Function): + @staticmethod + def forward( # type: ignore[override] + ctx, input_: torch.Tensor, process_group: torch.distributed.ProcessGroup + ) -> torch.Tensor: + ctx.process_group = process_group + return input_ + + @staticmethod + def backward( # type: ignore[override] + ctx, grad_output: torch.Tensor + ) -> Tuple[torch.Tensor, None]: + all_reduce(grad_output, process_group=ctx.process_group) + return grad_output, None + + +def copy_to_model_parallel_region( + x: torch.Tensor, process_group: torch.distributed.ProcessGroup +) -> torch.Tensor: + return _CopyToModelParallelRegion.apply(x, process_group) + + +class _ReduceFromModelParallelRegion(torch.autograd.Function): + @staticmethod + def forward( # type: ignore[override] + ctx, input_: torch.Tensor, process_group: torch.distributed.ProcessGroup + ) -> torch.Tensor: + all_reduce(input_, process_group=process_group) + ctx.mark_dirty(input_) + return input_ + + @staticmethod + def backward( # type: ignore[override] + ctx, grad_output: torch.Tensor + ) -> Tuple[torch.Tensor, None]: + return grad_output, None + + +def reduce_from_model_parallel_region( + x: torch.Tensor, process_group: torch.distributed.ProcessGroup +) -> torch.Tensor: + return _ReduceFromModelParallelRegion.apply(x, process_group) + + +class _GatherFromSequenceParallelRegion(torch.autograd.Function): + @staticmethod + def forward( # type: ignore[override] + ctx, x: torch.Tensor, process_group: torch.distributed.ProcessGroup + ) -> torch.Tensor: + ctx.process_group = process_group + return gather_along_first_dim(x, process_group=process_group) + + @staticmethod + def backward( # type: ignore[override] + ctx, grad_output: torch.Tensor + ) -> Tuple[torch.Tensor, None]: + return ( + reduce_scatter_along_first_dim( + grad_output, process_group=ctx.process_group + ), + None, + ) + + +def gather_from_sequence_parallel_region( + x: torch.Tensor, process_group: torch.distributed.ProcessGroup +) -> torch.Tensor: + return _GatherFromSequenceParallelRegion.apply(x, process_group) + + +class _ScatterToSequenceParallelRegion(torch.autograd.Function): + @staticmethod + def forward( # type: ignore[override] + ctx, x: torch.Tensor, process_group: torch.distributed.ProcessGroup + ) -> torch.Tensor: + ctx.process_group = process_group + return reduce_scatter_along_first_dim(x, process_group=process_group) + + @staticmethod + def backward( # type: ignore[override] + ctx, grad_output: torch.Tensor + ) -> Tuple[torch.Tensor, None]: + return ( + gather_along_first_dim(grad_output, process_group=ctx.process_group), + None, + ) + + +def scatter_to_sequence_parallel_region( + x: torch.Tensor, process_group: torch.distributed.ProcessGroup +) -> torch.Tensor: + return _ScatterToSequenceParallelRegion.apply(x, process_group) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..075a18886b0ea1e8308b068cdeb9362d677a0f72 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__init__.py @@ -0,0 +1,898 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Any, cast, List, Optional, Sequence, Tuple, Type, Union + +import torch + +from . import ( + attn_bias, + ck, + ck_decoder, + ck_splitk, + cutlass, + flash, + flash3, + triton_splitk, +) +from .attn_bias import ( + AttentionBias, + BlockDiagonalMask, + LowerTriangularMask, + VARLEN_BIASES, +) +from .common import ( + AttentionBwOpBase, + AttentionFwOpBase, + AttentionOp, + AttentionOpBase, + bmk2bmhk, + Context, + Gradients, + Inputs, +) +from .dispatch import ( + _dispatch_bw, + _dispatch_fw, + _ensure_op_supports_or_raise, + _get_use_fa3, + _set_use_fa3, +) + +MemoryEfficientAttentionCutlassOp = (cutlass.FwOp, cutlass.BwOp) +MemoryEfficientAttentionCutlassFwdFlashBwOp = (cutlass.FwOp, flash.BwOp) +MemoryEfficientAttentionFlashAttentionOp = (flash.FwOp, flash.BwOp) +MemoryEfficientAttentionCkOp = (ck.FwOp, ck.BwOp) +MemoryEfficientAttentionCkDecoderOp = (ck_decoder.FwOp, ck.BwOp) +MemoryEfficientAttentionSplitKCkOp = (ck_splitk.FwOp, ck.BwOp) + + +def _deserialize_bias(attn_bias_ctx, attn_bias_tensor: Optional[torch.Tensor]) -> Any: + if attn_bias_tensor is None: + return attn_bias_ctx + return attn_bias_tensor + + +# Note: `torch.compile` only allows custom autograd functions +# to accept a subset of types. Therefore we serialize `op` objects +# to `str` before entering the function, and unserialize them inside. +# See also: https://github.com/pytorch/pytorch/issues/118395 +_OPS_LOOKUP = { + flash.FwOp.NAME: flash.FwOp, + flash.BwOp.NAME: flash.BwOp, +} + + +def _serialize_op(op): + if op is not None and op.NAME in _OPS_LOOKUP: + return op.NAME + return op + + +def _unserialize_op(op): + if isinstance(op, str): + return _OPS_LOOKUP[op] + return op + + +class _fMHA(torch.autograd.Function): + @staticmethod + # type: ignore + def forward(ctx, op_fw, op_bw, *args: Any) -> Any: + inp = Inputs(*args) + + op_fw = _unserialize_op(op_fw) + op_bw = _unserialize_op(op_bw) + + out, op_ctx = _memory_efficient_attention_forward_requires_grad( + inp=inp, op=op_fw + ) + + # Saving attn_bias is a bit complicated, as the + # torch part should go in `save_for_backward` + if isinstance(inp.attn_bias, torch.Tensor): + attn_bias_tensor = inp.attn_bias + attn_bias_ctx = None + else: + attn_bias_tensor = None + attn_bias_ctx = inp.attn_bias + + ctx.save_for_backward( + inp.query, + inp.key, + inp.value, + op_ctx.out, + op_ctx.lse, + ) + ctx.rng_state = op_ctx.rng_state + ctx.attn_bias_tensor = attn_bias_tensor + if op_ctx.op_bw is not None: + if op_bw is not None and op_bw is not op_ctx.op_bw: + raise ValueError( + f"Specified op_bw={op_bw.NAME}, but forward op " + f"can only run with op_bw={op_ctx.op_bw.NAME}. Please set op_bw=None." + ) + op_bw = op_ctx.op_bw + if ( + op_fw is not None + and op_bw is not None + and isinstance(inp.attn_bias, VARLEN_BIASES) + and inp.attn_bias.q_seqinfo.seqstart.shape[0] > 2 + and op_bw.VARLEN_LSE_PACKED != op_fw.VARLEN_LSE_PACKED + ): + raise ValueError( + f"Specified op_bw={op_bw.NAME} is not compatible with the " + f"op_fw={op_fw.NAME}, because they use different format of logsumexp. " + f"NOTE: This is new with xFormers 0.0.28" + ) + if op_bw is None and ( + inp.query.requires_grad or inp.key.requires_grad or inp.value.requires_grad + ): + varlen_lse_packed = _detect_lse_packed_or_raise(op_ctx.lse, inp) + if varlen_lse_packed is not None and op_fw is not None: + assert ( + op_fw.VARLEN_LSE_PACKED == varlen_lse_packed + ), f"{op_fw.NAME}: wrong value for `VARLEN_LSE_PACKED` ?" + # NOTE: We need to check tensor strides to decide which operator we run in the BW pass. + # Unfortunately, PyTorch only allows to call this function during the FW pass, so + # we decide the operator to use now. + op_bw = _dispatch_bw(inp, varlen_lse_packed=varlen_lse_packed) + ctx.op_fw = op_fw + ctx.op_bw = op_bw + ctx.p = inp.p + # This allows to create gradients from a single storage, + # to avoid a "cat" in the BW pass. + # The heuristic is approximative, but: + # (1) It's not a big issue to create a shared storage + # (2) The heuristic needs to pass `torch.compile` + # (this is also why we run it in the FW pass, the BW pass is stricter) + ctx.qkv_share_storage = ( + inp.query.shape[0] == inp.key.shape[0] + and inp.query.shape[-1] == inp.value.shape[-1] + and inp.query.stride(-2) + == (inp.key.shape[-1] + inp.query.shape[-1] + inp.value.shape[-1]) + ) + + ctx.scale = inp.scale + ctx.attn_bias_ctx = attn_bias_ctx + ctx.n_args = len(args) + return out, op_ctx.lse + + @staticmethod + @torch.autograd.function.once_differentiable + def backward(ctx, grad, grad_lse): + # Re-create context + query, key, value, out, lse = ctx.saved_tensors + attn_bias_tensor = ctx.attn_bias_tensor + rng_state = ctx.rng_state + inp = Inputs( + query=query, + key=key, + value=value, + attn_bias=_deserialize_bias(ctx.attn_bias_ctx, attn_bias_tensor), + p=ctx.p, + scale=ctx.scale, + ) + op_ctx = Context( + lse=lse, + out=out, + rng_state=rng_state, + ) + grads = _memory_efficient_attention_backward( + ctx=op_ctx, + inp=inp, + grad=grad, + op=ctx.op_bw, + _skip_op_checks=True, + ) + return (None, None, grads.dq, grads.dk, grads.dv, grads.db) + (None,) * ( + ctx.n_args - 2 + ) + + +def memory_efficient_attention( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attn_bias: Optional[Union[torch.Tensor, AttentionBias]] = None, + p: float = 0.0, + scale: Optional[float] = None, + *, + op: Optional[AttentionOp] = None, + output_dtype: Optional[torch.dtype] = None, +) -> torch.Tensor: + """Implements the memory-efficient attention mechanism following + `"Self-Attention Does Not Need O(n^2) Memory" `_. + + :Inputs shape: + + - Input tensors must be in format ``[B, M, H, K]``, where B is the batch size, M \ + the sequence length, H the number of heads, and K the embeding size per head + + - If inputs have dimension 3, it is assumed that the dimensions are ``[B, M, K]`` and ``H=1`` + + - Inputs can also be of dimension 5 with GQA - see note below + + - Inputs can be non-contiguous - we only require the last dimension's stride to be 1 + + + :Equivalent pytorch code: + + .. code-block:: python + + scale = 1.0 / query.shape[-1] ** 0.5 + query = query * scale + query = query.transpose(1, 2) + key = key.transpose(1, 2) + value = value.transpose(1, 2) + attn = query @ key.transpose(-2, -1) + if attn_bias is not None: + attn = attn + attn_bias + attn = attn.softmax(-1) + attn = F.dropout(attn, p) + attn = attn @ value + return attn.transpose(1, 2).contiguous() + + :Examples: + + .. code-block:: python + + import xformers.ops as xops + + # Compute regular attention + y = xops.memory_efficient_attention(q, k, v) + + # With a dropout of 0.2 + y = xops.memory_efficient_attention(q, k, v, p=0.2) + + # Causal attention + y = xops.memory_efficient_attention( + q, k, v, + attn_bias=xops.LowerTriangularMask() + ) + + :Supported hardware: + + NVIDIA GPUs with compute capability above 6.0 (P100+), datatype ``f16``, ``bf16`` and ``f32``. + + :EXPERIMENTAL: Using with Multi Query Attention (MQA) and Grouped Query Attention (GQA): + + MQA/GQA is an experimental feature supported only for the forward pass. + If you have 16 heads in query, and 2 in key/value, you can provide 5-dim tensors + in the ``[B, M, G, H, K]`` format, where ``G`` is the number of head groups (here 2), and + ``H`` is the number of heads per group (8 in the example). + + Please note that xFormers will not automatically broadcast the inputs, so you will need + to broadcast it manually before calling `memory_efficient_attention`. + + :GQA/MQA example: + + .. code-block:: python + + import torch + import xformers.ops as xops + + B, M, K = 3, 32, 128 + kwargs = dict(device="cuda", dtype=torch.float16) + q = torch.randn([B, M, 8, K], **kwargs) + k = torch.randn([B, M, 2, K], **kwargs) + v = torch.randn([B, M, 2, K], **kwargs) + out_gqa = xops.memory_efficient_attention( + q.reshape([B, M, 2, 4, K]), + k.reshape([B, M, 2, 1, K]).expand([B, M, 2, 4, K]), + v.reshape([B, M, 2, 1, K]).expand([B, M, 2, 4, K]), + ) + + Raises: + NotImplementedError: if there is no operator available to compute the MHA + ValueError: if inputs are invalid + + :parameter query: Tensor of shape ``[B, Mq, H, K]`` + :parameter key: Tensor of shape ``[B, Mkv, H, K]`` + :parameter value: Tensor of shape ``[B, Mkv, H, Kv]`` + :parameter attn_bias: Bias to apply to the attention matrix - defaults to no masking. \ + For common biases implemented efficiently in xFormers, see :attr:`xformers.ops.fmha.attn_bias.AttentionBias`. \ + This can also be a :attr:`torch.Tensor` for an arbitrary mask (slower). + :parameter p: Dropout probability. Disabled if set to ``0.0`` + :parameter scale: Scaling factor for ``Q @ K.transpose()``. If set to ``None``, the default \ + scale (q.shape[-1]**-0.5) will be used. + :parameter op: The operators to use - see :attr:`xformers.ops.AttentionOpBase`. \ + If set to ``None`` (recommended), xFormers \ + will dispatch to the best available operator, depending on the inputs \ + and options. + :return: multi-head attention Tensor with shape ``[B, Mq, H, Kv]`` + """ + return _memory_efficient_attention( + Inputs( + query=query, + key=key, + value=value, + p=p, + attn_bias=attn_bias, + scale=scale, + output_dtype=output_dtype, + ), + op=op, + ) + + +torch.library.define( + "xformer::memory_efficient_attention_forward", + "(Tensor q, Tensor k, Tensor v, Tensor? b = None, float? p = 0.0, float? scale = None) -> Tensor", +) + + +@torch.library.impl("xformer::memory_efficient_attention_forward", "Meta") +def memory_efficient_attention_forward_meta(q, k, v): + return q.new_empty(q.shape) + + +# torch.compile has issue when tracing through op dispatch and ensure_op_support +# so provide a wrapper to register it as a custom torch library op. +@torch.library.impl("xformer::memory_efficient_attention_forward", "CUDA") +def memory_efficient_attention_forward_torch_wrapper( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attn_bias: Optional[Union[torch.Tensor, AttentionBias]] = None, + p: float = 0.0, + scale: Optional[float] = None, +) -> torch.Tensor: + """ + This provides a torch-compilable wrapper op to + memory_efficient_attention_forward in certain special cases. + + Note that the following are not supported + - `op` input (?) + - certain attn_bias types (?) + - output_dtype + - K != Kv + """ + return memory_efficient_attention_forward( + query, + key, + value, + attn_bias, + p, + scale, + ) + + +def memory_efficient_attention_forward( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attn_bias: Optional[Union[torch.Tensor, AttentionBias]] = None, + p: float = 0.0, + scale: Optional[float] = None, + *, + op: Optional[Type[AttentionFwOpBase]] = None, + output_dtype: Optional[torch.dtype] = None, +) -> torch.Tensor: + """ + Calculates the forward pass of :attr:`xformers.ops.memory_efficient_attention`. + """ + return _memory_efficient_attention_forward( + Inputs( + query=query, + key=key, + value=value, + p=p, + attn_bias=attn_bias, + scale=scale, + output_dtype=output_dtype, + ), + op=op, + ) + + +def memory_efficient_attention_forward_requires_grad( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attn_bias: Optional[Union[torch.Tensor, AttentionBias]] = None, + p: float = 0.0, + scale: Optional[float] = None, + *, + op: Optional[Type[AttentionFwOpBase]] = None, + output_dtype: Optional[torch.dtype] = None, +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Returns a tuple (output, lse), where `lse` can be used to compute the backward pass later. + See :attr:`xformers.ops.memory_efficient_attention` for an explanation of the arguments + See :attr:`xformers.ops.memory_efficient_attention_backward` for running the backward pass + """ + if p != 0.0: + raise NotImplementedError( + "dropout is not supported on the non-autograd API." + " If you want to use dropout, please call `memory_efficient_attention` directly" + ) + out, ctx = _memory_efficient_attention_forward_requires_grad( + Inputs( + query=query, + key=key, + value=value, + p=p, + attn_bias=attn_bias, + scale=scale, + output_dtype=output_dtype, + ), + op=op, + ) + return out, ctx.lse + + +def memory_efficient_attention_backward( + grad: torch.Tensor, + output: torch.Tensor, + lse: torch.Tensor, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attn_bias: Optional[Union[torch.Tensor, AttentionBias]] = None, + p: float = 0.0, + scale: Optional[float] = None, + *, + op: Optional[Type[AttentionBwOpBase]] = None, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Computes the gradient of the attention. + Returns a tuple (dq, dk, dv) + See :attr:`xformers.ops.memory_efficient_attention` for an explanation of the arguments. + `lse` is the tensor returned by + :attr:`xformers.ops.memory_efficient_attention_forward_requires_grad` + """ + if p != 0.0: + raise NotImplementedError( + "dropout is not supported on the non-autograd API." + " If you want to use dropout, please call `memory_efficient_attention` directly" + ) + gradients = _memory_efficient_attention_backward( + Context(out=output, lse=lse), + Inputs( + query=query, key=key, value=value, p=p, attn_bias=attn_bias, scale=scale + ), + grad, + op=op, + ) + return (gradients.dq, gradients.dk, gradients.dv) + + +def _memory_efficient_attention( + inp: Inputs, op: Optional[AttentionOp] = None +) -> torch.Tensor: + # fast-path that doesn't require computing the logsumexp for backward computation + if all(x.requires_grad is False for x in [inp.query, inp.key, inp.value]): + return _memory_efficient_attention_forward( + inp, op=op[0] if op is not None else None + ) + + output_shape = inp.normalize_bmhk() + + op_fw = _serialize_op(op[0] if op is not None else None) + op_bw = _serialize_op(op[1] if op is not None else None) + return _fMHA.apply( + op_fw, op_bw, inp.query, inp.key, inp.value, inp.attn_bias, inp.p, inp.scale + )[0].reshape(output_shape) + + +def _memory_efficient_attention_forward( + inp: Inputs, op: Optional[Type[AttentionFwOpBase]] +) -> torch.Tensor: + inp.validate_inputs() + output_shape = inp.normalize_bmhk() + if op is None: + op = _dispatch_fw(inp, False) + else: + _ensure_op_supports_or_raise(ValueError, "memory_efficient_attention", op, inp) + + out, *_ = op.apply(inp, needs_gradient=False) + return out.reshape(output_shape) + + +def _memory_efficient_attention_forward_requires_grad( + inp: Inputs, op: Optional[Type[AttentionFwOpBase]] +) -> Tuple[torch.Tensor, Context]: + inp.validate_inputs() + output_shape = inp.normalize_bmhk() + if op is None: + op = _dispatch_fw(inp, True) + else: + _ensure_op_supports_or_raise(ValueError, "memory_efficient_attention", op, inp) + out = op.apply(inp, needs_gradient=True) + assert out[1] is not None + return (out[0].reshape(output_shape), out[1]) + + +def _detect_lse_packed_or_raise(lse: torch.Tensor, inp: Inputs) -> Optional[bool]: + """ + Detects the LSE format if we're in a varlen case. + Returns `None` if the format is not relevant (eg not varlen) + Raises an exception if the `lse` has the wrong shape + """ + shape_mismatch_err = ( + "Input tensors have incompatible shapes.\n" + f" lse.shape : {lse.shape}\n" + f" query.shape : {inp.query.shape}\n" + f" attn_bias : {type(inp.attn_bias)}" + ) + # 1. Check ndim & head dimensions + # In any case, LSE should be [*, *GH] + if lse.ndim != (inp.query.ndim - 1) or lse.shape[1:-1] != inp.query.shape[2:-1]: + raise ValueError(shape_mismatch_err) + lse_bm = [lse.shape[0], lse.shape[-1]] + lse_packed_shape = [inp.query.shape[0], inp.query.shape[1]] + lse_packed = lse_bm[0] == lse_packed_shape[0] and lse_bm >= lse_packed_shape + # 2. Check correctness for varlen biases with query.shape = [1, M, *GH, K] + # Either [1, *GH, M] (packed) + # Or [num_seq, *GH, Mq] .. with `Mq >= max_q` (padded) + if isinstance(inp.attn_bias, VARLEN_BIASES): + si = inp.attn_bias.q_seqinfo + lse_padded_shape = [si.seqstart.shape[0] - 1, si.max_seqlen] + lse_padded = lse_bm[0] == lse_padded_shape[0] and lse_bm >= lse_padded_shape + if lse_packed and lse_padded: + return None + elif lse_packed: + return True + elif lse_padded: + return False + raise ValueError(shape_mismatch_err) + # 3. For non-varlen, shape must be [B, *GH] with query.shape=[B, M, *GH, K] + if not lse_packed: + raise ValueError(shape_mismatch_err) + return None + + +def _memory_efficient_attention_backward( + ctx: Context, + inp: Inputs, + grad: torch.Tensor, + op: Optional[Type[AttentionBwOpBase]], + *, + _skip_op_checks: bool = False, +) -> Gradients: + """Warning: grad/ctx.out is potentially in BMK format""" + inp.validate_inputs() + if grad.ndim != inp.query.ndim or grad.ndim != ctx.out.ndim: + raise ValueError( + "All tensors should be either in BMK (ndim=3) or BMHK (ndim=4) format. \n" + f"grad.shape : {grad.shape} \n" + f"out.shape : {ctx.out.shape} \n" + f"query.shape: {inp.query.shape}" + ) + shape_dq, shape_dk, shape_dv = tuple( + x.shape for x in (inp.query, inp.key, inp.value) + ) + inp.normalize_bmhk() + varlen_lse_packed = _detect_lse_packed_or_raise(ctx.lse, inp) + grad = bmk2bmhk(grad, 1) + ctx.out = bmk2bmhk(ctx.out, 1) + + if op is None: + op = _dispatch_bw(inp, varlen_lse_packed=varlen_lse_packed) + elif not _skip_op_checks: + _ensure_op_supports_or_raise( + ValueError, "memory_efficient_attention_backward", op, inp + ) + if varlen_lse_packed is not None and varlen_lse_packed != op.VARLEN_LSE_PACKED: + raise ValueError( + f"Wrong LSE format for {op.NAME} in variable seqlen case. " + f"Double-check that the BW operator {op.NAME} is compatible " + f"with the operator used in the FW pass." + ) + + grads = op.apply(ctx, inp, grad) + grads.dq = grads.dq.reshape(shape_dq) + grads.dk = grads.dk.reshape(shape_dk) + grads.dv = grads.dv.reshape(shape_dv) + return grads + + +def memory_efficient_attention_partial( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + attn_bias: Optional[Union[torch.Tensor, AttentionBias]] = None, + p: float = 0.0, + scale: Optional[float] = None, + *, + op: Optional[Union[AttentionOp, Type[AttentionFwOpBase]]] = None, + output_dtype: Optional[torch.dtype] = None, +) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Returns a tuple (output, lse), where `output` is the attention in the style of + memory_efficient_attention, and `lse` is extra data, a log-sum-exp. + The outputs of calls to this with the same query and separate keys and values + can be merged with merge_attentions to obtain the attention of the queries + against the disjoint union of the keys and values. + + Warning: The backward pass of this function is quite restricted. In particular + we assume that in the forward pass the outputs were only used in merge_attention + calculations, and that LSEs weren't used anywhere except in merge attentions. + """ + if p != 0.0: + raise NotImplementedError("dropout is not supported.") + fwop: Optional[Type[AttentionFwOpBase]] = op[0] if isinstance(op, tuple) else op + inp = Inputs( + query=query, + key=key, + value=value, + p=p, + attn_bias=attn_bias, + scale=scale, + output_dtype=output_dtype, + is_partial=True, + ) + + is_grad = torch.is_grad_enabled() and any( + x.requires_grad for x in [query, key, value] + ) + + if not is_grad: + out, ctx = _memory_efficient_attention_forward_requires_grad( + inp, + op=fwop, + ) + return out, ctx.lse + + if query.ndim == 5: + raise ValueError("gradients not supported for 5D tensors") + if isinstance(op, tuple): + op_fw = _serialize_op(op[0]) + op_bw = _serialize_op(op[1]) + elif op is None: + op_fw = op_bw = None + else: + op_fw = _serialize_op(op) + op_bw = None + return _fMHA.apply( + op_fw, + op_bw, + inp.query, + inp.key, + inp.value, + inp.attn_bias, + inp.p, + inp.scale, + inp.output_dtype, + inp.is_partial, + ) + + +def merge_attentions( + attn_split: Union[torch.Tensor, Sequence[torch.Tensor]], + lse_split: Union[torch.Tensor, Sequence[torch.Tensor]], + write_lse: bool = True, + output_dtype: Optional[torch.dtype] = None, +) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: + """ + Combine attention output computed on different parts of K/V for the same + query to get attention on the whole K/V. See https://arxiv.org/abs/2402.05099 + The result is equal to + Out_full = (Out1 * exp(LSE1) + Out2 * exp(LSE2) + ...) / (exp(LSE1) + exp(LSE2) + ...) + LSE_full = log(exp(LSE1) + exp(LSE2) + ...) + + Args: + attn_split: attention outputs for chunks, + either as a list of tensors of shapes [B, M, G, H, Kq] or [B, M, H, Kq] + or as a single tensor of shape [num_chunks, B, M, G, H, Kq] + or [num_chunks, B, M, H, Kq] + lse_split: LSE for chunks, + either as a list of tensors of shapes [B, G, H, M] or [B, H, M] + or as a single tensor of shape [num_chunks, B, G, H, M] or [num_chunks, B, H, M] + write_lse: whether to output LSE + output_dtype: dtype of attn_out + + Returns: + attn_out: [B, M, G, H, Kq] or [B, M, H, Kq] + lse_out: [B, G, H, M] or [B, H, M] if write_lse + or None otherwise + """ + + attn_is_concat = isinstance(attn_split, torch.Tensor) + lse_is_concat = isinstance(lse_split, torch.Tensor) + + attn_requires_grad = ( + attn_split.requires_grad # type: ignore + if attn_is_concat + else any(x.requires_grad for x in attn_split) + ) + lse_requires_grad = ( + lse_split.requires_grad # type: ignore + if lse_is_concat + else any(x.requires_grad for x in lse_split) + ) + requires_grad = torch.is_grad_enabled() and ( + attn_requires_grad or lse_requires_grad + ) + if requires_grad and not write_lse: + raise ValueError("write_lse should be true if inputs require gradients.") + + concat_path = attn_is_concat and lse_is_concat and not requires_grad + if concat_path: + attn_split = cast(torch.Tensor, attn_split) + lse_split = cast(torch.Tensor, lse_split) + if attn_split.ndim != lse_split.ndim + 1: + raise ValueError( + f"Incompatible input shapes: {attn_split.shape=}, {lse_split.shape=}" + ) + + is_bmhk = attn_split.ndim == 5 + if is_bmhk: + attn_split = attn_split.unsqueeze(3) + lse_split = lse_split.unsqueeze(2) + + num_chunks, B, M, G, H, Kq = attn_split.shape + num_chunks1, B1, G1, H1, M1 = lse_split.shape + if B != B1 or G != G1 or H != H1 or num_chunks != num_chunks1 or M != M: + raise ValueError( + f"Incompatible input shapes: {attn_split.shape=} {lse_split.shape=} " + f"{B}/{B1}, {G}/{G1}, {H}/{H1}, {num_chunks}/{num_chunks1}, {M}/{M}" + ) + + attn_split = attn_split.permute(1, 3, 4, 0, 2, 5) + lse_split = lse_split.permute(1, 2, 3, 0, 4) + + device = attn_split.device + attn_dtype = attn_split.dtype + lse_dtype = lse_split.dtype + else: + if attn_is_concat: + attn_split = attn_split.unbind(0) # type: ignore + if lse_is_concat: + lse_split = lse_split.unbind(0) # type: ignore + num_chunks = len(attn_split) + if len(lse_split) != num_chunks: + raise ValueError( + f"Incompatible number of LSE and attention chunks: {len(attn_split)=}, {len(lse_split)=}" + ) + + attn_unsqueezed = [] + lse_unsqueezed = [] + is_bmhk = False + for i in range(num_chunks): + if attn_split[i].ndim != lse_split[i].ndim + 1: + raise ValueError( + f"Incompatible input shapes for chunk {i}: {attn_split[i].shape=}, {lse_split[i].shape=}" + ) + + is_bmhk = attn_split[i].ndim == 4 + if is_bmhk: + attn_unsqueezed.append(attn_split[i].unsqueeze(2)) + lse_unsqueezed.append(lse_split[i].unsqueeze(1)) + else: + attn_unsqueezed.append(attn_split[i]) + lse_unsqueezed.append(lse_split[i]) + attn_split, lse_split = attn_unsqueezed, lse_unsqueezed + + B, M, G, H, Kq = attn_split[0].shape + B1, G1, H1, M1 = lse_split[0].shape + if B != B1 or G != G1 or H != H1 or M != M: + raise ValueError( + f"Incompatible input shapes: {attn_split[0].shape=}, {lse_split[0].shape=} " + f"{B}/{B1}, {G}/{G1}, {H}/{H1}, {M}/{M}" + ) + + for i in range(num_chunks): + if attn_split[i].shape != (B, M, G, H, Kq): + raise ValueError( + f"Incompatible input shapes for attention chunk {i}: " + f"{attn_split[i].shape=}, {(B, M, G, H, Kq)=}" + ) + if lse_split[i].shape != (B, G, H, M): + raise ValueError( + f"Incompatible input shapes for LSE chunk {i}: " + f"{lse_split[i].shape=}, {(B, G, H, M)=}" + ) + + attn_split[i] = attn_split[i].permute(0, 2, 3, 1, 4) # to (B, G, H, M, Kq) + + device = attn_split[0].device + attn_dtype = attn_split[0].dtype + lse_dtype = lse_split[0].dtype + + attn_out = torch.empty( + B, + M, + G, + H, + Kq, + device=device, + dtype=output_dtype or attn_dtype, + ) + if write_lse: + lse_out = torch.empty( + B, + G, + H, + M, + device=device, + dtype=lse_dtype, + ) + else: + lse_out = None + + if concat_path: + triton_splitk.merge_attentions(attn_out, lse_out, attn_split, lse_split) # type: ignore + else: + attn_out, lse_out = _MergeAttentions.apply(attn_out, lse_out, *attn_split, *lse_split) # type: ignore + + if is_bmhk: + attn_out = attn_out[:, :, 0] + if lse_out is not None: + lse_out = lse_out[:, 0] + + return attn_out, lse_out + + +class _MergeAttentions(torch.autograd.Function): + @staticmethod + # type: ignore + def forward( + ctx, attn_out: torch.Tensor, lse_out: torch.Tensor, *inputs: torch.Tensor + ) -> Tuple[torch.Tensor, torch.Tensor]: + num_chunks = len(inputs) // 2 + attn_split, lse_split = inputs[:num_chunks], inputs[num_chunks:] + + triton_splitk.merge_attentions_varargs(attn_out, lse_out, attn_split, lse_split) + + ctx.save_for_backward( + attn_out, + lse_out, + *inputs, + ) + return attn_out, lse_out + + @staticmethod + # type: ignore + def backward( + ctx, grad_attn: torch.Tensor, grad_lse: torch.Tensor + ) -> Tuple[Optional[torch.Tensor], ...]: + out, lse, *inputs = ctx.saved_tensors + num_chunks = len(inputs) // 2 + attn_split, lse_split = inputs[:num_chunks], inputs[num_chunks:] + dattn, dlse = triton_splitk.merge_attentions_varargs_backward( + attn_split, + lse_split, + out, + lse, + grad_attn, + grad_lse, + ) + ret = [None, None] + dattn + dlse + return tuple(ret) + + +ALL_FW_OPS: List[Type[AttentionFwOpBase]] = [ + cutlass.FwOp if torch.version.cuda else ck.FwOp, + flash.FwOp, + flash3.FwOp, + triton_splitk.FwOp, +] + +ALL_BW_OPS: List[Type[AttentionBwOpBase]] = [ + cutlass.BwOp if torch.version.cuda else ck.BwOp, + flash.BwOp, + flash3.BwOp, +] + +__all__ = [ + "AttentionBias", + "AttentionOp", + "AttentionOpBase", + "LowerTriangularMask", + "MemoryEfficientAttentionCutlassFwdFlashBwOp", + "MemoryEfficientAttentionCutlassOp", + "MemoryEfficientAttentionFlashAttentionOp", + "memory_efficient_attention", + "MemoryEfficientAttentionCkOp", + "MemoryEfficientAttentionCkDecoderOp", + "ALL_FW_OPS", + "ALL_BW_OPS", + "attn_bias", + "_get_use_fa3", + "_set_use_fa3", + "BlockDiagonalMask", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a42dcc52a19c4152bff45f3e84ba30447e770814 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/attn_bias.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/attn_bias.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0ad71878923c4f45de4d41dcbb33484f5b7c05ca Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/attn_bias.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/ck.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/ck.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dadcfaee4bcbd9a00e1a2c3b1018a5ad72d560a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/ck.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/ck_decoder.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/ck_decoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..715f07574d4465c911d96a39782a06c8611989ab Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/ck_decoder.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/ck_splitk.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/ck_splitk.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..99d34902446e0f0416976e1fdb7605cdec794b52 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/ck_splitk.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/common.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/common.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c8b0c979976ce97f36ee07db6ce9cce092fd25c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/common.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/cutlass.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/cutlass.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f9519f946317c7b01e7dac6ab5b76608cf82439 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/cutlass.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/dispatch.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/dispatch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f43bd3ff52d1135a9df015d17347420c22761e8 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/dispatch.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/flash.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/flash.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d286e65f0caca370ecb18d22eb9c073cb34e7ddc Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/flash.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/flash3.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/flash3.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b3ca09b5a7bb8e7ae27613435a2a072808ed4f9a Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/flash3.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/torch_attention_compat.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/torch_attention_compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c72d89d47ce1ae15248b1a83ccc2ce13e9a8e10e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/torch_attention_compat.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/triton_splitk.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/triton_splitk.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9b56d99385801b28629fb82710f64f39ec9fb46 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/__pycache__/triton_splitk.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/_triton/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/_triton/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6677db08c0dcd87f7570a3249f61cc3eabe0532a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/_triton/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/_triton/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/_triton/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a6963e418363f0f23210d9d452c68b21e55675c Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/_triton/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/_triton/__pycache__/splitk_kernels.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/_triton/__pycache__/splitk_kernels.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6047785517417365cbbbc7da2bca0f15407b3aaa Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/_triton/__pycache__/splitk_kernels.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/_triton/splitk_kernels.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/_triton/splitk_kernels.py new file mode 100644 index 0000000000000000000000000000000000000000..f79e781a8c3bcb2f1b4adb8c9084fe9f557edd25 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/_triton/splitk_kernels.py @@ -0,0 +1,1266 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import functools +import sys +from typing import Callable, Dict, Tuple, Union + +import torch +import triton +import triton.language as tl + +from xformers.triton.vararg_kernel import unroll_varargs, VAR_ARGS_ARRAY + +AUTOTUNER_KEY = [ + "Z", + "H", + "G", + "N_CTX_Q", + "N_CTX_K", + "BLOCK_DMODEL", + "PACKED_PER_VAL", + "N_GROUPS", + "BLOCK_N_PER_SPLIT", + "PAGE_SIZE", +] + + +@triton.jit +def _fwd_kernel_splitK( + Q, + K, + V, + sm_scale, + Out_splitK, # [B, H, split_k, Mq, K] + LSE_splitk, # [B, H, split_k, Mq] + block_tables, + Seq_len, + Seq_starts_k, + Seq_starts_q, + Seq_starts_q_multiplier, + additive_bias, + K_fp8_scale_shift, + V_fp8_scale_shift, + stride_qz, + stride_qm, + stride_qg, + stride_qh, + stride_qk, + stride_kz, + stride_kn, + stride_kg, + stride_kh, + stride_kk, + stride_vz, + stride_vn, + stride_vg, + stride_vh, + stride_vk, + stride_osk_z, + stride_osk_g, + stride_osk_h, + stride_osk_s, + stride_osk_m, + stride_osk_k, + stride_lsek_z, + stride_lsek_g, + stride_lsek_h, + stride_lsek_s, + stride_lsek_m, + stride_blocktablesz, + stride_blocktablesl, + stride_bias_b, + stride_bias_g, + stride_bias_h, + stride_bias_qm, + stride_bias_km, + stride_k_fp8_scale_shift_z: tl.constexpr, + stride_k_fp8_scale_shift_n: tl.constexpr, + stride_k_fp8_scale_shift_g: tl.constexpr, + stride_k_fp8_scale_shift_h: tl.constexpr, + stride_v_fp8_scale_shift_z: tl.constexpr, + stride_v_fp8_scale_shift_n: tl.constexpr, + stride_v_fp8_scale_shift_g: tl.constexpr, + stride_v_fp8_scale_shift_h: tl.constexpr, + kv_cache_blocks_per_row: tl.constexpr, + Z: tl.constexpr, + N_CTX_Q: tl.constexpr, # The number of queries + N_CTX_K: tl.constexpr, + BLOCK_N_PER_SPLIT: tl.constexpr, + H: tl.constexpr, + G: tl.constexpr, + BLOCK_DMODEL: tl.constexpr, + USE_SEQ_LEN: tl.constexpr, + PACKED_PER_VAL: tl.constexpr, + N_GROUPS: tl.constexpr, + # It's important that BOUNDS_CHECKS_N, BLOCK_M, BLOCK_N come at the end of + # the argument list, since they are provided by the heuristics/autotune decorator. + # Otherwise Triton throws IndexError + BOUNDS_CHECKS_N: tl.constexpr, + BLOCK_M: tl.constexpr, + BLOCK_N: tl.constexpr, + IS_SPLITK: tl.constexpr, + SPLIT_K_EARLY_EXIT: tl.constexpr, + IS_CAUSAL: tl.constexpr, + IS_LOCAL: tl.constexpr, + NUM_QUERIES_CAUSAL: tl.constexpr, # The N_CTX_Q queries are from this many sequence positions + USE_PAGED_ATTENTION: tl.constexpr, + PAGE_SIZE: tl.constexpr, + WINDOW_LEFT: tl.constexpr, + WINDOW_RIGHT: tl.constexpr, + WRITE_LSE: tl.constexpr, + HAS_ADDITIVE_BIAS: tl.constexpr, + NUM_PROGRAMS_DIM2_CONST: tl.constexpr, + IS_HIP: tl.constexpr, +): + """This kernel can accept non-quantized or int4-quantized keys/values. + PACKED_PER_VAL determines the quantization type: + - PACKED_PER_VAL == 1 means no quantization + - PACKED_PER_VAL == 8 means 4-bit quantization (8 packed quantized values inside one int32) + For the quantized case K/V should be int32 tensors. + Quantization can be row-wise (when N_GROUPS = 1) or group-wise with N_GROUPS = 2, 4, or 8. + Quantization coefficients are stored at the beginning of the row along the last dimension of K/V + So K[B, H, M, :] has a form + [ quant_coef0, quant_coef1, ...| + group0_quant_value0, group0_quant_value1,... | + group1_quant_value0, group1_quant_value1,...] + where each quant_coef is an int32 which should be interpreted as 2 packed float16: scale and offset. + + Note: this kernel needs to be processed by xformers.triton.vararg_kernel.unroll_varargs + before compilation. That will unroll variables marked with "VAR_ARGS_ARRAY" into lists. + See how FwOp.apply does it below. + + Set IS_SPLITK=False to indicate the MHA result should be written directly. + No metadata will be written. + """ + internal_dtype = ( + tl.float64 if Out_splitK.dtype.element_ty is tl.float64 else tl.float32 + ) + tl.static_assert( + (PACKED_PER_VAL == 1 and tl.constexpr(K.dtype.element_ty != tl.int32)) + or ( + (PACKED_PER_VAL == 4 or PACKED_PER_VAL == 8) + and tl.constexpr(K.dtype.element_ty == tl.int32) + ), + f"Only int4 and fp8 quantization is supported, K/V should have dtype int32 in " + f"the quantized case: {PACKED_PER_VAL=} {tl.constexpr(K.dtype)=} {tl.constexpr(K.dtype.element_ty)=}", + ) + tl.static_assert( + (((N_GROUPS == 1 or N_GROUPS == 2) or N_GROUPS == 4) or N_GROUPS == 8), + "Number of quantization groups can be 1 (row-wise quantization), 2, 4, or 8.", + ) + tl.static_assert( + N_GROUPS == 1 or K_fp8_scale_shift is None, + f"Only row-wise fp8 quantization is supported, but got {N_GROUPS=} > 1.", + ) + FP8_QUANTIZED: tl.constexpr = K_fp8_scale_shift is not None + INT4_QUANTIZED: tl.constexpr = PACKED_PER_VAL > 1 and not FP8_QUANTIZED + PACKED_D_PER_GROUP: tl.constexpr = BLOCK_DMODEL // PACKED_PER_VAL // N_GROUPS + D_PER_GROUP: tl.constexpr = BLOCK_DMODEL // N_GROUPS + + start_m = tl.program_id(0) + off_zhg = tl.program_id(1) + off_z = off_zhg // (H * G) + off_hg = off_zhg % (H * G) + off_h = off_hg // G + off_g = off_hg % G + splitk_idx = tl.program_id(2) + + if USE_SEQ_LEN: + kv_len = tl.load(Seq_len + off_z) + if SPLIT_K_EARLY_EXIT and kv_len == 0: + return + else: + kv_len = N_CTX_K + + if Seq_starts_k is None: + start_kv_idx = 0 + else: + start_kv_idx = tl.load(Seq_starts_k + off_z) + if USE_SEQ_LEN and PAGE_SIZE > 0: + # gappy with paged attention stores each "end" instead of each "length" + # because that's what FA3 needs. + kv_len -= start_kv_idx + + if Seq_starts_q is None: + q_len = N_CTX_Q + queries_use_batch_dim = 1 + off_m = 0 + else: + queries_use_batch_dim = 0 + off_m = tl.load(Seq_starts_q + off_z) * Seq_starts_q_multiplier + q_len = tl.load(Seq_starts_q + off_z + 1) * Seq_starts_q_multiplier - off_m + if q_len == 0: + return + + k_base = K + off_h * stride_kh + off_g * stride_kg + v_base = V + off_h * stride_vh + off_g * stride_vg + + if FP8_QUANTIZED: + k_fp8_scale_shift_base = ( + K_fp8_scale_shift + + off_h * stride_k_fp8_scale_shift_h + + off_g * stride_k_fp8_scale_shift_g + ) + v_fp8_scale_shift_base = ( + V_fp8_scale_shift + + off_h * stride_v_fp8_scale_shift_h + + off_g * stride_v_fp8_scale_shift_g + ) + else: + k_fp8_scale_shift_base = None + v_fp8_scale_shift_base = None + + # Boundaries of split-k chunk + chunk_hi = (splitk_idx + 1) * BLOCK_N_PER_SPLIT + chunk_lo = splitk_idx * BLOCK_N_PER_SPLIT + ignore_in_first_block = 0 + # For paged attention case K/V_block_ptr are defined inside the loop + # whereas for non-paged case they are defined before the loop. + if PAGE_SIZE > 0: + # Page contains several blocks + BLOCKS_IN_PAGE: tl.constexpr = PAGE_SIZE // BLOCK_N + # Align boundaries of split-k chunk to block boundaries + # In the last chunk, shift hi to the right, in the other chunks, shift it to the left + # TODO: Replace NUM_PROGRAMS_DIM2_CONST with tl.num_programs(2) after + # the next Triton upgrade. + is_last_chunk = splitk_idx == NUM_PROGRAMS_DIM2_CONST - 1 + shift = BLOCK_N - 1 if is_last_chunk else 0 + lo = (tl.maximum(chunk_lo, start_kv_idx) // BLOCK_N) * BLOCK_N + ignore_in_first_block = tl.maximum(0, (start_kv_idx - lo)) + hi = ((chunk_hi + shift) // BLOCK_N) * BLOCK_N + hi = tl.minimum(hi, kv_len + start_kv_idx) + block_table = block_tables + stride_blocktablesz * off_z + # Offset in integer blocks + logical_block_idx = lo // BLOCK_N + else: + lo = chunk_lo + hi = tl.minimum(chunk_hi, kv_len) + if Seq_starts_k is not None: + k_base += start_kv_idx * stride_kn + v_base += start_kv_idx * stride_vn + else: + k_base += off_z * stride_kz + v_base += off_z * stride_vz + # Additional shift by 1 along the last dimension in the quantized case, since + # the first element along that dim contains packed quantization coefficients. + K_block_ptr = tl.make_block_ptr( + base=k_base + stride_kk * INT4_QUANTIZED * N_GROUPS, + shape=(PACKED_D_PER_GROUP, hi), + strides=(stride_kk, stride_kn), + offsets=(0, lo), + block_shape=(PACKED_D_PER_GROUP, BLOCK_N), + order=(0, 1), + ) + V_block_ptr = tl.make_block_ptr( + base=v_base + stride_vk * INT4_QUANTIZED * N_GROUPS, + shape=(hi, PACKED_D_PER_GROUP), + strides=(stride_vn, stride_vk), + offsets=(lo, 0), + block_shape=(BLOCK_N, PACKED_D_PER_GROUP), + order=(1, 0), + ) + + if INT4_QUANTIZED: + # Pointers to quantization coefficients. Even those they are 1D, + # we use block pointers here so the pointer arithmetic is in int64, + # as otherwise the offsets for V_scale_shift_block_ptr may overflow. + K_scale_shift_block_ptr = tl.make_block_ptr( + base=k_base, + shape=(1, hi), + strides=(stride_kk, stride_kn), + offsets=(0, lo), + block_shape=(1, BLOCK_N), + order=(0, 1), + ) + V_scale_shift_block_ptr = tl.make_block_ptr( + base=v_base, + shape=(hi, 1), + strides=(stride_vn, stride_vk), + offsets=(lo, 0), + block_shape=(BLOCK_N, 1), + order=(1, 0), + ) + elif FP8_QUANTIZED: + if Seq_starts_k is not None: + k_fp8_scale_shift_base += start_kv_idx * stride_k_fp8_scale_shift_n + v_fp8_scale_shift_base += start_kv_idx * stride_v_fp8_scale_shift_n + else: + k_fp8_scale_shift_base += off_z * stride_k_fp8_scale_shift_z + v_fp8_scale_shift_base += off_z * stride_v_fp8_scale_shift_z + K_scale_shift_block_ptr = tl.make_block_ptr( + base=k_fp8_scale_shift_base, + shape=(1, hi), + strides=(1, stride_k_fp8_scale_shift_n), + offsets=(0, lo), + block_shape=(1, BLOCK_N), + order=(0, 1), + ) + V_scale_shift_block_ptr = tl.make_block_ptr( + base=v_fp8_scale_shift_base, + shape=(hi, 1), + strides=(stride_v_fp8_scale_shift_n, 1), + offsets=(lo, 0), + block_shape=(BLOCK_N, 1), + order=(1, 0), + ) + else: + K_scale_shift_block_ptr = None + V_scale_shift_block_ptr = None + + if HAS_ADDITIVE_BIAS: + additive_bias_block_ptr = tl.make_block_ptr( + base=additive_bias + + off_z * stride_bias_b + + off_g * stride_bias_g + + off_h * stride_bias_h, + shape=(N_CTX_Q, hi), + strides=(stride_bias_qm, stride_bias_km), + offsets=(start_m * BLOCK_M, lo), + block_shape=(BLOCK_M, BLOCK_N), + order=(0, 1), + ) + + if SPLIT_K_EARLY_EXIT and lo >= hi: + return + + Q_block_ptr = tl.make_block_ptr( + base=Q + + off_m * stride_qm + + off_h * stride_qh + + off_z * stride_qz * queries_use_batch_dim + + off_g * stride_qg, + shape=(q_len, BLOCK_DMODEL), + strides=(stride_qm, stride_qk), + offsets=(start_m * BLOCK_M, 0), + block_shape=(BLOCK_M, D_PER_GROUP), + order=(1, 0), + ) + + # initialize pointer to m and l + m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float("inf") + l_i = tl.zeros([BLOCK_M], dtype=tl.float32) + + # Before compilation, this kernel will be processed by xformers.triton.vararg_kernel.unroll_varargs. + # That turns tensors annotated as the one below into lists of tensors of length N_GROUPS. + # This is a solution for Triton native lack of support for lists of tensors. + acc: "VAR_ARGS_ARRAY" # noqa: F821 + + for i in range(len(acc)): # noqa: F821 + acc[i] = tl.zeros([BLOCK_M, D_PER_GROUP], dtype=internal_dtype) # noqa: F821 + # scale sm_scale by log_2(e) and use + # 2^x instead of exp in the loop because CSE and LICM + # don't work as expected with `exp` in the loop + # + # We declare log2e as a constant with a precisely-specified type to guarantee that + # triton will use the exact same value in all instances below, rather than sometimes + # using float32 and sometimes using float64. For more discussion see: + # https://github.com/triton-lang/triton/issues/5466 + log2e = tl.full((), 1.44269504, tl.float32) + qk_scale = sm_scale * log2e + # load q: it will stay in SRAM throughout + q: "VAR_ARGS_ARRAY" # noqa: F821 + for i in range(len(acc)): # noqa: F821 + q[i] = tl.load( # noqa: F821 + tl.advance(Q_block_ptr, (0, i * D_PER_GROUP)), boundary_check=(0,) + ) + + if IS_CAUSAL or IS_LOCAL: + # Why does the masking conditon below work as a causal mask? + # Assuming num_queries <= BLOCK_M: + # kv_pos = kv_start + range(0, BLOCK_N) + # q_offset = start_m * BLOCK_M + range(0, BLOCK_M) + # q_pos = kv_start + kv_len - num_queries + q_offset % num_queries + # mask = q_pos - kv_pos >= 0 + # So the final masking condition is: + # range(0, BLOCK_M) % num_queries - range(0, BLOCK_N) >= num_queries - kv_len + + q_offset = start_m * BLOCK_M + tl.arange(0, BLOCK_M) + diag_idx = (q_offset[:, None] % NUM_QUERIES_CAUSAL) - tl.arange(0, BLOCK_N)[ + None, : + ] + diag_idx_shifted = tl.constexpr(diag_idx - NUM_QUERIES_CAUSAL + kv_len) + + # loop over k, v and update accumulator + for start_n in range(lo, hi, BLOCK_N): + if PAGE_SIZE > 0: + # Offset in integer blocks from the beginning of the page + block_offset_in_page = logical_block_idx % BLOCKS_IN_PAGE + # Offset in integer pages + logical_page_idx = logical_block_idx // BLOCKS_IN_PAGE + physical_page_idx = tl.load( + block_table + stride_blocktablesl * logical_page_idx + ).to(tl.int32) + offset = physical_page_idx * PAGE_SIZE + block_offset_in_page * BLOCK_N + + current_block_size = min(hi - start_n, BLOCK_N) + K_block_ptr = tl.make_block_ptr( + base=k_base + stride_kk * INT4_QUANTIZED * N_GROUPS, + shape=(PACKED_D_PER_GROUP, offset + current_block_size), + strides=(stride_kk, stride_kn), + offsets=(0, offset), + block_shape=(PACKED_D_PER_GROUP, BLOCK_N), + order=(0, 1), + ) + V_block_ptr = tl.make_block_ptr( + base=v_base + stride_vk * INT4_QUANTIZED * N_GROUPS, + shape=(offset + current_block_size, PACKED_D_PER_GROUP), + strides=(stride_vn, stride_vk), + offsets=(offset, 0), + block_shape=(BLOCK_N, PACKED_D_PER_GROUP), + order=(1, 0), + ) + if INT4_QUANTIZED: + # Pointers to quantization coefficients. Even those they are 1D, + # we use block pointers here so the pointer arithmetic is in int64, + # as otherwise the offsets for V_scale_shift_block_ptr may overflow. + K_scale_shift_block_ptr = tl.make_block_ptr( + base=k_base, + shape=(1, offset + current_block_size), + strides=(stride_kk, stride_kn), + offsets=(0, offset), + block_shape=(1, BLOCK_N), + order=(0, 1), + ) + V_scale_shift_block_ptr = tl.make_block_ptr( + base=v_base, + shape=(offset + current_block_size, 1), + strides=(stride_vn, stride_vk), + offsets=(offset, 0), + block_shape=(BLOCK_N, 1), + order=(1, 0), + ) + elif FP8_QUANTIZED: + K_scale_shift_block_ptr = tl.make_block_ptr( + base=k_fp8_scale_shift_base, + shape=(1, offset + current_block_size), + strides=(1, stride_k_fp8_scale_shift_n), + offsets=(0, offset), + block_shape=(1, BLOCK_N), + order=(0, 1), + ) + V_scale_shift_block_ptr = tl.make_block_ptr( + base=v_fp8_scale_shift_base, + shape=(offset + current_block_size, 1), + strides=(stride_v_fp8_scale_shift_n, 1), + offsets=(offset, 0), + block_shape=(BLOCK_N, 1), + order=(1, 0), + ) + else: + K_scale_shift_block_ptr = None + V_scale_shift_block_ptr = None + logical_block_idx += 1 + + k: "VAR_ARGS_ARRAY" # noqa: F821 + v: "VAR_ARGS_ARRAY" # noqa: F821 + for i in range(len(acc)): # noqa: F821 + k[i], v[i] = load_dequantize_k_v_group( # noqa: F821 + K_block_ptr, + V_block_ptr, + K_scale_shift_block_ptr, + V_scale_shift_block_ptr, + BOUNDS_CHECKS_N, + PACKED_PER_VAL, + PACKED_D_PER_GROUP, + FP8_QUANTIZED, + Q.dtype.element_ty, + i, + IS_HIP, + ) + + # -- compute qk --- + qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32) + for i in range(len(acc)): # noqa: F821 + qk += tl.dot(q[i], k[i]) # noqa: F821 + qk *= qk_scale + + if start_n == lo and ignore_in_first_block > 0: + qk = tl.where( + tl.arange(0, BLOCK_N) < ignore_in_first_block, float("-inf"), qk + ) + + if HAS_ADDITIVE_BIAS: + loaded_bias = tl.load( + additive_bias_block_ptr, + boundary_check=(0, 1) if BOUNDS_CHECKS_N else (0,), + ) + qk += loaded_bias.to(tl.float32) * log2e + additive_bias_block_ptr = tl.advance(additive_bias_block_ptr, (0, BLOCK_N)) + + # TODO: This is slow, and only needed at the last iteration. + # Maybe we can unroll the last iteration instead? + if BOUNDS_CHECKS_N: + qk = tl.where(tl.arange(0, BLOCK_N) < hi - start_n, qk, float("-inf")) + if IS_CAUSAL: + # -- apply the causal mask -- + qk = tl.where(diag_idx_shifted >= start_n - start_kv_idx, qk, float("-inf")) + if IS_LOCAL: + # -- apply the local window size mask -- + qk = tl.where( + diag_idx_shifted < start_n - start_kv_idx + WINDOW_LEFT + 1, + qk, + float("-inf"), + ) + if not IS_CAUSAL and WINDOW_RIGHT >= 0: + qk = tl.where( + diag_idx_shifted >= start_n - start_kv_idx - WINDOW_RIGHT, + qk, + float("-inf"), + ) + + # -- compute scaling constant --- + m_i_new = tl.maximum(m_i, tl.max(qk, 1)) + alpha = tl.math.exp2(m_i - m_i_new) + p = tl.math.exp2(qk - m_i_new[:, None]) + if HAS_ADDITIVE_BIAS or (IS_CAUSAL or IS_LOCAL): + # NOTE: It's possible that an entire block is masked out. + # if this is the case, `m_i_new=nan` and everything becomes nan + alpha = tl.where(m_i_new == float("-inf"), 0, alpha) + p = tl.where(m_i_new[:, None] == float("-inf"), 0, p) + + # -- update m_i and l_i -- + l_i = l_i * alpha + tl.sum(p, 1) + m_i = m_i_new + p = p.to(Q.dtype.element_ty) + + # -- scale and update acc -- + for i in range(len(acc)): # noqa: F821 + acc[i] *= alpha[:, None] # noqa: F821 + acc[i] += tl.dot(p, v[i]) # noqa: F821 + + if not PAGE_SIZE: + # update pointers + K_block_ptr = tl.advance(K_block_ptr, (0, BLOCK_N)) + V_block_ptr = tl.advance(V_block_ptr, (BLOCK_N, 0)) + if PACKED_PER_VAL > 1: + K_scale_shift_block_ptr = tl.advance( + K_scale_shift_block_ptr, (0, BLOCK_N) + ) + V_scale_shift_block_ptr = tl.advance( + V_scale_shift_block_ptr, (BLOCK_N, 0) + ) + + # write back O + O_block_ptr = tl.make_block_ptr( + base=Out_splitK + + off_z.to(tl.int64) * stride_osk_z * queries_use_batch_dim + + off_m * stride_osk_m + + off_g * stride_osk_g + + off_h * stride_osk_h + + splitk_idx * stride_osk_s, + shape=(q_len, D_PER_GROUP), + strides=(stride_osk_m, 1), + offsets=(start_m * BLOCK_M, 0), + block_shape=(BLOCK_M, D_PER_GROUP), + order=(1, 0), + ) + for i in range(len(acc)): # noqa: F821 + # If for the current batch element there are no tokens in the current split-k chunk (because + # seqlen is too short), l_i will be 0, so we need to make sure attention is filled with zeros and not NaNs. + attn_out = tl.where(l_i[:, None] == 0, 0.0, acc[i] / l_i[:, None]) # noqa: F821 + tl.store( + tl.advance(O_block_ptr, (0, i * D_PER_GROUP)), + attn_out.to(Out_splitK.dtype.element_ty), # noqa: F821 + boundary_check=(0,), + ) + if WRITE_LSE: + LSE_splitk_ptr = ( + LSE_splitk + + off_z * stride_lsek_z * queries_use_batch_dim + + off_m * stride_lsek_m + + off_g * stride_lsek_g + + off_h * stride_lsek_h + + splitk_idx * stride_lsek_s + + (start_m * BLOCK_M + tl.arange(0, BLOCK_M)) * stride_lsek_m + ) + mask = start_m * BLOCK_M + tl.arange(0, BLOCK_M) < q_len + # Can be float64 to improve numerics + lse_dtype = LSE_splitk.dtype.element_ty + tl.store( + LSE_splitk_ptr, + (tl.math.log2(l_i.to(lse_dtype)) + m_i.to(lse_dtype)) / log2e, + mask=mask, + ) + + +def gen_config( + block_m: int, + block_n: int, + stages: int, + warps: int, +) -> triton.Config: + """A more compact way to define a triton.Config, so it fits on one line""" + + return triton.Config( + { + "BLOCK_M": block_m, + "BLOCK_N": block_n, + }, + num_stages=stages, + num_warps=warps, + ) + + +def _get_splitk_kernel(num_groups): + """ + Kernel _fwd_kernel_splitK needs to be post-processed by unroll_varargs + to specialize it for a given number of quantization groups N_GROUPS + before we can apply triton.heuristics and triton.autotune, so we + don't do them as decorators. + """ + + _fwd_kernel_splitK_unrolled = unroll_varargs(_fwd_kernel_splitK, N=num_groups) + kernel = triton.heuristics( + { + "BOUNDS_CHECKS_N": lambda args: bool( + (args["BLOCK_N_PER_SPLIT"] % args["BLOCK_N"]) + or ( + args["BLOCK_N_PER_SPLIT"] > 0 + and args["N_CTX_K"] % args["BLOCK_N_PER_SPLIT"] + ) + or args["USE_SEQ_LEN"] + ) + } + )(_fwd_kernel_splitK_unrolled) + return kernel + + +def early_config_prune(configs, named_args, **kwargs): + use_paged_attention = kwargs["USE_PAGED_ATTENTION"] + page_size = kwargs["PAGE_SIZE"] + if use_paged_attention: + return list( + filter(lambda config: page_size % config.kwargs["BLOCK_N"] == 0, configs) + ) + else: + return configs + + +@functools.lru_cache(None) +def autotune_kernel(kernel: Callable): + BLOCK_M_VALUES = [16, 32, 64, 128] + BLOCK_N_VALUES = [16, 32, 64, 128] + STAGES_VALUES = [1, 2] if torch.version.hip else [1, 2, 3] + WARPS_VALUES = [1, 2, 4, 8] + + TRITON_CONFIGS = [ + gen_config(block_m, block_n, stages, warps) + for block_m in BLOCK_M_VALUES + for block_n in BLOCK_N_VALUES + for stages in STAGES_VALUES + for warps in WARPS_VALUES + if block_n >= block_m + ] + + kernel = triton.autotune( + configs=TRITON_CONFIGS, + key=AUTOTUNER_KEY, + use_cuda_graph=True, + prune_configs_by={ + "early_config_prune": early_config_prune, + }, + )(kernel) + return kernel + + +# This object contains forward kernels wrapped into autotuner for different number +# of quantization groups. +_fwd_kernel_splitK_autotune: Dict[int, triton.runtime.Autotuner] = {} +# The loop below: +# - transforms the jitted kernel with unroll_varargs producing a new kernel of each value of num_groups +# - wraps the kernel into triton.heuristics +# - wraps kernel into Triton autotuner. Autotuning itself happens the first time the kernel is called +if sys.version_info >= (3, 9): + # unroll_varargs requires Python 3.9+ + for num_groups in [1, 2, 4, 8]: + _fwd_kernel_splitK_autotune[num_groups] = autotune_kernel( + _get_splitk_kernel(num_groups) + ) + + def get_autotuner_cache( + num_groups: int, + ) -> Dict[Tuple[Union[int, str]], triton.Config]: + """Returns a triton.runtime.autotuner.AutoTuner.cache object, which + represents mappings from kernel autotune keys (tuples describing kernel inputs) + to triton.Config + """ + return _fwd_kernel_splitK_autotune[num_groups].cache + + def set_autotuner_cache( + cache: Dict[Tuple[Union[int, str]], triton.Config], num_groups: int + ) -> None: + _fwd_kernel_splitK_autotune[num_groups].cache = cache + + +@triton.jit +def load_dequantize_k_v_group( + K_block_ptr, + V_block_ptr, + K_scale_shift_block_ptr, + V_scale_shift_block_ptr, + BOUNDS_CHECKS_N: tl.constexpr, + PACKED_PER_VAL: tl.constexpr, + PACKED_D_PER_GROUP: tl.constexpr, + FP8_QUANTIZED: tl.constexpr, + dtype: tl.constexpr, + group_id: tl.constexpr, + IS_HIP: tl.constexpr, +): + """Load K/V for a given block. In case of int4/fp8-quantized K/V, dequantize them after loading. + If quantization is group-wise, use group_id to advance the pointers to the current group. + """ + # Advance to the current quantization group + K_block_ptr = tl.advance(K_block_ptr, (PACKED_D_PER_GROUP * group_id, 0)) + V_block_ptr = tl.advance(V_block_ptr, (0, PACKED_D_PER_GROUP * group_id)) + + # -- load k, v -- + k = tl.load(K_block_ptr, boundary_check=(1,) if BOUNDS_CHECKS_N else ()) + v = tl.load(V_block_ptr, boundary_check=(0,) if BOUNDS_CHECKS_N else ()) + + # If K/V are quantized, load quantization coefficients and dequantize. + if FP8_QUANTIZED: + v_scale_shift = tl.load( + V_scale_shift_block_ptr, boundary_check=(0,) if BOUNDS_CHECKS_N else () + ) + if IS_HIP: + # MI300 doesn't have builtin casting instructions for fp8 -> bf16, + # so casting to f32 is actually more performant on this workload. + v_scale, v_shift = cast_uint32_to_float(v_scale_shift) + else: + v_scale, v_shift = cast_uint32_to_half2(v_scale_shift) + v = dequantize(v, v_scale, v_shift, PACKED_PER_VAL, IS_HIP).to(dtype) + + k_scale_shift = tl.load( + K_scale_shift_block_ptr, boundary_check=(1,) if BOUNDS_CHECKS_N else () + ) + if IS_HIP: + k_scale, k_shift = cast_uint32_to_float(k_scale_shift) + k = dequantize_k_hip(k, k_scale, k_shift, PACKED_PER_VAL).to(dtype) + else: + k_scale, k_shift = cast_uint32_to_half2(k_scale_shift) + k_t = dequantize( + tl.trans(k), + tl.trans(k_scale), + tl.trans(k_shift), + PACKED_PER_VAL, + IS_HIP, + ).to(dtype) + k = tl.trans(k_t) + elif PACKED_PER_VAL > 1: + # Int4 quantization. + K_scale_shift_block_ptr = tl.advance(K_scale_shift_block_ptr, (group_id, 0)) + V_scale_shift_block_ptr = tl.advance(V_scale_shift_block_ptr, (0, group_id)) + + k_scale_shift = tl.load( + K_scale_shift_block_ptr, boundary_check=(1,) if BOUNDS_CHECKS_N else () + ) + v_scale_shift = tl.load( + V_scale_shift_block_ptr, boundary_check=(0,) if BOUNDS_CHECKS_N else () + ) + if IS_HIP: + k_scale, k_shift = cast_uint32_to_float(k_scale_shift) + v_scale, v_shift = cast_uint32_to_float(v_scale_shift) + v = dequantize(v, v_scale, v_shift, PACKED_PER_VAL, IS_HIP).to(dtype) + k = dequantize_k_hip(k, k_scale, k_shift, PACKED_PER_VAL).to(dtype) + else: + k_scale, k_shift = cast_uint32_to_half2(k_scale_shift) + v_scale, v_shift = cast_uint32_to_half2(v_scale_shift) + v = dequantize(v, v_scale, v_shift, PACKED_PER_VAL, IS_HIP).to(dtype) + k_t = dequantize( + tl.trans(k), + tl.trans(k_scale), + tl.trans(k_shift), + PACKED_PER_VAL, + IS_HIP, + ).to(dtype) + k = tl.trans(k_t) + return k, v + + +@triton.jit +def cast_uint32_to_half2(scale_shift): + """Extract two float16 packed into one int32""" + scale = scale_shift & 0xFFFF + shift = scale_shift >> 16 + scale = scale.to(tl.uint16).to(tl.float16, bitcast=True) + shift = shift.to(tl.uint16).to(tl.float16, bitcast=True) + return scale, shift + + +@triton.jit +def cast_uint32_to_float(scale_shift): + """Extract two float16 packed into one int32 as float32""" + scale = scale_shift & 0xFFFF + shift = scale_shift >> 16 + scale = scale.to(tl.uint16).to(tl.float16, bitcast=True).to(tl.float32) + shift = shift.to(tl.uint16).to(tl.float16, bitcast=True).to(tl.float32) + return scale, shift + + +@triton.jit +def dequantize_k_hip( + x_, + scale, + shift, + PACKED_PER_VAL: tl.constexpr, +): + """PACKED_PER_VAL is the number of values packed into each element x_. + For example, for int4 quantization and x_ of type int32, PACKED_PER_VAL is 8. + """ + # x_ : (BLOCK_N, D // PACKED_PER_VAL) + # scale: (BLOCK_N, 1) + # offsets: (PACKED_PER_VAL,) + BLOCK_N: tl.constexpr = x_.shape[1] + BLOCK_DMODEL_PACKED: tl.constexpr = x_.shape[0] + offsets = tl.arange(0, PACKED_PER_VAL) * (32 // PACKED_PER_VAL) + quant_offset = ( + x_[:, None, :, :] >> offsets[:, None] + ) # (BLOCK_N, D // PACKED_PER_VAL, PACKED_PER_VAL) + + quant_offset = tl.reshape( + quant_offset, (BLOCK_DMODEL_PACKED * PACKED_PER_VAL, BLOCK_N) + ) + + if PACKED_PER_VAL == 4: + # FP8 quantization. + fp8_type = tl.float8e4b8 if torch.version.hip is not None else tl.float8e4nv + dequant = ( + quant_offset.to(tl.uint8).to(fp8_type, bitcast=True).to(scale.dtype) * scale + + shift + ) + else: + # Int4 quantization. + # Trick - instead of converting int4 to float16 we view it as float16 + # and then multiply by 32768 * 512 == 2**24 + quant_offset = ( + (quant_offset & 0xF) + .to(tl.uint16) + .to(tl.float16, bitcast=True) + .to(tl.float32) + ) + quant_offset = quant_offset * 32768.0 + scale_512 = scale * 512 + + dequant = quant_offset * scale_512 + shift + return dequant + + +@triton.jit +def dequantize( + x_, + scale, + shift, + PACKED_PER_VAL: tl.constexpr, + IS_HIP: tl.constexpr, +): + """PACKED_PER_VAL is the number of values packed into each element x_. + For example, for int4 quantization and x_ of type int32, PACKED_PER_VAL is 8. + """ + # x_ : (BLOCK_N, D // PACKED_PER_VAL) + # scale: (BLOCK_N, 1) + # offsets: (PACKED_PER_VAL,) + BLOCK_N: tl.constexpr = x_.shape[0] + BLOCK_DMODEL_PACKED: tl.constexpr = x_.shape[1] + offsets = tl.arange(0, PACKED_PER_VAL) * (32 // PACKED_PER_VAL) + quant_offset = ( + x_[:, :, None, :] >> offsets + ) # (BLOCK_N, D // PACKED_PER_VAL, PACKED_PER_VAL) + + quant_offset = tl.reshape( + quant_offset, (BLOCK_N, BLOCK_DMODEL_PACKED * PACKED_PER_VAL) + ) + if PACKED_PER_VAL == 4: + # FP8 quantization. + fp8_type = tl.float8e4b8 if torch.version.hip is not None else tl.float8e4nv + dequant = ( + quant_offset.to(tl.uint8).to(fp8_type, bitcast=True).to(scale.dtype) * scale + + shift + ) + else: + # Int4 quantization. + # Trick - instead of converting int4 to float16 we view it as float16 + # and then multiply by 32768 * 512 == 2**24 + if IS_HIP: + # Do final math in float32 to avoid casting to bf16 on MI300. There + # no direct instructions for this so its less performant on this workload. + quant_offset = ( + (quant_offset & 0xF) + .to(tl.uint16) + .to(tl.float16, bitcast=True) + .to(tl.float32) + ) + quant_offset = quant_offset * 32768.0 + else: + quant_offset = ( + (quant_offset & 0xF).to(tl.uint16).to(tl.float16, bitcast=True) + ) + quant_offset = (quant_offset * 32768.0).to(tl.float16) + scale_512 = scale * 512 + + dequant = quant_offset * scale_512 + shift + return dequant + + +@triton.jit +def _splitK_reduce( + Out_splitK, # [B, G, H, split_k, Mq, K] + LSE_splitK, # [B, G, H, split_k, Mq] + Out, # [B, H, M, K] + LSE, # [B, H, M] + split_k: tl.constexpr, + splitK_pow2: tl.constexpr, + stride_osk_z: tl.constexpr, + stride_osk_g: tl.constexpr, + stride_osk_h: tl.constexpr, + stride_osk_s: tl.constexpr, + stride_osk_m: tl.constexpr, + stride_osk_k: tl.constexpr, + stride_lsek_z: tl.constexpr, + stride_lsek_g: tl.constexpr, + stride_lsek_h: tl.constexpr, + stride_lsek_s: tl.constexpr, + stride_lsek_m: tl.constexpr, + stride_oz: tl.constexpr, + stride_og: tl.constexpr, + stride_oh: tl.constexpr, + stride_om: tl.constexpr, + stride_ok: tl.constexpr, + stride_lse_z: tl.constexpr, + stride_lse_g: tl.constexpr, + stride_lse_h: tl.constexpr, + stride_lse_m: tl.constexpr, + BLOCK_SIZE: tl.constexpr, + H: tl.constexpr, + G: tl.constexpr, + WRITE_LSE: tl.constexpr, +): + # grid = (M, B * G * H, 1) + off_m = tl.program_id(0).to(tl.int64) + off_zhg = tl.program_id(1).to(tl.int64) + off_z = off_zhg // (H * G) + off_h = (off_zhg // G) % H + off_g = off_zhg % G + + Out_splitK_ptr = ( + Out_splitK + + stride_osk_z * off_z + + stride_osk_g * off_g + + stride_osk_h * off_h + + stride_osk_m * off_m + + tl.arange(0, BLOCK_SIZE)[None, :] + + stride_osk_s * tl.arange(0, splitK_pow2)[:, None] + ) + + LSE_splitK_ptr0 = ( + LSE_splitK + + stride_lsek_z * off_z + + stride_lsek_g * off_g + + stride_lsek_h * off_h + + stride_lsek_m * off_m + + stride_lsek_s * tl.arange(0, splitK_pow2) + ) + + if splitK_pow2 > split_k: + mask_1d = tl.arange(0, splitK_pow2) < split_k + mask_2d = mask_1d[:, None] + lse_splitk = tl.load(LSE_splitK_ptr0, mask=mask_1d, other=float("-inf")) + lse_max = tl.max(lse_splitk) + out_splitk = tl.load( + Out_splitK_ptr, mask=mask_2d, other=0 + ) # (split_k, BLOCK_SIZE) + lse_splitk = tl.load( + LSE_splitK_ptr0, mask=mask_1d, other=float("-inf") + ) # (split_k,) + else: + lse_splitk = tl.load(LSE_splitK_ptr0) + lse_max = tl.max(lse_splitk) + out_splitk = tl.load(Out_splitK_ptr) + lse_splitk = tl.load(LSE_splitK_ptr0) + + sumexp_normalized_splitk = tl.math.exp2( + (lse_splitk - lse_max).to(tl.float32) * 1.44269504 + ) # (split_k,) + sumexp_normalized = tl.sum(sumexp_normalized_splitk, axis=0) # scalar + # Compute numerator + numerator_normalized = tl.sum( + out_splitk * sumexp_normalized_splitk[:, None], axis=0 + ) + acc = numerator_normalized / sumexp_normalized + acc = tl.where(lse_max == float("-inf"), 0.0, acc) + + Out_ptr = ( + Out + + stride_oz * off_z + + stride_oh * off_h + + stride_og * off_g + + stride_om * off_m + + tl.arange(0, BLOCK_SIZE) + ) + if acc.dtype is tl.float64 and Out.dtype.element_ty is not tl.float64: + # must avoid direct cast f64->f16 + acc = acc.to(tl.float32) + tl.store(Out_ptr, acc) + + if WRITE_LSE: + l_ptrs = ( + LSE + + off_z * stride_lse_z + + off_g * stride_lse_g + + off_h * stride_lse_h + + off_m * stride_lse_m + ) + to_store = lse_max + tl.math.log2(sumexp_normalized) / 1.44269504 + to_store = tl.where(lse_max == float("-inf"), lse_max, to_store) + tl.store(l_ptrs, to_store) + + +@triton.jit +def _splitK_reduce_varargs( + Out_splitK: "VAR_ARGS_ARRAY", # list of [B, G, H, Mq, K]; + LSE_splitK: "VAR_ARGS_ARRAY", # list of [B, G, H, Mq] + Out, # [B, G, H, M, K] + LSE, # [B, G, H, M] + stride_osk_z: "VAR_ARGS_ARRAY", + stride_osk_g: "VAR_ARGS_ARRAY", + stride_osk_h: "VAR_ARGS_ARRAY", + stride_osk_m: "VAR_ARGS_ARRAY", + stride_osk_k: "VAR_ARGS_ARRAY", + stride_lsek_z: "VAR_ARGS_ARRAY", + stride_lsek_g: "VAR_ARGS_ARRAY", + stride_lsek_h: "VAR_ARGS_ARRAY", + stride_lsek_m: "VAR_ARGS_ARRAY", + stride_oz, + stride_og, + stride_oh, + stride_om, + stride_ok, + stride_lse_z, + stride_lse_g, + stride_lse_h, + stride_lse_m, + BLOCK_SIZE: tl.constexpr, + H: tl.constexpr, + G: tl.constexpr, + WRITE_LSE: tl.constexpr, +): + """ + This version of reduce kernel takes attention and LSE of chunks as lists of tensors, + as opposed to _splitK_reduce, which takes each as a stacked tensor. + """ + # grid = (M, B * G * H, 1) + off_m = tl.program_id(0).to(tl.int64) + off_zhg = tl.program_id(1).to(tl.int64) + off_z = off_zhg // (H * G) + off_h = (off_zhg // G) % H + off_g = off_zhg % G + + out_splitk_offset: "VAR_ARGS_ARRAY" # noqa: F821 + for i in range(len(Out_splitK)): + out_splitk_offset[i] = ( # noqa: F821 + stride_osk_z[i] * off_z # type: ignore # noqa: F821 + + stride_osk_g[i] * off_g + + stride_osk_h[i] * off_h + + stride_osk_m[i] * off_m + + tl.arange(0, BLOCK_SIZE) + ) + lse_splitk_offset: "VAR_ARGS_ARRAY" # noqa: F821 + for i in range(len(Out_splitK)): + lse_splitk_offset[i] = ( # noqa: F821 + stride_lsek_z[i] * off_z # type: ignore # noqa: F821 + + stride_lsek_g[i] * off_g + + stride_lsek_h[i] * off_h + + stride_lsek_m[i] * off_m + ) + + lse_max = float("-inf") + for split_k_idx in range(len(Out_splitK)): # type: ignore # noqa: F821 + LSE_splitK_ptr = LSE_splitK[split_k_idx] + lse_splitk_offset[split_k_idx] # type: ignore # noqa: F821 + lse_splitk = tl.load(LSE_splitK_ptr) + lse_max = tl.maximum(lse_max, lse_splitk) + + sumexp_normalized = 0.0 + numerator_normalized = tl.zeros([BLOCK_SIZE], dtype=tl.float32) + + for split_k_idx in range(len(Out_splitK)): # type: ignore # noqa: F821 + out_splitk = tl.load(Out_splitK[split_k_idx] + out_splitk_offset[split_k_idx]) # type: ignore # noqa: F821 + lse_splitk = tl.load(LSE_splitK[split_k_idx] + lse_splitk_offset[split_k_idx]) # type: ignore # noqa: F821 + # Compute denominator + sumexp_normalized_splitk = tl.math.exp2( + (lse_splitk - lse_max).to(tl.float32) * 1.44269504 + ) + sumexp_normalized += sumexp_normalized_splitk + + # Compute numerator + numerator_normalized += out_splitk * sumexp_normalized_splitk + + acc = numerator_normalized / sumexp_normalized + acc = tl.where(lse_max == float("-inf"), 0.0, acc) + + Out_ptr = ( + Out + + stride_oz * off_z + + stride_oh * off_h + + stride_og * off_g + + stride_om * off_m + + tl.arange(0, BLOCK_SIZE) + ) + if acc.dtype is tl.float64 and Out.dtype.element_ty is not tl.float64: + # must avoid direct cast f64->f16 + acc = acc.to(tl.float32) + tl.store(Out_ptr, acc) + + if WRITE_LSE: + l_ptrs = ( + LSE + + off_z * stride_lse_z + + off_g * stride_lse_g + + off_h * stride_lse_h + + off_m * stride_lse_m + ) + to_store = lse_max + tl.math.log2(sumexp_normalized) / 1.44269504 + to_store = tl.where(lse_max == float("-inf"), lse_max, to_store) + tl.store(l_ptrs, to_store) + + +@triton.jit +def _splitK_reduce_varargs_backward( + Out_splitK: "VAR_ARGS_ARRAY", # list of [B, G, H, Mq, K]; + LSE_splitK: "VAR_ARGS_ARRAY", # list of [B, G, H, Mq] + Dout_splitK: "VAR_ARGS_ARRAY", # gradients - same shape as the inputs themselves + DLSE_splitK: "VAR_ARGS_ARRAY", + Out, # [B, G, H, M, K] + LSE, # [B, G, H, M] + DOut, + DLSE, + # strides of chunked inputs: attention and LSE + stride_osk_z: "VAR_ARGS_ARRAY", + stride_osk_g: "VAR_ARGS_ARRAY", + stride_osk_h: "VAR_ARGS_ARRAY", + stride_osk_m: "VAR_ARGS_ARRAY", + stride_osk_k: "VAR_ARGS_ARRAY", + stride_lsek_z: "VAR_ARGS_ARRAY", + stride_lsek_g: "VAR_ARGS_ARRAY", + stride_lsek_h: "VAR_ARGS_ARRAY", + stride_lsek_m: "VAR_ARGS_ARRAY", + # strides of merged outputs: attention and LSE + stride_oz, + stride_og, + stride_oh, + stride_om, + stride_ok, + stride_lse_z, + stride_lse_g, + stride_lse_h, + stride_lse_m, + # strides of gradients + stride_doz, + stride_dog, + stride_doh, + stride_dom, + stride_dok, + stride_dlse_z, + stride_dlse_g, + stride_dlse_h, + stride_dlse_m, + BLOCK_SIZE: tl.constexpr, + H: tl.constexpr, + G: tl.constexpr, +): + """ + Backward for _splitK_reduce_varargs. Similar to forward, it takes + attention and LSE of chunks as lists of tensors, + and outputs the corresponding gradients in the same format. + """ + + # grid = (M, B * G * H, 1) + off_m = tl.program_id(0).to(tl.int64) + off_zhg = tl.program_id(1).to(tl.int64) + off_z = off_zhg // (H * G) + off_h = (off_zhg // G) % H + off_g = off_zhg % G + + # Compute offsets inside each attention/LSE chunk. + # Note that each chunk can have different strides, so offsets can also be different. + out_splitk_offset: "VAR_ARGS_ARRAY" # noqa: F821 + for i in range(len(Out_splitK)): + out_splitk_offset[i] = ( # type: ignore # noqa: F821 + stride_osk_z[i] * off_z + + stride_osk_g[i] * off_g + + stride_osk_h[i] * off_h + + stride_osk_m[i] * off_m + + tl.arange(0, BLOCK_SIZE) + ) + lse_splitk_offset: "VAR_ARGS_ARRAY" # noqa: F821 + for i in range(len(Out_splitK)): + lse_splitk_offset[i] = ( # type: ignore # noqa: F821 + stride_lsek_z[i] * off_z + + stride_lsek_g[i] * off_g + + stride_lsek_h[i] * off_h + + stride_lsek_m[i] * off_m + ) + + lse_max = float("-inf") + for split_k_idx in range(len(Out_splitK)): # type: ignore # noqa: F821 + LSE_splitK_ptr = LSE_splitK[split_k_idx] + lse_splitk_offset[split_k_idx] # type: ignore # noqa: F821 + lse_splitk = tl.load(LSE_splitK_ptr) + lse_max = tl.maximum(lse_max, lse_splitk) + + # Load attention and the corresponding gradient + offset_out = ( + stride_oz * off_z + + stride_oh * off_h + + stride_og * off_g + + stride_om * off_m + + tl.arange(0, BLOCK_SIZE) + ) + offset_dout = ( + stride_doz * off_z + + stride_doh * off_h + + stride_dog * off_g + + stride_dom * off_m + + tl.arange(0, BLOCK_SIZE) + ) + out = tl.load(Out + offset_out) + dattn = tl.load(DOut + offset_dout) + + # Load LSE and the corresponding gradient + offset_lse = ( + stride_lse_z * off_z + + stride_lse_h * off_h + + stride_lse_g * off_g + + stride_lse_m * off_m + ) + offset_dlse = ( + stride_dlse_z * off_z + + stride_dlse_h * off_h + + stride_dlse_g * off_g + + stride_dlse_m * off_m + ) + lse = tl.load(LSE + offset_lse) + dlse = tl.load(DLSE + offset_dlse) + + for split_k_idx in range(len(Out_splitK)): # type: ignore # noqa: F821 + # Load attention and LSE of chunks + out_splitk = tl.load(Out_splitK[split_k_idx] + out_splitk_offset[split_k_idx]) # type: ignore # noqa: F821 + lse_splitk = tl.load(LSE_splitK[split_k_idx] + lse_splitk_offset[split_k_idx]) # type: ignore # noqa: F821 + + # Pointers to save gradients of attention and LSE of chunks + dout_splitk_ptr = Dout_splitK[split_k_idx] + out_splitk_offset[split_k_idx] # type: ignore # noqa: F821 + dlse_splitk_ptr = DLSE_splitK[split_k_idx] + lse_splitk_offset[split_k_idx] # type: ignore # noqa: F821 + + # dX/dattn_i = dX/dattn * dattn/dattn_i + dX/dlse * dlse/dattn_i, and dlse/dattn_i == 0 + dattn_dattn_i = tl.exp(lse_splitk - lse_max) / tl.exp(lse - lse_max) + dX_dattn_i = dattn_dattn_i * dattn + tl.store(dout_splitk_ptr, dX_dattn_i) + + dattn_dlse_i = (out_splitk - out) * dattn_dattn_i + + # dX/dlse_i = dX/dattn * dattn/dlse_i + dX/dlse * dlse/dlse_i + dlse_dlse_i = dattn_dattn_i + dX_dlse_i = dlse_dlse_i * dlse + tl.sum( + dattn_dlse_i * dattn + ) # Sum is over the hidden dimension + tl.store(dlse_splitk_ptr, dX_dlse_i) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/attn_bias.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/attn_bias.py new file mode 100644 index 0000000000000000000000000000000000000000..ecfe549e57385015378c1f96f8a152808157c197 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/attn_bias.py @@ -0,0 +1,2064 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. +""" +This file contains biases that can be used as the `attn_bias` argument in +:attr:`xformers.ops.memory_efficient_attention`. +Essentially, a bias is a Tensor which will be added to the ``Q @ K.t`` before +computing the ``softmax``. + + +The goal of having custom made classes (instead of dense tensors) is that +we want to avoid having to load the biases from memory in the kernel, for +performance reasons. We also want to be able to know before-hand which +parts of the attention matrix we will need to compute (eg causal masks). + + +Some very common biases are LowerTriangularMask and BlockDiagonalMask. +""" + +import math +from dataclasses import dataclass +from typing import ( + Any, + cast, + ClassVar, + Iterable, + List, + Optional, + Sequence, + Tuple, + Type, + Union, +) + +import torch + + +def _to_device(t: torch.Tensor, device: torch.device): + if t.device == device: + return t + if device == torch.device("cpu"): + return t.to(device) + + return t.to(device, non_blocking=True) + + +def _to_device_tensor(seq: Sequence[int], dtype: torch.dtype, device: torch.device): + if device == torch.device("cpu"): + return torch.tensor(seq, dtype=dtype) + + return torch.tensor(seq, dtype=dtype, pin_memory=True).to(device, non_blocking=True) + + +class AttentionBias: + """Base class for a custom bias that can be applied \ + as the attn_bias argument in + :attr:`xformers.ops.memory_efficient_attention`. + + That function has the ability to add a tensor, the + attention bias, to the QK^T matrix before it is used + in the softmax part of the attention calculation. + The attention bias tensor with shape + (B or 1, n_queries, number of keys) + can be given as the attn_bias input. + The most common use case is for an attention bias is + to contain only zeros and negative infinities, which forms + a mask so that some queries only attend to some keys. + + Children of this class define alternative things which can + be used as the attn_bias input to define an attention bias which + forms such a mask, for some common cases. + + When using an :attr:`xformers.ops.AttentionBias` + instead of a :attr:`torch.Tensor`, the mask matrix does + not need to be materialized, and can be + hardcoded into some kernels for better performance. + + See: + + - :attr:`xformers.ops.fmha.attn_bias.LowerTriangularMask` + - :attr:`xformers.ops.fmha.attn_bias.LowerTriangularFromBottomRightMask` + - :attr:`xformers.ops.fmha.attn_bias.LowerTriangularMaskWithTensorBias` + - :attr:`xformers.ops.fmha.attn_bias.BlockDiagonalMask` + - :attr:`xformers.ops.fmha.attn_bias.BlockDiagonalCausalMask` + + """ + + HOLDS_DENSE_TENSOR = False + + def materialize( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + """ + Materializes the bias as a `torch.Tensor`. This is very slow + and we don't attempt to make it fast. Only use for debugging/testing. + + Shape should be like `[*, q_seqlen, k_seqlen]` + """ + raise NotImplementedError() + + +def _get_default_bias_device(device: Optional[torch.device] = None) -> torch.device: + if device is None: + if torch.cuda.is_available(): + return torch.device("cuda") + if torch.mtia.is_available(): + return torch.device("mtia") + return torch.device("cpu") + return device + + +def _materialize_causal_mask( + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + *, + window_size: Optional[int] = None, + from_bottomright: bool = False, +) -> torch.Tensor: + create_as = dtype if dtype is not torch.bfloat16 else torch.float32 + tensor = torch.full( # type: ignore + shape, + dtype=create_as, + fill_value=1, + device=device, + ) + + num_queries, num_keys = shape[-2:] + shift = 0 + if from_bottomright: + shift = num_keys - num_queries + + mask = torch.tril(tensor, diagonal=shift).to(dtype) # type: ignore + if window_size is not None: + mask = torch.triu(mask, diagonal=shift - window_size + 1) + mask = torch.log(mask) + return mask.to(dtype) + + +@dataclass +class LocalAttentionFromBottomRightMask(AttentionBias): + """ + A local attention mask + + The query at position :math:`q` can attend the key at position :math:`k` if + :math:`q - window\\_left <= k + s <= q + window\\_right` + + With :math:`s = num\\_queries - num\\_keys` + + :Example: + + .. code-block:: python + + import torch + from xformers.ops import fmha + + bias = fmha.attn_bias.LocalAttentionFromBottomRightMask(window_left=1, window_right=2) + print(bias.materialize(shape=(4, 4)).exp()) + print(bias.materialize(shape=(4, 5)).exp()) + + .. code-block:: text + + # 4x4 + tensor([[1., 1., 1., 0.], + [1., 1., 1., 1.], + [0., 1., 1., 1.], + [0., 0., 1., 1.]]) + + # 4x5 + tensor([[1., 1., 1., 1., 0.], + [0., 1., 1., 1., 1.], + [0., 0., 1., 1., 1.], + [0., 0., 0., 1., 1.]]) + + :Illustration: + + .. figure:: /_static/local_attn.png + :width: 240px + + The total window size is :math:`window\\_left + 1 + window\\_right` + """ + + window_left: int + window_right: int + + def to(self, device) -> "LocalAttentionFromBottomRightMask": + return self + + def __post_init__(self) -> None: + if self.window_left < 0: + raise ValueError( + "Invalid window value passed to " + "`LocalAttentionFromBottomRightMask`: expected" + f"`window_left > 0` but got window_left={self.window_left}" + ) + if self.window_right < 0: + raise ValueError( + "Invalid window value passed to " + "`LocalAttentionFromBottomRightMask`: expected" + f"`window_right > 0` but got window_right={self.window_right}" + ) + + def materialize( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + create_as = dtype if dtype is not torch.bfloat16 else torch.float32 + mask = torch.full( # type: ignore + shape, + dtype=create_as, + fill_value=1, + device=device, + ) + + num_queries, num_keys = shape[-2:] + shift = num_keys - num_queries + + mask = torch.triu(mask, diagonal=shift - self.window_left) + mask = torch.tril(mask, diagonal=shift + self.window_right) + mask = torch.log(mask) + return mask.to(dtype) + + +class LowerTriangularFromBottomRightMask(AttentionBias): + """ + A causal masking. + + This mask is exactly the same as :attr:`LowerTriangularMask` when there is + the same number of queries and keys. + When the number of queries is different from the number of keys, + it is a triangular mask shifted so that the last query can attend to + the last key. + In other words, a query Q cannot attend to a key which is nearer the + final key than Q is to the final query. + + + .. figure:: /_static/causal_bottom_right.png + + The difference between :attr:`LowerTriangularMask` (left) and + :attr:`LowerTriangularFromBottomRightMask` (right). They become + equivalent if the number of queries equals the number of keys. + """ + + def to(self, device: torch.device) -> "LowerTriangularFromBottomRightMask": + assert ( + type(self) is LowerTriangularFromBottomRightMask + ), "Please implement in subclass" + return self + + def materialize( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + return _materialize_causal_mask( + shape, dtype=dtype, device=device, from_bottomright=True + ) + + def make_local_attention( + self, window_size: int + ) -> "LowerTriangularFromBottomRightLocalAttentionMask": + """ + Create a new bias which combines local + causal attention. + + See :attr:`LowerTriangularFromBottomRightLocalAttentionMask` + """ + return LowerTriangularFromBottomRightLocalAttentionMask(window_size) + + +@dataclass +class LowerTriangularFromBottomRightLocalAttentionMask( + LowerTriangularFromBottomRightMask +): + """ + A mask that combines both :attr:`LowerTriangularFromBottomRightMask` and + local attention. + + A query whose distance from the final query is X cannot attend to a key + whose distance to the final key is either of: + + * less than X (i.e. "causal attention", same as :attr:`LowerTriangularFromBottomRightMask`) + * greater than or equal to X + window_size (i.e. "local attention") + + + .. figure:: /_static/causal_bottom_right_local.png + + The mask from :attr:`LowerTriangularFromBottomRightLocalAttentionMask`. + The green area is calculated, and the grey area is masked out. + """ + + _window_size: int + + def to( + self, device: torch.device + ) -> "LowerTriangularFromBottomRightLocalAttentionMask": + assert ( + type(self) is LowerTriangularFromBottomRightLocalAttentionMask + ), "Please implement in subclass" + return self + + def __post_init__(self) -> None: + if self._window_size <= 0: + raise ValueError( + f"Expected `window_size > 0`, but window_size={self._window_size}" + ) + + def materialize( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + return _materialize_causal_mask( + shape, + dtype=dtype, + device=device, + window_size=self._window_size, + from_bottomright=True, + ) + + +@dataclass +class _SeqLenInfo: + """ + (Internal) Represents the division of a dimension into blocks. + + For example, to represents a dimension of length 7 divided into + three blocks of lengths 2, 3 and 2, use `from_seqlength([2, 3, 2])`. + The members will be: + max_seqlen: 3 + min_seqlen: 2 + seqstart_py: [0, 2, 5, 7] + seqstart: torch.IntTensor([0, 2, 5, 7]) + """ + + seqstart: torch.Tensor + max_seqlen: int + min_seqlen: int + seqstart_py: List[int] + + def to(self, device: torch.device) -> "_SeqLenInfo": + assert type(self) is _SeqLenInfo, "Please implement in subclass" + if self.seqstart.device == device: + return self + return _SeqLenInfo( + seqstart=_to_device(self.seqstart, device), + max_seqlen=self.max_seqlen, + min_seqlen=self.min_seqlen, + seqstart_py=self.seqstart_py, + ) + + def intervals(self) -> Iterable[Tuple[int, int]]: + yield from zip(self.seqstart_py, self.seqstart_py[1:]) + + @classmethod + def _get_seqstart( + cls, seqlens: Iterable[int], *, device: torch.device + ) -> Tuple[int, int, List[int], torch.Tensor]: + """ + Given sequence lengths, returns the min/max value and the sequence start + positions (offsets), with first element being 0 (returned in list and Tensor). + """ + + assert not isinstance(seqlens, torch.Tensor) + seqstart_py = [0] + max_seqlen = -1 + min_seqlen = -1 + for seqlen in seqlens: + min_seqlen = min(min_seqlen, seqlen) if min_seqlen != -1 else seqlen + max_seqlen = max(max_seqlen, seqlen) + seqstart_py.append(seqstart_py[len(seqstart_py) - 1] + seqlen) + seqstart = _to_device_tensor(seqstart_py, dtype=torch.int32, device=device) + + return (min_seqlen, max_seqlen, seqstart_py, seqstart) + + @classmethod + def from_seqlens( + cls, seqlens: Iterable[int], *, device: Optional[torch.device] = None + ) -> "_SeqLenInfo": + """ + Input tensors are assumed to be in shape [B, M, *] + """ + device = _get_default_bias_device(device) + min_seqlen, max_seqlen, seqstart_py, seqstart = cls._get_seqstart( + seqlens, device=device + ) + + return cls( + max_seqlen=max_seqlen, + min_seqlen=min_seqlen, + seqstart=seqstart, + seqstart_py=seqstart_py, + ) + + def from_seqlens_inplace(self, seqlens: Iterable[int]) -> None: + """ + Perform in-place update. You can only update with the same shape. + Can be useful with CUDA graphs. + """ + min_seqlen, max_seqlen, seqstart_py, seqstart = self._get_seqstart( + seqlens, device=self.seqstart.device + ) + + assert len(seqstart_py) == len(self.seqstart_py), ( + f"Old / New len {len(self.seqstart_py)} / {len(seqstart)}, " + f"Contents {self.seqstart_py} / {seqstart}" + ) + assert self.max_seqlen >= max_seqlen, ( + f"For inplace update, new max_seqlen {max_seqlen} " + f"cannot exceed the previous max_seqlen {self.max_seqlen}" + ) + for i in range(len(seqstart_py)): + self.seqstart_py[i] = seqstart_py[i] + self.seqstart.copy_(seqstart, non_blocking=True) + + def split( + self, x: torch.Tensor, batch_sizes: Optional[Sequence[int]] = None + ) -> List[torch.Tensor]: + if self.seqstart_py[-1] != x.shape[1] or x.shape[0] != 1: + raise ValueError( + f"Invalid `torch.Tensor` of shape {x.shape}, expected format " + f"(B, M, *) with B=1 and M={self.seqstart_py[-1]}\n" + f" seqstart: {self.seqstart_py}" + ) + if batch_sizes is None: + batch_sizes = [1] * (len(self.seqstart_py) - 1) + split_chunks = [] + it = 0 + for batch_size in batch_sizes: + split_chunks.append( + self.seqstart_py[it + batch_size] - self.seqstart_py[it] + ) + it += batch_size + return [ + tensor.reshape([bs, -1, *tensor.shape[2:]]) + for bs, tensor in zip(batch_sizes, x.split(split_chunks, dim=1)) + ] + + +@dataclass +class _PaddedSeqLenInfo(_SeqLenInfo): + """ + (Internal) Represents the division of a dimension into blocks which are + padded out to the same total length. + + For example, to represent a dimension of length 12 with space for + three blocks of length 4, but where the occupied lengths are + 2, 3 and 2, use `from_seqlens_padded([2, 3, 2], 4)`. + + The layout along the dimension is + + 0 ─► block 0 + block 0 + + + 4 ─► block 1 + block 1 + block 1 + + 8 ─► block 2 + block 2 + + + 12 ─► + + The members will be: + max_seqlen: 3 + min_seqlen: 2 + seqstart_py: [0, 4, 8, 12] + seqstart: torch.IntTensor([0, 4, 8, 12]) + seqlen_py: [2, 3, 2] + seqlen: torch.IntTensor([2, 3, 2]) + padding: 4 + """ + + seqlen: torch.Tensor + seqlen_py: List[int] + padding: int + # From parent: seqstart[i] contains the start position + # of the i-th sequence + # seqstart: torch.Tensor + + def __post_init__(self) -> None: + assert len(self.seqstart_py) == len(self.seqlen_py) + 1 + + def to(self, device: torch.device) -> "_PaddedSeqLenInfo": + assert type(self) is _PaddedSeqLenInfo, "Please implement in subclass" + if self.seqlen.device == device: + return self + return _PaddedSeqLenInfo( + # _SeqLenInfo + seqstart=_to_device(self.seqstart, device), + max_seqlen=self.max_seqlen, + min_seqlen=self.min_seqlen, + seqstart_py=self.seqstart_py, + # _PaddedSeqLenInfo + seqlen=_to_device(self.seqlen, device), + seqlen_py=self.seqlen_py, + padding=self.padding, + ) + + def intervals(self) -> Iterable[Tuple[int, int]]: + for (start, _), length in zip(super().intervals(), self.seqlen_py): + yield start, start + length + + @classmethod + def from_seqlens( + cls, seqlens: Iterable[int], *, device: Optional[torch.device] = None + ) -> "_SeqLenInfo": + raise RuntimeError( + "Use either `_SeqLenInfo.from_seqlens` or `_PaddedSeqLenInfo.from_seqlens_padded`" + ) + + @classmethod + def from_seqlens_padded( + cls, + seqlens: Sequence[int], + padding: int, + *, + device: Optional[torch.device] = None, + ) -> "_PaddedSeqLenInfo": + """ + Input tensors are assumed to be in shape [B, M, *] + seqstart = padding * torch.arange(batch_size) + """ + assert not isinstance(seqlens, torch.Tensor) + assert all( + seqlen <= padding for seqlen in seqlens + ), f"Seqlens {seqlens} Padding {padding}" + device = _get_default_bias_device(device) + seqstart_py = list(range(0, len(seqlens) * padding + 1, padding)) + seqlen = _to_device_tensor(seqlens, dtype=torch.int32, device=device) + return cls( + seqlen=seqlen, + seqlen_py=seqlens if isinstance(seqlens, list) else list(seqlens), + max_seqlen=max(seqlens), + min_seqlen=min(seqlens), + seqstart=_to_device_tensor(seqstart_py, dtype=torch.int32, device=device), + seqstart_py=seqstart_py, + padding=padding, + ) + + def from_seqlens_padded_inplace(self, seqlens: Sequence[int]) -> None: + """ + Perform in-place update. You can only update with the same shape. + Can be useful with CUDA graphs. + Note: we don't update padding because they would have been already baked + into CUDA graphs during the generation. + """ + assert not isinstance(seqlens, torch.Tensor) + assert all( + seqlen <= self.padding for seqlen in seqlens + ), f"Seqlens {seqlens} Padding {self.padding}" + seqlen_tensor = torch.tensor(seqlens, dtype=torch.int32) + + assert len(self.seqlen_py) == len(seqlens), ( + f"Old/New len {len(self.seqlen_py)} / {len(seqlens)}, " + f"Contents {self.seqlen_py} / {seqlens}" + ) + assert self.max_seqlen >= max(seqlens), ( + f"For inplace update, new max_seqlen {max(seqlens)} " + f"cannot exceed the previous max_seqlen {self.max_seqlen}" + ) + + for i in range(len(self.seqlen_py)): + self.seqlen_py[i] = seqlens[i] + + self.seqlen.copy_(seqlen_tensor, non_blocking=True) + + def split( + self, x: torch.Tensor, batch_sizes: Optional[Sequence[int]] = None + ) -> List[torch.Tensor]: + raise NotImplementedError("_PaddedSeqLenInfo.split") + + +@dataclass +class _GappySeqInfo(_SeqLenInfo): + """ + (Internal) Flexible equivalent of _PaddedSeqLenInfo. There are two + distinct semantics. + + (1) For non-paged masks: + Represents the division of a dimension into blocks which are + anywhere. Each just has a start and a length. The final start is the total + length of the dimension. + + For example, to represent a dimension of length 14 like follows with + three occupied lengths of + 6, 3 and 1, use `from_seqlens_padded([0, 7, 12, 14], [6, 3, 1])`. + + The layout along the dimension is + + 0 ─► block 0 + block 0 + block 0 + block 0 + 4 ─► block 0 + block 0 + + block 1 + 8 ─► block 1 + block 1 + + + 12 ─► block 2 + + + The members will be: + max_seqlen: 6 + min_seqlen: 1 + seqstart_py: [0, 7, 12, 14] + seqstart: torch.IntTensor([0, 7, 12, 14]) + seqlen_py: [6, 3, 1] + seqlen: torch.IntTensor([6, 3, 1]) + + (2) For paged masks: + The notional space is divided into batch-size-many blocks. + seqstart and seqstart_py is an offset in the block, not in + the whole space, and the extra last element is not important. + And seqlen is the index of the last key in the block. + Otherwise as above. + """ + + seqlen: torch.Tensor + seqlen_py: Sequence[int] + # From parent: seqstart[i] contains the start position + # of the i-th sequence + # seqstart: torch.Tensor + + def to(self, device: torch.device) -> "_GappySeqInfo": + assert type(self) is _GappySeqInfo, "Please implement in subclass" + if self.seqlen.device == device: + return self + return _GappySeqInfo( + # _SeqLenInfo + seqstart=_to_device(self.seqstart, device), + max_seqlen=self.max_seqlen, + min_seqlen=self.min_seqlen, + seqstart_py=self.seqstart_py, + # _GappySeqInfo + seqlen=_to_device(self.seqlen, device), + seqlen_py=self.seqlen_py, + ) + + def intervals(self) -> Iterable[Tuple[int, int]]: + for (start, _), length in zip(super().intervals(), self.seqlen_py): + yield start, start + length + + @classmethod + def from_seqlens( + cls, seqlens: Iterable[int], *, device: Optional[torch.device] = None + ) -> "_SeqLenInfo": + raise NotImplementedError() + + @classmethod + def from_seqlens_gappy( + cls, + seqstarts: Sequence[int], + seqlens: Sequence[int], + paged: bool, + *, + device: torch.device, + ) -> "_GappySeqInfo": + assert not isinstance(seqlens, torch.Tensor) + seqstart_py = list(seqstarts) + if len(seqlens) == 0: + raise ValueError("No elements") + if len(seqstarts) - len(seqlens) != 1: + raise ValueError( + f"len(seqstarts)={seqstarts} should be len(seqlens)={seqlens}" + ) + max_seqlen = max(seqlens) + min_seqlen = min(seqlens) + if paged: + seqstart_py.append(-1) + seqlens = [i + j for i, j in zip(seqstart_py, seqlens)] + seqlen = _to_device_tensor(seqlens, dtype=torch.int32, device=device) + return cls( + seqlen=seqlen, + seqlen_py=seqlens, + max_seqlen=max_seqlen, + min_seqlen=min_seqlen, + seqstart=_to_device_tensor(seqstart_py, dtype=torch.int32, device=device), + seqstart_py=seqstart_py, + ) + + def split( + self, x: torch.Tensor, batch_sizes: Optional[Sequence[int]] = None + ) -> List[torch.Tensor]: + raise NotImplementedError("_GappySeqInfo.split") + + +@dataclass +class BlockDiagonalMask(AttentionBias): + """ + A block-diagonal mask that can be passed as ``attn_bias`` + argument to :attr:`xformers.ops.memory_efficient_attention`. + + Queries and Keys are each divided into the same number of blocks. + Queries in block i only attend to keys in block i. + + .. figure:: /_static/block_diag_bias.png + + This bias can be used to handle a batch of sequences of + different lengths, via :attr:`BlockDiagonalMask.from_tensor_list` + + :Example: + + .. code-block:: python + + import torch + from xformers.ops import fmha + + K = 16 + dtype = torch.float16 + device = "cuda" + list_x = [ + torch.randn([1, 3, 1, K], dtype=dtype, device=device), + torch.randn([1, 6, 1, K], dtype=dtype, device=device), + torch.randn([1, 2, 1, K], dtype=dtype, device=device), + ] + attn_bias, x = fmha.BlockDiagonalMask.from_tensor_list(list_x) + linear = torch.nn.Linear(K, K * 3).to(device=device, dtype=dtype) + + q, k, v = linear(x).reshape([1, -1, 1, 3, K]).unbind(-2) + out = fmha.memory_efficient_attention(q, k, v, attn_bias=attn_bias) + list_out = attn_bias.split(out) + print(list_out[0].shape) # [1, 3, 1, K] + assert tuple(list_out[0].shape) == (1, 3, 1, K) + + """ + + q_seqinfo: _SeqLenInfo + k_seqinfo: _SeqLenInfo + _batch_sizes: Optional[Sequence[int]] = None + + def to(self, device) -> "BlockDiagonalMask": + assert type(self) is BlockDiagonalMask, "Please implement in subclass" + return BlockDiagonalMask( + q_seqinfo=self.q_seqinfo.to(device), + k_seqinfo=self.k_seqinfo.to(device), + _batch_sizes=self._batch_sizes, + ) + + def _create_block_mask( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + return torch.zeros( + shape, + dtype=dtype, + device=device, + ) + + def materialize( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + """Materialize the attention bias - for debugging & testing""" + assert shape[-1] == self.k_seqinfo.seqstart_py[-1], ( + shape[-1], + self.k_seqinfo.seqstart_py[-1], + ) + assert shape[-2] == self.q_seqinfo.seqstart_py[-1], ( + shape[-2], + self.q_seqinfo.seqstart_py[-1], + ) + mask = torch.empty(shape[-2:], dtype=dtype, device=device) + mask.fill_(-math.inf) + for i, ((q_start, q_end), (k_start, k_end)) in enumerate( + zip( + self.q_seqinfo.intervals(), + self.k_seqinfo.intervals(), + ) + ): + mask[q_start:q_end, k_start:k_end] = self._create_block_mask( + (q_end - q_start, k_end - k_start), + dtype=dtype, + device=device, + ) + for _ in range(len(shape) - 2): + mask = mask.unsqueeze(0) + return mask.expand(shape) + + @classmethod + def from_seqlens( + cls, + q_seqlen: Sequence[int], + kv_seqlen: Optional[Sequence[int]] = None, + *, + device: Optional[torch.device] = None, + ) -> "BlockDiagonalMask": + """Creates a :attr:`BlockDiagonalMask` from a list of tensors lengths for query and key/value. + + Args: + q_seqlen (Union[Sequence[int], torch.Tensor]): List or tensor of sequence lengths for query tensors + kv_seqlen (Union[Sequence[int], torch.Tensor], optional): List or tensor of sequence lengths for key/value. + (Defaults to ``q_seqlen``.) + Returns: + BlockDiagonalMask + """ + device = _get_default_bias_device(device) + assert kv_seqlen is None or len(q_seqlen) == len(kv_seqlen) + q_seqinfo = _SeqLenInfo.from_seqlens(q_seqlen, device=device) + if kv_seqlen is None or q_seqlen == kv_seqlen: + k_seqinfo = q_seqinfo + else: + k_seqinfo = _SeqLenInfo.from_seqlens(kv_seqlen, device=device) + return cls(q_seqinfo=q_seqinfo, k_seqinfo=k_seqinfo) + + @classmethod + def from_tensor_list( + cls, + tensors: Sequence[torch.Tensor], + ) -> Tuple["BlockDiagonalMask", torch.Tensor]: + """Creates a :attr:`BlockDiagonalMask` from a list of tensors, and returns the tensors + concatenated on the sequence length dimension + + .. figure:: /_static/block_diag_cat_split.png + + See also :attr:`BlockDiagonalMask.split` to split the returned + :attr:`torch.Tensor` back to a list of tensors of varying sequence length + + Args: + tensors (Sequence[torch.Tensor]): A list of tensors of shape ``[B, M_i, *]``. + All tensors should have the same dimension and the same batch size ``B``, but + they can have different sequence length ``M``. + + Returns: + Tuple[BlockDiagonalMask, torch.Tensor]: The corresponding bias for the attention + along with `tensors` concatenated on the sequence length dimension, with shape ``[1, sum_i{M_i}, *]`` + """ + batch_sizes = [tensor.shape[0] for tensor in tensors] + seqlens = [] + for x in tensors: + for _ in range(x.shape[0]): + seqlens.append(x.shape[1]) + block_diag = cls.from_seqlens(seqlens) + block_diag._batch_sizes = batch_sizes + tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in tensors) + concat_tensors = torch.cat(tensors_bs1, dim=1) + return block_diag, concat_tensors + + @classmethod + def from_tensor_lists_qkv( + cls, + tensors_q: Sequence[torch.Tensor], + tensors_k: Sequence[torch.Tensor], + tensors_v: Optional[Sequence[torch.Tensor]] = None, + ) -> Tuple["BlockDiagonalMask", torch.Tensor, torch.Tensor, Optional[torch.Tensor]]: + assert len(tensors_q) == len(tensors_k) + assert tensors_v is None or len(tensors_v) == len(tensors_q) + batch_sizes = [tensor.shape[0] for tensor in tensors_q] + q_seqlens, kv_seqlens = [], [] + for i, (q, k) in enumerate(zip(tensors_q, tensors_k)): + assert q.shape[0] == k.shape[0] + q_seqlens += [q.shape[1]] * q.shape[0] + kv_seqlens += [k.shape[1]] * k.shape[0] + assert tensors_v is None or tensors_v[i].shape[:2] == k.shape[:2] + block_diag = cls.from_seqlens(q_seqlens, kv_seqlens) + block_diag._batch_sizes = batch_sizes + return ( + block_diag, + torch.cat([x.reshape([1, -1, *x.shape[2:]]) for x in tensors_q], dim=1), + torch.cat([x.reshape([1, -1, *x.shape[2:]]) for x in tensors_k], dim=1), + ( + torch.cat([x.reshape([1, -1, *x.shape[2:]]) for x in tensors_v], dim=1) + if tensors_v is not None + else None + ), + ) + + def split_queries(self, tensor: torch.Tensor) -> Sequence[torch.Tensor]: + return self.q_seqinfo.split(tensor, self._batch_sizes) + + def split_kv(self, tensor: torch.Tensor) -> Sequence[torch.Tensor]: + return self.k_seqinfo.split(tensor, self._batch_sizes) + + def split(self, tensor: torch.Tensor) -> Sequence[torch.Tensor]: + """The inverse operation of :attr:`BlockDiagonalCausalMask.from_tensor_list` + + Args: + tensor (torch.Tensor): Tensor of tokens of shape ``[1, sum_i{M_i}, *]`` + + Returns: + Sequence[torch.Tensor]: A list of tokens with possibly different sequence lengths + """ + assert self.q_seqinfo is self.k_seqinfo + return self.q_seqinfo.split(tensor, self._batch_sizes) + + def make_causal(self) -> "BlockDiagonalCausalMask": + """Makes each block causal""" + return BlockDiagonalCausalMask( + q_seqinfo=self.q_seqinfo, + k_seqinfo=self.k_seqinfo, + _batch_sizes=self._batch_sizes, + ) + + def make_causal_from_bottomright(self) -> "BlockDiagonalCausalFromBottomRightMask": + """Makes each block causal with a possible non-causal prefix""" + return BlockDiagonalCausalFromBottomRightMask( + q_seqinfo=self.q_seqinfo, + k_seqinfo=self.k_seqinfo, + _batch_sizes=self._batch_sizes, + ) + + def make_local_attention( + self, window_size: int + ) -> "BlockDiagonalCausalLocalAttentionMask": + """Experimental: Makes each block causal with local attention""" + return BlockDiagonalCausalLocalAttentionMask( + q_seqinfo=self.q_seqinfo, + k_seqinfo=self.k_seqinfo, + _batch_sizes=self._batch_sizes, + _window_size=window_size, + ) + + def make_local_attention_from_bottomright( + self, window_size: int + ) -> "BlockDiagonalCausalLocalAttentionFromBottomRightMask": + """Experimental: Makes each block causal with local attention, start from bottom right""" + return BlockDiagonalCausalLocalAttentionFromBottomRightMask( + q_seqinfo=self.q_seqinfo, + k_seqinfo=self.k_seqinfo, + _batch_sizes=self._batch_sizes, + _window_size=window_size, + ) + + +@dataclass +class BlockDiagonalCausalMask(BlockDiagonalMask): + """ + Same as :attr:`xformers.ops.fmha.attn_bias.BlockDiagonalMask`, except that each block is causal. + + Queries and Keys are each divided into the same number of blocks. + A query Q in block i cannot attend to a key which is not in block i, + nor one which is farther from the initial key in block i than Q + is from the initial query in block i. + """ + + def to(self, device) -> "BlockDiagonalCausalMask": + assert type(self) is BlockDiagonalCausalMask, "Please implement in subclass" + return BlockDiagonalCausalMask( + q_seqinfo=self.q_seqinfo.to(device), + k_seqinfo=self.k_seqinfo.to(device), + _batch_sizes=self._batch_sizes, + ) + + def _create_block_mask( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + return LowerTriangularMask().materialize( + shape, + dtype=dtype, + device=device, + ) + + +@dataclass +class BlockDiagonalCausalFromBottomRightMask(BlockDiagonalMask): + """ + Same as :attr:`xformers.ops.fmha.attn_bias.BlockDiagonalMask`, except that each block is causal. + This mask allows for a non-causal prefix + NOTE: Each block should have `num_keys >= num_queries` otherwise the forward pass is not + defined (softmax of vector of `-inf` in the attention) + + Queries and keys are each divided into the same number of blocks. + A query Q in block i cannot attend to a key which is not in block i, + nor one which nearer the final key in block i than Q is to the + final query in block i. + """ + + def to(self, device) -> "BlockDiagonalCausalFromBottomRightMask": + assert ( + type(self) is BlockDiagonalCausalFromBottomRightMask + ), "Please implement in subclass" + return BlockDiagonalCausalFromBottomRightMask( + q_seqinfo=self.q_seqinfo.to(device), + k_seqinfo=self.k_seqinfo.to(device), + _batch_sizes=self._batch_sizes, + ) + + def __post_init__(self) -> None: + for i, ((q_start, q_end), (k_start, k_end)) in enumerate( + zip( + self.q_seqinfo.intervals(), + self.k_seqinfo.intervals(), + ) + ): + num_queries = q_end - q_start + num_keys = k_end - k_start + if num_keys < num_queries: + raise ValueError( + f"Block #{i} has num_keys={num_keys} and num_queries={num_queries}." + " Expected `num_keys >= num_queries`" + ) + + def _create_block_mask( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + return LowerTriangularFromBottomRightMask().materialize( + shape=shape, dtype=dtype, device=device + ) + + +@dataclass +class BlockDiagonalPaddedKeysMask(AttentionBias): + """ + Same as :attr:`xformers.ops.fmha.attn_bias.BlockDiagonalMask`, + except we support padding for k/v + + The keys and values are divided into blocks which are padded out to + the same total length. + For example, if there is space for 12 keys, for three blocks of + max length 4, but we only want to use the first 2, 3 and 2 + of each block, use `kv_padding=4` and `kv_seqlens=[2, 3, 2]`. + The queries are divided into blocks, without padding, of lengths given by + q_seqlen. + + A query Q in block i cannot attend to a key which is not in block i, + nor one which is not in use (i.e. in the padded area). + """ + + q_seqinfo: _SeqLenInfo + k_seqinfo: _PaddedSeqLenInfo + + def to(self, device) -> "BlockDiagonalPaddedKeysMask": + assert type(self) is BlockDiagonalPaddedKeysMask, "Please implement in subclass" + return BlockDiagonalPaddedKeysMask( + q_seqinfo=self.q_seqinfo.to(device), + k_seqinfo=self.k_seqinfo.to(device), + ) + + def _create_block_mask( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + return torch.zeros([1], device=device, dtype=dtype) + + def materialize( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + """Materialize the attention bias - for debugging & testing""" + if shape[-1] != self.k_seqinfo.seqstart_py[-1]: + raise ValueError("k shapes wrong") + if shape[-2] != self.q_seqinfo.seqstart_py[-1]: + raise ValueError("q shapes wrong") + mask = torch.empty(shape[-2:], dtype=dtype, device=device) + mask.fill_(-math.inf) + for i, ((q_start, q_end), (k_start, k_end)) in enumerate( + zip( + self.q_seqinfo.intervals(), + self.k_seqinfo.intervals(), + ) + ): + mask[q_start:q_end, k_start:k_end] = self._create_block_mask( + (q_end - q_start, k_end - k_start), + dtype=dtype, + device=device, + ) + for _ in range(len(shape) - 2): + mask = mask.unsqueeze(0) + return mask.expand(shape) + + @classmethod + def from_seqlens( + cls, + q_seqlen: Sequence[int], + kv_padding: int, + kv_seqlen: Sequence[int], + causal_diagonal: Any = None, + *, + device: Optional[torch.device] = None, + ) -> "BlockDiagonalPaddedKeysMask": + """Creates a :attr:`BlockDiagonalPaddedKeysMask` from a list of tensor + lengths for query and key/value. + + Args: + q_seqlen (Sequence[int]): List or tensor of sequence lengths for query tensors + kv_padding (int): Padding for k/v - also an upperbound on each individual key length + kv_seqlen (Sequence[int]): List or tensor of sequence lengths for key/value. + causal_diagonal: unused, for BC only + Returns: + BlockDiagonalPaddedKeysMask + """ + device = _get_default_bias_device(device) + assert kv_seqlen is None or len(q_seqlen) == len(kv_seqlen), ( + q_seqlen, + kv_seqlen, + ) + q_seqinfo = _SeqLenInfo.from_seqlens(q_seqlen, device=device) + k_seqinfo = _PaddedSeqLenInfo.from_seqlens_padded( + kv_seqlen, kv_padding, device=device + ) + return cls(q_seqinfo=q_seqinfo, k_seqinfo=k_seqinfo) + + def make_paged( + self, + block_tables: torch.Tensor, + page_size: int, + paged_type: Type["PagedBlockDiagonalPaddedKeysMask"], + ) -> "PagedBlockDiagonalPaddedKeysMask": + paged_bias = paged_type( + q_seqinfo=self.q_seqinfo, + k_seqinfo=_PaddedSeqLenInfo( + seqstart=self.k_seqinfo.seqstart, + seqstart_py=self.k_seqinfo.seqstart_py, + seqlen=self.k_seqinfo.seqlen, + seqlen_py=self.k_seqinfo.seqlen_py, + padding=block_tables.shape[1] * page_size, + max_seqlen=self.k_seqinfo.max_seqlen, + min_seqlen=self.k_seqinfo.min_seqlen, + ), + block_tables=block_tables, + page_size=page_size, + ) + return paged_bias + + +@dataclass +class BlockDiagonalCausalWithOffsetPaddedKeysMask(BlockDiagonalPaddedKeysMask): + """ + Same as :attr:`xformers.ops.fmha.attn_bias.BlockDiagonalCausalMask`, + except an offset on causality is allowed for each block and we support padding for k/v + + The keys and values are divided into blocks which are padded out to + the same total length. + For example, if there is space for 12 keys, for three blocks of + max length 4, but we only want to use the first 2, 3 and 2 + of each block, use `kv_padding=4` and `kv_seqlens=[2, 3, 2]`. + The queries are divided into blocks, without padding, of lengths given by + q_seqlen. + + A query Q in block i cannot attend to a key which is not in block i, + nor one which is not in use (i.e. in the padded area), + nor one which is nearer to the final key in block i + than Q is to the final query in block i. + """ + + causal_diagonal: Any = None # unused. Exists for BC only. + + def to(self, device) -> "BlockDiagonalCausalWithOffsetPaddedKeysMask": + assert ( + type(self) is BlockDiagonalCausalWithOffsetPaddedKeysMask + ), "Please implement in subclass" + return BlockDiagonalCausalWithOffsetPaddedKeysMask( + q_seqinfo=self.q_seqinfo.to(device), + k_seqinfo=self.k_seqinfo.to(device), + ) + + def _create_block_mask( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + return LowerTriangularFromBottomRightMask().materialize( + shape=shape, dtype=dtype, device=device + ) + + @classmethod + def from_seqlens( + cls, + q_seqlen: Sequence[int], + kv_padding: int, + kv_seqlen: Sequence[int], + causal_diagonal: Any = None, + *, + device: Optional[torch.device] = None, + ) -> "BlockDiagonalCausalWithOffsetPaddedKeysMask": + """Creates a :attr:`BlockDiagonalCausalWithOffsetPaddedKeysMask` from a list of tensor + lengths for query and key/value. + + Args: + q_seqlen (Sequence[int]): List or tensor of sequence lengths for query tensors + kv_padding (int): Padding for k/v - also an upperbound on each individual key length + kv_seqlen (Sequence[int]): List or tensor of sequence lengths for key/value. + causal_diagonal: unused, for BC only + Returns: + BlockDiagonalCausalWithOffsetPaddedKeysMask + """ + assert kv_seqlen is None or len(q_seqlen) == len(kv_seqlen), ( + q_seqlen, + kv_seqlen, + ) + device = _get_default_bias_device(device) + q_seqinfo = _SeqLenInfo.from_seqlens(q_seqlen, device=device) + k_seqinfo = _PaddedSeqLenInfo.from_seqlens_padded( + kv_seqlen, kv_padding, device=device + ) + return cls(q_seqinfo=q_seqinfo, k_seqinfo=k_seqinfo) + + +@dataclass +class BlockDiagonalLocalAttentionPaddedKeysMask(BlockDiagonalPaddedKeysMask): + """ + Like :attr:`xformers.ops.fmha.attn_bias.BlockDiagonalCausalLocalAttentionPaddedKeysMask`, + except that this is non-causal. + + A query Q in block i cannot attend to a key which is not in block i, + nor one which is not in use (i.e. in the padded area), + nor one whose distance to the final key in block i + is more than window_left further or window_right nearer + than Q is to the final query in block i. + + A query attends to at most window_left + window_right - 1 keys. + + NOTE that if window_right is 0, then this is like a + BlockDiagonalCausalLocalAttentionPaddedKeysMask whose window_size is equal to + window_left - 1. + """ + + window_left: int + window_right: int + + def to(self, device) -> "BlockDiagonalLocalAttentionPaddedKeysMask": + assert ( + type(self) is BlockDiagonalLocalAttentionPaddedKeysMask + ), "Please implement in subclass" + return BlockDiagonalLocalAttentionPaddedKeysMask( + q_seqinfo=self.q_seqinfo.to(device), + k_seqinfo=self.k_seqinfo.to(device), + window_left=self.window_left, + window_right=self.window_right, + ) + + def _create_block_mask( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + return LocalAttentionFromBottomRightMask( + window_left=self.window_left, window_right=self.window_right + ).materialize(shape=shape, dtype=dtype, device=device) + + @classmethod + def from_seqlens_local( + cls, + q_seqlen: Sequence[int], + kv_padding: int, + kv_seqlen: Sequence[int], + window_left: int, + window_right: int, + ) -> "BlockDiagonalLocalAttentionPaddedKeysMask": + assert kv_seqlen is None or len(q_seqlen) == len(kv_seqlen), ( + q_seqlen, + kv_seqlen, + ) + q_seqinfo = _SeqLenInfo.from_seqlens(q_seqlen) + k_seqinfo = _PaddedSeqLenInfo.from_seqlens_padded(kv_seqlen, kv_padding) + return cls( + q_seqinfo=q_seqinfo, + k_seqinfo=k_seqinfo, + window_left=window_left, + window_right=window_right, + ) + + +@dataclass +class BlockDiagonalCausalLocalAttentionPaddedKeysMask(BlockDiagonalPaddedKeysMask): + """ + Like :attr:`xformers.ops.fmha.attn_bias.BlockDiagonalCausalWithOffsetPaddedKeysMask`, + except with a window size. + + A query Q in block i cannot attend to a key which is not in block i, + nor one which is not in use (i.e. in the padded area), + nor one which is nearer to the final key in block i + than Q is to the final query in block i, nor one that is at least + window_size further from the final key in block i than Q is + to the final query in block i. + """ + + _window_size: int + + def to(self, device) -> "BlockDiagonalCausalLocalAttentionPaddedKeysMask": + assert ( + type(self) is BlockDiagonalCausalLocalAttentionPaddedKeysMask + ), "Please implement in subclass" + return BlockDiagonalCausalLocalAttentionPaddedKeysMask( + q_seqinfo=self.q_seqinfo.to(device), + k_seqinfo=self.k_seqinfo.to(device), + _window_size=self._window_size, + ) + + def _create_block_mask( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + return _materialize_causal_mask( + shape=shape, + dtype=dtype, + device=device, + window_size=self._window_size, + from_bottomright=True, + ) + + @classmethod + def from_seqlens_local( + cls, + q_seqlen: Sequence[int], + kv_padding: int, + kv_seqlen: Sequence[int], + window_size: int, + ) -> "BlockDiagonalCausalLocalAttentionPaddedKeysMask": + assert kv_seqlen is None or len(q_seqlen) == len(kv_seqlen), ( + q_seqlen, + kv_seqlen, + ) + q_seqinfo = _SeqLenInfo.from_seqlens(q_seqlen) + k_seqinfo = _PaddedSeqLenInfo.from_seqlens_padded(kv_seqlen, kv_padding) + return cls(q_seqinfo=q_seqinfo, k_seqinfo=k_seqinfo, _window_size=window_size) + + +@dataclass +class PagedBlockDiagonalPaddedKeysMask(AttentionBias): + """ + Same as BlockDiagonalPaddedKeysMask, but for paged attention. + block_tables has shape [batch_size, max_num_pages] and K/V have shape + [1, max_num_pages * page_size, num_heads, head_dim] + or [1, max_num_pages * page_size, num_groups, num_heads, head_dim] + """ + + q_seqinfo: _SeqLenInfo + k_seqinfo: _PaddedSeqLenInfo + block_tables: torch.Tensor + page_size: int + + _UNPAGED_TYPE: ClassVar[Type[BlockDiagonalPaddedKeysMask]] = ( + BlockDiagonalPaddedKeysMask + ) + + def to(self, device: torch.device) -> "PagedBlockDiagonalPaddedKeysMask": + assert ( + type(self) is PagedBlockDiagonalPaddedKeysMask + ), "Please implement in subclass" + return PagedBlockDiagonalPaddedKeysMask( + q_seqinfo=self.q_seqinfo.to(device), + k_seqinfo=self.k_seqinfo.to(device), + block_tables=_to_device(self.block_tables, device), + page_size=self.page_size, + ) + + def materialize( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + """Materialize the attention bias - for debugging & testing""" + # First create a non-paged mask, then cut individual pages and + # copy them to their places in the physical mask, using block tables + + max_row_len = self.block_tables.shape[1] * self.page_size + bias_nonpaged = self._UNPAGED_TYPE( + q_seqinfo=self.q_seqinfo, + k_seqinfo=_PaddedSeqLenInfo.from_seqlens_padded( + self.k_seqinfo.seqlen_py, max_row_len + ), + ) + mask_nonpaged = bias_nonpaged.materialize(shape, dtype, device) + + n_used_blocks = cast(int, self.block_tables.max().item() + 1) + max_physical_len = n_used_blocks * self.page_size + mask_paged = torch.empty( + mask_nonpaged.shape[:-1] + (max_physical_len,), dtype=dtype, device=device + ) + mask_paged.fill_(-math.inf) + for b, (q_start, q_end) in enumerate(self.q_seqinfo.intervals()): + for logical_page_idx in range(self.block_tables.shape[1]): + physical_page_idx = cast( + int, self.block_tables[b][logical_page_idx].item() + ) + k_logical_start = b * max_row_len + logical_page_idx * self.page_size + k_logical_end = k_logical_start + self.page_size + k_physical_start = physical_page_idx * self.page_size + k_physical_end = k_physical_start + self.page_size + mask_paged[..., q_start:q_end, k_physical_start:k_physical_end] = ( + mask_nonpaged[..., q_start:q_end, k_logical_start:k_logical_end] + ) + return mask_paged + + @classmethod + def from_seqlens( + cls, + q_seqlen: Sequence[int], + kv_seqlen: Sequence[int], + block_tables: torch.Tensor, + page_size: int, + *, + device: Optional[torch.device] = None, + ) -> "PagedBlockDiagonalPaddedKeysMask": + """Creates a :attr:`PagedBlockDiagonalPaddedKeysMask` from a list of tensor + lengths for query and key/value. + + Args: + q_seqlen (Sequence[int]): List or tensor of sequence lengths for query tensors + kv_padding (int): Padding for k/v - also an upperbound on each individual key length + kv_seqlen (Sequence[int]): List or tensor of sequence lengths for key/value. + causal_diagonal: unused, for BC only + Returns: + PagedBlockDiagonalPaddedKeysMask + """ + assert len(q_seqlen) == len(kv_seqlen), ( + q_seqlen, + kv_seqlen, + ) + device = _get_default_bias_device(device) + q_seqinfo = _SeqLenInfo.from_seqlens(q_seqlen, device=device) + k_seqinfo = _PaddedSeqLenInfo.from_seqlens_padded( + kv_seqlen, padding=block_tables.shape[1] * page_size, device=device + ) + return cls( + q_seqinfo=q_seqinfo, + k_seqinfo=k_seqinfo, + block_tables=block_tables, + page_size=page_size, + ) + + +@dataclass +class PagedBlockDiagonalCausalWithOffsetPaddedKeysMask( + PagedBlockDiagonalPaddedKeysMask +): + """ + Same as BlockDiagonalCausalWithOffsetPaddedKeysMask, but for paged attention. + block_tables has shape [batch_size, max_num_pages] and K/V have shape + [1, max_num_pages * page_size, num_heads, head_dim] + or [1, max_num_pages * page_size, num_groups, num_heads, head_dim] + """ + + _UNPAGED_TYPE = BlockDiagonalCausalWithOffsetPaddedKeysMask + + def to( + self, device: torch.device + ) -> "PagedBlockDiagonalCausalWithOffsetPaddedKeysMask": + assert ( + type(self) is PagedBlockDiagonalCausalWithOffsetPaddedKeysMask + ), "Please implement in subclass" + return PagedBlockDiagonalCausalWithOffsetPaddedKeysMask( + q_seqinfo=self.q_seqinfo.to(device), + k_seqinfo=self.k_seqinfo.to(device), + block_tables=_to_device(self.block_tables, device), + page_size=self.page_size, + ) + + +@dataclass +class BlockDiagonalGappyKeysMask(AttentionBias): + """ + Same as :attr:`xformers.ops.fmha.attn_bias.BlockDiagonalMask`, + except k/v is gappy. + + A query Q in block i only attends to a key which is in block i. + """ + + q_seqinfo: _SeqLenInfo + k_seqinfo: _GappySeqInfo + + def to(self, device: torch.device) -> "BlockDiagonalGappyKeysMask": + assert type(self) is BlockDiagonalGappyKeysMask, "Please implement in subclass" + return BlockDiagonalGappyKeysMask( + q_seqinfo=self.q_seqinfo.to(device), + k_seqinfo=self.k_seqinfo.to(device), + ) + + def materialize( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + """Materialize the attention bias - for debugging & testing""" + if shape[-1] != self.k_seqinfo.seqstart_py[-1]: + raise ValueError("k shapes wrong", (shape, self.k_seqinfo)) + if shape[-2] != self.q_seqinfo.seqstart_py[-1]: + raise ValueError("q shapes wrong", (shape, self.q_seqinfo)) + mask = torch.empty(shape[-2:], dtype=dtype, device=device) + mask.fill_(-math.inf) + for (q_start, q_end), (k_start, k_end) in zip( + self.q_seqinfo.intervals(), + self.k_seqinfo.intervals(), + ): + mask[q_start:q_end, k_start:k_end] = 0 + for _ in range(len(shape) - 2): + mask = mask.unsqueeze(0) + return mask.expand(shape) + + @classmethod + def from_seqlens( + cls, + q_seqlen: Sequence[int], + kv_seqstarts: Sequence[int], + kv_seqlen: Sequence[int], + *, + device: Optional[torch.device] = None, + ) -> "BlockDiagonalGappyKeysMask": + """Creates a :attr:`BlockDiagonalGappyKeysMask` from a list of tensor + lengths for query and key/value. + """ + assert len(q_seqlen) == len(kv_seqlen), ( + q_seqlen, + kv_seqlen, + ) + device = _get_default_bias_device(device) + q_seqinfo = _SeqLenInfo.from_seqlens(q_seqlen, device=device) + k_seqinfo = _GappySeqInfo.from_seqlens_gappy( + kv_seqstarts, kv_seqlen, False, device=device + ) + return cls(q_seqinfo=q_seqinfo, k_seqinfo=k_seqinfo) + + def make_paged( + self, + block_tables: torch.Tensor, + page_size: int, + notional_padding: int, + paged_type: Type["PagedBlockDiagonalGappyKeysMask"], + ) -> AttentionBias: + """ + Assuming our keys actually live in separate blocks of length + notional_padding, convert to a Paged version, avoiding GPU syncs. + """ + if notional_padding % page_size: + raise ValueError( + "Notional padding should be divisible by the page size," + f" but got {notional_padding=}, {page_size=}." + ) + max_row_len = block_tables.shape[1] * page_size + new_seqstarts_py = [ + start - i * notional_padding + for i, start in enumerate(self.k_seqinfo.seqstart_py[:-1]) + ] + new_seqstarts_py.append(-1) + assert all( + 0 <= i < max_row_len for i in new_seqstarts_py[:-1] + ), f"{max_row_len=} {new_seqstarts_py=}" + + # Sequence info is duplicated on CPU and GPU, + # but we process them independently to avoid GPU sync. + batch_size = len(self.k_seqinfo.seqlen_py) + notional_starts = notional_padding * torch.arange( + batch_size + 1, + device=block_tables.device, + dtype=torch.int32, + ) + new_seqstarts = self.k_seqinfo.seqstart - notional_starts + + new_seqlens_py = [ + i + j for i, j in zip(new_seqstarts_py, self.k_seqinfo.seqlen_py) + ] + new_seqlens = self.k_seqinfo.seqlen + new_seqstarts[:-1] + + k_seqinfo = _GappySeqInfo( + seqlen=new_seqlens, + seqlen_py=new_seqlens_py, + max_seqlen=self.k_seqinfo.max_seqlen, + min_seqlen=self.k_seqinfo.min_seqlen, + seqstart=new_seqstarts, + seqstart_py=new_seqstarts_py, + ) + assert self.k_seqinfo.max_seqlen <= max_row_len + paged_bias = paged_type( + q_seqinfo=self.q_seqinfo, + k_seqinfo=k_seqinfo, + block_tables=block_tables, + page_size=page_size, + ) + return paged_bias + + +@dataclass +class BlockDiagonalCausalWithOffsetGappyKeysMask(BlockDiagonalGappyKeysMask): + """ + Same as :attr:`xformers.ops.fmha.attn_bias.BlockDiagonalCausalMask`, + except k/v is gappy. + + A query Q in block i cannot attend to a key which is not in block i, + nor one which is nearer to the final key in block i + than Q is to the final query in block i. + """ + + def to(self, device: torch.device) -> "BlockDiagonalCausalWithOffsetGappyKeysMask": + assert ( + type(self) is BlockDiagonalCausalWithOffsetGappyKeysMask + ), "Please implement in subclass" + return BlockDiagonalCausalWithOffsetGappyKeysMask( + q_seqinfo=self.q_seqinfo.to(device), + k_seqinfo=self.k_seqinfo.to(device), + ) + + def materialize( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + """Materialize the attention bias - for debugging & testing""" + if shape[-1] != self.k_seqinfo.seqstart_py[-1]: + raise ValueError("k shapes wrong") + if shape[-2] != self.q_seqinfo.seqstart_py[-1]: + raise ValueError("q shapes wrong") + mask = torch.empty(shape[-2:], dtype=dtype, device=device) + mask.fill_(-math.inf) + for i, ((q_start, q_end), (k_start, k_end)) in enumerate( + zip( + self.q_seqinfo.intervals(), + self.k_seqinfo.intervals(), + ) + ): + mask[ + q_start:q_end, k_start:k_end + ] = LowerTriangularFromBottomRightMask().materialize( + shape=(q_end - q_start, k_end - k_start), dtype=dtype, device=device + ) + + for _ in range(len(shape) - 2): + mask = mask.unsqueeze(0) + return mask.expand(shape) + + +@dataclass +class PagedBlockDiagonalGappyKeysMask(AttentionBias): + """ + Equivalent BlockDiagonalGappyKeysMask, but for paged attention. + block_tables has shape [batch_size, max_num_pages] and K/V have shape + [1, max_num_pages * page_size, num_heads, head_dim] + or [1, max_num_pages * page_size, num_groups, num_heads, head_dim] + """ + + q_seqinfo: _SeqLenInfo + k_seqinfo: _GappySeqInfo + block_tables: torch.Tensor + page_size: int + + _UNPAGED_TYPE: ClassVar[Type[BlockDiagonalGappyKeysMask]] = ( + BlockDiagonalGappyKeysMask + ) + + def to(self, device: torch.device) -> "PagedBlockDiagonalGappyKeysMask": + assert ( + type(self) is PagedBlockDiagonalGappyKeysMask + ), "Please implement in subclass" + return PagedBlockDiagonalGappyKeysMask( + q_seqinfo=self.q_seqinfo.to(device), + k_seqinfo=self.k_seqinfo.to(device), + block_tables=_to_device(self.block_tables, device), + page_size=self.page_size, + ) + + def materialize( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + """Materialize the attention bias - for debugging & testing""" + # First create a non-paged mask, then cut individual pages and + # copy them to their places in the physical mask, using block tables + + max_row_len = self.block_tables.shape[1] * self.page_size + new_seqstarts = [ + start + i * max_row_len + for i, start in enumerate(self.k_seqinfo.seqstart_py[:-1]) + ] + [shape[-1]] + new_seqlens = [ + end - start + for start, end in zip(self.k_seqinfo.seqstart_py, self.k_seqinfo.seqlen_py) + ] + bias_nonpaged = self._UNPAGED_TYPE( + q_seqinfo=self.q_seqinfo, + k_seqinfo=_GappySeqInfo.from_seqlens_gappy( + new_seqstarts, + new_seqlens, + False, + device=torch.device(device), + ), + ) + mask_nonpaged = bias_nonpaged.materialize(shape, dtype, device) + + n_used_blocks = cast(int, self.block_tables.max().item() + 1) + max_physical_len = n_used_blocks * self.page_size + mask_paged = torch.empty( + mask_nonpaged.shape[:-1] + (max_physical_len,), dtype=dtype, device=device + ) + mask_paged.fill_(-math.inf) + for b, (q_start, q_end) in enumerate(self.q_seqinfo.intervals()): + for logical_page_idx in range(self.block_tables.shape[1]): + physical_page_idx = cast( + int, self.block_tables[b][logical_page_idx].item() + ) + k_logical_start = b * max_row_len + logical_page_idx * self.page_size + k_logical_end = k_logical_start + self.page_size + k_physical_start = physical_page_idx * self.page_size + k_physical_end = k_physical_start + self.page_size + mask_paged[..., q_start:q_end, k_physical_start:k_physical_end] = ( + mask_nonpaged[..., q_start:q_end, k_logical_start:k_logical_end] + ) + return mask_paged + + @classmethod + def from_seqlens( + cls, + q_seqlen: Sequence[int], + kv_seqstarts: Sequence[int], + kv_seqlen: Sequence[int], + block_tables: torch.Tensor, + page_size: int, + *, + device: Optional[torch.device] = None, + ) -> "PagedBlockDiagonalGappyKeysMask": + """Creates a :attr:`PagedBlockDiagonalGappyKeysMask` from a list of tensor + lengths for query and key/value. + + Note that unlike :attr:`BlockDiagonalGappyKeysMask`, kv_seqstarts is + addressing in a different space for each batch element. For example + if you were doing a BlockDiagonalPaddedKeysMask with two batch + elements and padding=100, but wanted to change it so that the first + key is ignored, then you would use BlockDiagonalGappyKeysMask with kv_seqstarts + [1, 101, 200]. But if you were using PagedBlockDiagonalPaddedKeysMask + but wanted to ignore the first key, you would provide this function with + kv_seqstarts = [1, 1]. + """ + assert len(q_seqlen) == len(kv_seqlen) == len(kv_seqstarts), ( + q_seqlen, + kv_seqlen, + kv_seqstarts, + ) + device = block_tables.device if device is None else device + q_seqinfo = _SeqLenInfo.from_seqlens(q_seqlen, device=device) + k_seqinfo = _GappySeqInfo.from_seqlens_gappy( + kv_seqstarts, kv_seqlen, True, device=device + ) + return cls( + q_seqinfo=q_seqinfo, + k_seqinfo=k_seqinfo, + block_tables=block_tables, + page_size=page_size, + ) + + +@dataclass +class PagedBlockDiagonalCausalWithOffsetGappyKeysMask(PagedBlockDiagonalGappyKeysMask): + """ + Same as BlockDiagonalCausalWithOffsetGappyKeysMask, but for paged attention. + block_tables has shape [batch_size, max_num_pages] and K/V have shape + [1, max_num_pages * page_size, num_heads, head_dim] or + [1, max_num_pages * page_size, num_groups, num_heads, head_dim] + """ + + _UNPAGED_TYPE = BlockDiagonalCausalWithOffsetGappyKeysMask + + def to( + self, device: torch.device + ) -> "PagedBlockDiagonalCausalWithOffsetGappyKeysMask": + assert ( + type(self) is PagedBlockDiagonalCausalWithOffsetGappyKeysMask + ), "Please implement in subclass" + return PagedBlockDiagonalCausalWithOffsetGappyKeysMask( + q_seqinfo=self.q_seqinfo.to(device), + k_seqinfo=self.k_seqinfo.to(device), + block_tables=_to_device(self.block_tables, device), + page_size=self.page_size, + ) + + +@dataclass +class BlockDiagonalCausalLocalAttentionMask(BlockDiagonalCausalMask): + """ + (Experimental feature) + Same as :attr:`xformers.ops.fmha.attn_bias.BlockDiagonalCausalMask`. + This makes the mask "local" and the attention pattern banded. + + The ith query in a block only attends to keys in its block with index + greater than i - window_size and less than or equal to i. + """ + + _window_size: int = 0 # forced due to inheritance and default arguments + + def to(self, device) -> "BlockDiagonalCausalLocalAttentionMask": + assert ( + type(self) is BlockDiagonalCausalLocalAttentionMask + ), "Please implement in subclass" + return BlockDiagonalCausalLocalAttentionMask( + q_seqinfo=self.q_seqinfo.to(device), + k_seqinfo=self.k_seqinfo.to(device), + _batch_sizes=self._batch_sizes, + _window_size=self._window_size, + ) + + def __post_init__(self): + if self._window_size <= 0: + raise ValueError( + f"Expected `window_size > 0`, but window_size={self._window_size}" + ) + q_seqlen = [ + y - x + for x, y in zip( + self.q_seqinfo.seqstart_py[:-1], self.q_seqinfo.seqstart_py[1:] + ) + ] + kv_seqlen = [ + y - x + for x, y in zip( + self.k_seqinfo.seqstart_py[:-1], self.k_seqinfo.seqstart_py[1:] + ) + ] + for q, k in zip(q_seqlen, kv_seqlen): + if q - self._window_size >= k: + # Each query only attends to keys no further than window_size back. + # When q > k + window_size, there will be a query for which the window doesn't reach any key. + raise RuntimeError( + f"No keys are attended in q_seqlen {q} k_seqlen {k} with sliding window {self._window_size}" + ) + + def _create_block_mask( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + return _materialize_causal_mask( + shape, + dtype=dtype, + device=device, + window_size=self._window_size, + ) + + +@dataclass +class BlockDiagonalCausalLocalAttentionFromBottomRightMask( + BlockDiagonalCausalFromBottomRightMask +): + """ + (Experimental feature) + Same as :attr:`xformers.ops.fmha.attn_bias.BlockDiagonalCausalMask`. + This makes the mask "local" and the attention pattern banded. + + A query with distance j from the last query in its block only attends to + keys in the same block, and only those whose distance to the last key + in the block is greater than or equal to j and less than window_size + j. + """ + + _window_size: int = 0 # forced due to inheritance and default arguments + + def to(self, device) -> "BlockDiagonalCausalLocalAttentionFromBottomRightMask": + assert ( + type(self) is BlockDiagonalCausalLocalAttentionFromBottomRightMask + ), "Please implement in subclass" + return BlockDiagonalCausalLocalAttentionFromBottomRightMask( + q_seqinfo=self.q_seqinfo.to(device), + k_seqinfo=self.k_seqinfo.to(device), + _batch_sizes=self._batch_sizes, + _window_size=self._window_size, + ) + + def __post_init__(self): + super().__post_init__() + if self._window_size <= 0: + raise ValueError( + f"Expected `window_size > 0`, but window_size={self._window_size}" + ) + + def _create_block_mask( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + return _materialize_causal_mask( + shape, + dtype=dtype, + device=device, + window_size=self._window_size, + from_bottomright=True, + ) + + +class AttentionBiasSubTensor(torch.Tensor, AttentionBias): + HOLDS_DENSE_TENSOR = False + + _subtensor: torch.Tensor + + @staticmethod + def __new__(cls, *, _subtensor=None, device=None, **kwargs): + raise NotImplementedError() + + def __init__(self, *args, **kwargs) -> None: + super().__init__() + + def __repr__(self): + return f"{self.__class__.__name__}" + + @classmethod + def __torch_dispatch__(cls, func, types, args=(), kwargs=None): + kwargs = kwargs or {} + if func._overloadpacket in [ + torch.ops.aten.clone, + torch.ops.aten.detach, + torch.ops.aten._to_copy, + torch.ops.aten.to, + ]: + return cls(_subtensor=func(args[0]._subtensor, *args[1:], **kwargs)) + return NotImplemented + + def __tensor_flatten__(self): + return ["_subtensor"], None + + @classmethod + def __tensor_unflatten__(cls, inner_tensors, meta, outer_size, outer_stride): + assert meta is None + return cls(_subtensor=inner_tensors["_subtensor"]) + + def materialize( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + """ + Materializes the bias as a `torch.Tensor`. This is very slow + and we don't attempt to make it fast. Only use for debugging/testing. + + Shape should be like `[*, q_seqlen, k_seqlen]` + """ + raise NotImplementedError() + + +class _AddDenseBias(torch.autograd.Function): + @staticmethod + def forward(ctx, causal_bias, tensor): + assert type(causal_bias) is LowerTriangularMask + return LowerTriangularMaskWithTensorBias(tensor) + + @staticmethod + def backward(ctx, grad_out): + return None, grad_out + + +class LowerTriangularMask(AttentionBiasSubTensor): + """ + A lower-triangular (aka causal) mask + + A query Q cannot attend to a key which is farther from the + initial key than Q is from the initial query. + + See also :attr:`LowerTriangularFromBottomRightMask` if the number + of queries is not equal to the number of keys/values. + """ + + HOLDS_DENSE_TENSOR = False + + @staticmethod + def __new__(cls, *, _subtensor=None, device="cpu", **kwargs): + """ + Note: create on CPU by default to avoid initializing CUDA context + by mistake. + """ + if _subtensor is None: + _subtensor = torch.empty((0,), device=device) + tensor = torch.Tensor._make_wrapper_subclass( # type: ignore[attr-defined] + cls, + [], + device=_subtensor.device, + dtype=_subtensor.dtype, + requires_grad=False, + ) + tensor._subtensor = _subtensor + return tensor + + def materialize( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + return _materialize_causal_mask(shape, dtype=dtype, device=device) + + def add_bias(self, bias: torch.Tensor) -> "LowerTriangularMaskWithTensorBias": + """ + Creates a new causal mask with an arbitrary ``torch.Tensor`` bias + """ + return _AddDenseBias.apply(self, bias) + + +class LowerTriangularMaskWithTensorBias(LowerTriangularMask): + """A lower-triangular (aka causal) mask with an additive bias""" + + HOLDS_DENSE_TENSOR = True + + @staticmethod + def __new__(cls, bias): + tensor = torch.Tensor._make_wrapper_subclass( # type: ignore[attr-defined] + cls, + bias.shape, + device=bias.device, + dtype=bias.dtype, + requires_grad=bias.requires_grad, + ) + tensor._subtensor = bias + return tensor + + def materialize( + self, + shape: Tuple[int, ...], + dtype: torch.dtype = torch.float32, + device: Union[str, torch.device] = "cpu", + ) -> torch.Tensor: + return super().materialize(shape, dtype=dtype, device=device) + self._subtensor + + @classmethod + def __torch_dispatch__(cls, func, types, args=(), kwargs=None): + kwargs = kwargs or {} + if func._overloadpacket in [ + torch.ops.aten.unsqueeze, + torch.ops.aten.select, + torch.ops.aten.slice, + torch.ops.aten.clone, + torch.ops.aten.detach, + torch.ops.aten._to_copy, + torch.ops.aten.to, + torch.ops.aten.view, + ]: + output = func( + *[a._subtensor if isinstance(a, cls) else a for a in args], + **kwargs, + ) + return cls(output) + return NotImplemented + + +torch._dynamo.allow_in_graph(LowerTriangularMask) +torch._dynamo.allow_in_graph(LowerTriangularMaskWithTensorBias) + +VARLEN_BIASES = ( + BlockDiagonalMask, + BlockDiagonalGappyKeysMask, + BlockDiagonalPaddedKeysMask, + PagedBlockDiagonalPaddedKeysMask, + PagedBlockDiagonalGappyKeysMask, +) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/ck.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/ck.py new file mode 100644 index 0000000000000000000000000000000000000000..b5dccacd82ba2734a9bcf79b7c047355de161010 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/ck.py @@ -0,0 +1,492 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +from dataclasses import replace +from enum import Enum +from typing import Any, Iterable, List, Mapping, Optional, Set, Tuple, Union + +import torch + +from ..common import get_operator, register_operator +from . import attn_bias +from .attn_bias import ( + AttentionBias, + AttentionBiasSubTensor, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + BlockDiagonalCausalLocalAttentionMask, + BlockDiagonalCausalMask, + BlockDiagonalCausalWithOffsetGappyKeysMask, + BlockDiagonalCausalWithOffsetPaddedKeysMask, + BlockDiagonalGappyKeysMask, + BlockDiagonalMask, + BlockDiagonalPaddedKeysMask, + LowerTriangularFromBottomRightLocalAttentionMask, + LowerTriangularFromBottomRightMask, + LowerTriangularMask, + LowerTriangularMaskWithTensorBias, + PagedBlockDiagonalCausalWithOffsetPaddedKeysMask, + PagedBlockDiagonalGappyKeysMask, + PagedBlockDiagonalPaddedKeysMask, +) +from .common import ( + AttentionBwOpBase, + AttentionFwOpBase, + check_lastdim_alignment_stride1, + Context, + Gradients, + Inputs, +) + + +def _minimum_gemm_alignment(inp: Inputs) -> int: + return 1 + + +def _get_seqlen_info( + inp: Inputs, +) -> Tuple[ + Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor], int, int +]: + attn_bias = inp.attn_bias + if isinstance( + attn_bias, + ( + BlockDiagonalMask, + BlockDiagonalPaddedKeysMask, + BlockDiagonalGappyKeysMask, + PagedBlockDiagonalPaddedKeysMask, + PagedBlockDiagonalGappyKeysMask, + ), + ): + attn_bias.k_seqinfo.to(inp.query.device) + attn_bias.q_seqinfo.to(inp.query.device) + seqstart_k = attn_bias.k_seqinfo.seqstart + seqstart_q = attn_bias.q_seqinfo.seqstart + max_seqlen_q = attn_bias.q_seqinfo.max_seqlen + max_seqlen_k = attn_bias.k_seqinfo.max_seqlen + seqlen = ( + None + if isinstance(attn_bias, BlockDiagonalMask) + else attn_bias.k_seqinfo.seqlen + ) + else: + seqstart_k = None + seqstart_q = None + max_seqlen_q = -1 + max_seqlen_k = -1 + seqlen = None + + if isinstance(attn_bias, PagedBlockDiagonalGappyKeysMask): + seqstart_k = attn_bias.k_seqinfo.seqstart[:-1] + seqlen = seqlen - seqstart_k + + return seqstart_k, seqstart_q, seqlen, max_seqlen_q, max_seqlen_k + + +def _get_tensor_bias( + attn_bias: Optional[Union[torch.Tensor, AttentionBias]], +) -> Optional[torch.Tensor]: + if isinstance(attn_bias, AttentionBiasSubTensor): + if isinstance(attn_bias, LowerTriangularMaskWithTensorBias): + return attn_bias._subtensor + elif isinstance(attn_bias, torch.Tensor): + return attn_bias + return None + + +def _check_bias_alignment( + reasons: List[str], attn_bias: Optional[Union[torch.Tensor, AttentionBias]] +) -> None: + attn_bias_tensor = _get_tensor_bias(attn_bias) + if attn_bias_tensor is not None: + alignment = 128 // torch.finfo(attn_bias_tensor.dtype).bits + show_padding_hint = False + for d in range(attn_bias_tensor.ndim - 1): + if attn_bias_tensor.stride(d) % alignment != 0: + reasons.append( + f"attn_bias.stride(-2) % {alignment} != 0 (attn_bias.stride() = {attn_bias_tensor.stride()})" + ) + show_padding_hint = True + if show_padding_hint: + reasons.append( + """\ +HINT: To use an `attn_bias` with a sequence length that is not a multiple of 8, \ +you need to ensure memory is aligned by slicing a bigger tensor. \ +Example: use `attn_bias = torch.zeros([1, 1, 5, 8])[:,:,:,:5]` instead of `torch.zeros([1, 1, 5, 5])`""" + ) + # We can have stride=0 sometimes if dimension=1 + if attn_bias_tensor.stride(-1) > 1: + reasons.append( + f"attn_bias.stride(-1) > 1 (attn_bias.stride() = {attn_bias_tensor.stride()}) - " + "you should call `.contiguous()` on the bias" + ) + + +class _CustomMaskType(int, Enum): + """ + (Matches CustomMaskType in C++.) + """ + + NoCustomMask = 0 + CausalFromTopLeft = 1 + CausalFromBottomRight = 2 + + +def _custom_mask_type(bias: Optional[Union[torch.Tensor, AttentionBias]]) -> int: + if isinstance( + bias, + ( + LowerTriangularMask, + BlockDiagonalCausalMask, + BlockDiagonalCausalLocalAttentionMask, + ), + ): + return int(_CustomMaskType.CausalFromTopLeft) + if isinstance( + bias, + ( + LowerTriangularFromBottomRightMask, + LowerTriangularFromBottomRightLocalAttentionMask, + attn_bias.BlockDiagonalCausalFromBottomRightMask, + BlockDiagonalCausalWithOffsetPaddedKeysMask, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + PagedBlockDiagonalCausalWithOffsetPaddedKeysMask, + ), + ): + return int(_CustomMaskType.CausalFromBottomRight) + return int(_CustomMaskType.NoCustomMask) + + +@register_operator +class FwOp(AttentionFwOpBase): + """xFormers' MHA kernel based on Composable Kernel.""" + + OPERATOR = get_operator("xformers", "efficient_attention_forward_ck") + SUPPORTED_DEVICES: Set[str] = {"cuda"} + SUPPORTED_DTYPES: Set[torch.dtype] = {torch.half, torch.bfloat16} + SUPPORTED_MAX_K = 512 + + SUPPORTED_ATTN_BIAS_TYPES: Iterable[Any] = ( + type(None), + torch.Tensor, + LowerTriangularMask, + LowerTriangularFromBottomRightMask, + LowerTriangularFromBottomRightLocalAttentionMask, + LowerTriangularMaskWithTensorBias, + BlockDiagonalMask, + BlockDiagonalCausalMask, + BlockDiagonalCausalWithOffsetGappyKeysMask, + BlockDiagonalCausalWithOffsetPaddedKeysMask, + BlockDiagonalGappyKeysMask, + BlockDiagonalPaddedKeysMask, + attn_bias.BlockDiagonalCausalFromBottomRightMask, + attn_bias.BlockDiagonalCausalLocalAttentionMask, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + PagedBlockDiagonalPaddedKeysMask, + PagedBlockDiagonalCausalWithOffsetPaddedKeysMask, + PagedBlockDiagonalGappyKeysMask, + ) + + SUPPORTS_DROPOUT = True + SUPPORTS_CUSTOM_SCALE = True + SUPPORTS_DIFFERENT_VALUE_EMBED = True + SUPPORTS_PARTIAL = True + SUPPORTS_BMGHK = True + NAME = "ckF" + + ERROR_ATOL: Mapping[torch.dtype, float] = { + torch.float: 3e-4, + torch.half: 6e-3, + torch.bfloat16: 2.8e-2, + } + ERROR_RTOL: Mapping[torch.dtype, float] = { + torch.float: 2e-5, + torch.half: 3e-3, + torch.bfloat16: 2e-2, + } + + _TEST_K: List[int] = [ + 32, # 64x64 kernel + 96, + 128, # 64x128 kernel + 256, # 64x128 with accumulation in gmem + 512, + ] + + @classmethod + def apply( + cls, inp: Inputs, needs_gradient: bool + ) -> Tuple[torch.Tensor, Optional[Context]]: + if type(inp.attn_bias) not in FwOp.SUPPORTED_ATTN_BIAS_TYPES: + raise NotImplementedError("Unsupported attn_bias type") + if inp.query.ndim in [1, 2, 3]: + raise NotImplementedError("Unsupported number of dimensions") + if inp.query.ndim in [4]: + return cls.apply_bmhk(inp, needs_gradient=needs_gradient) + assert inp.query.ndim == 5, f"query has shape {inp.query.shape}" + ctx: Optional[Context] = None + + # when the input is expanded 5-D, the group dimension has zero stride + if inp.key.stride()[3] == 0: + assert ( + inp.value.stride()[3] == 0 + ), "key and value should be expanded in the same way" + k_shape = inp.key.size() + k_stride = inp.key.stride() + key = inp.key.as_strided( + (k_shape[0], k_shape[1], k_shape[2], k_shape[4]), + (k_stride[0], k_stride[1], k_stride[2], k_stride[4]), + ) + v_shape = inp.value.size() + v_stride = inp.value.stride() + value = inp.value.as_strided( + (v_shape[0], v_shape[1], v_shape[2], v_shape[4]), + (v_stride[0], v_stride[1], v_stride[2], v_stride[4]), + ) + else: + key = inp.key.flatten(2, 3) + value = inp.value.flatten(2, 3) + + [_, _, G, Hq, _] = inp.query.shape + attn_bias_replace = inp.attn_bias + if isinstance(inp.attn_bias, LowerTriangularMaskWithTensorBias): + bias_tensor = _get_tensor_bias(inp.attn_bias) + if bias_tensor is not None and bias_tensor.ndim == 5: + attn_bias_replace = LowerTriangularMaskWithTensorBias( + bias_tensor.flatten(1, 2) + ) + elif isinstance(inp.attn_bias, torch.Tensor) and inp.attn_bias.ndim == 5: + attn_bias_replace = inp.attn_bias.flatten(1, 2) + inp = replace( + inp, + query=inp.query.flatten(2, 3), + key=key, + value=value, + attn_bias=attn_bias_replace, + ) + out, ctx = cls.apply_bmhk(inp, needs_gradient=needs_gradient) + out = out.unflatten(2, (G, Hq)) + if ctx is not None: + lse = ctx.lse.unflatten(1, (G, Hq)) + ctx = replace(ctx, lse=lse, out=out) + return out, ctx + + @classmethod + def apply_bmhk( + cls, inp: Inputs, needs_gradient: bool + ) -> Tuple[torch.Tensor, Optional[Context]]: + if type(inp.attn_bias) not in FwOp.SUPPORTED_ATTN_BIAS_TYPES: + raise NotImplementedError("Unsupported attn_bias type") + seqstart_k, seqstart_q, seqlen_k, max_seqlen_q, _ = _get_seqlen_info(inp) + out, lse, rng_seed, rng_offset = cls.OPERATOR( + query=inp.query, + key=inp.key, + value=inp.value, + attn_bias=_get_tensor_bias(inp.attn_bias), + seqstart_q=seqstart_q, + seqstart_k=seqstart_k, + max_seqlen_q=max_seqlen_q, + dropout_p=inp.p, + compute_logsumexp=needs_gradient, + custom_mask_type=_custom_mask_type(inp.attn_bias), + scale=inp.scale, + seqlen_k=seqlen_k, + window_size=( + inp.attn_bias._window_size + if isinstance( + inp.attn_bias, + ( + BlockDiagonalCausalLocalAttentionMask, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + LowerTriangularFromBottomRightLocalAttentionMask, + ), + ) + else None + ), + block_tables=( + inp.attn_bias.block_tables + if isinstance( + inp.attn_bias, + ( + PagedBlockDiagonalPaddedKeysMask, + PagedBlockDiagonalGappyKeysMask, + ), + ) + else None + ), + page_size=( + inp.attn_bias.page_size + if isinstance( + inp.attn_bias, + ( + PagedBlockDiagonalPaddedKeysMask, + PagedBlockDiagonalGappyKeysMask, + ), + ) + else None + ), + ) + + ctx: Optional[Context] = None + if needs_gradient: + ctx = Context( + out=out, + lse=lse, + # cutlass forward is only compatible with cutlass backward if + # dropout is used (because of the way RNG states are passed and the + # way random numbers are generated during backward) + op_bw=BwOp if inp.p != 0 else None, + ) + if inp.p != 0: + ctx.rng_state = torch.tensor( + [rng_seed, rng_offset], dtype=torch.int64, device="cpu" + ) + return out, ctx + + @classmethod + def not_supported_reasons(cls, d: Inputs) -> List[str]: + reasons = super(FwOp, cls).not_supported_reasons(d) + matmul_alignment_mn = _minimum_gemm_alignment(d) + check_lastdim_alignment_stride1(reasons, "query", d.query, matmul_alignment_mn) + check_lastdim_alignment_stride1(reasons, "value", d.value, matmul_alignment_mn) + _check_bias_alignment(reasons, d.attn_bias) + return reasons + + +@register_operator +class BwOp(AttentionBwOpBase): + __doc__ = FwOp.__doc__ + + OPERATOR = get_operator("xformers", "efficient_attention_backward_ck") + SUPPORTED_DEVICES = FwOp.SUPPORTED_DEVICES + SUPPORTED_DTYPES = FwOp.SUPPORTED_DTYPES + SUPPORTED_MAX_K = 256 + SUPPORTED_ATTN_BIAS_TYPES: Iterable[Any] = ( + type(None), + torch.Tensor, + LowerTriangularMask, + LowerTriangularFromBottomRightMask, + LowerTriangularFromBottomRightLocalAttentionMask, + # TODO: Fix handling of gradient through the fMHA autograd function + # LowerTriangularMaskWithTensorBias, + BlockDiagonalMask, + BlockDiagonalCausalMask, + attn_bias.BlockDiagonalCausalFromBottomRightMask, + attn_bias.BlockDiagonalCausalLocalAttentionMask, + ) + SUPPORTS_ATTN_BIAS_GRAD = True + SUPPORTS_DROPOUT = FwOp.SUPPORTS_DROPOUT + SUPPORTS_CUSTOM_SCALE = FwOp.SUPPORTS_CUSTOM_SCALE + SUPPORTS_DIFFERENT_VALUE_EMBED = FwOp.SUPPORTS_DIFFERENT_VALUE_EMBED + SUPPORTS_UNPADDED_LSE = True + NAME = "ckB" + + _TEST_K: List[int] = [ + 32, # 64x64 kernel + 64, + 96, + 128, # 64x128/128x128 kernel + 256, + ] + + @classmethod + def not_supported_reasons(cls, d: Inputs) -> List[str]: + reasons = super(BwOp, cls).not_supported_reasons(d) + matmul_alignment_mn = _minimum_gemm_alignment(d) + + check_lastdim_alignment_stride1(reasons, "query", d.query, matmul_alignment_mn) + check_lastdim_alignment_stride1(reasons, "key", d.key, matmul_alignment_mn) + check_lastdim_alignment_stride1(reasons, "value", d.value, matmul_alignment_mn) + _check_bias_alignment(reasons, d.attn_bias) + attn_bias_tensor = _get_tensor_bias(d.attn_bias) + + # Backprop of gradient through broadcasted bias is not supported + if attn_bias_tensor is not None and attn_bias_tensor.requires_grad: + # Don't forget that inputs are either in BMK or BMHK! + if d.query.ndim == 3 and attn_bias_tensor.ndim == 3: + expected_bias_shape = (*d.query.shape[:2], d.key.shape[1]) + else: + # bias is B H Mq Mk + expected_bias_shape = ( + d.query.shape[0], + d.query.shape[2] if d.query.ndim == 4 else 1, + d.query.shape[1], + d.key.shape[1], + ) + if tuple(attn_bias_tensor.shape) != expected_bias_shape: + reasons.append( + "Broadcasting the `attn_bias` tensor is not supported " + f"(shape: {tuple(attn_bias_tensor.shape)}" + f"/ expected: {expected_bias_shape})" + ) + + return reasons + + @classmethod + def apply(cls, ctx: Context, inp: Inputs, grad: torch.Tensor) -> Gradients: + if type(inp.attn_bias) not in BwOp.SUPPORTED_ATTN_BIAS_TYPES: + raise NotImplementedError("Unsupported attn_bias type") + + seqstart_k, seqstart_q, seqlen_k, max_seqlen_q, max_seqlen_k = _get_seqlen_info( + inp + ) + dtype = inp.query.dtype + + rng_seed = rng_offset = 0 + if inp.p != 0.0: + if ( + ctx.rng_state is None + or ctx.rng_state.dtype != torch.int64 + or ctx.rng_state.device.type != "cpu" + or ctx.rng_state.shape != (2,) + ): + raise NotImplementedError(f"Invalid rng_state: {ctx.rng_state}") + rng_seed, rng_offset = ctx.rng_state.tolist() + + (grad_q, grad_k, grad_v, grad_bias) = cls.OPERATOR( + grad.to(dtype), + inp.query, + inp.key, + inp.value, + attn_bias=_get_tensor_bias(inp.attn_bias), + seqstart_q=seqstart_q, + seqstart_k=seqstart_k, + max_seqlen_q=max_seqlen_q, + max_seqlen_k=max_seqlen_k, + seqlen_k=seqlen_k, + logsumexp=ctx.lse, + output=ctx.out.to(dtype), + dropout_p=inp.p, + # if not using dropout, seed and offset are irrelevant but still expected + # in function signature so just pass 0 + # seed and offset could be None if a different FW op other than cutlass + # was used. + rng_seed=rng_seed, + rng_offset=rng_offset, + custom_mask_type=_custom_mask_type(inp.attn_bias), + scale=inp.scale, + window_size=( + inp.attn_bias._window_size + if isinstance( + inp.attn_bias, + ( + BlockDiagonalCausalLocalAttentionMask, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + LowerTriangularFromBottomRightLocalAttentionMask, + ), + ) + else None + ), + ) + + # c++/CUDA implementation returns an uninitialized tensor if bias doesn't + # require grad + if not ( + isinstance(inp.attn_bias, torch.Tensor) and inp.attn_bias.requires_grad + ): + grad_bias = None + + return Gradients(dq=grad_q, dk=grad_k, dv=grad_v, db=grad_bias) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/ck_decoder.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/ck_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..a5c820bfc7d7c33df239c51b47f0cc89e1b348db --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/ck_decoder.py @@ -0,0 +1,139 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Any, Iterable, List, Optional, Set, Tuple + +import torch + +from ..common import get_operator, register_operator +from .attn_bias import BlockDiagonalCausalWithOffsetPaddedKeysMask +from .common import AttentionFwOpBase, Context, Inputs + + +@register_operator +class FwOp(AttentionFwOpBase): + """ + An operator optimized for K=256 (so the contiguous dim fits into registers). + Tested to work on MI250x. + """ + + OPERATOR = get_operator("xformers", "efficient_attention_forward_decoder_ck") + SUPPORTED_DEVICES: Set[str] = {"cuda"} + SUPPORTED_DTYPES: Set[torch.dtype] = {torch.half, torch.bfloat16, torch.float} + SUPPORTED_MAX_K: int = 256 + SUPPORTED_ATTN_BIAS_TYPES: Iterable[Any] = ( + type(None), + BlockDiagonalCausalWithOffsetPaddedKeysMask, + ) + SUPPORTS_DROPOUT = False + SUPPORTS_CUSTOM_SCALE = True + SUPPORTS_BMGHK = True + NAME = "ck_decoderF" + + @classmethod + def not_supported_reasons(cls, d: Inputs) -> List[str]: + reasons = super(FwOp, cls).not_supported_reasons(d) + + attn_bias = d.attn_bias + if isinstance(attn_bias, BlockDiagonalCausalWithOffsetPaddedKeysMask): + if d.query.shape[0] != 1: + reasons.append( + f"One formal batch element expected; got {d.query.shape[0]}" + ) + + if d.query.shape[-1] > cls.SUPPORTED_MAX_K: + reasons.append( + f"Got head_dim={d.query.shape[-1]}; only head_dim<={cls.SUPPORTED_MAX_K} is supported for now." + ) + + threads_per_warp = 64 # TODO: ideally query the platform here + required_alignment = 0 + head_dim = d.query.shape[-1] + for vec_size in (4, 2, 1): + if head_dim <= vec_size * threads_per_warp: + required_alignment = vec_size + + if not required_alignment: + reasons.append(f"Got head_dim={head_dim} which is too large") + + if head_dim % required_alignment != 0: + reasons.append( + f"Got head_dim={head_dim}; it needs to be divisible by {required_alignment}" + ) + + if d.key.stride(-1) != 1: + reasons.append("expect keys to have last dim contiguous") + + if d.value.stride(-1) != 1: + reasons.append("expect values to have last dim contiguous") + + q_starts = attn_bias.q_seqinfo.seqstart_py + padding = attn_bias.k_seqinfo.padding + bsz = d.key.shape[1] // padding + num_queries = d.query.shape[1] // bsz + + if q_starts != list(range(0, 1 + bsz, num_queries)): + reasons.append("expect to have same num_queries in each batch") + if bsz != len(q_starts) - 1: + reasons.append("empty lanes not supported yet") + + if attn_bias.k_seqinfo.padding > 8192: + reasons.append("key padding exceeds 8192") + + return reasons + + @classmethod + def apply( + cls, inp: Inputs, needs_gradient: bool + ) -> Tuple[torch.Tensor, Optional[Context]]: + if needs_gradient: + raise NotImplementedError("backward pass is not supported") + attn_bias = inp.attn_bias + q, k, v = inp.get_qkv_in_bmghk() + if attn_bias is not None: + assert isinstance(attn_bias, BlockDiagonalCausalWithOffsetPaddedKeysMask) + attn_bias.k_seqinfo.to(k.device) + attn_bias.q_seqinfo.to(q.device) + padding = attn_bias.k_seqinfo.padding + seq_positions_gpu = attn_bias.k_seqinfo.seqlen + else: + padding = k.shape[1] + seq_positions_gpu = None + + if attn_bias is not None: + # key: (1, B * padding, G, 1 if multiquery else Hkv, D) + # value: like key + # query: (1, B * q_seqlen, G, Hq, D) + multiquery = k.stride(3) == 0 + if multiquery: + key = k[0, :, :, :1].unflatten(0, (-1, padding)) + value = v[0, :, :, :1].unflatten(0, (-1, padding)) + else: + key = k[0].unflatten(0, (-1, padding)) + value = v[0].unflatten(0, (-1, padding)) + query = q[0].unflatten(0, (key.shape[0], -1)) + else: + # key: (B, padding, G, 1 if multiquery else Hkv, D) + # value: like key + # query: (B, q_seqlen, G, Hq, D) + key = k + query = q + value = v + + if inp.scale is not None: + qk_scale = inp.scale + else: + qk_scale = torch.rsqrt( + torch.tensor(key.shape[-1], dtype=torch.float32) + ).item() + + out = cls.OPERATOR( + query=query, + key=key, + value=value, + seq_positions=seq_positions_gpu, + scale=qk_scale, + ) + return out, None diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/ck_splitk.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/ck_splitk.py new file mode 100644 index 0000000000000000000000000000000000000000..75d89d32400201b1f800900a7a60a1accef068bc --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/ck_splitk.py @@ -0,0 +1,208 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Any, Iterable, List, Optional, Tuple + +import torch + +from xformers.ops.common import get_operator, register_operator +from xformers.ops.fmha.attn_bias import BlockDiagonalCausalWithOffsetPaddedKeysMask +from xformers.ops.fmha.common import ( + AttentionFwOpBase, + check_lastdim_alignment_stride1, + Context, + Inputs, +) + + +@register_operator +class FwOp(AttentionFwOpBase): + + OPERATOR = get_operator("xformers", "efficient_attention_forward_decoder_splitk_ck") + SUPPORTED_DEVICES = {"cuda"} + SUPPORTED_DTYPES = { + torch.half, + torch.bfloat16, + torch.float, + } # Those are dtypes of Q. In the quantized case K/V has dtype int32 + SUPPORTED_MAX_K = 256 + SUPPORTED_ATTN_BIAS_TYPES: Iterable[Any] = ( + type(None), + BlockDiagonalCausalWithOffsetPaddedKeysMask, + ) + SUPPORTS_DROPOUT = False + SUPPORTS_CUSTOM_SCALE = True + SUPPORTS_BMGHK = True + NAME = "ck_splitKF" + + SPLIT_K: Optional[int] = None + BLOCK_M = 16 + BLOCK_N = 64 + + NUM_GROUPS = 1 # Default quantization is row-wise + + @classmethod + def shape_not_supported_reasons( + cls, Mq: int, Mkv: int, K: int, Kv: int + ) -> List[str]: + reasons = super().shape_not_supported_reasons(Mq, Mkv, K, Kv) + # if K not in {16, 32, 64, 128}: + # reasons.append(f"Embed dim {K} not supported") + return reasons + + @classmethod + def not_supported_reasons(cls, d: Inputs) -> List[str]: + reasons = super(FwOp, cls).not_supported_reasons(d) + check_lastdim_alignment_stride1(reasons, "query", d.query, 8) + if d.key.dtype != torch.int32: + check_lastdim_alignment_stride1(reasons, "key", d.key, 8) + check_lastdim_alignment_stride1(reasons, "value", d.value, 8) + if cls.OPERATOR is None: + reasons.append("triton is not available") + if d.device.type == "cuda": + # Has only been tested on 8.0 / 9.0. + if torch.cuda.get_device_capability(d.device) < (7, 0): + reasons.append( + "requires GPU with sm80 minimum compute capacity, e.g., A100/H100/L4" + ) + + q_len = d.query.shape[1] + if isinstance(d.attn_bias, BlockDiagonalCausalWithOffsetPaddedKeysMask): + seqinfo = d.attn_bias.q_seqinfo + if q_len != seqinfo.seqstart_py[-1]: + reasons.append( + f"Expected total {seqinfo.seqstart_py[-1]} queries not {q_len}" + ) + q_len = seqinfo.min_seqlen + if q_len != seqinfo.max_seqlen: + reasons.append( + "Variable query len is not supported in the presence of causal mask." + ) + + if d.key.ndim in [4, 5] and d.key.shape[-2] != 1: + if d.key.stride(-2) == 0 and d.value.stride(-2) == 0 and q_len > 1: + reasons.append("multiquery is only supported with query seqlen=1") + + if d.attn_bias is not None and q_len > 1: + reasons.append( + "query with seqlen > 1 is not supported in the presence of causal mask" + ) + return reasons + + @classmethod + def get_split_k(cls, B: int, H: int, Mk: int) -> int: + """Heuristic for the number of splits""" + bh = max(B * H, 1) # NOTE: Handle B*h=0 case + split_k = max(Mk, 1024) // bh + max_chunk_size = 64 if Mk <= 512 and bh <= 64 else 128 + while split_k > 0 and Mk / split_k < max_chunk_size: + split_k = split_k // 2 + split_k = min(split_k, 64) + split_k = max(split_k, 1) + return split_k + + @classmethod + def apply( + cls, inp: Inputs, needs_gradient: bool + ) -> Tuple[torch.Tensor, Optional[Context]]: + attn_bias = inp.attn_bias + q, k, v = inp.get_qkv_in_bmghk() + + if attn_bias is not None: + assert isinstance(attn_bias, BlockDiagonalCausalWithOffsetPaddedKeysMask) + attn_bias.k_seqinfo.to(k.device) + attn_bias.q_seqinfo.to(q.device) + padding = attn_bias.k_seqinfo.padding + seq_positions_gpu = attn_bias.k_seqinfo.seqlen + else: + padding = k.shape[1] + seq_positions_gpu = None + + if attn_bias is not None: + # key: (1, B * padding, G, 1 if multiquery else Hkv, D) + # value: like key + # query: (1, B * q_seqlen, G, Hq, D) + multiquery = k.stride(3) == 0 + if multiquery: + key = k[0, :, :, :1].unflatten(0, (-1, padding)) + value = v[0, :, :, :1].unflatten(0, (-1, padding)) + else: + key = k[0].unflatten(0, (-1, padding)) + value = v[0].unflatten(0, (-1, padding)) + query = q[0].unflatten(0, (key.shape[0], -1)) + else: + # key: (B, padding, G, 1 if multiquery else Hkv, D) + # value: like key + # query: (B, q_seqlen, G, Hq, D) + key = k + query = q + value = v + + B, _, _, H, _ = query.shape + _, Mk, _, _, _ = key.shape + + if cls.SPLIT_K is not None: + split_k = cls.SPLIT_K + else: + # Use heuristics + split_k = cls.get_split_k(B, H, Mk) + + if inp.scale is not None: + qk_scale = inp.scale + else: + qk_scale = torch.rsqrt( + torch.tensor(k.shape[-1], dtype=torch.float32) + ).item() + + out = cls.OPERATOR( + query=query, + key=key, + value=value, + seq_positions=seq_positions_gpu, + scale=qk_scale, + split_k=split_k, + ) + + return out, None + + +class FwOp_S1(FwOp): + SPLIT_K = 1 + NAME = "ck_splitK1" + + +class FwOp_S2(FwOp): + SPLIT_K = 2 + NAME = "ck_splitK2" + + +class FwOp_S4(FwOp): + SPLIT_K = 4 + NAME = "ck_splitK4" + + +class FwOp_S8(FwOp): + SPLIT_K = 8 + NAME = "ck_splitK8" + + +class FwOp_S16(FwOp): + SPLIT_K = 16 + NAME = "ck_splitK16" + + +class FwOp_S32(FwOp): + SPLIT_K = 32 + NAME = "ck_splitK32" + + +class FwOp_S64(FwOp): + SPLIT_K = 64 + NAME = "ck_splitK64" + + +class FwOp_S128(FwOp): + SPLIT_K = 128 + NAME = "ck_splitK128" diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/common.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/common.py new file mode 100644 index 0000000000000000000000000000000000000000..608bad77d330a041542ab93690fe7eb8fea599e9 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/common.py @@ -0,0 +1,581 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import math +from dataclasses import dataclass +from functools import partial +from typing import ( + Any, + Callable, + Iterable, + List, + Mapping, + Optional, + Set, + Tuple, + Type, + Union, +) + +import torch + +from ..._cpp_lib import _built_with_cuda +from ..common import BaseOperator +from .attn_bias import ( + AttentionBias, + AttentionBiasSubTensor, + BlockDiagonalGappyKeysMask, + BlockDiagonalMask, + BlockDiagonalPaddedKeysMask, + LowerTriangularMask, + PagedBlockDiagonalGappyKeysMask, + PagedBlockDiagonalPaddedKeysMask, +) + + +def _is_bias_type_supported_in_BMK(attn_bias_type: Any) -> bool: + # NoneType + if isinstance(None, attn_bias_type): + return True + if attn_bias_type in [LowerTriangularMask, torch.Tensor]: + return True + return False + + +def _attn_bias_apply( + attn_bias: Optional[Union[torch.Tensor, AttentionBias]], + op: Callable[[torch.Tensor], torch.Tensor], +) -> Optional[Union[torch.Tensor, AttentionBias]]: + if isinstance(attn_bias, torch.Tensor) and attn_bias.ndim != 0: + return op(attn_bias) + return attn_bias + + +class ScaledTensor(torch.Tensor): + __slots__ = ["scale", "dequant_func", "original_dtype"] + + # Disabling custom torch function handling for this class + __torch_function__ = torch._C._disabled_torch_function_impl + + def __new__( + cls, + data: torch.Tensor, + scale: torch.Tensor, + dequant_func: Callable[[torch.Tensor, torch.Tensor], torch.Tensor], + original_dtype: torch.dtype, + require_grad: bool = False, + ) -> "ScaledTensor": + """ + Creates a new ScaledTensor subclass instance. + + Parameters: + - data: The underlying quantized tensor (e.g., int8, int4). + - scale: The scale tensor or scalar to be used for dequantization. + - dequant_func: A callable that applies dequantization, which takes both the data and scale as input. + - original_dtype: The data type before quantization (e.g., float32, float16). + - require_grad: Whether or not to track gradients (default: False for inference use). + """ + # Use _make_subclass to create a new ScaledTensor instance, which is a subclass of torch.Tensor. + instance = torch.Tensor._make_subclass(cls, data, require_grad=require_grad) + + # Store the dequantization scale and function as attributes. + instance.scale = scale # type: ignore + instance.dequant_func = dequant_func # type: ignore + + # Store the original data type of the tensor, so we can cast it back after dequantization. + instance.original_dtype = original_dtype # type: ignore + + # Return the new instance of ScaledTensor. + return instance + + def dequantize(self) -> torch.Tensor: + """ + Applies the custom dequantization function provided at the tensor's creation. + After dequantization, the data is cast back to its original data type. + """ + # Explicitly create a new torch.Tensor to ensure the return type is torch.Tensor, not ScaledTensor. + data = torch.Tensor(self.float()) + + # Call the dequantization function, passing in the data and the scale. + dequantized_data = self.dequant_func(data, self.scale) # type: ignore + + # Cast the dequantized data back to the original data type. + return dequantized_data.to(self.original_dtype) # type: ignore + + def unpack(self) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Unpacks the ScaledTensor by returning its data and scale as a tuple. + Returns: + - A tuple of (data, scale), both of which are torch.Tensor objects. + """ + return self.data, self.scale # type: ignore + + def __repr__(self): + """ + Custom string representation for ScaledTensor. + """ + return f"ScaledTensor(data={self.data}, scale={self.scale}, original_dtype={self.original_dtype})" + + +def pack_fp8_tensorwise_per_head( + x: torch.Tensor, scale: Union[torch.Tensor, float], original_dtype +) -> ScaledTensor: + """ + Pack a tensor into a tensorwise fp8 ScaledTensor. + """ + if isinstance(scale, float): + scale = torch.tensor([scale], device=x.device) + + def dequant_func(x, scale): + return x * scale[:, None, :, None] + + return ScaledTensor( + data=x, + scale=scale, + dequant_func=dequant_func, + original_dtype=original_dtype, + ) + + +@dataclass +class Inputs: + """ + Stores inputs to the `memory_efficient_attention` operators + """ + + query: torch.Tensor + key: torch.Tensor + value: torch.Tensor + attn_bias: Optional[Union[torch.Tensor, AttentionBias]] = None + p: float = 0.0 + scale: Optional[float] = None + output_dtype: Optional[torch.dtype] = None + is_partial: bool = False + + @property + def device(self) -> torch.device: + return self.query.device + + @property + def scale_float(self) -> float: + return self.query.shape[-1] ** (-0.5) if self.scale is None else self.scale + + def get_qkv_in_bmghk(self) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if self.query.ndim == 5: + return self.query, self.key, self.value + if self.query.ndim == 4: + return ( + self.query.unsqueeze(2), + self.key.unsqueeze(2), + self.value.unsqueeze(2), + ) + if self.value.ndim == 3: + return ( + self.query[:, :, None, None], + self.key[:, :, None, None], + self.value[:, :, None, None], + ) + assert False + + def normalize_bmhk(self) -> Tuple[int, ...]: + if self.query.ndim not in [3, 4, 5]: + raise ValueError( + f"Invalid shape for query: {self.query.shape}. " + "Expected shape [batch, seqlen, head_groups, num_heads_per_group, K]" + ", [batch, seqlen, num_heads, K], or [batch, seqlen, K]." + ) + if self.value.dtype == torch.int32: + # Quantized K/V case, in which the last dims of Q and K are different. + # NB we currently don't have any implementations for quantized KV with + # SUPPORTS_DIFFERENT_VALUE_EMBED. + output_shape = tuple(self.query.shape) + else: + output_shape = (self.query.shape[:-1]) + (self.value.shape[-1],) + # Convert from legacy format + if self.query.ndim == 3: + self.query = self.query.unsqueeze(2) + self.key = self.key.unsqueeze(2) + self.value = self.value.unsqueeze(2) + self.attn_bias = _attn_bias_apply( + self.attn_bias, partial(torch.unsqueeze, dim=1) + ) + return output_shape + + def validate_inputs(self) -> None: + qkv = (self.query, self.key, self.value) + if self.query.ndim not in (3, 4, 5) or any( + x.ndim != self.query.ndim for x in qkv + ): + raise ValueError( + f"Query/Key/Value should all have BMGHK, BMHK or BMK shape.\n" + f" query.shape: {self.query.shape}\n" + f" key.shape : {self.key.shape}\n" + f" value.shape: {self.value.shape}" + ) + if any(x.device != self.query.device for x in qkv): + raise ValueError("Query/Key/Value should all be on the same device") + if isinstance( + self.attn_bias, + ( + BlockDiagonalMask, + BlockDiagonalPaddedKeysMask, + PagedBlockDiagonalPaddedKeysMask, + BlockDiagonalGappyKeysMask, + PagedBlockDiagonalGappyKeysMask, + ), + ): + bias_device = self.attn_bias.q_seqinfo.seqstart.device + if bias_device != self.query.device: + raise ValueError( + f"Attention bias and Query/Key/Value should be on the same device\n" + f" query.device: {self.query.device}\n" + f" attn_bias : {bias_device}\n" + ) + + quantized_dtypes = self.key.dtype == self.value.dtype == torch.int32 + non_quantized_dtypes = all(x.dtype == self.query.dtype for x in qkv) + if not (quantized_dtypes or non_quantized_dtypes): + raise ValueError( + "Query/Key/Value should either all have the same dtype, or " + "(in the quantized case) Key/Value should have dtype torch.int32\n" + f" query.dtype: {self.query.dtype}\n" + f" key.dtype : {self.key.dtype}\n" + f" value.dtype: {self.value.dtype}" + ) + # Biases with tensors attached are meant to be in BMHK format + # This would require to permute biases/gradients which can be expensive, + # so let's just forbid it - BMK is a legacy format anyway + if self.query.ndim == 3 and not _is_bias_type_supported_in_BMK( + type(self.attn_bias) + ): + raise ValueError( + f"Please provide inputs in BMHK format rather " + f"than BMK when using bias type `{type(self.attn_bias).__name__}`" + ) + attn_bias_t: Optional[torch.Tensor] = None + if isinstance(self.attn_bias, AttentionBiasSubTensor): + if self.attn_bias.HOLDS_DENSE_TENSOR: + attn_bias_t = self.attn_bias._subtensor + elif isinstance(self.attn_bias, torch.Tensor): + attn_bias_t = self.attn_bias + if self.query.ndim == 4 and attn_bias_t is not None: + expected_shape = ( + self.query.shape[0], + self.query.shape[2], + self.query.shape[1], + self.key.shape[1], + ) + if attn_bias_t.shape != expected_shape: + raise ValueError( + f"Invalid shape for attention bias: {attn_bias_t.shape} (expected {expected_shape})\n" + f" query.shape: {self.query.shape}\n" + f" key.shape : {self.key.shape}\n" + f" value.shape: {self.value.shape}" + ) + if isinstance(self.attn_bias, BlockDiagonalMask): + if any(x.shape[0] != 1 for x in qkv): + raise ValueError( + f"Expected batch_size=1 when using block-diagonal bias\n" + f" query.shape: {self.query.shape}\n" + f" key.shape : {self.key.shape}\n" + f" value.shape: {self.value.shape}" + ) + if self.p < 0.0 or self.p > 1.0: + raise ValueError(f"Invalid dropout probability: p={self.p}") + # Check that shapes match between inputs + B, Mq = self.query.shape[:2] + K = self.query.shape[-1] + B, Mkv = self.key.shape[:2] + Kv = self.value.shape[-1] + quantized_kv_cache = self.value.dtype == torch.int32 + key_embed_dim = Kv if quantized_kv_cache else K + + valid_shapes = True + if self.query.ndim == 3: # BMK + valid_shapes = ( + self.query.shape == (B, Mq, K) + and self.key.shape == (B, Mkv, K) + and self.value.shape == (B, Mkv, Kv) + ) + H = self.query.shape[-2] + if self.query.ndim == 4: # BMHK + valid_shapes = ( + self.query.shape == (B, Mq, H, K) + and self.key.shape == (B, Mkv, H, key_embed_dim) + and self.value.shape == (B, Mkv, H, Kv) + ) + G = self.query.shape[2] + if self.query.ndim == 5: # BMNHK + valid_shapes = ( + self.query.shape == (B, Mq, G, H, K) + and self.key.shape == (B, Mkv, G, H, key_embed_dim) + and self.value.shape == (B, Mkv, G, H, Kv) + ) + if not valid_shapes: + raise ValueError( + f"Incompatible shapes for attention inputs:\n" + f" query.shape: {self.query.shape}\n" + f" key.shape : {self.key.shape}\n" + f" value.shape: {self.value.shape}\n" + "HINT: We don't support broadcasting, please use `expand` " + "yourself before calling `memory_efficient_attention` if you need to" + ) + + def get_output_dtype(self) -> torch.dtype: + if self.output_dtype is None: + if self.is_partial and self.query.dtype is not torch.float64: + return torch.float32 + return self.query.dtype + return self.output_dtype + + @property + def nbytes(self) -> int: + """ + Number of bytes in the input, not counting the attention bias. + """ + return sum( + x.untyped_storage().nbytes() for x in [self.query, self.key, self.value] + ) + + +@dataclass +class Context: + lse: torch.Tensor + out: torch.Tensor + # NOTE: If `rng_state` is set, `op_bw` should be set as well + # as the randomness is backend-dependant + op_bw: Optional[Type["AttentionBwOpBase"]] = None + rng_state: Optional[Any] = None + qkv_share_storage: bool = False + + def get_padded_lse(self, pad_to: int, force_pad_inf: bool = False) -> torch.Tensor: + pad_amount = (pad_to - (self.lse.shape[2] % pad_to)) % pad_to + lse = self.lse + if pad_amount > 0: + if force_pad_inf: + lse = lse[:, :, : self.out.shape[1]] + pad_amount = (pad_to - (lse.shape[2] % pad_to)) % pad_to + lse = torch.nn.functional.pad(lse, [0, pad_amount], value=math.inf) + elif force_pad_inf and self.out.shape[1] != lse.shape[2]: + lse[:, :, self.out.shape[1] :].fill_(math.inf) + return lse + + +@dataclass +class Gradients: + dq: torch.Tensor + dk: torch.Tensor + dv: torch.Tensor + # bias gradient. None if there is no tensor bias or if it doesn't require grad + db: Optional[torch.Tensor] = None + + +class AttentionOpBase(BaseOperator): + """Base class for any attention operator in xFormers + + See: + + - :attr:`xformers.ops.fmha.cutlass.FwOp` + - :attr:`xformers.ops.fmha.cutlass.BwOp` + - :attr:`xformers.ops.fmha.flash.FwOp` + - :attr:`xformers.ops.fmha.flash.BwOp` + - :attr:`xformers.ops.fmha.triton.FwOp` + - :attr:`xformers.ops.fmha.triton.BwOp` + """ + + OPERATOR: Any + SUPPORTED_DEVICES: Set[str] + CUDA_MINIMUM_COMPUTE_CAPABILITY: Tuple[int, int] = (5, 0) + SUPPORTED_DTYPES: Set[torch.dtype] + SUPPORTED_MAX_K: float + SUPPORTED_MIN_K: int = 0 + SUPPORTED_ATTN_BIAS_TYPES: Iterable[Any] = (type(None),) + SUPPORTS_DROPOUT: bool + SUPPORTS_CUSTOM_SCALE: bool = False + SUPPORTS_DIFFERENT_VALUE_EMBED: bool = False + SUPPORTS_OUTPUT_DTYPE: bool = False + SUPPORTS_PARTIAL: bool = False + IS_DETERMINISTIC: bool = True + SUPPORTS_BMGHK: bool = False + NAME: str + OPERATOR_CATEGORY = "memory_efficient_attention" + # Format for the LSE computed in the FW pass, and accepted in the BW pass, + # for BlockDiagonalMask and children. + # When using a varlen bias, both the FW and BW operators must have the + # same value for `VARLEN_LSE_PACKED` + VARLEN_LSE_PACKED: bool = True + + _TEST_BATCH_SIZES: List[int] = [1, 300] + _TEST_K: List[int] = [32, 128] + + @classmethod + def supports(cls, d: Inputs) -> bool: + return not cls.not_supported_reasons(d) + + @classmethod + def shape_not_supported_reasons( + cls, Mq: int, Mkv: int, K: int, Kv: int + ) -> List[str]: + reasons = [] + if not cls.SUPPORTS_DIFFERENT_VALUE_EMBED and K != Kv: + reasons.append("query.shape[-1] != value.shape[-1]") + if max(K, Kv) > cls.SUPPORTED_MAX_K: + reasons.append( + f"max(query.shape[-1], value.shape[-1]) > {cls.SUPPORTED_MAX_K}" + ) + if min(K, Kv) < cls.SUPPORTED_MIN_K: + reasons.append( + f"min(query.shape[-1], value.shape[-1]) < {cls.SUPPORTED_MIN_K}" + ) + return reasons + + @classmethod + def not_supported_reasons(cls, d: Inputs) -> List[str]: + """ + Returns a list of reasons why this is not supported. + The kernel can run these inputs only if the returned list is empty + """ + query_shape = d.query.shape + reasons = cls.shape_not_supported_reasons( + Mq=query_shape[1], + Mkv=d.key.shape[1], + K=query_shape[-1], + Kv=query_shape[-1] if d.value.dtype == torch.int32 else d.value.shape[-1], + ) + device_type = d.query.device.type + dtype = d.query.dtype + if device_type not in cls.SUPPORTED_DEVICES: + reasons.append(f"device={device_type} (supported: {cls.SUPPORTED_DEVICES})") + if ( + device_type == "cuda" + and not _built_with_cuda + and (torch.version.hip is None) + ): + reasons.append("xFormers wasn't build with CUDA support") + if device_type == "cuda" and (torch.version.hip is None): + device_capability = torch.cuda.get_device_capability(d.device) + if device_capability < cls.CUDA_MINIMUM_COMPUTE_CAPABILITY: + reasons.append( + f"requires device with capability > {cls.CUDA_MINIMUM_COMPUTE_CAPABILITY} " + f"but your GPU has capability {device_capability} (too old)" + ) + if dtype not in cls.SUPPORTED_DTYPES: + reasons.append(f"dtype={dtype} (supported: {cls.SUPPORTED_DTYPES})") + if type(d.attn_bias) not in cls.SUPPORTED_ATTN_BIAS_TYPES: + reasons.append(f"attn_bias type is {type(d.attn_bias)}") + if not cls.SUPPORTS_OUTPUT_DTYPE: + if d.output_dtype is not None and d.output_dtype is not dtype: + reasons.append("Custom output dtype not supported") + if d.is_partial and not cls.SUPPORTS_PARTIAL: + reasons.append("Partial attention not supported") + if (d.p != 0.0) and not cls.SUPPORTS_DROPOUT: + reasons.append("dropout > 0.0") + if d.scale is not None and not cls.SUPPORTS_CUSTOM_SCALE: + reasons.append("has custom scale") + # bfloat16 is only supported on A100+ + # ... although the kernels can still run and give the + # correct result + if dtype is torch.bfloat16 and ( + not device_type.startswith("cuda") + or torch.cuda.get_device_capability(d.query.device)[0] < 8 + ): + reasons.append("bf16 is only supported on A100+ GPUs") + if not cls.is_available(): + reasons.append( + "operator wasn't built - see `python -m xformers.info` for more info" + ) + if not cls.IS_DETERMINISTIC and torch.are_deterministic_algorithms_enabled(): + reasons.append( + "operator is non-deterministic, but `torch.use_deterministic_algorithms` is set" + ) + if not cls.SUPPORTS_BMGHK and d.query.ndim == 5: + reasons.append("operator does not support BMGHK format") + return reasons + + +class AttentionFwOpBase(AttentionOpBase): + ERROR_ATOL: Mapping[torch.dtype, float] = { + torch.float: 3e-4, + torch.half: 4e-3, + torch.bfloat16: 2e-2, + } + ERROR_RTOL: Mapping[torch.dtype, float] = { + torch.float: 2e-5, + torch.half: 4e-4, + torch.bfloat16: 5e-3, + } + + @classmethod + def apply( + cls, inp: Inputs, needs_gradient: bool + ) -> Tuple[torch.Tensor, Optional[Context]]: + raise NotImplementedError() + + +class AttentionBwOpBase(AttentionOpBase): + # NOTE on tolerances: These are tested for `scales => (1/32)**0.5` + # In the BW pass, imprecisions accumulate in the Q@K.T recalculation + # These imprecisions are multiplied by the `scale` and then exponentiated + # So if the scale is too high, we get a lot of errors + + ERROR_ATOL: Mapping[torch.dtype, float] = { + torch.float: 9e-4, + torch.half: 0.2, + torch.bfloat16: 0.9, + } + ERROR_RTOL: Mapping[torch.dtype, float] = { + torch.float: 1e-4, + torch.half: 2e-2, + torch.bfloat16: 0.1, + } + SUPPORTS_ATTN_BIAS_GRAD = False + SUPPORTS_PARTIAL = True + + @classmethod + def not_supported_reasons(cls, d: Inputs) -> List[str]: + reasons = super(AttentionBwOpBase, cls).not_supported_reasons(d) + if ( + isinstance(d.attn_bias, torch.Tensor) + and d.attn_bias.requires_grad + and not cls.SUPPORTS_ATTN_BIAS_GRAD + ): + reasons.append( + "Computing the bias gradient is not supported (attn_bias.requires_grad = True)" + ) + + return reasons + + @classmethod + def apply(cls, ctx: Context, inp: Inputs, grad: torch.Tensor) -> Gradients: + raise NotImplementedError() + + +AttentionOp = Tuple[ + Optional[Type[AttentionFwOpBase]], Optional[Type[AttentionBwOpBase]] +] + + +def bmk2bmhk(tensor, num_heads: int) -> torch.Tensor: + if tensor.ndim == 4: + return tensor + return tensor.reshape( + [tensor.shape[0] // num_heads, num_heads, tensor.shape[1], tensor.shape[2]] + ).permute((0, 2, 1, 3)) + + +def check_lastdim_alignment_stride1( + reasons: List[str], name: str, x: torch.Tensor, alignment: int +) -> None: + if x.shape[-1] % alignment != 0: + reasons.append(f"{name}.shape[-1] % {alignment} != 0") + elif x.stride(-2) % alignment != 0: + reasons.append( + f"{name}.stride(-2) % {alignment} != 0 ({name}.stride() = {x.stride()})" + ) + # We can have stride=0 sometimes if dimension=1 + if x.stride(-1) > 1: + reasons.append( + f"{name}.stride(-1) > 1 ({name}.stride() = {x.stride()}) - you should call `.contiguous()` on the input" + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/cutlass.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/cutlass.py new file mode 100644 index 0000000000000000000000000000000000000000..032afbdf49fbc81ac66553807111232601525434 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/cutlass.py @@ -0,0 +1,461 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +from dataclasses import replace +from enum import Enum +from functools import partial +from typing import Any, Iterable, List, Optional, Set, Tuple, Union + +import torch + +from ..common import get_operator, register_operator +from . import attn_bias +from .attn_bias import ( + AttentionBias, + AttentionBiasSubTensor, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + BlockDiagonalCausalLocalAttentionMask, + BlockDiagonalCausalMask, + BlockDiagonalCausalWithOffsetPaddedKeysMask, + BlockDiagonalMask, + LowerTriangularFromBottomRightLocalAttentionMask, + LowerTriangularFromBottomRightMask, + LowerTriangularMask, + LowerTriangularMaskWithTensorBias, +) +from .common import ( + _attn_bias_apply, + AttentionBwOpBase, + AttentionFwOpBase, + check_lastdim_alignment_stride1, + Context, + Gradients, + Inputs, +) +from .torch_attention_compat import is_pt_cutlass_compatible + + +def _uses_tensorcores(sm: int, is_half: bool) -> bool: + if sm >= 80: + return True + if sm >= 70: + return is_half + return False + + +def _minimum_gemm_alignment(inp: Inputs) -> int: + if inp.device.type != "cuda": + return 1 + cap = torch.cuda.get_device_capability(inp.device) + sm = cap[0] * 10 + cap[1] + bits_per_scalar = {torch.float: 32, torch.half: 16, torch.bfloat16: 16}[ + inp.query.dtype + ] + uses_tensorcores = _uses_tensorcores(sm, bits_per_scalar == 16) + matmul_alignment_mn = 1 + if sm >= 80: + matmul_alignment_mn = 4 + if uses_tensorcores: + matmul_alignment_mn = max(matmul_alignment_mn, 128 // bits_per_scalar) + return matmul_alignment_mn + + +def _get_seqlen_info( + inp: Inputs, +) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor], int, int]: + attn_bias = inp.attn_bias + if isinstance( + attn_bias, (BlockDiagonalMask, BlockDiagonalCausalWithOffsetPaddedKeysMask) + ): + assert attn_bias.k_seqinfo.seqstart.device == inp.query.device + seqstart_k = attn_bias.k_seqinfo.seqstart + seqstart_q = attn_bias.q_seqinfo.seqstart + max_seqlen_q = attn_bias.q_seqinfo.max_seqlen + max_seqlen_k = attn_bias.k_seqinfo.max_seqlen + else: + seqstart_k = None + seqstart_q = None + max_seqlen_q = -1 + max_seqlen_k = -1 + + return seqstart_k, seqstart_q, max_seqlen_q, max_seqlen_k + + +def _get_tensor_bias( + attn_bias: Optional[Union[torch.Tensor, AttentionBias]], +) -> Optional[torch.Tensor]: + if isinstance(attn_bias, AttentionBiasSubTensor): + if isinstance(attn_bias, LowerTriangularMaskWithTensorBias): + return attn_bias._subtensor + elif isinstance(attn_bias, torch.Tensor): + return attn_bias + return None + + +def _check_bias_alignment( + reasons: List[str], attn_bias: Optional[Union[torch.Tensor, AttentionBias]] +) -> None: + attn_bias_tensor = _get_tensor_bias(attn_bias) + if attn_bias_tensor is not None: + alignment = 128 // torch.finfo(attn_bias_tensor.dtype).bits + show_padding_hint = False + for d in range(attn_bias_tensor.ndim - 1): + if attn_bias_tensor.stride(d) % alignment != 0: + reasons.append( + f"attn_bias.stride(-2) % {alignment} != 0 (attn_bias.stride() = {attn_bias_tensor.stride()})" + ) + show_padding_hint = True + if show_padding_hint: + reasons.append( + """\ +HINT: To use an `attn_bias` with a sequence length that is not a multiple of 8, \ +you need to ensure memory is aligned by slicing a bigger tensor. \ +Example: use `attn_bias = torch.zeros([1, 1, 5, 8])[:,:,:,:5]` instead of `torch.zeros([1, 1, 5, 5])`""" + ) + # We can have stride=0 sometimes if dimension=1 + if attn_bias_tensor.stride(-1) > 1: + reasons.append( + f"attn_bias.stride(-1) > 1 (attn_bias.stride() = {attn_bias_tensor.stride()}) - " + "you should call `.contiguous()` on the bias" + ) + + +class _CustomMaskType(int, Enum): + """ + (Matches CustomMaskType in C++.) + """ + + NoCustomMask = 0 + CausalFromTopLeft = 1 + CausalFromBottomRight = 2 + + +def _custom_mask_type(bias: Optional[Union[torch.Tensor, AttentionBias]]) -> int: + if isinstance( + bias, + ( + LowerTriangularMask, + BlockDiagonalCausalMask, + BlockDiagonalCausalLocalAttentionMask, + ), + ): + return int(_CustomMaskType.CausalFromTopLeft) + if isinstance( + bias, + ( + LowerTriangularFromBottomRightMask, + LowerTriangularFromBottomRightLocalAttentionMask, + attn_bias.BlockDiagonalCausalFromBottomRightMask, + BlockDiagonalCausalWithOffsetPaddedKeysMask, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + ), + ): + return int(_CustomMaskType.CausalFromBottomRight) + return int(_CustomMaskType.NoCustomMask) + + +@register_operator +class FwOp(AttentionFwOpBase): + """xFormers' MHA kernel based on CUTLASS. + Supports a large number of settings (including without TensorCores, f32 ...) + and GPUs as old as P100 (Sm60) + """ + + OPERATOR = ( + get_operator("aten", "_efficient_attention_forward") + if is_pt_cutlass_compatible() + else None + ) + SUPPORTED_DEVICES: Set[str] = {"cuda"} + SUPPORTED_DTYPES: Set[torch.dtype] = {torch.float, torch.half, torch.bfloat16} + SUPPORTED_MAX_K = 65536 + SUPPORTED_ATTN_BIAS_TYPES: Iterable[Any] = ( + type(None), + torch.Tensor, + LowerTriangularMask, + LowerTriangularFromBottomRightMask, + LowerTriangularFromBottomRightLocalAttentionMask, + LowerTriangularMaskWithTensorBias, + BlockDiagonalMask, + BlockDiagonalCausalMask, + BlockDiagonalCausalWithOffsetPaddedKeysMask, + attn_bias.BlockDiagonalCausalFromBottomRightMask, + attn_bias.BlockDiagonalCausalLocalAttentionMask, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + ) + SUPPORTS_DROPOUT = True + SUPPORTS_CUSTOM_SCALE = True + SUPPORTS_DIFFERENT_VALUE_EMBED = True + SUPPORTS_BMGHK = True + VARLEN_LSE_PACKED = False + NAME = "cutlassF-pt" + + _TEST_K: List[int] = [ + 32, # 64x64 kernel + 128, # 64x128 kernel + 256, # 64x128 with accumulation in gmem + ] + + @classmethod + def apply( + cls, inp: Inputs, needs_gradient: bool + ) -> Tuple[torch.Tensor, Optional[Context]]: + if type(inp.attn_bias) not in FwOp.SUPPORTED_ATTN_BIAS_TYPES: + raise NotImplementedError("Unsupported attn_bias type") + if inp.query.ndim in [3, 4]: + return cls.apply_bmhk(inp, needs_gradient=needs_gradient) + assert inp.query.ndim == 5, f"query has shape {inp.query.shape}" + ctx: Optional[Context] = None + # XXX: Hackfix for BMGHK with H=1 + # In that case we don't want to run G different streams because it adds + # some overhead + if inp.query.ndim == 5 and inp.query.shape[3] == 1: + slice_op = partial(torch.squeeze, dim=3) + inp = replace( + inp, + query=slice_op(inp.query), + key=slice_op(inp.key), + value=slice_op(inp.value), + attn_bias=_attn_bias_apply( + inp.attn_bias, partial(torch.squeeze, dim=2) + ), + ) + out, ctx = cls.apply_bmhk(inp, needs_gradient=needs_gradient) + out = out.unsqueeze(3) + if ctx is not None: + ctx = replace(ctx, lse=ctx.lse.unsqueeze(1), out=out) + return out, ctx + + # Workaround until this is properly implemented in C++ + # run each head group in a different stream + n_groups = inp.key.shape[2] + main_stream = torch.cuda.current_stream() + streams = [main_stream] + [ + torch.cuda.Stream(device=inp.query.device) for _ in range(n_groups - 1) + ] + outs = [] + for group, stream in enumerate(streams): + stream.wait_stream(main_stream) + with torch.cuda.stream(stream): + query = inp.query[:, :, group] + key = inp.key[:, :, group] + value = inp.value[:, :, group] + bias = _attn_bias_apply( + inp.attn_bias, partial(torch.select, dim=1, index=group) + ) + outs.append( + cls.apply_bmhk( + replace(inp, query=query, key=key, value=value, attn_bias=bias), + needs_gradient=needs_gradient, + ) + ) + for s in streams[1:]: + main_stream.wait_stream(s) + out = torch.stack([o[0] for o in outs], dim=2) + if needs_gradient: + ctx = Context( + out=out, + lse=torch.stack([o[1].lse for o in outs], dim=1), # type: ignore + op_bw=outs[0][1].op_bw, # type: ignore + ) + return out, ctx + + @classmethod + def apply_bmhk( + cls, inp: Inputs, needs_gradient: bool + ) -> Tuple[torch.Tensor, Optional[Context]]: + if type(inp.attn_bias) not in FwOp.SUPPORTED_ATTN_BIAS_TYPES: + raise NotImplementedError("Unsupported attn_bias type") + seqstart_k, seqstart_q, max_seqlen_q, max_seqlen_k = _get_seqlen_info(inp) + out, lse, rng_seed, rng_offset, _, _ = cls.OPERATOR( + query=inp.query, + key=inp.key, + value=inp.value, + bias=_get_tensor_bias(inp.attn_bias), + cu_seqlens_q=seqstart_q, + cu_seqlens_k=seqstart_k, + max_seqlen_q=max_seqlen_q, + max_seqlen_k=max_seqlen_k, + dropout_p=inp.p, + compute_log_sumexp=needs_gradient, + custom_mask_type=_custom_mask_type(inp.attn_bias), + scale=inp.scale, + seqlen_k=( + inp.attn_bias.k_seqinfo.seqlen + if isinstance( + inp.attn_bias, BlockDiagonalCausalWithOffsetPaddedKeysMask + ) + else None + ), + window_size=( + inp.attn_bias._window_size + if isinstance( + inp.attn_bias, + ( + BlockDiagonalCausalLocalAttentionMask, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + LowerTriangularFromBottomRightLocalAttentionMask, + ), + ) + else None + ), + ) + ctx: Optional[Context] = None + if needs_gradient: + ctx = Context(out=out, lse=lse) + if inp.p != 0: + # cutlass forward is only compatible with cutlass backward if + # dropout is used (because of the way RNG states are passed and the + # way random numbers are generated during backward) + ctx.rng_state = (rng_seed, rng_offset) + ctx.op_bw = BwOp + return out, ctx + + @classmethod + def not_supported_reasons(cls, d: Inputs) -> List[str]: + reasons = super(FwOp, cls).not_supported_reasons(d) + matmul_alignment_mn = _minimum_gemm_alignment(d) + check_lastdim_alignment_stride1(reasons, "query", d.query, matmul_alignment_mn) + check_lastdim_alignment_stride1(reasons, "value", d.value, matmul_alignment_mn) + _check_bias_alignment(reasons, d.attn_bias) + return reasons + + +@register_operator +class BwOp(AttentionBwOpBase): + __doc__ = FwOp.__doc__ + + OPERATOR = ( + get_operator("aten", "_efficient_attention_backward") + if is_pt_cutlass_compatible() + else None + ) + + SUPPORTED_DEVICES = FwOp.SUPPORTED_DEVICES + SUPPORTED_DTYPES = FwOp.SUPPORTED_DTYPES + SUPPORTED_MAX_K = FwOp.SUPPORTED_MAX_K + SUPPORTED_ATTN_BIAS_TYPES: Iterable[Any] = ( + type(None), + torch.Tensor, + LowerTriangularMask, + LowerTriangularFromBottomRightMask, + # TODO: Still some infs/nans in the BW pass for + # local + causal + # LowerTriangularFromBottomRightLocalAttentionMask, + # TODO: Fix handling of gradient through the fMHA autograd function + # LowerTriangularMaskWithTensorBias, + BlockDiagonalMask, + BlockDiagonalCausalMask, + attn_bias.BlockDiagonalCausalFromBottomRightMask, + attn_bias.BlockDiagonalCausalLocalAttentionMask, + ) + SUPPORTS_ATTN_BIAS_GRAD = True + SUPPORTS_DROPOUT = FwOp.SUPPORTS_DROPOUT + SUPPORTS_CUSTOM_SCALE = FwOp.SUPPORTS_CUSTOM_SCALE + SUPPORTS_DIFFERENT_VALUE_EMBED = FwOp.SUPPORTS_DIFFERENT_VALUE_EMBED + VARLEN_LSE_PACKED = False + NAME = "cutlassB-pt" + + _TEST_K: List[int] = [ + 32, # 64x64 kernel + 128, # 64x128/128x128 kernel + 256, # 64x128 with accumulation in gmem + ] + + @classmethod + def not_supported_reasons(cls, d: Inputs) -> List[str]: + reasons = super(BwOp, cls).not_supported_reasons(d) + matmul_alignment_mn = _minimum_gemm_alignment(d) + + check_lastdim_alignment_stride1(reasons, "query", d.query, matmul_alignment_mn) + check_lastdim_alignment_stride1(reasons, "key", d.key, matmul_alignment_mn) + check_lastdim_alignment_stride1(reasons, "value", d.value, matmul_alignment_mn) + _check_bias_alignment(reasons, d.attn_bias) + attn_bias_tensor = _get_tensor_bias(d.attn_bias) + + # Backprop of gradient through broadcasted bias is not supported + if attn_bias_tensor is not None and attn_bias_tensor.requires_grad: + # Don't forget that inputs are either in BMK or BMHK! + if d.query.ndim == 3 and attn_bias_tensor.ndim == 3: + expected_bias_shape = (*d.query.shape[:2], d.key.shape[1]) + else: + # bias is B H Mq Mk + expected_bias_shape = ( + d.query.shape[0], + d.query.shape[2] if d.query.ndim == 4 else 1, + d.query.shape[1], + d.key.shape[1], + ) + if tuple(attn_bias_tensor.shape) != expected_bias_shape: + reasons.append( + "Broadcasting the `attn_bias` tensor is not supported " + f"(shape: {tuple(attn_bias_tensor.shape)}" + f"/ expected: {expected_bias_shape})" + ) + return reasons + + @classmethod + def apply(cls, ctx: Context, inp: Inputs, grad: torch.Tensor) -> Gradients: + if type(inp.attn_bias) not in BwOp.SUPPORTED_ATTN_BIAS_TYPES: + raise NotImplementedError("Unsupported attn_bias type") + + seqstart_k, seqstart_q, max_seqlen_q, max_seqlen_k = _get_seqlen_info(inp) + dtype = inp.query.dtype + + rng_seed = rng_offset = torch.Tensor() + if inp.p != 0.0: + assert ctx.rng_state is not None + rng_seed, rng_offset = ctx.rng_state + tensor_bias = _get_tensor_bias(inp.attn_bias) + + force_pad_inf = torch.cuda.get_device_capability(inp.query.device) == (7, 5) + (grad_q, grad_k, grad_v, grad_bias) = cls.OPERATOR( + grad.to(dtype), + inp.query, + inp.key, + inp.value, + bias=tensor_bias, + bias_requires_grad=( + tensor_bias.requires_grad if tensor_bias is not None else False + ), + cu_seqlens_q=seqstart_q, + cu_seqlens_k=seqstart_k, + max_seqlen_q=max_seqlen_q, + max_seqlen_k=max_seqlen_k, + logsumexp=ctx.get_padded_lse(32, force_pad_inf=force_pad_inf), + out=ctx.out.to(dtype), + dropout_p=inp.p, + # if not using dropout, seed and offset are irrelevant but still expected + # in function signature so just pass 0 + # seed and offset could be None if a different FW op other than cutlass + # was used. + philox_seed=rng_seed, + philox_offset=rng_offset, + custom_mask_type=_custom_mask_type(inp.attn_bias), + scale=inp.scale, + num_splits_key=None, # Let C++ determine it + window_size=( + inp.attn_bias._window_size + if isinstance( + inp.attn_bias, + ( + BlockDiagonalCausalLocalAttentionMask, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + LowerTriangularFromBottomRightLocalAttentionMask, + ), + ) + else None + ), + ) + + # c++/CUDA implementation returns an uninitialized tensor if bias doesn't + # require grad + if not ( + isinstance(inp.attn_bias, torch.Tensor) and inp.attn_bias.requires_grad + ): + grad_bias = None + + return Gradients(dq=grad_q, dk=grad_k, dv=grad_v, db=grad_bias) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/dispatch.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..5908635dac17faa34d1e3e2822b4e12fc73e58bf --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/dispatch.py @@ -0,0 +1,188 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import textwrap +from collections import deque +from typing import Any, List, Optional, Sequence, Tuple, Type, TypeVar + +import torch + +from . import attn_bias, ck, cutlass, flash, flash3, triton_splitk +from .common import AttentionBwOpBase, AttentionFwOpBase, Inputs + +T = TypeVar("T", Type[AttentionFwOpBase], Type[AttentionBwOpBase]) + + +_USE_FLASH_ATTENTION_3 = True + + +def _set_use_fa3(use_flash_attention3: bool) -> None: + global _USE_FLASH_ATTENTION_3 + _USE_FLASH_ATTENTION_3 = use_flash_attention3 + + +def _get_use_fa3() -> bool: + global _USE_FLASH_ATTENTION_3 + return _USE_FLASH_ATTENTION_3 + + +def fa3_available() -> bool: + has_cuda = torch.version.cuda is not None + is_90a = has_cuda and torch.cuda.get_device_capability() >= (9, 0) + has_valid_flash3 = flash3._C_flashattention3 is not None # pyre-ignore[16] + return is_90a and has_valid_flash3 + + +def _format_inputs_description(inp: Inputs) -> str: + return f"""query : shape={tuple(inp.query.shape)} ({inp.query.dtype}) +key : shape={tuple(inp.key.shape)} ({inp.key.dtype}) +value : shape={tuple(inp.value.shape)} ({inp.value.dtype}) +attn_bias : {type(inp.attn_bias)} +p : {inp.p}""" + + +def _ensure_op_supports_or_raise(exc_type, name: str, op, inp: Inputs) -> None: + reasons = op.not_supported_reasons(inp) + if not reasons: + return + raise exc_type( + f"""Operator `{name}` does not support inputs: +{textwrap.indent(_format_inputs_description(inp), ' ')} +{_format_not_supported_reasons(op, reasons)}""" + ) + + +def _format_not_supported_reasons(op, reasons: List[str]) -> str: + return f"`{op.NAME}` is not supported because:\n " + "\n ".join(reasons) + + +def _run_priority_list( + name: str, + priority_list: Sequence[T], + inp: Inputs, + extra_op_reasons: Optional[List[Tuple[Any, List[str]]]] = None, +) -> T: + not_supported_reasons: List[List[str]] = [] + for op in priority_list: + not_supported = op.not_supported_reasons(inp) + if not not_supported: + return op + not_supported_reasons.append(not_supported) + + # Let's write a nice message explaining what we tried and why it's not supported + msg = f"""No operator found for `{name}` with inputs: +{textwrap.indent(_format_inputs_description(inp), ' ')}""" + for op, not_supported in zip(priority_list, not_supported_reasons): + msg += "\n" + _format_not_supported_reasons(op, not_supported) + if extra_op_reasons is not None: + for op, not_supported in extra_op_reasons: + msg += "\n" + _format_not_supported_reasons(op, not_supported) + raise NotImplementedError(msg) + + +def _dispatch_fw_priority_list( + inp: Inputs, needs_gradient: bool +) -> Sequence[Type[AttentionFwOpBase]]: + if torch.version.cuda: + flash3_op = [flash3.FwOp] if _get_use_fa3() else [] + priority_list_ops = deque( + flash3_op + + [ + flash.FwOp, + cutlass.FwOp, + ] + ) + else: + priority_list_ops = deque( + [ + ck.FwOp, + ] + ) + if not needs_gradient: + mqa_or_gqa = ( + inp.key.ndim > 3 and inp.key.stride(-2) == 0 and inp.key.shape[-2] > 1 + ) + # Split-KV is useful with MQA + # for short Q-seqlen / long K-seqlen + if mqa_or_gqa and inp.query.shape[1] <= 32 and inp.key.shape[1] >= 256: + parallelism_BH = 0 # BMK + if inp.query.ndim == 3: + parallelism_BH = inp.query.shape[0] + elif inp.query.ndim == 4: # BMHK + parallelism_BH = inp.query.shape[0] * inp.query.shape[2] + elif inp.query.ndim == 5: # BMGHK + parallelism_BH = inp.query.shape[0] * inp.query.shape[2] + if parallelism_BH > 0 and parallelism_BH < 64: + # priority_list_ops.appendleft(ck_splitk.FwOp) + priority_list_ops.appendleft(triton_splitk.FwOp) + # Without variable seqlen flash is fastest + if torch.version.cuda and not isinstance( + inp.attn_bias, attn_bias.BlockDiagonalMask + ): + if _get_use_fa3(): + priority_list_ops.remove(flash3.FwOp) + priority_list_ops.remove(flash.FwOp) + priority_list_ops.appendleft(flash.FwOp) + + return priority_list_ops + + +def _dispatch_fw(inp: Inputs, needs_gradient: bool) -> Type[AttentionFwOpBase]: + """Computes the best operator for forward + + Raises: + NotImplementedError: if not operator was found + + Returns: + AttentionOp: The best operator for the configuration + """ + return _run_priority_list( + "memory_efficient_attention_forward", + _dispatch_fw_priority_list(inp, needs_gradient), + inp, + ) + + +def _dispatch_bw( + inp: Inputs, varlen_lse_packed: Optional[bool] +) -> Type[AttentionBwOpBase]: + if torch.version.cuda: + priority_list_ops: List[Type[AttentionBwOpBase]] = [ + flash.BwOp, + cutlass.BwOp, + ] + if _get_use_fa3(): + priority_list_ops = [flash3.BwOp] + priority_list_ops + else: + priority_list_ops = [ + ck.BwOp, + ] + + # NOTE: If we have a variable seqlen `attn_bias`, we need to get a BW pass + # that supports the LSE format + # *unless* we are in the case where both formats are the same (bs=1) + extra_op_reasons = [] + if ( + isinstance(inp.attn_bias, attn_bias.VARLEN_BIASES) + and inp.attn_bias.q_seqinfo.seqstart.shape[0] > 2 + ): + assert varlen_lse_packed is not None + for op in priority_list_ops: + if op.VARLEN_LSE_PACKED != varlen_lse_packed: + extra_op_reasons.append( + ( + op, + [ + f"LSE is in {'packed' if varlen_lse_packed else 'padded'} format" + ], + ) + ) + priority_list_ops = [ + op for op in priority_list_ops if op.VARLEN_LSE_PACKED == varlen_lse_packed + ] + return _run_priority_list( + "memory_efficient_attention_backward", priority_list_ops, inp + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/flash.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/flash.py new file mode 100644 index 0000000000000000000000000000000000000000..bd91e56e502a571aa784836bf8ce47798f18d0c4 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/flash.py @@ -0,0 +1,847 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import importlib.util +import os +from itertools import zip_longest +from typing import Any, Iterable, List, Optional, Set, Tuple, Union + +import torch + +from ..common import get_operator, register_operator +from .attn_bias import ( + AttentionBias, + BlockDiagonalCausalFromBottomRightMask, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + BlockDiagonalCausalLocalAttentionMask, + BlockDiagonalCausalLocalAttentionPaddedKeysMask, + BlockDiagonalCausalMask, + BlockDiagonalCausalWithOffsetGappyKeysMask, + BlockDiagonalCausalWithOffsetPaddedKeysMask, + BlockDiagonalGappyKeysMask, + BlockDiagonalLocalAttentionPaddedKeysMask, + BlockDiagonalMask, + BlockDiagonalPaddedKeysMask, + LocalAttentionFromBottomRightMask, + LowerTriangularFromBottomRightLocalAttentionMask, + LowerTriangularFromBottomRightMask, + LowerTriangularMask, + PagedBlockDiagonalCausalWithOffsetGappyKeysMask, + PagedBlockDiagonalCausalWithOffsetPaddedKeysMask, + PagedBlockDiagonalGappyKeysMask, + PagedBlockDiagonalPaddedKeysMask, + VARLEN_BIASES, +) +from .common import ( + AttentionBwOpBase, + AttentionFwOpBase, + check_lastdim_alignment_stride1, + Context, + Gradients, + Inputs, +) +from .torch_attention_compat import is_pt_flash_old + +FLASH_VERSION = "0.0.0" +VARLEN_LSE_PACKED = False +pt_flash_is_old = False +_TRY_PT_FLASH_ATTN = ( + torch.version.hip is None and torch.backends.cuda.is_flash_attention_available() +) +_USE_PT_FLASH_ATTN = False + + +if importlib.util.find_spec("..._C_flashattention", package=__package__): + from ... import _C_flashattention # type: ignore[attr-defined] + from ..._cpp_lib import _build_metadata + + if _build_metadata is not None: + FLASH_VERSION = _build_metadata.flash_version.lstrip("v") + VARLEN_LSE_PACKED = True + +elif importlib.util.find_spec("flash_attn"): + import flash_attn + import flash_attn.flash_attn_interface + + if hasattr(flash_attn.flash_attn_interface, "flash_attn_cuda"): + _C_flashattention = flash_attn.flash_attn_interface.flash_attn_cuda + else: + _C_flashattention = flash_attn.flash_attn_interface.flash_attn_gpu + + FLASH_VERSION = flash_attn.__version__ + FLASH_VER_MIN = (2, 7, 1) + FLASH_VER_LAST = (2, 8, 0) # last supported, inclusive + flash_ver_parsed = tuple(int(s) for s in FLASH_VERSION.split(".")[:3]) + if ( + flash_ver_parsed < FLASH_VER_MIN or flash_ver_parsed > FLASH_VER_LAST + ) and os.environ.get("XFORMERS_IGNORE_FLASH_VERSION_CHECK", "0") != "1": + raise ImportError( + f"Requires Flash-Attention version >={'.'.join([str(i) for i in FLASH_VER_MIN])}," + f"<={'.'.join([str(i) for i in FLASH_VER_LAST])} " + f"but got {FLASH_VERSION}." + ) + VARLEN_LSE_PACKED = True + +elif _TRY_PT_FLASH_ATTN: + pt_flash_is_old = is_pt_flash_old(force=True) is True + FLASH_VERSION = torch.nn.attention._get_flash_version() # type: ignore + VARLEN_LSE_PACKED = not pt_flash_is_old + _USE_PT_FLASH_ATTN = True + + +if FLASH_VERSION != "0.0.0": + + @torch.library.custom_op( + "xformers_flash::flash_fwd", + mutates_args=(), + device_types=["cuda"], + ) + def _flash_fwd( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + cu_seqlens_q: Optional[torch.Tensor], + cu_seqlens_k: Optional[torch.Tensor], + seqused_k: Optional[torch.Tensor], + max_seqlen_q: int, + max_seqlen_k: int, + p: float, + softmax_scale: float, + is_causal: bool, + window_left: int, + window_right: int, + return_softmax: bool, + block_tables: Optional[torch.Tensor], + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + softcap = 0.0 + if _USE_PT_FLASH_ATTN: + ret = torch.ops.aten._flash_attention_forward( + query, + key, + value, + cu_seqlens_q, # cum_seq_q + cu_seqlens_k, # cum_seq_k + max_seqlen_q, # max_q + max_seqlen_k, # max_k + p, # dropout_p + is_causal, + return_debug_mask=False, + scale=softmax_scale, + window_size_left=window_left, + window_size_right=window_right, + seqused_k=seqused_k, + alibi_slopes=None, # alibi_slopes + ) + if pt_flash_is_old: + ( + attention, + logsumexp, + philox_seed, + philox_offset, + _, + ) = ret + rng_state = torch.stack([philox_seed, philox_offset]) + else: + attention, logsumexp, rng_state, _, _ = ret + return attention, logsumexp, rng_state + else: + if cu_seqlens_q is None: + assert cu_seqlens_k is None + assert seqused_k is None + out, softmax_lse, p, rng_state = _C_flashattention.fwd( + query, + key, + value, + None, # out + None, # alibi_slopes + p, + softmax_scale, + is_causal, + window_left, # window_size_left + window_right, # window_size_right + softcap, + return_softmax, + None, # rng + ) + else: + out, softmax_lse, p, rng_state = _C_flashattention.varlen_fwd( + query, + key, + value, + None, # out + cu_seqlens_q, + cu_seqlens_k, + seqused_k, + None, # leftpad_k_ + block_tables, + None, # alibi_slopes + max_seqlen_q, + max_seqlen_k, + p, + softmax_scale, + False, + is_causal, + window_left, + window_right, + softcap, + return_softmax, + None, # gen + ) + return out, softmax_lse, rng_state + + @torch.library.register_fake("xformers_flash::flash_fwd") + def _flash_fwd_abstract( + query, + key, + value, + cu_seqlens_q, + cu_seqlens_k, + seqused_k, + max_seqlen_q, + max_seqlen_k, + p, + softmax_scale, + is_causal, + window_left, + window_right, + return_softmax, + block_tables, + ): + out = torch.empty_like(query) + if cu_seqlens_q is None: + B, M, H, K = query.shape + lse_shape = [B, H, M] + else: + M, H, K = query.shape + B = cu_seqlens_q.shape[0] - 1 + if VARLEN_LSE_PACKED: + lse_shape = [H, M] + else: + lse_shape = [B, H, max_seqlen_q] + softmax_lse = torch.empty(lse_shape, device=query.device, dtype=torch.float32) + rng_state = torch.empty([2], device=query.device, dtype=torch.int64) + return out, softmax_lse, rng_state + + @torch.library.custom_op( + "xformers_flash::flash_bwd", + mutates_args=(), + device_types=["cuda"], + ) + def _flash_bwd( + grads_share_storage: bool, + grad: torch.Tensor, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + out: torch.Tensor, + lse: torch.Tensor, + cu_seqlens_q: torch.Tensor, + cu_seqlens_k: torch.Tensor, + max_seqlen_q: int, + max_seqlen_k: int, + p: float, + softmax_scale: float, + is_causal: bool, + window_left: int, + window_right: int, + rng_state: torch.Tensor, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + softcap = 0.0 + if _USE_PT_FLASH_ATTN: + assert softcap == 0.0 + if rng_state is not None and pt_flash_is_old: + rng_state0 = rng_state[0] + rng_state1 = rng_state[1] + else: + rng_state0 = rng_state1 = rng_state + dq, dk, dv = torch.ops.aten._flash_attention_backward( + grad, + query, + key, + value, + out, + lse, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + p, + is_causal, + rng_state0, + rng_state1, + scale=softmax_scale, + window_size_left=window_left, + window_size_right=window_right, + ) + else: + dq, dk, dv = _create_dq_dk_dv(grads_share_storage, query, key, value) + if cu_seqlens_k is None: + assert cu_seqlens_q is None + _C_flashattention.bwd( + grad, + query, + key, + value, + out, + lse, + dq, + dk, + dv, + None, # alibi_slopes + p, + softmax_scale, + is_causal, + window_left, + window_right, + softcap, + False, # deterministic + None, + rng_state, + ) + else: + _C_flashattention.varlen_bwd( + grad, + query, + key, + value, + out, + lse, + dq, + dk, + dv, + cu_seqlens_q, + cu_seqlens_k, + None, # alibi_slopes + max_seqlen_q, + max_seqlen_k, + p, + softmax_scale, + False, # zero_tensors + is_causal, + window_left, + window_right, + softcap, + False, # deterministic + None, + rng_state, + ) + return dq, dk, dv + + @torch.library.register_fake("xformers_flash::flash_bwd") + def _flash_bwd_abstract( + grads_share_storage, + grad, + query, + key, + value, + *args, + **kwargs, + ): + return _create_dq_dk_dv(grads_share_storage, query, key, value) + + def _create_dq_dk_dv( + grads_share_storage: bool, query, key, value + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + # Create dq,dk,dv + # If Q/K/V come from a single QKV tensor, let's put the gradient in the + # right strides, so we can avoid a `cat` + if grads_share_storage: + chunk = torch.empty( + (*query.shape[0:-2], 3, query.shape[-2], query.shape[-1]), + dtype=query.dtype, + device=query.device, + ) + return chunk.select(-3, 0), chunk.select(-3, 1), chunk.select(-3, 2) + return torch.empty_like(query), torch.empty_like(key), torch.empty_like(value) + + +def _convert_input_format( + inp: Inputs, + supports_mqa: bool, + use_kvsplit: bool = False, +) -> Tuple[ + Inputs, + Optional[torch.Tensor], + int, + Optional[torch.Tensor], + int, + Optional[torch.Tensor], +]: + assert inp.query.ndim in [4, 5] + query, key, value = inp.query, inp.key, inp.value + batch = query.shape[0] + seqlen_q = query.shape[1] + seqlen_kv = key.shape[1] + head_dim_q = query.shape[-1] + head_dim_v = value.shape[-1] + + attn_bias = inp.attn_bias + if isinstance(attn_bias, BlockDiagonalMask): + assert attn_bias.k_seqinfo.seqstart.device == inp.query.device + cu_seqlen_k = attn_bias.k_seqinfo.seqstart + cu_seqlen_q = attn_bias.q_seqinfo.seqstart + max_seqlen_q = attn_bias.q_seqinfo.max_seqlen + max_seqlen_k = attn_bias.k_seqinfo.max_seqlen + seqused_k = None + elif isinstance( + attn_bias, + ( + BlockDiagonalGappyKeysMask, + BlockDiagonalPaddedKeysMask, + PagedBlockDiagonalGappyKeysMask, + PagedBlockDiagonalPaddedKeysMask, + ), + ): + assert attn_bias.k_seqinfo.seqstart.device == inp.query.device + cu_seqlen_k = attn_bias.k_seqinfo.seqstart + cu_seqlen_q = attn_bias.q_seqinfo.seqstart + max_seqlen_q = attn_bias.q_seqinfo.max_seqlen + max_seqlen_k = attn_bias.k_seqinfo.max_seqlen + seqused_k = attn_bias.k_seqinfo.seqlen + else: + cu_seqlen_k = None + cu_seqlen_q = None + seqused_k = None + max_seqlen_q = inp.query.shape[1] + max_seqlen_k = inp.key.shape[1] + + if query.ndim == 5: # GQA + assert supports_mqa + + # Fold the group/head_in_group dimensions together + def fold(x): + # Either the head is replicated + if x.stride(3) == 0: + return x[:, :, :, 0] + # Or we reshape + return x.reshape( + [ + x.shape[0], + x.shape[1], + -1, + x.shape[4], + ] + ) + + query = fold(query) + key = fold(key) + value = fold(value) + # Optimize for MHA + if supports_mqa and key.ndim == 4 and key.stride(2) == 0 and value.stride(2) == 0: + key = key[:, :, :1] + value = value[:, :, :1] + # Initially we have `query.shape = [batch, seqlen, num_heads, head_dim_q]` + # We want format `[batch * seqlen, num_heads, head_dim_q]` + if cu_seqlen_k is not None: + query = query.reshape([batch * seqlen_q, -1, head_dim_q]) + key = key.reshape([batch * seqlen_kv, -1, head_dim_q]) + value = value.reshape([batch * seqlen_kv, -1, head_dim_v]) + if isinstance( + attn_bias, + (PagedBlockDiagonalGappyKeysMask, PagedBlockDiagonalPaddedKeysMask), + ): + num_pages = value.shape[0] // attn_bias.page_size + key = key.view(num_pages, attn_bias.page_size, *key.shape[1:]) + value = value.view(num_pages, attn_bias.page_size, *value.shape[1:]) + + new_inp = Inputs( + query=query, + key=key, + value=value, + attn_bias=attn_bias, + p=inp.p, + scale=inp.scale, + output_dtype=inp.output_dtype, + is_partial=inp.is_partial, + ) + return new_inp, cu_seqlen_q, max_seqlen_q, cu_seqlen_k, max_seqlen_k, seqused_k + + +def _is_causal(attn_bias: Optional[Union[torch.Tensor, AttentionBias]]) -> bool: + return isinstance( + attn_bias, + ( + LowerTriangularMask, + LowerTriangularFromBottomRightMask, + LowerTriangularFromBottomRightLocalAttentionMask, + BlockDiagonalCausalMask, + BlockDiagonalCausalLocalAttentionMask, + BlockDiagonalCausalFromBottomRightMask, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + BlockDiagonalCausalLocalAttentionPaddedKeysMask, + BlockDiagonalCausalWithOffsetGappyKeysMask, + BlockDiagonalCausalWithOffsetPaddedKeysMask, + PagedBlockDiagonalCausalWithOffsetGappyKeysMask, + PagedBlockDiagonalCausalWithOffsetPaddedKeysMask, + ), + ) + + +def _is_paged_attention_supported(attn_bias_type) -> bool: + if issubclass(attn_bias_type, PagedBlockDiagonalPaddedKeysMask): + return not _USE_PT_FLASH_ATTN + if issubclass( + attn_bias_type, + (PagedBlockDiagonalGappyKeysMask, PagedBlockDiagonalPaddedKeysMask), + ): + return not torch.mtia.is_available() + + return True + + +def _window_size( + attn_bias: Optional[Union[torch.Tensor, AttentionBias]], +) -> Tuple[int, int]: + win_left = -1 + win_right = -1 + if isinstance( + attn_bias, + ( + BlockDiagonalCausalLocalAttentionMask, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + BlockDiagonalCausalLocalAttentionPaddedKeysMask, + LowerTriangularFromBottomRightLocalAttentionMask, + ), + ): + win_left = attn_bias._window_size - 1 + if isinstance( + attn_bias, + ( + BlockDiagonalLocalAttentionPaddedKeysMask, + LocalAttentionFromBottomRightMask, + ), + ): + win_left = attn_bias.window_left + win_right = attn_bias.window_right + return (win_left, win_right) + + +def _check_needs_no_topleft(d: Inputs, reasons: List[str]) -> None: + # Flash does not support TopLeft, so only allow causal masks with TopLeft + # if each batch element has equal number of queries and keys. + if isinstance(d.attn_bias, BlockDiagonalCausalMask): + # Flash does not support TopLeft, so only allow BlockDiagonalCausalMask + # if each batch element has equal number of queries and keys. + for k_start, q_start in zip_longest( + d.attn_bias.k_seqinfo.seqstart_py, d.attn_bias.q_seqinfo.seqstart_py + ): + if k_start != q_start: + reasons.append( + "Only support BlockDiagonalCausalMask if equal" + " numbers of keys and queries" + ) + break + elif isinstance(d.attn_bias, LowerTriangularMask): + if d.query.shape[1] != d.key.shape[1]: + reasons.append( + "Only support LowerTriangularMask if equal number of" "keys and queries" + ) + + +def _check_strides_for_bmghk(x: torch.Tensor, name: str, reasons: List[str]) -> None: + """ + We want to be able to collapse the G/H dimensions together + """ + if x.ndim == 5: + stride_g, stride_h = x.stride(2), x.stride(3) + if x.shape[2] == 1: + return + if x.shape[3] == 1 or stride_h == 0: + return + if stride_g != stride_h * x.shape[-2]: + reasons.append( + f"GQA is only supported when the G/H dimensions are contiguous\n" + f" {name}.stride: {x.stride()}\n" + f" {name}.shape : {list(x.shape)}" + ) + + +def _post_process_lse( + lse: torch.Tensor, + inp: Inputs, + original_query_shape: Tuple[int, ...], + varlen_lse_packed: bool = VARLEN_LSE_PACKED, +) -> torch.Tensor: + # Easy case: no varlen + if not isinstance(inp.attn_bias, VARLEN_BIASES): + if len(original_query_shape) == 5: + # [B, GH, M] => [B, G, H, M] + return lse.unflatten(1, original_query_shape[2:4]) + return lse + + # Already packed: just bring back the batch dimension + if varlen_lse_packed: + if len(original_query_shape) == 5: + # (1, G, H, total_q) + return lse.unflatten(0, original_query_shape[2:4]).unsqueeze(0) + # (1, H, total_q) + return lse.unsqueeze(0) + + if not inp.is_partial: + # (B, H, M) + return lse + + # reshape from (B, G*H, max_seqlen) to (1, G*H, B*max_seqlen) + # Unfortunately this flatten is not just a view. + lse_hkm = lse.permute(1, 0, 2).flatten(start_dim=1)[None] + if len(original_query_shape) == 5: + return lse_hkm.unflatten(1, original_query_shape[2:4]) + return lse_hkm + + +@register_operator +class FwOp(AttentionFwOpBase): + """Operator that computes memory-efficient attention using \ + `Flash-Attention `_ \ + implementation. + """ + + OPERATOR = get_operator("xformers_flash", "flash_fwd") + SUPPORTED_DEVICES: Set[str] = {"cuda"} + CUDA_MINIMUM_COMPUTE_CAPABILITY = (8, 0) + SUPPORTED_DTYPES: Set[torch.dtype] = {torch.half, torch.bfloat16} + SUPPORTED_MAX_K = 256 + SUPPORTED_ATTN_BIAS_TYPES: Iterable[Any] = ( + type(None), + LowerTriangularMask, + LowerTriangularFromBottomRightMask, + LowerTriangularFromBottomRightLocalAttentionMask, + BlockDiagonalMask, + BlockDiagonalCausalMask, + BlockDiagonalCausalLocalAttentionMask, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + BlockDiagonalCausalLocalAttentionPaddedKeysMask, + BlockDiagonalCausalFromBottomRightMask, + BlockDiagonalCausalWithOffsetGappyKeysMask, + BlockDiagonalCausalWithOffsetPaddedKeysMask, + BlockDiagonalGappyKeysMask, + BlockDiagonalPaddedKeysMask, + LocalAttentionFromBottomRightMask, + PagedBlockDiagonalCausalWithOffsetPaddedKeysMask, + PagedBlockDiagonalPaddedKeysMask, + ) + + SUPPORTED_ATTN_BIAS_TYPES = [ + b for b in SUPPORTED_ATTN_BIAS_TYPES if _is_paged_attention_supported(b) + ] + + SUPPORTS_DROPOUT = True + SUPPORTS_CUSTOM_SCALE = True + SUPPORTS_DIFFERENT_VALUE_EMBED = False + SUPPORTS_BMGHK = True + SUPPORTS_PARTIAL = True + VARLEN_LSE_PACKED = VARLEN_LSE_PACKED + NAME = f"fa2F@{FLASH_VERSION}-pt" if _USE_PT_FLASH_ATTN else f"fa2F@{FLASH_VERSION}" + VERSION = FLASH_VERSION + + @classmethod + def not_supported_reasons(cls, d: Inputs) -> List[str]: + reasons = super(FwOp, cls).not_supported_reasons(d) + check_lastdim_alignment_stride1(reasons, "query", d.query, 8) + _check_needs_no_topleft(d, reasons) + _check_strides_for_bmghk(d.query, "query", reasons) + _check_strides_for_bmghk(d.key, "key", reasons) + _check_strides_for_bmghk(d.value, "value", reasons) + + if ( + d.is_partial + and not VARLEN_LSE_PACKED + and isinstance(d.attn_bias, VARLEN_BIASES) + ): + q_seqinfo = d.attn_bias.q_seqinfo + if q_seqinfo.min_seqlen != q_seqinfo.max_seqlen: + # Flash provides padded LSE which we don't handle. + reasons.append("partial attention with heterogeneous queries") + return reasons + + @classmethod + def apply( + cls, inp: Inputs, needs_gradient: bool + ) -> Tuple[torch.Tensor, Optional[Context]]: + return_softmax = False + original_query_shape = inp.query.shape + + out_shape = [ + *inp.query.shape[:-1], + inp.value.shape[-1], + ] + # no cumulative seqlen + ( + inp, + cu_seqlens_q, + max_seqlen_q, + cu_seqlens_k, + max_seqlen_k, + seqused_k, + ) = _convert_input_format(inp, supports_mqa=True) + + if inp.query.numel() > 0 and inp.key.numel() > 0: + win_left, win_right = _window_size(inp.attn_bias) + block_tables = ( + inp.attn_bias.block_tables + if isinstance(inp.attn_bias, PagedBlockDiagonalPaddedKeysMask) + else None + ) + out, softmax_lse, rng_state = cls.OPERATOR( + inp.query, + inp.key, + inp.value, + cu_seqlens_q, + cu_seqlens_k, + seqused_k, + max_seqlen_q, + max_seqlen_k, + inp.p, + inp.scale_float, + _is_causal(inp.attn_bias), + window_left=win_left, + window_right=win_right, + return_softmax=return_softmax, + block_tables=block_tables, + ) + out = out.reshape(out_shape) + else: + out = torch.zeros(out_shape, device=inp.query.device, dtype=inp.query.dtype) + rng_state = None + softmax_lse = torch.empty( + ( + [inp.query.shape[2], inp.query.shape[0] * inp.query.shape[1]] + if VARLEN_LSE_PACKED and isinstance(inp.attn_bias, VARLEN_BIASES) + else [inp.query.shape[0], inp.query.shape[2], inp.query.shape[1]] + ), + device=inp.query.device, + dtype=torch.float32, + ) + if not needs_gradient: + return out, None + ctx = Context( + out=out, + lse=_post_process_lse(softmax_lse, inp, original_query_shape), + ) + if inp.p != 0.0: + ctx.op_bw = BwOp + ctx.rng_state = rng_state + return (out, ctx) + + +@register_operator +class BwOp(AttentionBwOpBase): + __doc__ = FwOp.__doc__ + + OPERATOR = get_operator("xformers_flash", "flash_bwd") + SUPPORTED_DEVICES = FwOp.SUPPORTED_DEVICES + CUDA_MINIMUM_COMPUTE_CAPABILITY = FwOp.CUDA_MINIMUM_COMPUTE_CAPABILITY + SUPPORTED_DTYPES = FwOp.SUPPORTED_DTYPES + SUPPORTED_MAX_K = FwOp.SUPPORTED_MAX_K + SUPPORTED_ATTN_BIAS_TYPES: Iterable[Any] = tuple( + set(FwOp.SUPPORTED_ATTN_BIAS_TYPES).difference( + { + BlockDiagonalCausalLocalAttentionPaddedKeysMask, + BlockDiagonalCausalWithOffsetGappyKeysMask, + BlockDiagonalCausalWithOffsetPaddedKeysMask, + BlockDiagonalGappyKeysMask, + BlockDiagonalPaddedKeysMask, + PagedBlockDiagonalCausalWithOffsetPaddedKeysMask, + PagedBlockDiagonalPaddedKeysMask, + } + ) + ) + SUPPORTS_DROPOUT = FwOp.SUPPORTS_DROPOUT + SUPPORTS_CUSTOM_SCALE = FwOp.SUPPORTS_CUSTOM_SCALE + SUPPORTS_DIFFERENT_VALUE_EMBED = FwOp.SUPPORTS_DIFFERENT_VALUE_EMBED + IS_DETERMINISTIC = False + SUPPORTS_BMGHK = False # NOTE: Don't forget to update fmha doc when changing this! + VARLEN_LSE_PACKED = VARLEN_LSE_PACKED + NAME = f"fa2B@{FLASH_VERSION}-pt" if _USE_PT_FLASH_ATTN else f"fa2B@{FLASH_VERSION}" + VERSION = FLASH_VERSION + + MAX_HEADDIM_DROPOUT_SM8x = 224 + + @classmethod + def not_supported_reasons(cls, d: Inputs) -> List[str]: + reasons = super(BwOp, cls).not_supported_reasons(d) + check_lastdim_alignment_stride1(reasons, "query", d.query, 8) + _check_needs_no_topleft(d, reasons) + if d.device.type == "cuda": + # Due to limited shared-memory, some GPUs are limited in head dimension + device_capability = torch.cuda.get_device_capability(d.device) + is_sm80_or_sm90 = device_capability in [(8, 0), (9, 0)] + if ( + max(d.key.shape[-1], d.query.shape[-1]) > cls.MAX_HEADDIM_DROPOUT_SM8x + and not is_sm80_or_sm90 + and d.p != 0.0 + ): + reasons.append( + "requires a GPU with compute capability 8.0 " + f"(A100) or 9.0 (H100) for dropout when 'query.shape[-1] > {cls.MAX_HEADDIM_DROPOUT_SM8x}'" + ) + return reasons + + @classmethod + def apply(cls, ctx: Context, inp: Inputs, grad: torch.Tensor) -> Gradients: + dq_shape, dk_shape, dv_shape = inp.query.shape, inp.key.shape, inp.value.shape + ( + inp, + cu_seqlens_q, + max_seqlen_q, + cu_seqlens_k, + max_seqlen_k, + seqused_k, + ) = _convert_input_format(inp, supports_mqa=False) + # assert ctx.lse.is_contiguous() + assert seqused_k is None + ctx_lse = ctx.lse + if isinstance(inp.attn_bias, VARLEN_BIASES) and VARLEN_LSE_PACKED: + assert ctx_lse.shape[0] == 1 + ctx_lse = ctx_lse[0] + else: + # NOTE: cutlass pads the last dimension, we need to slice it + assert ctx_lse.shape[2] >= max_seqlen_q + ctx_lse = ctx_lse[:, :, :max_seqlen_q].contiguous() + kernel_out_shape = [ + *inp.query.shape[:-1], + inp.value.shape[-1], + ] + assert grad.dtype in cls.SUPPORTED_DTYPES + + if inp.query.numel() and inp.key.numel(): + win_left, win_right = _window_size(inp.attn_bias) + grads = Gradients( + *cls.OPERATOR( + ctx.qkv_share_storage, + grad.reshape(kernel_out_shape).contiguous(), + inp.query, + inp.key, + inp.value, + ctx.out.reshape(kernel_out_shape), + ctx_lse, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + inp.p, + inp.scale_float, + _is_causal(inp.attn_bias), + window_left=win_left, + window_right=win_right, + rng_state=ctx.rng_state if inp.p > 0.0 else None, + ) + ) + else: + grads = Gradients( + dq=torch.zeros_like(inp.query), + dk=torch.zeros_like(inp.key), + dv=torch.zeros_like(inp.value), + ) + if grads.dq.numel() == 0: + grads.dk.zero_() + grads.dv.zero_() + if grads.dv.numel() == 0: + grads.dq.zero_() + grads.dq = grads.dq.reshape(dq_shape) + grads.dk = grads.dk.reshape(dk_shape) + grads.dv = grads.dv.reshape(dv_shape) + return grads diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/flash3.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/flash3.py new file mode 100644 index 0000000000000000000000000000000000000000..b68d51f3ab83ad9a9874efde6f0e5d8477715825 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/flash3.py @@ -0,0 +1,895 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import importlib.util +import logging +import os +from typing import Any, Iterable, List, Optional, Sequence, Set, Tuple, TypeVar + +import torch +from torch._C import parse_schema +from torch.utils.flop_counter import ( + _unpack_flash_attention_nested_shapes, + register_flop_formula, +) + +from ..common import get_operator, register_operator +from .attn_bias import ( + BlockDiagonalCausalFromBottomRightMask, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + BlockDiagonalCausalLocalAttentionMask, + BlockDiagonalCausalLocalAttentionPaddedKeysMask, + BlockDiagonalCausalMask, + BlockDiagonalCausalWithOffsetGappyKeysMask, + BlockDiagonalCausalWithOffsetPaddedKeysMask, + BlockDiagonalGappyKeysMask, + BlockDiagonalLocalAttentionPaddedKeysMask, + BlockDiagonalMask, + BlockDiagonalPaddedKeysMask, + LocalAttentionFromBottomRightMask, + LowerTriangularFromBottomRightLocalAttentionMask, + LowerTriangularFromBottomRightMask, + LowerTriangularMask, + PagedBlockDiagonalCausalWithOffsetGappyKeysMask, + PagedBlockDiagonalCausalWithOffsetPaddedKeysMask, + PagedBlockDiagonalGappyKeysMask, + PagedBlockDiagonalPaddedKeysMask, + VARLEN_BIASES, +) +from .common import ( + AttentionBwOpBase, + AttentionFwOpBase, + check_lastdim_alignment_stride1, + Context, + Gradients, + Inputs, + ScaledTensor, +) +from .flash import ( + _check_needs_no_topleft, + _convert_input_format, + _is_causal, + _post_process_lse, + _window_size, +) + +FLASH_VERSION = "0.0.0" +logger = logging.getLogger(__name__) + +T = TypeVar("T") + + +def maybe_contiguous(x: T) -> T: + return x.contiguous() if x is not None and x.stride(-1) != 1 else x # type: ignore[attr-defined] + + +def _flash_attention3_incompatible_reason() -> Optional[str]: + if not hasattr(torch.ops.flash_attn_3, "fwd") or not hasattr( + torch.ops.flash_attn_3, "bwd" + ): + return "PyTorch has no `flash_attn_3` - is your Flash-Attention version recent enough?" + if not torch.ops.flash_attn_3.fwd.default._schema.is_backward_compatible_with( + parse_schema( + "flash_attn_3::fwd(Tensor q, Tensor k, Tensor v, Tensor(k_new!)? k_new=None, " + "Tensor(v_new!)? v_new=None, Tensor? q_v=None, Tensor(out!)? out=None, " + "Tensor? cu_seqlens_q=None, Tensor? cu_seqlens_k=None, " + "Tensor? cu_seqlens_k_new=None, Tensor? seqused_q=None, Tensor? seqused_k=None, " + "int? max_seqlen_q=None, int? max_seqlen_k=None, Tensor? page_table=None, " + "Tensor? kv_batch_idx=None, Tensor? leftpad_k=None, Tensor? rotary_cos=None, Tensor? rotary_sin=None, " + "Tensor? seqlens_rotary=None, Tensor? q_descale=None, Tensor? k_descale=None, Tensor? v_descale=None, " + "float? softmax_scale=None, bool is_causal=False, int window_size_left=-1, int window_size_right=-1, " + "int attention_chunk=0, float softcap=0., bool is_rotary_interleaved=False, " + "Tensor? scheduler_metadata=None, int num_splits=0, bool? pack_gqa=None, int sm_margin=0) " + "-> (Tensor(out!), Tensor, Tensor, Tensor)" + ) + ): + return "flash_attn_3::fwd operator is not compatible" + if not torch.ops.flash_attn_3.bwd.default._schema.is_backward_compatible_with( + parse_schema( + "flash_attn_3::bwd(Tensor dout, Tensor q, Tensor k, Tensor v, Tensor out, Tensor softmax_lse, " + "Tensor(dq!)? dq=None, Tensor(dk!)? dk=None, Tensor(dv!)? dv=None, Tensor? cu_seqlens_q=None, " + "Tensor? cu_seqlens_k=None, Tensor? seqused_q=None, Tensor? seqused_k=None, int? max_seqlen_q=None, " + "int? max_seqlen_k=None, float? softmax_scale=None, bool is_causal=False, int window_size_left=-1, " + "int window_size_right=-1, float softcap=0., bool deterministic=False, int sm_margin=0) " + "-> (Tensor(dq!), Tensor(dk!), Tensor(dv!), Tensor, Tensor, Tensor, Tensor, Tensor)" + ) + ): + return "flash_attn_3::bwd operator is not compatible" + return None + + +FLASH3_HAS_PAGED_ATTENTION = True +FLASH3_HAS_FLOAT8 = False +_C_flashattention3 = None +if importlib.util.find_spec("...flash_attn_3._C", package=__package__): + from ..._cpp_lib import _build_metadata + from ...flash_attn_3 import _C # type: ignore[attr-defined] # noqa: F401 + + if _build_metadata is not None: + FLASH_VERSION = _build_metadata.flash_version.lstrip("v") + _C_flashattention3 = torch.ops.flash_attn_3 + +elif importlib.util.find_spec("flash_attn_3") and importlib.util.find_spec( + "flash_attn_3._C" +): + import flash_attn_3._C # type: ignore[attr-defined] # noqa: F401 + + incompat_reason = _flash_attention3_incompatible_reason() + if incompat_reason is None: + _C_flashattention3 = torch.ops.flash_attn_3 + FLASH_VERSION = "pip_pkg" + FLASH3_HAS_PAGED_ATTENTION = True + FLASH3_HAS_FLOAT8 = True + else: + logger.warning(f"Flash-Attention 3 package can't be used: {incompat_reason}") + + +def _heuristic_kvsplit( + inp: Inputs, + enable_kvsplit_attn: bool, +) -> bool: + atten_bias = inp.attn_bias + + # make sure Q doesn't have varlen + # pyre-ignore Undefined attribute [16] + if atten_bias.q_seqinfo.min_seqlen != atten_bias.q_seqinfo.max_seqlen: # type: ignore[union-attr] + return False + + # filter out prefill case + # pyre-ignore Undefined attribute [16] + if atten_bias.q_seqinfo.max_seqlen == atten_bias.k_seqinfo.max_seqlen: # type: ignore[union-attr] + return False + + return enable_kvsplit_attn + + +def mask_non_zeros(s_q: int, s_k: int, window_left: int, window_right: int) -> int: + # Exact formula for easy cases + if window_left < 0 and window_right < 0: # full + return s_q * s_k + if window_left < 0 and window_right == 0: # causal + # (from bottom right) + return (s_q * (s_q + 1)) // 2 + s_q * max(0, s_k - s_q) + + # NOTE: Flops calculations here assume `s_q == s_k` + # otherwise the local attention computations are too involved + # See also https://docs.google.com/spreadsheets/d/1u1ItCZcHLArcqXLj7mwR4H1pI3lMKU1zlxCYi8JCYgk/edit?usp=sharing + if window_left < 0: + window_left = s_k + if window_right < 0: + window_right = s_k + + # below the diagonal + # ┌───────┐ + # │ ╲ │ + # │ ╲ │ <- Upper triangle ("ut") + # │┄┄┄╲ │ <--- `lastq_ut` + # │╲ ╲ │ + # │ ╲ ╲ │ <- Lower part + # │ ╲ ╲│ + # └───────┘ + mask_nz = min(s_q, s_k) # diagonal + # Below diagonal (with `window_left`) + lastq_ut = min(window_left, s_q) + mask_nz += ((lastq_ut - 1) * lastq_ut) // 2 # upper triangle + mask_nz += (s_q - lastq_ut) * window_left # lower part + # Above diagonal (with `window_right`) + # (counting rows from the bottom for symmetry) + firstq_bt = min(window_right + 1, s_q) + mask_nz += ((firstq_bt - 1) * firstq_bt) // 2 # bottom triangle + mask_nz += (s_q - firstq_bt) * window_right + + return mask_nz + + +# Copied from PyTorch, modified to support MQA/GQA and local attention +# No need to take care of this for the bwd because we don't "unexpand" the keys +# and values (in the fwd we expand to help with the seqlen/headdim swap trick). +def sdpa_flop_count( + query_shape, key_shape, value_shape, window_left: int, window_right: int +): + """ + Count flops for self-attention. + + NB: We can assume that value_shape == key_shape + """ + b, h_q, s_q, d_q = query_shape + _b2, h_kv, s_k, _d2 = key_shape + _b3, _h2, _s3, d_v = value_shape + assert b == _b2 == _b3 + assert h_kv == _h2 + assert d_q == _d2 + assert s_k == _s3 + assert d_q == _d2 + assert h_q % h_kv == 0 + # How many values are computed in the attention? + mask_nz = mask_non_zeros(s_q, s_k, window_left, window_right) + + # q@k.T + total_flops = 2 * b * h_q * d_q * mask_nz + # attn@v + total_flops += 2 * b * h_q * d_v * mask_nz + return total_flops + + +if _C_flashattention3 is not None: + # returns: out, q_padded, k_padded, v_padded, out_padded, softmax_lse, p + @torch.library.custom_op( + "xformers_flash3::flash_fwd", mutates_args=(), device_types=["cuda"] + ) + def mha_fwd( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + cu_seqlens_q: Optional[torch.Tensor], + cu_seqlens_k: Optional[torch.Tensor], + seqused_k: Optional[torch.Tensor], + leftpad_k: Optional[torch.Tensor], + max_seqlen_q: int, + max_seqlen_k: int, + p: float, + softmax_scale: float, + is_causal: bool, + descale_q: Optional[torch.Tensor] = None, + descale_k: Optional[torch.Tensor] = None, + descale_v: Optional[torch.Tensor] = None, + block_table: Optional[torch.Tensor] = None, + use_kvsplit: bool = False, + window_left: int = -1, + window_right: int = -1, + ) -> Tuple[torch.Tensor, torch.Tensor]: + query, key = [maybe_contiguous(x) for x in (query, key)] + value = ( + value.contiguous() + if value.stride(-1) != 1 and value.stride(-3) != 1 + else value + ) + cu_seqlens_q, cu_seqlens_k, seqused_k = [ + maybe_contiguous(x) for x in (cu_seqlens_q, cu_seqlens_k, seqused_k) + ] + block_table = maybe_contiguous(block_table) + + def _get_batch(): + if cu_seqlens_q is not None: + return cu_seqlens_q.shape[0] - 1 + return query.shape[0] + + is_paged = block_table is not None + bs = _get_batch() + orig_query_shape = query.shape + + pack_gqa = None + if use_kvsplit: + # For KV split, we need to make sure query in shape [batch, seqlen, num_heads, head_dim_q] + # to be compatible with `pack_gqa` feature + query = query.view(bs, -1, query.shape[-2], query.shape[-1]) + cu_seqlens_q = None + + # Auto-detect if we should use GQA parallel mode + if query.shape[1] <= 64 and query.shape[2] != key.shape[2]: + pack_gqa = True + + assert _C_flashattention3 is not None + out, softmax_lse, *rest = _C_flashattention3.fwd( + query, + key, + value, + None, + None, # k_new, v_new + None, # qv + None, # out + cu_seqlens_q, + cu_seqlens_k if not is_paged else None, + None, # cu_seqlens_k_new + None, # seqused_q + seqused_k, + max_seqlen_q, + max_seqlen_k, + block_table, + None, # kv_batch_idx + leftpad_k, + None, # rotary_cos + None, # rotary_sin + None, # seqlens_rotary + descale_q, + descale_k, + descale_v, + softmax_scale, + is_causal, + window_left, + window_right, + 0, # attention_chunk + 0.0, # softcap + not use_kvsplit, # rotary_interleaved + None, # scheduler_metadata + 1 if not use_kvsplit else 0, # num_splits + pack_gqa, # pack_gqa + 0, # sm_margin + ) + + if query.shape != orig_query_shape: + # Reshape softmax_lse to match expected output format + num_heads_q = query.shape[-2] + orig_lse_shape = softmax_lse.shape + softmax_lse = softmax_lse.view( + orig_lse_shape[0], num_heads_q, -1, orig_lse_shape[2] + ) + softmax_lse = softmax_lse.permute(1, 0, 2, 3).reshape(num_heads_q, -1) + + return out, softmax_lse + + @torch.library.register_fake("xformers_flash3::flash_fwd") + def mha_fwd_fake( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + cu_seqlens_q: Optional[torch.Tensor], + cu_seqlens_k: Optional[torch.Tensor], + seqused_k: Optional[torch.Tensor], + leftpad_k: Optional[torch.Tensor], + max_seqlen_q: int, + max_seqlen_k: int, + p: float, + softmax_scale: float, + is_causal: bool, + descale_q: Optional[torch.Tensor] = None, + descale_k: Optional[torch.Tensor] = None, + descale_v: Optional[torch.Tensor] = None, + block_table: Optional[torch.Tensor] = None, + use_kvsplit: bool = False, + window_left: int = -1, + window_right: int = -1, + ) -> Tuple[torch.Tensor, torch.Tensor]: + query_shape = query.shape + if query.dtype == torch.float8_e4m3fn or query.dtype == torch.float8_e5m2: + out = query.new_empty(query_shape, dtype=torch.bfloat16) + else: + out = query.new_empty(query_shape) + # Query is (B, M, H, K) or (total_M, H, K) + # LSE is (B, H, M) or (H, total_M) + lse_shape = ( + (query_shape[0], query_shape[2], query_shape[1]) + if cu_seqlens_q is None + else (query_shape[1], query_shape[0]) + ) + lse = query.new_empty(lse_shape, dtype=torch.float32) + return out, lse + + @register_flop_formula(torch.ops.xformers_flash3.flash_fwd, get_raw=True) + def mha_fwd_flops( + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + cu_seqlens_q: Optional[torch.Tensor], + cu_seqlens_k: Optional[torch.Tensor], + seqused_k: Optional[torch.Tensor], + leftpad_k: Optional[torch.Tensor], + max_seqlen_q: int, + max_seqlen_k: int, + p: float, + softmax_scale: float, + is_causal: bool, + descale_q: Optional[torch.Tensor] = None, + descale_k: Optional[torch.Tensor] = None, + descale_v: Optional[torch.Tensor] = None, + block_table: Optional[torch.Tensor] = None, + use_kvsplit: bool = False, + window_left: int = -1, + window_right: int = -1, + # The FLOPs counter might pass more args (out_val, out_shape, ...) + *args, + **kwargs, + ): + assert 3 <= query.ndim <= 4 + assert 3 <= key.ndim <= 4 + assert 3 <= value.ndim <= 4 + # This FLOP formula is used by torch.compile's partitioner "automatic + # activation checkpointing" (AutoAC) to decide which ops to preserve + # for backward or to recompute. However, this formula is data-dependent! + # This makes all invocations reuse the choices made based on the first + # inputs, which may be sub-optimal but also lead to inconsistent + # behavior across runs. In the presence of tensor parallelism it might + # also lead to deadlocks if AutoAC recomputes different collectives + # on different ranks. For distributed jobs it seems more robust to have + # all ranks always use the "worst case" FLOP estimate. Ranks are in + # lockstep anyways and will be going as fast as the slowest one. + if os.environ.get("XFORMERS_FLOP_FORMULA_WORST_CASE", "0") == "1": + cu_seqlens_q = cu_seqlens_k = max_seqlen_q = max_seqlen_k = None # type: ignore[assignment] + query = query.unsqueeze(0) if query.ndim == 3 else query + key = key.unsqueeze(0) if key.ndim == 3 else key + value = value.unsqueeze(0) if value.ndim == 3 else value + sizes = _unpack_flash_attention_nested_shapes( + query=query.transpose(-2, -3) if query.ndim == 4 else query, + key=key.transpose(-2, -3) if key.ndim == 4 else key, + value=value.transpose(-2, -3) if value.ndim == 4 else value, + cum_seq_q=cu_seqlens_q, + cum_seq_k=cu_seqlens_k, + max_q=max_seqlen_q, + max_k=max_seqlen_k, + ) + if is_causal: + window_right = 0 + res = sum( + sdpa_flop_count( + query_shape, + key_shape, + value_shape, + window_left=window_left, + window_right=window_right, + ) + for query_shape, key_shape, value_shape, _ in sizes + ) + return res + + def _create_dq_dk_dv( + grads_share_storage: bool, query, key, value + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + # Create dq,dk,dv + # If Q/K/V come from a single QKV tensor, let's put the gradient in the + # right strides, so we can avoid a `cat` + if grads_share_storage: + chunk = torch.empty( + (*query.shape[0:-2], 3, query.shape[-2], query.shape[-1]), + dtype=query.dtype, + device=query.device, + ) + return chunk.select(-3, 0), chunk.select(-3, 1), chunk.select(-3, 2) + return torch.empty_like(query), torch.empty_like(key), torch.empty_like(value) + + @torch.library.custom_op( + "xformers_flash3::flash_bwd", mutates_args=(), device_types=["cuda"] + ) + def mha_bwd( + grads_share_storage: bool, + dout: torch.Tensor, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + out: torch.Tensor, + softmax_lse: torch.Tensor, + cu_seqlens_q: torch.Tensor, + cu_seqlens_k: torch.Tensor, + max_seqlen_q: int, + max_seqlen_k: int, + softmax_scale: float, + is_causal: bool, + window_left: int, + window_right: int, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + dq, dk, dv = _create_dq_dk_dv(grads_share_storage, query, key, value) + is_deterministic = False + if cu_seqlens_q is None: + assert cu_seqlens_k is None + + assert _C_flashattention3 is not None + dq, dk, dv, softmax_d, *rest = _C_flashattention3.bwd( + dout, + query, + key, + value, + out, + softmax_lse, + dq, + dk, + dv, + cu_seqlens_q, + cu_seqlens_k, + None, # seqused_q + None, # seqused_k + max_seqlen_q, + max_seqlen_k, + softmax_scale, + is_causal, + window_left, + window_right, + 0.0, # not used, softcap + is_deterministic, + 0, # not used, sm_margin + ) + return dq, dk, dv + + @torch.library.register_fake("xformers_flash3::flash_bwd") + def mha_bwd_fake( + grads_share_storage: bool, + dout: torch.Tensor, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + out: torch.Tensor, + softmax_lse: torch.Tensor, + cu_seqlens_q: torch.Tensor, + cu_seqlens_k: torch.Tensor, + max_seqlen_q: int, + max_seqlen_k: int, + softmax_scale: float, + is_causal: bool, + window_left: int, + window_right: int, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + dq = torch.empty_like(query) + dk = torch.empty_like(key) + dv = torch.empty_like(value) + return dq, dk, dv + + @register_flop_formula(torch.ops.xformers_flash3.flash_bwd, get_raw=True) + def mha_bwd_flops( + grads_share_storage: bool, + dout: torch.Tensor, + query: torch.Tensor, + key: torch.Tensor, + value: torch.Tensor, + out: torch.Tensor, + softmax_lse: torch.Tensor, + cu_seqlens_q: torch.Tensor, + cu_seqlens_k: torch.Tensor, + max_seqlen_q: int, + max_seqlen_k: int, + softmax_scale: float, + is_causal: bool, + window_left: int, + window_right: int, + # The FLOPs counter might pass more args (out_val, out_shape, ...) + *args, + **kwargs, + ): + return ( + 5 + * mha_fwd_flops( + query, + key, + value, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + seqused_k=None, + leftpad_k=None, + max_seqlen_q=max_seqlen_q, + max_seqlen_k=max_seqlen_k, + p=0.0, + softmax_scale=1.0, + is_causal=is_causal, + descale_q=None, + descale_k=None, + descale_v=None, + block_table=None, + use_kvsplit=False, + window_left=window_left, + window_right=window_right, + ) + // 2 + ) + + +def _check_different_value_headdim_ampere(d: Inputs, reasons: List[str]) -> None: + if ( + d.query.device.type == "cuda" + and (torch.version.hip is None) + and d.query.shape[-1] != d.value.shape[-1] + ): + device_capability = torch.cuda.get_device_capability(d.device) + if device_capability < (9, 0): + reasons.append( + f"Q/K head-dim ({d.query.shape[-1]}) must be equal " + f"to V head-dim ({d.value.shape[-1]}) for Ampere GPUs" + ) + + +def _get_blocktables(inp_attn_bias) -> Optional[torch.Tensor]: + return ( + inp_attn_bias.block_tables + if isinstance( + inp_attn_bias, + (PagedBlockDiagonalGappyKeysMask, PagedBlockDiagonalPaddedKeysMask), + ) + else None + ) + + +@register_operator +class FwOp(AttentionFwOpBase): + """Operator that computes memory-efficient attention using \ + `Flash-Attention `_ \ + implementation. + """ + + OPERATOR = get_operator("xformers_flash3", "flash_fwd") + SUPPORTED_DEVICES: Set[str] = {"cuda"} + CUDA_MINIMUM_COMPUTE_CAPABILITY = (8, 0) + SUPPORTED_DTYPES: Set[torch.dtype] = { + torch.half, + torch.bfloat16, + } | ({torch.float8_e4m3fn} if FLASH3_HAS_FLOAT8 else set()) + SUPPORTED_MAX_K = 256 + SUPPORTED_MIN_K = 32 + SUPPORTED_ATTN_BIAS_TYPES: Iterable[Any] = ( + type(None), + LowerTriangularMask, + LowerTriangularFromBottomRightMask, + LowerTriangularFromBottomRightLocalAttentionMask, + BlockDiagonalMask, + BlockDiagonalCausalMask, + BlockDiagonalCausalLocalAttentionMask, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + BlockDiagonalCausalLocalAttentionPaddedKeysMask, + BlockDiagonalCausalFromBottomRightMask, + BlockDiagonalCausalWithOffsetGappyKeysMask, + BlockDiagonalCausalWithOffsetPaddedKeysMask, + BlockDiagonalLocalAttentionPaddedKeysMask, + BlockDiagonalGappyKeysMask, + BlockDiagonalPaddedKeysMask, + LocalAttentionFromBottomRightMask, + ) + ( + ( + PagedBlockDiagonalCausalWithOffsetGappyKeysMask, + PagedBlockDiagonalCausalWithOffsetPaddedKeysMask, + PagedBlockDiagonalGappyKeysMask, + PagedBlockDiagonalPaddedKeysMask, + ) + if FLASH3_HAS_PAGED_ATTENTION + else tuple() + ) + + SUPPORTS_DROPOUT = False + SUPPORTS_CUSTOM_SCALE = True + SUPPORTS_DIFFERENT_VALUE_EMBED = True # Only hopper + SUPPORTS_BMGHK = True + SUPPORTS_PARTIAL = True + UNPADDED_LSE = True + NAME = f"fa3F@{FLASH_VERSION}" + VERSION = FLASH_VERSION + + @classmethod + def not_supported_reasons(cls, d: Inputs) -> List[str]: + reasons = super(FwOp, cls).not_supported_reasons(d) + check_lastdim_alignment_stride1(reasons, "query", d.query, 8) + check_lastdim_alignment_stride1(reasons, "key", d.value, 8) + check_lastdim_alignment_stride1(reasons, "value", d.value, 8) + _check_needs_no_topleft(d, reasons) + _check_different_value_headdim_ampere(d, reasons) + if ( + _get_blocktables(d.attn_bias) is not None + and d.query.shape[-1] != d.value.shape[-1] + ): + reasons.append( + f"Q/K head-dim ({d.query.shape[-1]}) must be equal " + f"to V head-dim ({d.value.shape[-1]}) for paged attention" + ) + return reasons + + @classmethod + def apply( + cls, + inp: Inputs, + needs_gradient: bool, + use_kvsplit: bool = False, + ) -> Tuple[torch.Tensor, Optional[Context]]: + original_query_shape = inp.query.shape + out_shape = [ + *inp.query.shape[:-1], + inp.value.shape[-1], + ] + + def unpack_func(x) -> Tuple[torch.Tensor, Any]: + return x.unpack() if isinstance(x, ScaledTensor) else (x, None) + + inp.query, descale_q = unpack_func(inp.query) + inp.key, descale_k = unpack_func(inp.key) + inp.value, descale_v = unpack_func(inp.value) + ( + inp, + cu_seqlens_q, + max_seqlen_q, + cu_seqlens_k, + max_seqlen_k, + seqused_k, + ) = _convert_input_format(inp, supports_mqa=True, use_kvsplit=use_kvsplit) + + q = inp.query + k = inp.key + v = inp.value + + if inp.query.numel() > 0 and inp.key.numel() > 0: + win_left, win_right = _window_size(inp.attn_bias) + block_tables = _get_blocktables(inp.attn_bias) + leftpad_k = None + if isinstance(inp.attn_bias, PagedBlockDiagonalGappyKeysMask): + assert cu_seqlens_q is not None + assert cu_seqlens_k is not None + if len(cu_seqlens_q) == len(cu_seqlens_k): + # case #1: len(cu_seqlens_k) = batch_size + 1 + leftpad_k = cu_seqlens_k[:-1] + else: + # case #2: len(cu_seqlens_k) = batch_size + assert ( + len(cu_seqlens_q) - len(cu_seqlens_k) == 1 + ), f"{len(cu_seqlens_q)=} {len(cu_seqlens_k)=}" + leftpad_k = cu_seqlens_k + out, softmax_lse = cls.OPERATOR( + q, + k, + v, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + seqused_k=seqused_k, + leftpad_k=leftpad_k, + max_seqlen_q=max_seqlen_q, + max_seqlen_k=max_seqlen_k, + p=inp.p, + softmax_scale=inp.scale_float, + is_causal=_is_causal(inp.attn_bias), + descale_q=descale_q, + descale_k=descale_k, + descale_v=descale_v, + block_table=block_tables, + use_kvsplit=use_kvsplit, + window_left=win_left, + window_right=win_right, + ) + out = out.reshape(out_shape) + else: + out = torch.zeros( + inp.query.shape, device=inp.query.device, dtype=inp.query.dtype + ) + softmax_lse = torch.empty( + [inp.query.shape[0], inp.query.shape[2], inp.query.shape[1]], + device=inp.query.device, + dtype=torch.float32, + ) + ctx = Context( + out=out, + lse=softmax_lse, + ) + + if not needs_gradient: + return out, None + ctx = Context( + out=out, + lse=_post_process_lse( + softmax_lse, inp, tuple(original_query_shape), varlen_lse_packed=True + ), + ) + return (out, ctx) + + +@register_operator +class BwOp(AttentionBwOpBase): + __doc__ = FwOp.__doc__ + + OPERATOR = get_operator("xformers_flash3", "flash_bwd") + SUPPORTED_DEVICES = FwOp.SUPPORTED_DEVICES + CUDA_MINIMUM_COMPUTE_CAPABILITY = FwOp.CUDA_MINIMUM_COMPUTE_CAPABILITY + SUPPORTED_DTYPES = FwOp.SUPPORTED_DTYPES + SUPPORTED_MAX_K = FwOp.SUPPORTED_MAX_K + SUPPORTED_MIN_K = 64 + SUPPORTED_ATTN_BIAS_TYPES = ( + # Exclude padded or gappy masks, since seqused_k is not supported by the kernel. + type(None), + LowerTriangularMask, + LowerTriangularFromBottomRightMask, + LowerTriangularFromBottomRightLocalAttentionMask, + BlockDiagonalMask, + BlockDiagonalCausalMask, + BlockDiagonalCausalLocalAttentionMask, + BlockDiagonalCausalLocalAttentionFromBottomRightMask, + BlockDiagonalCausalFromBottomRightMask, + LocalAttentionFromBottomRightMask, + ) + + SUPPORTS_DROPOUT = FwOp.SUPPORTS_DROPOUT + SUPPORTS_CUSTOM_SCALE = FwOp.SUPPORTS_CUSTOM_SCALE + SUPPORTS_DIFFERENT_VALUE_EMBED = FwOp.SUPPORTS_DIFFERENT_VALUE_EMBED + IS_DETERMINISTIC = False + SUPPORTS_BMGHK = False + SUPPORTS_LSE_FORMATS: Sequence[str] = ["", "varlen_flat"] + NAME = f"fa3B@{FLASH_VERSION}" + VERSION = FLASH_VERSION + + @classmethod + def not_supported_reasons(cls, d: Inputs) -> List[str]: + reasons = super(BwOp, cls).not_supported_reasons(d) + check_lastdim_alignment_stride1(reasons, "query", d.query, 8) + check_lastdim_alignment_stride1(reasons, "key", d.value, 8) + check_lastdim_alignment_stride1(reasons, "value", d.value, 8) + _check_needs_no_topleft(d, reasons) + _check_different_value_headdim_ampere(d, reasons) + return reasons + + @classmethod + def apply(cls, ctx: Context, inp: Inputs, grad: torch.Tensor) -> Gradients: + dq_shape, dk_shape, dv_shape = inp.query.shape, inp.key.shape, inp.value.shape + ( + inp, + cu_seqlens_q, + max_seqlen_q, + cu_seqlens_k, + max_seqlen_k, + _, # seqused_k, + ) = _convert_input_format(inp, supports_mqa=False) + ctx_lse = ctx.lse + + if isinstance(inp.attn_bias, VARLEN_BIASES): + assert ctx_lse.shape[0] == 1 + ctx_lse = ctx_lse[0] + else: + # NOTE: cutlass pads the last dimension, we need to slice it + assert ctx_lse.shape[2] >= max_seqlen_q + ctx_lse = ctx_lse[:, :, :max_seqlen_q].contiguous() + + kernel_out_shape = [ + *inp.query.shape[:-1], + inp.value.shape[-1], + ] + assert grad.dtype in cls.SUPPORTED_DTYPES + + if inp.query.numel() and inp.key.numel(): + win_left, win_right = _window_size(inp.attn_bias) + dq, dk, dv = cls.OPERATOR( + ctx.qkv_share_storage, + grad.reshape(kernel_out_shape).contiguous(), + inp.query, + inp.key, + inp.value, + ctx.out.reshape(kernel_out_shape), + ctx.lse, + cu_seqlens_q, + cu_seqlens_k, + max_seqlen_q, + max_seqlen_k, + window_left=win_left, + window_right=win_right, + softmax_scale=inp.scale_float, + is_causal=_is_causal(inp.attn_bias), + ) + grads = Gradients(dq, dk, dv) + else: + grads = Gradients( + dq=torch.zeros_like(inp.query), + dk=torch.zeros_like(inp.key), + dv=torch.zeros_like(inp.value), + ) + + grads.dq = grads.dq.reshape(dq_shape) + grads.dk = grads.dk.reshape(dk_shape) + grads.dv = grads.dv.reshape(dv_shape) + return grads + + +@register_operator +class FwOp_KVSplit(FwOp): + """Operator that computes memory-efficient attention using \ + `Flash-Attention3 `_ \ + implementation with heuristic rules to dispatch decoding shapes to KVSplit Attention \ + """ + + NAME = f"fa3F_splitKV@{FLASH_VERSION}" + enable_kvsplit_attn: bool = True + + SUPPORTED_ATTN_BIAS_TYPES: Iterable[Any] = ( + type(None), + BlockDiagonalCausalWithOffsetPaddedKeysMask, + BlockDiagonalPaddedKeysMask, + BlockDiagonalCausalWithOffsetGappyKeysMask, + BlockDiagonalGappyKeysMask, + BlockDiagonalLocalAttentionPaddedKeysMask, + ) + ( + ( + PagedBlockDiagonalCausalWithOffsetGappyKeysMask, + PagedBlockDiagonalCausalWithOffsetPaddedKeysMask, + PagedBlockDiagonalGappyKeysMask, + PagedBlockDiagonalPaddedKeysMask, + ) + if FLASH3_HAS_PAGED_ATTENTION + else tuple() + ) + + @classmethod + def apply( # type: ignore[override] + cls, + inp: Inputs, + needs_gradient: bool, + ) -> Tuple[torch.Tensor, Optional[Context]]: + use_kvsplit = _heuristic_kvsplit(inp, cls.enable_kvsplit_attn) + + return super().apply(inp, needs_gradient, use_kvsplit) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/torch_attention_compat.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/torch_attention_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..84d8b8d25d23a1d6f5ccdb07d416b598255139b0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/torch_attention_compat.py @@ -0,0 +1,152 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Optional + +import torch +from torch._C import parse_schema + + +def is_pt_cutlass_compatible(force: bool = False) -> bool: + if torch.version.hip is not None: + if force: + raise ImportError("CUTLASS is not supported on ROCm") + return False + compatible = True + + fwd_schema_str = ( + "aten::_efficient_attention_forward(Tensor query, Tensor key, Tensor value, " + "Tensor? bias, Tensor? cu_seqlens_q, Tensor? cu_seqlens_k, SymInt? max_seqlen_q, " + "SymInt? max_seqlen_k, float dropout_p, int custom_mask_type, bool compute_log_sumexp=False, *, " + "float? scale=None, Tensor? seqlen_k=None, int? window_size=None) -> " + "(Tensor output, Tensor logsumexp, Tensor philox_seed, Tensor philox_offset, " + "SymInt max_seqlen_batch_q, SymInt max_seqlen_batch_k)" + ) + expected_fwd_schema = parse_schema(fwd_schema_str) + + current_schema = torch.ops.aten._efficient_attention_forward.default._schema + if not current_schema.is_backward_compatible_with(expected_fwd_schema): + compatible = False + + if force: + raise ImportError( + f"Current Torch CUTLASS doesnt have a compatible aten::_efficient_attention_forward schema\n" + f"EXPECTED:\n{expected_fwd_schema}\n" + f"but GOT:\n{current_schema}" + ) + + bwd_schema_str = ( + "aten::_efficient_attention_backward(Tensor grad_out_, Tensor query, Tensor key, Tensor value, " + "Tensor? bias, Tensor out, Tensor? cu_seqlens_q, Tensor? cu_seqlens_k, SymInt max_seqlen_q, " + "SymInt max_seqlen_k, Tensor logsumexp, float dropout_p, Tensor philox_seed, Tensor philox_offset, " + "int custom_mask_type, bool bias_requires_grad, *, float? scale=None, int? num_splits_key=None, " + "int? window_size=None, bool shared_storage_dqdkdv=False) -> (Tensor, Tensor, Tensor, Tensor)" + ) + + expected_bwd_schema = parse_schema(bwd_schema_str) + + current_schema = torch.ops.aten._efficient_attention_backward.default._schema + if not current_schema.is_backward_compatible_with(expected_bwd_schema): + compatible = False + + if force: + raise ImportError( + f"Current Torch CUTLASS doesnt have a compatible aten::_efficient_attention_backward schema\n" + f"EXPECTED:\n{expected_bwd_schema}\n" + f"but GOT:\n{current_schema}" + ) + + return compatible + + +def is_pt_flash_old(force: bool) -> Optional[bool]: + """ + Returns True if the current PyTorch version has the old Flash-Attention + ops instead of the new ones. + If it has none at all, raises an ImportError or returns None. + """ + if not torch.backends.cuda.is_flash_attention_available(): + if force: + raise ImportError("Flash SDP backend is disabled") + return None + + if not hasattr(torch.nn, "attention") or not hasattr( + torch.nn.attention, "_get_flash_version" + ): + if force: + raise ImportError( + f"Current Torch {torch.__version__} doesnt implement " + "torch.nn.attention._get_flash_version()" + ) + return None + + FLASH_VERSION = torch.nn.attention._get_flash_version() + + compatible = True + + # old = before 25/2/2025 + # https://github.com/pytorch/pytorch/commit/3ecfe6be256c585bcadf4c845d7119545444a222 + old_fwd_schema_str = ( + "aten::_flash_attention_forward(Tensor query, Tensor key, Tensor value, " + "Tensor? cum_seq_q, Tensor? cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, " + "bool is_causal, bool return_debug_mask, *, float? scale=None, " + "SymInt? window_size_left=None, SymInt? window_size_right=None, " + "Tensor? seqused_k=None, Tensor? alibi_slopes=None) -> (Tensor output, Tensor softmax_logsumexp, " + "Tensor philox_seed, Tensor philox_offset, Tensor debug_attn_mask)" + ) + fwd_schema_str = ( + "aten::_flash_attention_forward(Tensor query, Tensor key, Tensor value, " + "Tensor? cum_seq_q, Tensor? cum_seq_k, SymInt max_q, SymInt max_k, float dropout_p, " + "bool is_causal, bool return_debug_mask, *, float? scale=None, " + "SymInt? window_size_left=None, SymInt? window_size_right=None, " + "Tensor? seqused_k=None, Tensor? alibi_slopes=None) -> (Tensor output, Tensor softmax_logsumexp, " + "Tensor rng_state, Tensor unused, Tensor debug_attn_mask)" + ) + expected_fwd_schema = parse_schema(fwd_schema_str) + expected_old_fwd_schema = parse_schema(old_fwd_schema_str) + + current_schema = torch.ops.aten._flash_attention_forward.default._schema + old = current_schema.is_backward_compatible_with(expected_old_fwd_schema) + if not old and not current_schema.is_backward_compatible_with(expected_fwd_schema): + compatible = False + + if force: + raise ImportError( + f"Current Torch with Flash-Attention {FLASH_VERSION} doesnt have " + "a compatible aten::_flash_attention_forward schema\n" + f"EXPECTED:\n{expected_old_fwd_schema}\n" + f"or:\n{expected_fwd_schema}\n" + f"but GOT:\n{current_schema}" + ) + + bwd_schema_old_str = ( + "aten::_flash_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, " + "Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, " + "float dropout_p, bool is_causal, Tensor philox_seed, Tensor philox_offset, *, float? scale=None, " + "SymInt? window_size_left=None, SymInt? window_size_right=None) -> (Tensor, Tensor, Tensor)" + ) + bwd_schema_str = ( + "aten::_flash_attention_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, " + "Tensor out, Tensor logsumexp, Tensor cum_seq_q, Tensor cum_seq_k, SymInt max_q, SymInt max_k, " + "float dropout_p, bool is_causal, Tensor rng_state, Tensor unused, *, float? scale=None, " + "SymInt? window_size_left=None, SymInt? window_size_right=None) -> (Tensor, Tensor, Tensor)" + ) + expected_bwd_schema = parse_schema(bwd_schema_old_str if old else bwd_schema_str) + + current_schema = torch.ops.aten._flash_attention_backward.default._schema + if not current_schema.is_backward_compatible_with(expected_bwd_schema): + compatible = False + + if force: + raise ImportError( + f"Current Torch with Flash-Attention {FLASH_VERSION} doesnt have " + "a compatible aten::_flash_attention_backward schema\n" + f"EXPECTED:\n{expected_bwd_schema}\n" + f"but GOT:\n{current_schema}" + ) + + if not compatible: + return None + return old diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/triton_splitk.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/triton_splitk.py new file mode 100644 index 0000000000000000000000000000000000000000..dcf6a60d424ad1d7844ebeebaf1a0c30e2668435 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/fmha/triton_splitk.py @@ -0,0 +1,1221 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import functools +import sys +from dataclasses import dataclass +from typing import ( + Any, + cast, + Dict, + Iterable, + List, + Optional, + Sequence, + Tuple, + Type, + TYPE_CHECKING, + Union, +) + +import torch + +from ... import _is_triton_available +from ..common import register_operator +from .attn_bias import ( + BlockDiagonalCausalLocalAttentionPaddedKeysMask, + BlockDiagonalCausalWithOffsetGappyKeysMask, + BlockDiagonalCausalWithOffsetPaddedKeysMask, + BlockDiagonalGappyKeysMask, + BlockDiagonalLocalAttentionPaddedKeysMask, + BlockDiagonalPaddedKeysMask, + PagedBlockDiagonalCausalWithOffsetGappyKeysMask, + PagedBlockDiagonalCausalWithOffsetPaddedKeysMask, + PagedBlockDiagonalGappyKeysMask, + PagedBlockDiagonalPaddedKeysMask, +) +from .common import AttentionFwOpBase, check_lastdim_alignment_stride1, Context, Inputs + + +def _strides(x: Optional[torch.Tensor], *stride_names: str): + if x is None: + return {f"stride_{name}": None for name in stride_names} + assert x.ndim == len(stride_names) + return {f"stride_{name}": s for name, s in zip(stride_names, x.stride())} + + +def _is_supported_causal_bias(attn_bias: Any) -> bool: + return isinstance( + attn_bias, + ( + BlockDiagonalCausalWithOffsetPaddedKeysMask, + BlockDiagonalCausalWithOffsetGappyKeysMask, + BlockDiagonalCausalLocalAttentionPaddedKeysMask, + PagedBlockDiagonalCausalWithOffsetPaddedKeysMask, + PagedBlockDiagonalCausalWithOffsetGappyKeysMask, + ), + ) + + +def _is_supported_local_bias(attn_bias: Any) -> bool: + return isinstance( + attn_bias, + ( + BlockDiagonalCausalLocalAttentionPaddedKeysMask, + BlockDiagonalLocalAttentionPaddedKeysMask, + ), + ) + + +def _is_supported_gappy_bias(attn_bias: Any) -> bool: + return isinstance( + attn_bias, + ( + BlockDiagonalGappyKeysMask, + PagedBlockDiagonalGappyKeysMask, + ), + ) + + +def _is_supported_paged_bias(attn_bias: Any) -> bool: + return isinstance( + attn_bias, + ( + PagedBlockDiagonalGappyKeysMask, + PagedBlockDiagonalPaddedKeysMask, + ), + ) + + +@dataclass +class InputsFp8(Inputs): + """ + Each of k/v_fp8_scales is an int32 tensor of shape (1, B * Mkv, Hq), + or (1, page_size * max_pages_per_lane, Hq) in the paged case. + Each int32 element contains two packed fp16 number + - scales and shifts for row-wise FP8 quantization. + """ + + k_fp8_scale_shift: Optional[torch.Tensor] = None + v_fp8_scale_shift: Optional[torch.Tensor] = None + + @property + def nbytes(self) -> int: + """ + Number of bytes in the input, not counting the attention bias. + """ + return ( + super(InputsFp8, self).nbytes + + ( + self.k_fp8_scale_shift.untyped_storage().nbytes() + if self.k_fp8_scale_shift is not None + else 0 + ) + + ( + self.v_fp8_scale_shift.untyped_storage().nbytes() + if self.v_fp8_scale_shift is not None + else 0 + ) + ) + + +if TYPE_CHECKING or _is_triton_available(): + from ._triton.splitk_kernels import _fwd_kernel_splitK, _splitK_reduce +else: + _fwd_kernel_splitK = None + _splitK_reduce = None + + +def _is_cuda() -> bool: + return torch.version.cuda is not None + + +def _is_cuda_at_least_sm80(device: torch.device) -> bool: + return _is_cuda() and torch.cuda.get_device_capability(device) >= ( + 8, + 0, + ) + + +@register_operator +class FwOp(AttentionFwOpBase): + """Flash-Attention with Split-K. Supports fused int4 and fp8 K/V quantization. + Quantized path will be taken if input K/V have type int32. + + Int4 quantization can be row-wise or group-wise (when cls.NUM_GROUPS > 1) along + the last dimension of K and V. Currently 1, 2, 4, or 8 groups per row are supported. + Quantization coefficients (scale and shift) are represented as two + float16 constants per group, packed into int32. Quantization coefficients of + all groups are placed at the beginning of the row. So, if unquantized K/V have head + dimension D, the quantized versions have head dimension D // 8 + NUM_GROUPS + and dtype int32. + Pseudocode for dequantizing one row can look like: + group_size = D // 8 + for i in range(NUM_GROUPS): + group_start = NUM_GROUPS + i * group_size + group_quant = K[..., group_start: group_start + group_size] + scale, shift = unpack_int32_into_float16x2(group_quant[0]) + group_dequant = group_quant[..., 1:] * scale + shift + ... + + For fp8 only row-wise quantization is supported. To use it, provide input of type + xformers.ops.fmha.triton_splitk.InputsFp8 (instead of the usual xformers.ops.fmha.Inputs) to + xformers.ops.fmha.triton_splitk.FwOp.apply or xformers.ops.fmha._memory_efficient_attention_forward. + + This op uses Paged Attention when bias is one of the Paged* classes. + In this case bias has additional fields: + - block_tables of shape [batch_size, max_num_pages] + - K/V of shape [1, max_num_pages * page_size, num_heads, head_dim] + or [1, max_num_pages * page_size, num_groups, num_heads, head_dim] + + The shape which the kernel takes the queries and the output + is quite different from the user interface. There are three + types of input (a) no bias / tensor bias, (b) variable q_len + (which is only for non causal) and (c) other bias objects. + From the interface to the kernel the following changes happen. + + (0) In all cases, a group dimension may need to be added. + + (1) For (c), a batch dimension is created, reshaping from (1, B*Mq, G, Hq, K) + to (B, Mq, G, Hq, K) + + (2) For (a) and (c), in the case of multiquery (i.e. the head dimension + of keys and values is expanded), the head-swapping trick + reshaping from (B, Mq, G, Hq, K) to (B, M=Hq*Mq, G, H=1, K) + + (3) For (b), in the case of multiquery, the head-swapping trick + trick, reshaping from (1, Mq, G, Hq, K) to (1, Mq*Hq, G, H=1, K) + Note here that Mq is a single long dimension which spans all the queries + in the batch, unlike in case (C). Also that Hq has to run faster than + Mq in order that the queries in a batch element remain evenly spaced. + + In all cases, the shape as seen by the kernel is called (Bqq, Mqq, G, H, K). + The kernel operates on B batch elements and M queries per batch element. + """ + + OPERATOR = True + SUPPORTED_DEVICES = {"cuda"} + CUDA_MINIMUM_COMPUTE_CAPABILITY = (8, 0) + SUPPORTED_DTYPES = { + torch.half, + torch.bfloat16, + } # Those are dtypes of Q. In the quantized case K/V has dtype int32 + SUPPORTED_MAX_K = 512 + SUPPORTED_ATTN_BIAS_TYPES: Iterable[Any] = ( + type(None), + torch.Tensor, + BlockDiagonalCausalWithOffsetPaddedKeysMask, + BlockDiagonalCausalLocalAttentionPaddedKeysMask, + BlockDiagonalLocalAttentionPaddedKeysMask, + BlockDiagonalGappyKeysMask, + BlockDiagonalCausalWithOffsetGappyKeysMask, + BlockDiagonalPaddedKeysMask, + PagedBlockDiagonalCausalWithOffsetPaddedKeysMask, + PagedBlockDiagonalCausalWithOffsetGappyKeysMask, + PagedBlockDiagonalGappyKeysMask, + PagedBlockDiagonalPaddedKeysMask, + ) + SUPPORTS_DROPOUT = False + SUPPORTS_CUSTOM_SCALE = True + SUPPORTS_BMGHK = True + SUPPORTS_OUTPUT_DTYPE = True + SUPPORTS_PARTIAL = True + NAME = "triton_splitKF" + + SPLIT_K: Optional[int] = None + MAX_BLOCK_M = 32 + + # Whether blocks attending to no part of a variable sequence length + # should exit early. This requires extra kernels to run beforehand + # to initialise the outputs. + # TODO: avoid these by making the reduce kernel work out it doesn't need + # to look at the irrelevant places. + SPLIT_K_EARLY_EXIT: bool = False + + # Perform kernel-level Triton autotune + AUTOTUNE = False + + NUM_GROUPS = 1 # Default quantization is row-wise + NUM_GROUPS_VALUES = [1, 2, 4, 8] + + # Values below are used when autotune=False. + # Note that under certain conditions different values might be used, see the code just before the kernel launch. + BLOCK_M: int = 16 # When M > 1, different BLOCK_M can be used. + BLOCK_N: int = 64 + # On AMD or for M > 1 different NUM_STAGES and NUM_WARPS can be used. + NUM_STAGES: int = 1 + NUM_WARPS: int = 2 + + @classmethod + def shape_not_supported_reasons( + cls, Mq: int, Mkv: int, K: int, Kv: int + ) -> List[str]: + reasons = super().shape_not_supported_reasons(Mq, Mkv, K, Kv) + if K not in {16, 32, 64, 128, 256, 512}: + reasons.append(f"Embed dim {K} not supported") + if Mkv == 0: + # Other ops support this; but here, triton compilation + # crashes on A100 + reasons.append("Query length is 0") + return reasons + + @classmethod + def not_supported_reasons(cls, d: Inputs) -> List[str]: + reasons = super(FwOp, cls).not_supported_reasons(d) + if (sys.version_info.major, sys.version_info.minor) < (3, 9): + reasons.append("triton_splitk requires python 3.9 or above!") + check_lastdim_alignment_stride1(reasons, "query", d.query, 8) + if d.key.dtype != torch.int32: + check_lastdim_alignment_stride1(reasons, "key", d.key, 8) + check_lastdim_alignment_stride1(reasons, "value", d.value, 8) + if cls.OPERATOR is None: + reasons.append("triton is not available") + if d.device.type == "cuda": + # Has only been tested on 8.0 / 9.0. + if _is_cuda() and not _is_cuda_at_least_sm80(d.device): + reasons.append( + "requires NVidia GPU with sm80 minimum compute capacity, e.g., A100/H100/L4" + ) + # TODO: AMD GPU support matrix needs to be figured out. MI300X is tested to work. + + q_len = d.query.shape[1] + is_block_diagonal = isinstance( + d.attn_bias, (BlockDiagonalPaddedKeysMask, BlockDiagonalGappyKeysMask) + ) + is_paged = _is_supported_paged_bias(d.attn_bias) + is_causal = _is_supported_causal_bias(d.attn_bias) + is_local = _is_supported_local_bias(d.attn_bias) + if is_block_diagonal or is_paged: + seqinfo = d.attn_bias.q_seqinfo # type: ignore + if q_len != seqinfo.seqstart_py[-1]: + reasons.append( + f"Expected total {seqinfo.seqstart_py[-1]} queries not {q_len}" + ) + q_len = seqinfo.max_seqlen + if is_causal and q_len != seqinfo.min_seqlen: + reasons.append( + f"Variable query len is not supported for causal masks: got {seqinfo.max_seqlen=} {seqinfo.min_seqlen=}." + ) + elif is_local and q_len != seqinfo.min_seqlen: + reasons.append( + f"Variable query len is not supported for local masks: got {seqinfo.max_seqlen=} {seqinfo.min_seqlen=}." + ) + if q_len > 16 and (is_causal or is_local): + # 16 is the minimum BLOCK_M which gets used + # XXX I don't really understand why this is needed. + reasons.append( + "Query length should not be larger than 16 for causal or local attention biases" + ) + + if is_paged: + page_size = d.attn_bias.page_size # type: ignore + if d.key.shape[1] % page_size: + reasons.append( + "For paged attention, key.shape[1] should be divisible " + "by the page size, " + f"but got {d.key.shape[1]=}, {page_size=}." + ) + if page_size % cls.BLOCK_N: + reasons.append( + "For paged attention, page size should be divisible " + "by the block size, " + f"but got {page_size=}, {cls.BLOCK_N=}." + ) + + if isinstance(d.attn_bias, torch.Tensor): + if d.attn_bias.ndim not in (4, 5): + reasons.append( + "Additive attention bias has to have shape (B, G, H, Mq, Mkv) " + f"or (B, H, Mq, Mkv), but got {d.attn_bias.shape}." + ) + if cls.SPLIT_K is not None and cls.SPLIT_K > 1: + reasons.append( + "Additive attention bias is not supported with split-k > 1." + ) + + return reasons + + @classmethod + def get_split_k(cls, B: int, G: int, H: int, Mk: int, Mq: int) -> int: + """Heuristic for the number of splits""" + bh = max(B * H, 1) # NOTE: Handle B*h=0 case + if torch.version.hip: + split_k = max(Mk + bh - 1, 1024) // bh + max_chunk_size = 64 + split_k_stop_val = max(1024 / (B * G * H), 1) + while split_k > 1 and Mk / (split_k - 1) < max_chunk_size: + split_k = split_k - 1 + + while split_k > split_k_stop_val: + split_k = split_k // 2 + + split_size = (Mk + split_k - 1) // split_k + + chunk_size = split_size // max_chunk_size * max_chunk_size + if chunk_size < split_size: + split_k += 1 + + split_k_upper_bound = 512 + else: + if Mq > 1 and B * G * H > 64: + return 1 + split_k = max(Mk, 1024) // bh + max_chunk_size = 64 if Mk <= 512 and bh <= 64 else 128 + split_k_stop_val = Mk / max_chunk_size + split_k_upper_bound = 64 + + while split_k > split_k_stop_val: + split_k = split_k // 2 + + split_k = min(split_k, split_k_upper_bound) + split_k = max(split_k, 1) + + return split_k + + @classmethod + def get_kernel(cls): + from ._triton.splitk_kernels import ( + _fwd_kernel_splitK_autotune, + _get_splitk_kernel, + ) + + if cls.AUTOTUNE: + return _fwd_kernel_splitK_autotune[cls.NUM_GROUPS] + else: + return _get_splitk_kernel(cls.NUM_GROUPS) + + @classmethod + def get_fp8_scale_shift( + cls, inp: Inputs + ) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor]]: + if not hasattr(inp, "k_fp8_scale_shift"): + return None, None + inp_ = cast(InputsFp8, inp) + k_fp8_scale_shift = inp_.k_fp8_scale_shift + v_fp8_scale_shift = inp_.v_fp8_scale_shift + assert k_fp8_scale_shift is not None + assert v_fp8_scale_shift is not None + if k_fp8_scale_shift.ndim == 3: + return k_fp8_scale_shift.unsqueeze(2), v_fp8_scale_shift.unsqueeze(2) + if k_fp8_scale_shift.ndim == 4: + return k_fp8_scale_shift, v_fp8_scale_shift + raise ValueError( + "FP8 scales have to be provided in BMH or BMGH format, " + f"but got {k_fp8_scale_shift.shape=}" + ) + + @classmethod + def apply( + cls, + inp: Inputs, + needs_gradient: bool, + ) -> Tuple[torch.Tensor, Optional[Context]]: + """ + Note that inp can be of type InputsFp8, in which case K/V are assumed to be row-wise FP8-quantized. + This is different from int4 quantization, where coefficients are kept together with the quantized + values at the beginning of each row, and inp has type Inputs. + """ + + k_fp8_scale_shift, v_fp8_scale_shift = cls.get_fp8_scale_shift(inp) + + output_dtype = inp.get_output_dtype() + if not isinstance(inp.attn_bias, torch.Tensor): + attn_bias_tensor = None + attn_bias = cast( + Optional[ + Union[ + BlockDiagonalCausalWithOffsetPaddedKeysMask, + BlockDiagonalCausalLocalAttentionPaddedKeysMask, + BlockDiagonalLocalAttentionPaddedKeysMask, + BlockDiagonalGappyKeysMask, + BlockDiagonalCausalWithOffsetGappyKeysMask, + BlockDiagonalPaddedKeysMask, + PagedBlockDiagonalCausalWithOffsetPaddedKeysMask, + PagedBlockDiagonalCausalWithOffsetGappyKeysMask, + PagedBlockDiagonalGappyKeysMask, + PagedBlockDiagonalPaddedKeysMask, + ] + ], + inp.attn_bias, + ) + else: + attn_bias_tensor = inp.attn_bias + attn_bias = None + + seq_len = None + seq_starts_k = None + seq_starts_q = None + seq_starts_q_multiplier = None + q, k, v = inp.get_qkv_in_bmghk() + IS_CAUSAL = False + IS_LOCAL = False + NUM_QUERIES_CAUSAL = 1 + variable_q = False + window_left = -1 + window_right = -1 + + is_block_diagonal = isinstance(attn_bias, BlockDiagonalPaddedKeysMask) + is_gappy = _is_supported_gappy_bias(attn_bias) + is_paged = _is_supported_paged_bias(attn_bias) + if attn_bias is not None: + assert is_paged or is_block_diagonal or is_gappy + assert attn_bias.k_seqinfo.seqlen.device == inp.query.device + seq_len = attn_bias.k_seqinfo.seqlen + assert seq_len.stride(0) == 1 + if is_gappy: + seq_starts_k = attn_bias.k_seqinfo.seqstart + assert seq_starts_k.stride(0) == 1 + assert q.shape[0] == 1 + B = len(seq_len) + G, Hq, Kq = q.shape[-3:] + # force a bool because triton cannot take np.bool_ + multiple_q = bool(attn_bias.q_seqinfo.max_seqlen > 1) + IS_CAUSAL = multiple_q and _is_supported_causal_bias(attn_bias) + IS_LOCAL = _is_supported_local_bias(attn_bias) + variable_q = multiple_q and not IS_CAUSAL + Kkv = v.shape[-1] + if isinstance(attn_bias, BlockDiagonalLocalAttentionPaddedKeysMask): + window_left = attn_bias.window_left + window_right = attn_bias.window_right + elif isinstance(attn_bias, BlockDiagonalCausalLocalAttentionPaddedKeysMask): + window_left = attn_bias._window_size - 1 + + if variable_q: + seq_starts_q = attn_bias.q_seqinfo.seqstart + seq_starts_q_multiplier = 1 + assert seq_starts_q.stride(0) == 1 + else: + q = q.view(B, -1, G, Hq, Kq) + + kv_shape = (1 if is_paged or is_gappy else B, -1, G, Hq, Kkv) + k = k.view(kv_shape) + v = v.view(kv_shape) + if k_fp8_scale_shift is not None and v_fp8_scale_shift is not None: + k_fp8_scale_shift = k_fp8_scale_shift.view(kv_shape[:-1]) + v_fp8_scale_shift = v_fp8_scale_shift.view(kv_shape[:-1]) + + Mq = q.shape[1] + NUM_QUERIES_CAUSAL = Mq + else: + B, Mq, G, Hq, Kq = q.shape + + if attn_bias_tensor is not None and attn_bias_tensor.ndim == 4: + # (B, H, Mq, Mkv) -> (B, G, H, Mq, Mkv) + attn_bias_tensor = attn_bias_tensor.unsqueeze(1) + + # In the case of MQA/GQA, we make q have sequence length (H * Mq) and only one "head". + mqa_swap_seqlen_head = False + if ( + k.shape[3] > 1 + and k.stride(3) == 0 + and v.stride(3) == 0 + and attn_bias_tensor is None + ): + mqa_swap_seqlen_head = True + if variable_q: + seq_starts_q_multiplier = Hq + assert q.shape[0] == 1 + # The idea is Hq,Mq are reshaped to (M=Mq*Hq, H=1) + q = q.permute(0, 1, 3, 2, 4).reshape(1, -1, G, 1, Kq) + else: + # This is a copy iff Mq, G and H are all > 1. + # The idea is Hq,Mq are reshaped to (M=Hq*Mq, H=1) + q = q.permute(0, 3, 1, 2, 4).reshape(q.shape[0], -1, G, 1, Kq) + k = k[:, :, :, :1] + v = v[:, :, :, :1] + if k_fp8_scale_shift is not None and v_fp8_scale_shift is not None: + k_fp8_scale_shift = k_fp8_scale_shift[:, :, :, :1] + v_fp8_scale_shift = v_fp8_scale_shift[:, :, :, :1] + + if k.dtype == torch.int32: + if k_fp8_scale_shift is not None: + Lk = k.shape[-1] * 4 + PACKED_PER_VAL = 4 + else: + # Quantized K/V + PACKED_PER_VAL = 8 + Lk = (k.shape[-1] - cls.NUM_GROUPS) * 8 + else: + Lk = k.shape[-1] + PACKED_PER_VAL = 1 + assert cls.NUM_GROUPS == 1, f"{cls.NUM_GROUPS=}" + + _, Mk, G, H, Kkv = k.shape + Bqq, Mqq, G, H, Kq = q.shape + assert Lk == Kq, f"Keys have head dim {Lk} but queries have head dim {Kq}" + if variable_q: + assert attn_bias is not None + assert seq_starts_q_multiplier is not None + M = attn_bias.q_seqinfo.max_seqlen * seq_starts_q_multiplier + else: + M = Mqq + page_size = inp.attn_bias.page_size if is_paged else 0 # type: ignore + block_tables = None + kv_cache_blocks_per_row = 0 + if is_paged: + block_tables = inp.attn_bias.block_tables # type: ignore + kv_cache_blocks_per_row = block_tables.shape[1] + Mk = block_tables.shape[1] * page_size + elif attn_bias is not None: + Mk = min(Mk, attn_bias.k_seqinfo.max_seqlen) + + if cls.SPLIT_K is not None: + split_k = cls.SPLIT_K + else: + # Use heuristics + split_k = ( + cls.get_split_k(B, G, H, Mk, Mq) if attn_bias_tensor is None else 1 + ) + + # M_ceil = Mqq rounded up to a multiple of MAX_BLOCK_M + M_ceil = (Mqq + cls.MAX_BLOCK_M - 1) // cls.MAX_BLOCK_M * cls.MAX_BLOCK_M + IS_SPLITK = split_k > 1 # or cls.autotune? + output_shape = (Bqq, Mq, G, Hq, Kq) + if IS_SPLITK: + o_splitk_dtype = ( + torch.float64 if output_dtype == torch.float64 else torch.float32 + ) + if cls.SPLIT_K_EARLY_EXIT: + o_splitk = torch.zeros( + [Bqq, G, H, split_k, M_ceil, Kq], + dtype=o_splitk_dtype, + device=q.device, + ) + else: + o_splitk = torch.empty( + [Bqq, G, H, split_k, M_ceil, Kq], + dtype=o_splitk_dtype, + device=q.device, + ) + else: + o_splitk = torch.empty( + [Bqq, split_k, Mqq, G, H, Kq], + dtype=output_dtype, + device=q.device, + ).permute(0, 3, 4, 1, 2, 5) + lse, lse_splitk = None, None + # LSE may need higher precision than output + output_f64_lse = output_dtype in (torch.float32, torch.float64) + if IS_SPLITK or needs_gradient: + if cls.SPLIT_K_EARLY_EXIT: + lse_splitk = torch.full( + [Bqq, G, H, split_k, Mqq], + -float("inf"), + dtype=( + torch.float64 if IS_SPLITK or output_f64_lse else torch.float32 + ), + device=q.device, + ) + else: + lse_splitk = torch.empty( + [Bqq, G, H, split_k, Mqq], + dtype=( + torch.float64 if IS_SPLITK or output_f64_lse else torch.float32 + ), + device=q.device, + ) + + def grid(META): + import triton + + return triton.cdiv(M, META["BLOCK_M"]), B * G * H, split_k + + split_size = (Mk + split_k - 1) // split_k + use_seq_len = seq_len is not None + + kernel = cls.get_kernel() + BLOCK_M = cls.BLOCK_M + BLOCK_N = cls.BLOCK_N + if cls.AUTOTUNE: + extra_args = {} + else: + # TODO: remove this when autotuning on AMD is working + num_warps = cls.NUM_WARPS + num_stages = cls.NUM_STAGES + if torch.version.hip: + mkv = k.shape[1] // B if is_paged else k.shape[1] + # TODO: Determine heursistics for paged attention + use_fp8_path = k_fp8_scale_shift is not None + if B == 1: + if use_fp8_path: + # Use specialized configs for FP8 + if mkv <= 256: + BLOCK_N = 16 + num_warps = 8 + num_stages = 1 if is_paged else 2 + elif mkv <= 8192: + BLOCK_N = 32 + num_warps = 8 + num_stages = 1 + elif mkv <= 16384: + BLOCK_N = 64 + num_warps = 8 + num_stages = 1 + elif mkv >= 131072: + BLOCK_N = 128 + num_warps = 2 + num_stages = 1 + else: + # Note: We don't have data for when transitioning num_wraps works well + BLOCK_N = 64 + num_warps = 4 + num_stages = 1 + else: + num_warps = 4 + num_stages = 1 # TODO num_stages = 0 gives better perf on AMD, but sometimes produces NaNs + BLOCK_N = 32 + elif B <= 4 and split_k <= 128: + num_warps = 2 + num_stages = 1 + BLOCK_N = 32 + elif B <= 16: + if use_fp8_path: + if mkv <= 256: + BLOCK_N = 16 + num_warps = 8 + num_stages = 1 if is_paged else 2 + elif mkv <= 2048: + BLOCK_N = 32 + num_warps = 4 + num_stages = 1 + elif mkv < 131072: + # Note: This isn't benchmarked, but fp8 seems to scale well. + BLOCK_N = 64 + num_warps = 1 + num_stages = 1 + else: + BLOCK_N = 128 + num_warps = 1 + num_stages = 1 + else: + if M < 16: + num_warps = 2 + num_stages = 1 + else: + num_warps = 1 + num_stages = 1 + BLOCK_N = 32 + elif B <= 64 and use_fp8_path: + if is_paged: + num_stages = 1 + if mkv <= 256: + BLOCK_N = 64 + num_warps = 8 + elif mkv <= 8192: + BLOCK_N = 64 + num_warps = 1 + elif mkv <= 16384: + BLOCK_N = 128 + num_warps = 2 + else: + # Note: This isn't benchmarked, but fp8 seems to scale well. + BLOCK_N = 128 + num_warps = 1 + else: + if mkv <= 256: + BLOCK_N = 16 + num_warps = 8 + num_stages = 2 + elif mkv <= 2048: + BLOCK_N = 32 + num_warps = 4 + num_stages = 1 + elif mkv < 131072: + # Note: This isn't benchmarked, but fp8 seems to scale well. + BLOCK_N = 64 + num_warps = 1 + num_stages = 1 + else: + BLOCK_N = 128 + num_warps = 1 + num_stages = 1 + elif B <= 128 and use_fp8_path: + num_stages = 1 + if is_paged: + if mkv <= 256: + num_warps = 4 + BLOCK_N = 16 + elif mkv <= 2048: + num_warps = 1 + BLOCK_N = 64 + elif mkv < 131072: + num_warps = 2 + BLOCK_N = 128 + else: + # Note: This isn't benchmarked, but fp8 seems to scale well. + num_warps = 1 + BLOCK_N = 128 + else: + if mkv <= 256: + num_warps = 4 + BLOCK_N = 16 + else: + num_warps = 1 + BLOCK_N = 64 + elif B <= 256 and use_fp8_path: + num_stages = 1 + if is_paged: + if mkv <= 2048: + num_warps = 1 + BLOCK_N = 64 + elif mkv < 131072: + num_warps = 2 + BLOCK_N = 128 + else: + # Note: This isn't benchmarked, but fp8 seems to scale well. + num_warps = 1 + BLOCK_N = 128 + else: + if mkv <= 256: + num_warps = 2 + BLOCK_N = 32 + else: + num_warps = 1 + BLOCK_N = 64 + else: + num_warps = 1 + num_stages = 1 + BLOCK_N = 64 + else: + should_modify_warp_and_block = ( + Kkv == 128 + and Kq == 128 + and torch.cuda.get_device_capability() >= (8, 9) + ) + if should_modify_warp_and_block: + if Mq > 1: + num_warps = 4 + # Choose minimal round block size which covers M. + if M > 16: + BLOCK_M = 32 + if M > 32: + BLOCK_M = 64 + if M > 64: + BLOCK_M = 128 + extra_args = { + "BLOCK_M": BLOCK_M, + "BLOCK_N": BLOCK_N, + "num_warps": num_warps, + "num_stages": num_stages, + } + if _is_triton_available(): + # Triton 3.3.1fb is required for AMD specific changes to + # improve performance. + # TODO: Remove once the triton update lands everywhere. + import triton + + IS_TRITON_UPGRADE = triton.__version__ == "3.3.1fb" + else: + IS_TRITON_UPGRADE = False + IS_HIP = IS_TRITON_UPGRADE and torch.version.hip is not None + kernel[grid]( + Q=q, + K=k, + V=v, + sm_scale=inp.scale_float, + Out_splitK=o_splitk, + LSE_splitk=lse_splitk, + block_tables=block_tables, + Seq_len=seq_len, + Seq_starts_k=seq_starts_k, + Seq_starts_q=seq_starts_q, + Seq_starts_q_multiplier=seq_starts_q_multiplier, + additive_bias=attn_bias_tensor, + K_fp8_scale_shift=k_fp8_scale_shift, + V_fp8_scale_shift=v_fp8_scale_shift, + **_strides(q, "qz", "qm", "qg", "qh", "qk"), + **_strides(k, "kz", "kn", "kg", "kh", "kk"), + **_strides(v, "vz", "vn", "vg", "vh", "vk"), + **_strides(o_splitk, "osk_z", "osk_g", "osk_h", "osk_s", "osk_m", "osk_k"), + **_strides(lse_splitk, "lsek_z", "lsek_g", "lsek_h", "lsek_s", "lsek_m"), + **_strides(block_tables, "blocktablesz", "blocktablesl"), + **_strides( + attn_bias_tensor, "bias_b", "bias_g", "bias_h", "bias_qm", "bias_km" + ), + **_strides( + k_fp8_scale_shift, + "k_fp8_scale_shift_z", + "k_fp8_scale_shift_n", + "k_fp8_scale_shift_g", + "k_fp8_scale_shift_h", + ), + **_strides( + v_fp8_scale_shift, + "v_fp8_scale_shift_z", + "v_fp8_scale_shift_n", + "v_fp8_scale_shift_g", + "v_fp8_scale_shift_h", + ), + kv_cache_blocks_per_row=kv_cache_blocks_per_row, + Z=B, + H=H, + G=G, + N_CTX_Q=M, + N_CTX_K=Mk, + BLOCK_N_PER_SPLIT=split_size, + BLOCK_DMODEL=Lk, + USE_SEQ_LEN=use_seq_len, + PACKED_PER_VAL=PACKED_PER_VAL, + N_GROUPS=cls.NUM_GROUPS, + IS_CAUSAL=IS_CAUSAL, + IS_LOCAL=IS_LOCAL, + NUM_QUERIES_CAUSAL=NUM_QUERIES_CAUSAL, + IS_SPLITK=IS_SPLITK, + SPLIT_K_EARLY_EXIT=cls.SPLIT_K_EARLY_EXIT, + USE_PAGED_ATTENTION=is_paged, + PAGE_SIZE=page_size, + WINDOW_LEFT=window_left, + WINDOW_RIGHT=window_right, + WRITE_LSE=IS_SPLITK or needs_gradient, + HAS_ADDITIVE_BIAS=attn_bias_tensor is not None, + NUM_PROGRAMS_DIM2_CONST=split_k, + IS_HIP=IS_HIP, + **extra_args, + ) + if not IS_SPLITK: + out = o_splitk[:, :, :, 0] # Bqq, G, H, Mqq, Kq + if variable_q and mqa_swap_seqlen_head: + out = out.view(1, G, Mq, Hq, Kq).permute(0, 2, 1, 3, 4).contiguous() + else: + out = out.view(Bqq, G, Hq, Mq, Kq) + # This is a copy iff mqa_swap_seqlen_head and Mq, G and Hq are all > 1. + out = out.permute(0, 3, 1, 2, 4).contiguous() + if needs_gradient: + assert lse_splitk is not None + lse = lse_splitk[:, :, :, 0] # Bqq, G, H, Mqq + if variable_q and mqa_swap_seqlen_head: + lse = lse.view(1, G, Mq, Hq).permute(0, 1, 3, 2) + else: + lse = lse.view(Bqq, G, Hq, Mq) + if attn_bias is not None and not variable_q: + lse = lse.permute(1, 2, 0, 3).reshape(1, G, Hq, B * Mq) + else: + lse = None + + if inp.query.ndim == 4: + # BMGHK -> BMHK + assert G == 1 + if lse is not None: + lse = lse[:, 0] + out = out[:, :, 0] + + if lse is None: + return out, None + return out, Context(out=out, lse=lse) + + out = torch.empty(output_shape, device=q.device, dtype=output_dtype) + + # Merge attention and LSE outputs from different split-k chunks + assert lse_splitk is not None + output_lse = None + if needs_gradient: + lse_dtype = torch.float64 if output_f64_lse else torch.float32 + if attn_bias is None or variable_q: + output_lse = torch.empty( + (Bqq, G, Hq, Mq), device=q.device, dtype=lse_dtype + ) + lse = output_lse + else: + output_lse = torch.empty( + (1, G, Hq, B * Mq), device=q.device, dtype=lse_dtype + ) + lse = output_lse.view(G, Hq, B, Mq).permute(2, 0, 1, 3) + + o_splitk = o_splitk[:, :, :, :, :Mqq] + + if mqa_swap_seqlen_head: + if variable_q: + o_splitk = o_splitk.view(Bqq, G, split_k, Mq, Hq, Kq).permute( + 0, 1, 4, 2, 3, 5 + ) + lse_splitk = lse_splitk.view(Bqq, G, split_k, Mq, Hq).permute( + 0, 1, 4, 2, 3 + ) + else: + o_splitk = o_splitk.view(Bqq, G, split_k, Hq, Mq, Kq).permute( + 0, 1, 3, 2, 4, 5 + ) + lse_splitk = lse_splitk.view(Bqq, G, split_k, Hq, Mq).permute( + 0, 1, 3, 2, 4 + ) + + merge_attentions(out, lse, o_splitk, lse_splitk) + + if inp.query.ndim == 4: + # BMGHK -> BMHK + assert G == 1 + out = out[:, :, 0] + if output_lse is not None: + output_lse = output_lse[:, 0] + if Mk == 0: + out.zero_() + + if attn_bias is not None and not variable_q: + out = out.view(1, B * Mq, G, Hq, Kq) + + if output_lse is None: + return out, None + + return out, Context(out=out, lse=output_lse) + + @classmethod + @functools.lru_cache + def get_operator( + cls, + splitk: int, + *, + block_m: Optional[int] = None, + block_n: Optional[int] = None, + num_warps: Optional[int] = None, + num_stages: Optional[int] = None, + split_k_early_exit: Optional[bool] = None, + ) -> Type[AttentionFwOpBase]: + kwargs = { + "NAME": f"triton_splitK{splitk}", + "SPLIT_K": splitk, + } + if block_m is not None: + kwargs["BLOCK_M"] = block_m + if block_n is not None: + kwargs["BLOCK_N"] = block_n + if num_warps is not None: + kwargs["NUM_WARPS"] = num_warps + if num_stages is not None: + kwargs["NUM_STAGES"] = num_stages + if split_k_early_exit is not None: + kwargs["SPLIT_K_EARLY_EXIT"] = split_k_early_exit + return type( + f"FwOp_S{splitk}", + (cls,), + kwargs, + ) + + +def merge_attentions( + attn_out: torch.Tensor, + lse_out: Optional[torch.Tensor], + attn_split: torch.Tensor, + lse_split: torch.Tensor, +): + import triton + + from ._triton.splitk_kernels import _splitK_reduce + + B, M, G, H, Kq = attn_out.shape + B1, G1, H1, split_k, M1, Kq1 = attn_split.shape + B2, G2, H2, split_k1, M2 = lse_split.shape + + assert ( + B == B1 == B2 + and G == G1 == G2 + and H == H1 == H2 + and M == M1 == M2 + and Kq == Kq1 + ), f"Incompatible shapes: {attn_out.shape=}, {attn_split.shape=}, {lse_split.shape=}" + assert ( + split_k == split_k1 + ), f"Incompatible shapes: {attn_split.shape=}, {lse_split.shape=}" + if lse_out is not None: + B3, G3, H3, M3 = lse_out.shape + assert ( + B == B3 and G == G3 and H == H3 and M == M3 + ), f"Incompatible shapes: {attn_out.shape=}, {lse_out.shape=}" + + num_warps = 4 if B * G * H < 32 or torch.version.hip else 2 + splitK_pow2 = triton.next_power_of_2(split_k) + grid = (M, B * G * H, 1) + _splitK_reduce[grid]( + attn_split, + lse_split, + attn_out, + lse_out, + split_k=split_k, + splitK_pow2=splitK_pow2, + **_strides(attn_split, "osk_z", "osk_g", "osk_h", "osk_s", "osk_m", "osk_k"), + **_strides(lse_split, "lsek_z", "lsek_g", "lsek_h", "lsek_s", "lsek_m"), + **_strides(attn_out, "oz", "om", "og", "oh", "ok"), + **_strides(lse_out, "lse_z", "lse_g", "lse_h", "lse_m"), + BLOCK_SIZE=attn_out.shape[-1], + G=G, + H=H, + WRITE_LSE=lse_out is not None, + num_warps=num_warps, + ) + + +@torch.library.custom_op( + "xformers::fmha_merge_attentions_varargs", + mutates_args=("attn_out", "lse_out"), + device_types=["cuda"], +) +def merge_attentions_varargs( + attn_out: torch.Tensor, + lse_out: Optional[torch.Tensor], + attn_split: Sequence[torch.Tensor], + lse_split: Sequence[torch.Tensor], +) -> None: + from xformers.triton.vararg_kernel import unroll_varargs + + from ._triton.splitk_kernels import _splitK_reduce_varargs + + kernel_args, grid = _prepare_reduce_kernel_params( + attn_out, lse_out, attn_split, lse_split + ) + reduce_kernel = unroll_varargs(_splitK_reduce_varargs, N=len(attn_split)) + reduce_kernel[grid]( + *attn_split, + *lse_split, + Out=attn_out, + LSE=lse_out, + **kernel_args, + BLOCK_SIZE=attn_out.shape[-1], + WRITE_LSE=lse_out is not None, + ) + + +@torch.library.register_fake("xformers::fmha_merge_attentions_varargs") +def merge_attentions_varargs_fake( + attn_out: torch.Tensor, + lse_out: Optional[torch.Tensor], + attn_split: Sequence[torch.Tensor], + lse_split: Sequence[torch.Tensor], +) -> None: + return + + +@torch.library.custom_op( + "xformers::merge_attentions_varargs_backward", + mutates_args=(), + device_types=["cuda"], +) +def merge_attentions_varargs_backward( + attn_split: List[torch.Tensor], + lse_split: List[torch.Tensor], + attn_out: torch.Tensor, + lse_out: torch.Tensor, + grad_attn: torch.Tensor, + grad_lse: torch.Tensor, +) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: + from xformers.triton.vararg_kernel import unroll_varargs + + from ._triton.splitk_kernels import _splitK_reduce_varargs_backward + + dattn_splitk = [torch.empty_like(x) for x in attn_split] + dlse_splitk = [torch.empty_like(x) for x in lse_split] + + kernel_args, grid = _prepare_reduce_kernel_params( + attn_out, lse_out, attn_split, lse_split, grad_attn, grad_lse + ) + + reduce_kernel_backward = unroll_varargs( + _splitK_reduce_varargs_backward, N=len(attn_split) + ) + reduce_kernel_backward[grid]( + *attn_split, + *lse_split, + *dattn_splitk, + *dlse_splitk, + Out=attn_out, + LSE=lse_out, + DOut=grad_attn, + DLSE=grad_lse, + **kernel_args, + BLOCK_SIZE=attn_out.shape[-1], + ) + + return dattn_splitk, dlse_splitk + + +@torch.library.register_fake("xformers::merge_attentions_varargs_backward") +def merge_attentions_varargs_backward_fake( + attn_split: List[torch.Tensor], + lse_split: List[torch.Tensor], + attn_out: torch.Tensor, + lse_out: torch.Tensor, + grad_attn: torch.Tensor, + grad_lse: torch.Tensor, +) -> Tuple[List[torch.Tensor], List[torch.Tensor]]: + dattn_splitk = [torch.empty_like(x) for x in attn_split] + dlse_splitk = [torch.empty_like(x) for x in lse_split] + return dattn_splitk, dlse_splitk + + +def _prepare_reduce_kernel_params( + attn_out: torch.Tensor, + lse_out: Optional[torch.Tensor], + attn_split: Sequence[torch.Tensor], + lse_split: Sequence[torch.Tensor], + grad_attn: Optional[torch.Tensor] = None, + grad_lse: Optional[torch.Tensor] = None, +) -> Tuple[Dict[str, int], Tuple[int, int, int]]: + B, M, G, H, Kq = attn_out.shape + B1, G1, H1, M1, Kq1 = attn_split[0].shape + B2, G2, H2, M2 = lse_split[0].shape + + assert ( + B == B1 == B2 + and G == G1 == G2 + and H == H1 == H2 + and M == M1 == M2 + and Kq == Kq1 + ), f"Incompatible shapes: {attn_out.shape=}, {attn_split[0].shape=}, {lse_split[0].shape=}" + if lse_out is not None: + B3, G3, H3, M3 = lse_out.shape + assert ( + B == B3 and G == G3 and H == H3 and M == M3 + ), f"Incompatible shapes: {attn_out.shape=}, {lse_out.shape=}" + + attn_split_strides = {} + lse_split_strides = {} + for i in range(len(attn_split)): + attn_split_strides.update( + _strides( + attn_split[i], + "osk_z" + str(i), + "osk_g" + str(i), + "osk_h" + str(i), + "osk_m" + str(i), + "osk_k" + str(i), + ) + ) + lse_split_strides.update( + _strides( + lse_split[i], + "lsek_z" + str(i), + "lsek_g" + str(i), + "lsek_h" + str(i), + "lsek_m" + str(i), + ) + ) + + num_warps = 4 if B * G * H < 32 or torch.version.hip else 2 + grid = (M, B * G * H, 1) + + kernel_args = { + "G": G, + "H": H, + "num_warps": num_warps, + **attn_split_strides, + **lse_split_strides, + } + kernel_args.update(_strides(attn_out, "oz", "om", "og", "oh", "ok")) + kernel_args.update(_strides(lse_out, "lse_z", "lse_g", "lse_h", "lse_m")) + if grad_attn is not None: + kernel_args.update(_strides(grad_attn, "doz", "dom", "dog", "doh", "dok")) + kernel_args.update(_strides(grad_lse, "dlse_z", "dlse_g", "dlse_h", "dlse_m")) + return kernel_args, grid + + +FwOp_Map = { + k: FwOp.get_operator(k) for k in [1, 2, 4, 8, 16, 32, 48, 64, 72, 80, 96, 112, 128] +} +FwOp_S1 = FwOp_Map[1] +FwOp_S2 = FwOp_Map[2] +FwOp_S4 = FwOp_Map[4] +FwOp_S8 = FwOp_Map[8] +FwOp_S16 = FwOp_Map[16] +FwOp_S32 = FwOp_Map[32] +FwOp_S64 = FwOp_Map[64] +FwOp_S128 = FwOp_Map[128] diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/indexing.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/indexing.py new file mode 100644 index 0000000000000000000000000000000000000000..4fafda54406130daf957b428b3e5e446fbdeaf3a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/indexing.py @@ -0,0 +1,237 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Optional, Sequence + +import torch + +from xformers.ops._triton import ( + index_select_cat_bwd, + index_select_cat_fwd, + scaled_index_add_bwd, + scaled_index_add_fwd, +) + +from .common import BaseOperator, register_operator + + +# Keeping these operator registry here so that +# it's easy to check if they are available +@register_operator +class ScaledIndexAddFw(BaseOperator): + OPERATOR = scaled_index_add_fwd + OPERATOR_CATEGORY = "indexing" + NAME = "scaled_index_addF" + + +@register_operator +class ScaledIndexAddBw(BaseOperator): + OPERATOR = scaled_index_add_bwd + OPERATOR_CATEGORY = "indexing" + NAME = "scaled_index_addB" + + +@register_operator +class IndexSelect(BaseOperator): + OPERATOR = index_select_cat_fwd + OPERATOR_CATEGORY = "indexing" + NAME = "index_select" + + +class _ScaledIndexAdd(torch.autograd.Function): + @staticmethod + # type: ignore + def forward( + ctx, + x: torch.Tensor, + index: torch.Tensor, + source: torch.Tensor, + scaling: Optional[torch.Tensor], + alpha: float, + ) -> torch.Tensor: + if scaled_index_add_fwd is not None: + scaled_index_add_fwd(x, index, source, scaling, alpha) + else: + raise RuntimeError( + "Triton is needed for forward pass but it is not available!" + ) + + ctx.mark_dirty(x) + ctx.save_for_backward(index, scaling, source) + ctx.source_shape = source.shape + ctx.alpha = alpha + return x + + @staticmethod + @torch.autograd.function.once_differentiable + def backward(ctx, grad_output): + index, scaling, source = ctx.saved_tensors + grad_source = torch.empty_like(source) + grad_scaling = ( + None + if scaling is None + else torch.empty( + ctx.source_shape, dtype=scaling.dtype, device=scaling.device + ) + ) + + if scaled_index_add_bwd is not None: + scaled_index_add_bwd( + grad_output, + grad_source, + grad_scaling, + source, + scaling, + index, + ctx.alpha, + ) + else: + raise RuntimeError( + "Triton is needed for backward pass but it is not available!" + ) + + return ( + grad_output, # gradient of input + None, # gradient of index + grad_source, # gradient of source + grad_scaling, # gradient of scaling + None, # gradient of alpha + ) + + +def scaled_index_add( + input: torch.Tensor, # [B, M, D] + index: torch.Tensor, # [Bi] - int64 + source: torch.Tensor, # [Bi, M, D] + scaling: Optional[torch.Tensor] = None, # [D] + alpha: float = 1.0, +) -> torch.Tensor: + """ + In-place scaling+index_add + + Indices in ``index`` are assumed to be unique + + The max index in ``index`` is assumed to be less than the size of dim0 of ``input``. + + :Note: + + The FW pass is done in-place (``input`` is modified) + + :Equivalent pytorch code: + + .. code-block:: python + + return torch.index_add(input, dim=0, source=scaling * src, index=indices, alpha=alpha) + """ + + return _ScaledIndexAdd.apply(input, index, source, scaling, alpha) + + +class _IndexSelectCat(torch.autograd.Function): + @staticmethod + # type: ignore + def forward( + ctx, + *args: torch.Tensor, + ) -> torch.Tensor: + assert len(args) % 2 == 0 + sources = args[: len(args) // 2] + indices = args[len(args) // 2 :] + + output_numel = 0 + for source, index in zip(sources, indices): + num_rows, num_cols = source.shape + num_indices = index.shape[0] + output_numel += num_indices * num_cols + + output = torch.empty( + [output_numel], dtype=sources[0].dtype, device=sources[0].device + ) + + processed_numel = 0 + for source, index in zip(sources, indices): + num_indices = index.shape[0] + num_cols = source.shape[1] + + if index_select_cat_fwd is not None: + index_select_cat_fwd( + output[ + processed_numel : processed_numel + num_indices * num_cols + ].view([num_indices, num_cols]), + source, + index, + ) + else: + raise RuntimeError( + "Triton is needed for forward pass but it is not available!" + ) + + processed_numel += num_indices * num_cols + + ctx.save_for_backward(*indices) + ctx.source_shapes = [source.shape for source in sources] + + return output + + @staticmethod + @torch.autograd.function.once_differentiable + def backward(ctx, grad_output): + indices = ctx.saved_tensors + + gradients = [] + processed_numel = 0 + for source_shape, index in zip(ctx.source_shapes, indices): + num_rows, num_cols = source_shape + num_indices = index.shape[0] + + grad_output_slice = grad_output[ + processed_numel : processed_numel + num_indices * num_cols + ].reshape([num_indices, num_cols]) + processed_numel += num_indices * num_cols + + grad_source_slice = torch.zeros( + [num_rows, num_cols], + dtype=grad_output.dtype, + device=grad_output.device, + ) + + if index_select_cat_bwd is not None: + index_select_cat_bwd( + grad_source_slice, + index, + grad_output_slice, + ) + else: + raise RuntimeError( + "Triton is needed for backward pass but it is not available!" + ) + gradients.append(grad_source_slice) + + return (*gradients, *([None] * len(gradients))) + + +def index_select_cat( + sources: Sequence[torch.Tensor], indices: Sequence[torch.Tensor] +) -> torch.Tensor: + """ + Indices in ``index`` are assumed to be unique + In each (index, source) pair, the max index in ``index`` is assumed to be less than the size of dim0 of ``source`` + + :Example: + + Given: + - ``sources[0]`` of shape ``[S0, D0]`` + - ``indices[0]`` of shape ``[I0]`` + - ``sources[1]`` of shape ``[S1, D1]`` + - ``indices[1]`` of shape ``[I1]`` + returns a ``torch.Tensor`` of shape ``[I0 * D0 + I1 * D1]`` + + :Equivalent pytorch code: + + .. code-block:: python + + return torch.cat([s[i.long()].flatten() for s, i in zip(sources, indices)], dim=0) + """ + return _IndexSelectCat.apply(*sources, *indices) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/modpar_layers.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/modpar_layers.py new file mode 100644 index 0000000000000000000000000000000000000000..e9caac43e13bafd27f73677787ad8d37adcc5390 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/modpar_layers.py @@ -0,0 +1,160 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Callable, List + +import torch +import torch.distributed + +from .differentiable_collectives import ( + copy_to_model_parallel_region, + reduce_from_model_parallel_region, +) +from .seqpar import sequence_parallel_leading_matmul, sequence_parallel_trailing_matmul + + +def _init_2d_weight( + weight: torch.Tensor, + init_method: Callable[[torch.Tensor], torch.Tensor], + process_group: torch.distributed.ProcessGroup, + partition_dim: int, +) -> None: + # Mimick FairScale's _initialize_affine_weight, for backwards compatibility. + # The reason we initialize the full unpartitioned/gathered weight is so that + # different ranks get different initial values and thus "break the symmetry" + # and in order to achieve the same init for any value of model parallelism. + rank = process_group.rank() + world_size = process_group.size() + + nrows, ncols = weight.shape + if partition_dim == 0: + full_weight = weight.new_empty(nrows * world_size, ncols) + my_weight_slice = full_weight[rank::world_size, :] + else: + full_weight = weight.new_empty(nrows, ncols * world_size) + my_weight_slice = full_weight[:, rank::world_size] + + init_method(full_weight) + + with torch.no_grad(): + weight.copy_(my_weight_slice) + + +class ColumnParallelLinear(torch.nn.Module): + def __init__( + self, + in_features: int, + out_features: List[int], + *, + process_group: torch.distributed.ProcessGroup, + bias: bool = True, + gather_output: bool = True, + init_method: Callable[ + [torch.Tensor], torch.Tensor + ] = torch.nn.init.xavier_normal_, + sequence_parallel: bool = False, + fuse_sequence_parallel: bool = True, + ) -> None: + super(ColumnParallelLinear, self).__init__() + + if not isinstance(out_features, list): + raise TypeError( + "xFormers's implementation of ColumnParallelLinear requires out_features to be a list" + ) + if bias: + raise ValueError( + "xFormers's implementation of ColumnParallelLinear requires bias=False" + ) + if gather_output: + raise ValueError( + "xFormers's implementation of ColumnParallelLinear requires gather_output=False" + ) + + self.in_features = in_features + self.global_out_features = out_features + self.sequence_parallel = sequence_parallel + self.fuse_sequence_parallel = fuse_sequence_parallel + self.process_group = process_group + mp_size = process_group.size() + assert all(dim % mp_size == 0 for dim in out_features) + self.my_out_features = [dim // mp_size for dim in out_features] + + self.weights = torch.nn.ParameterList( + [ + torch.nn.Parameter(torch.empty((dim, in_features))) + for dim in self.my_out_features + ] + ) + + for w in self.weights: + _init_2d_weight(w, init_method, process_group, partition_dim=0) + + def forward(self, input_: torch.Tensor) -> List[torch.Tensor]: + if self.sequence_parallel: + outputs = sequence_parallel_leading_matmul( + input_, + [w.t() for w in self.weights], + fuse=self.fuse_sequence_parallel, + process_group=self.process_group, + ) + else: + input_ = copy_to_model_parallel_region(input_, self.process_group) + outputs = [torch.matmul(input_, w.t()) for w in self.weights] + return outputs + + +class RowParallelLinear(torch.nn.Module): + def __init__( + self, + in_features: int, + out_features: int, + *, + process_group: torch.distributed.ProcessGroup, + bias: bool = True, + input_is_parallel: bool = False, + init_method: Callable[ + [torch.Tensor], torch.Tensor + ] = torch.nn.init.xavier_normal_, + sequence_parallel: bool = False, + fuse_sequence_parallel: bool = True, + ): + super(RowParallelLinear, self).__init__() + + if bias: + raise ValueError( + "xFormers's implementation of RowParallelLinear requires bias=False" + ) + if not input_is_parallel: + raise ValueError( + "xFormers's implementation of RowParallelLinear requires input_is_parallel=True" + ) + + self.global_in_features = in_features + self.out_features = out_features + self.sequence_parallel = sequence_parallel + self.fuse_sequence_parallel = fuse_sequence_parallel + self.process_group = process_group + mp_size = process_group.size() + assert in_features % mp_size == 0 + self.my_in_features = in_features // mp_size + + self.weight = torch.nn.Parameter( + torch.empty((out_features, self.my_in_features)) + ) + + _init_2d_weight(self.weight, init_method, process_group, partition_dim=1) + + def forward(self, input_: torch.Tensor) -> torch.Tensor: + if self.sequence_parallel: + output = sequence_parallel_trailing_matmul( + input_, + self.weight.t(), + fuse=self.fuse_sequence_parallel, + process_group=self.process_group, + ) + else: + output = torch.matmul(input_, self.weight.t()) + output = reduce_from_model_parallel_region(output, self.process_group) + return output diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/rmsnorm.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/rmsnorm.py new file mode 100644 index 0000000000000000000000000000000000000000..94a3743fbdf57e98fb1697bfc4f8a391d6a27651 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/rmsnorm.py @@ -0,0 +1,113 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. +from typing import Optional + +import torch +from torch import nn + +from .. import _is_triton_available + + +def rms_norm(x, weight: Optional[torch.Tensor], eps: float = 1e-6): + """ + RMS Normalization along the last dimension. + + This is similar to torch.nn.functional.normalize but with eps being added + instead of max. + + Expects x contiguous of shape (..., dim), and returns normalized data + of the same shape. For each dim-length vector x, the result has + + x / sqrt( x*x.sum() + eps) + + If weights are included, they are a contiguous parameter of length dim + which multiplies the result. + + This functionality is experimental. Its API might be changed without warnings. + Use it at your own risk. + """ + assert _is_triton_available() + from ._triton.rmsnorm_kernels import _rms_norm_forward + + if torch.is_grad_enabled() and ( + x.requires_grad or (weight is not None and weight.requires_grad) + ): + raise ValueError("Gradients not supported.") + + return _rms_norm_forward(x, weight, eps) + + +def rms_norm_add( + x: torch.Tensor, y: torch.Tensor, weight: Optional[torch.Tensor], eps: float = 1e-6 +): + """ + An addition fused with rms_norm. + + z = rms_norm_add(x, y, weight, eps) + + is equivalent to + + x += y + z = rms_norm(x, weight, eps) + + where x, y and z are all contiguous. + + This functionality is experimental. Its API might be changed without warnings. + Use it at your own risk. + """ + if torch.is_grad_enabled() and ( + x.requires_grad + or y.requires_grad + or (weight is not None and weight.requires_grad) + ): + raise ValueError("Gradients not supported.") + assert _is_triton_available() + from ._triton.rmsnorm_kernels import _rms_norm_add_forward + + return _rms_norm_add_forward(x, y, weight, eps) + + +class RMSNorm(torch.nn.Module): + """ + RMS Normalization layer along the last dimension. + + This is similar to torch.nn.functional.normalize but with eps being added + instead of max. + + Expects contiguous input of shape (..., dim), and returns normalized data + of the same shape. For each dim-length vector x, the result has + + x / sqrt( x*x.sum() + eps) + + If weights are included, they are a parameter of length dim which multiplies + the result. + + This functionality is experimental. Its API might be changed without warnings. + Use it at your own risk. + """ + + def __init__(self, dim: int, include_weight: bool = True, eps: float = 1e-6): + super().__init__() + self.eps = eps + if include_weight: + self.weight: Optional[nn.Parameter] = nn.Parameter(torch.ones(dim)) + else: + self.weight = None + + def forward(self, x: torch.Tensor): + return rms_norm(x, self.weight, self.eps) # type: ignore + + def increment_and_forward_(self, x: torch.Tensor, y: torch.Tensor): + """ + An addition fused with forward. + + z = layer.increment_and_forward_(x, y) + + is equivalent to + + x += y + z = layer(x) + """ + return rms_norm_add(x, y, self.weight, self.eps) # type: ignore diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/rope_padded.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/rope_padded.py new file mode 100644 index 0000000000000000000000000000000000000000..2329a38c4f6ad8c213a364dd036f371e89580962 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/rope_padded.py @@ -0,0 +1,300 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. +from typing import Optional, Tuple + +import torch + +from xformers.ops.fmha.attn_bias import ( # type: ignore + BlockDiagonalCausalWithOffsetPaddedKeysMask, +) + +from .. import _is_triton_available + + +def rope_padded( + xq: torch.Tensor, + xk: torch.Tensor, + xv: torch.Tensor, + cache_k: torch.Tensor, + cache_v: torch.Tensor, + attn_bias: BlockDiagonalCausalWithOffsetPaddedKeysMask, + *, + theta: float = 10000.0, + linear_scale: float = 1.0, + use_dynamic_scaling: bool = False, + dynamic_old_context_len: float = 8192.0, + dynamic_scale_factor: float = 16.0, + dynamic_low_freq_factor: float = 1.0, + dynamic_high_freq_factor: float = 32.0, + out_q: Optional[torch.Tensor] = None, + first_seqpos: Optional[torch.Tensor] = None, + seqpos: Optional[torch.Tensor] = None, + adjacents: bool = True, + internal_dtype: str = "", +): + """ + Performs RoPE (rotary embeddings) and kv-cache emplacement for a heterogeneous + batch for inference in the style given by + BlockDiagonalCausalWithOffsetPaddedKeysMask. + The batch is concatenated along the sequence dimension, so the + actual dim-0 length of all tensors is 1. + + xq, xk and xv should be (1, slen, n_heads, dim), where + xq's n_heads can differ from xk and xv. + + This function places the roped xk in the right place in cache_k, and + xv (unmodified) in the right place in cache_v, and returns out_q + (the roped xq) such that things are ready to call + + xformers.ops.memory_efficient_attention( + out_q, cache_k, cache_v, attn_bias=attn_bias + ) + + This functionality is experimental. Its API might be changed without warnings. + Use it at your own risk. + + Arguments: + xq: tensor of queries to apply rope to + xk: tensor of keys to apply rope to + xv: tensor of values to copy into cache_v + cache_k: cache of keys, MODIFIED IN PLACE + cache_v: cache of values, MODIFIED IN PLACE + attn_bias: details the layout of caches. + Used to determine frequencies for the + RoPE calculation as well as the locations in cache_k and cache_v + to write to. Must be on the device. + first_seqpos: Optionally a tensor containing the sequence position of the + beginning of the cache for each batch element. + Providing a tensor of zeros is the same as providing None. + This affects the numerical calculation but not which memory + locations are read or written. + seqpos: Optionally a 1D tensor containing the sequence position of each + query. This should have length equal to xq.shape[1] . + This affects the numerical calculation but not which memory + locations are read or written. + adjacents: If True, the inputs are in adjacent pairs along the final dim axis. + This is like the released LLaMA model. + If False, the dim axis is split in two equal pieces. + I.e. the features are ordered with all the real parts before all + the imaginary parts. This matches HuggingFace, e.g. + https://github.com/huggingface/transformers/blob/ + f143037789288ba532dada934a118e648e715738/ + src/transformers/models/llama/modeling_llama.py#L126-L130 + linear_scale: A scaling factor to apply to the sequence ids when computing + the RoPE frequencies. When set to K, all sequence indices + are divided by K. + use_dynamic_scaling: If true, dynamic scaling in use, using a scaling like + “YaRN: Efficient Context Window Extension of Large Language Models” + dynamic_old_context_len: used with use_dynamic_scaling + dynamic_scale_factor: used with use_dynamic_scaling + dynamic_low_freq_factor: used with use_dynamic_scaling + dynamic_high_freq_factor: used with use_dynamic_scaling + internal_dtype: set to "f32" or "f64" to enforce dtype in the calculation + """ + if torch.is_grad_enabled() and ( + xq.requires_grad + or xk.requires_grad + or xv.requires_grad + or cache_k.requires_grad + or cache_v.requires_grad + or out_q is not None + ): + raise ValueError("Gradients not supported.") + assert _is_triton_available() + import triton + + from ._triton.rope_padded_kernels import _rope_padded_kernel + + n_total_queries = attn_bias.q_seqinfo.seqstart_py[-1] + cache_length = attn_bias.k_seqinfo.seqstart_py[-1] + ndim = xq.ndim + if ndim not in [4, 5]: + raise ValueError("Unexpected xq dimension") + xq_stride = xq.stride() + xk_stride = xk.stride() + xv_stride = xv.stride() + cache_k_stride = cache_k.stride() + cache_v_stride = cache_v.stride() + cache_k_shape = cache_k.shape + xk_shape = xk.shape + n_kv_heads = xk_shape[-2] + expected_kv_heads = n_kv_heads + if xk_stride[-2] == 0: + n_kv_heads = 1 + expected_cache_heads = n_kv_heads + if n_kv_heads == 1 and cache_k_stride[-2] == 0: + # If there's 1 kv head, don't care how expanded + # cache_k is. User might expand before or after rope. + expected_cache_heads = cache_k_shape[-2] + + if ndim == 4: + bsz, q_len, n_q_heads, dim = xq.shape + assert q_len == n_total_queries + if xk_shape != (1, n_total_queries, expected_kv_heads, dim): + raise ValueError( + f"unexpected k shape {xk_shape}: expected {(1, n_total_queries, expected_kv_heads, dim)}" + ) + if xv.shape != (1, n_total_queries, expected_kv_heads, dim): + raise ValueError( + f"unexpected v shape {xv.shape}: expected {(1, n_total_queries, expected_kv_heads, dim)}" + ) + if cache_k_shape != (1, cache_length, expected_cache_heads, dim): + raise ValueError("unexpected cache_k shape") + if cache_v.shape != (1, cache_length, expected_cache_heads, dim): + raise ValueError("unexpected cache_v shape") + n_groups = 1 + out_q_stride: Tuple[int, ...] = (0, n_q_heads * dim, dim, 1) + + else: + bsz, q_len, n_groups, n_q_heads, dim = xq.shape + assert q_len == n_total_queries + if xk_shape != (1, n_total_queries, n_groups, expected_kv_heads, dim): + raise ValueError( + f"unexpected k shape {xk_shape}: expected {(1, n_total_queries, n_groups, expected_kv_heads, dim)}" + ) + if xv.shape != (1, n_total_queries, n_groups, expected_kv_heads, dim): + raise ValueError( + f"unexpected v shape {xv.shape}: expected {(1, n_total_queries, n_groups, expected_kv_heads, dim)}" + ) + if cache_k_shape != (1, cache_length, n_groups, expected_cache_heads, dim): + raise ValueError( + f"unexpected cache_k shape {cache_k_shape}: " + f"expected {(1, cache_length, n_groups, expected_cache_heads, dim)}" + ) + if cache_v.shape != (1, cache_length, n_groups, expected_cache_heads, dim): + raise ValueError( + f"unexpected cache_v shape {cache_v.shape}: " + f"expected {(1, cache_length, n_groups, expected_cache_heads, dim)}" + ) + out_q_stride = ( + 0, + n_q_heads * dim * n_groups, + n_q_heads * dim, + dim, + 1, + ) + + if bsz != 1: + raise ValueError( + "Expected batch size dimension to be 1 as batches should be concatenated." + ) + if xq_stride[-1] != 1: + raise ValueError("Each q head must be contiguous") + if xk_stride[-1] != 1: + raise ValueError("Each k head must be contiguous") + if xv_stride[-1] != 1: + raise ValueError("Each v head must be contiguous") + if cache_k_stride[-1] != 1: + raise ValueError("Each cache_k head must be contiguous") + if cache_v_stride[-1] != 1: + raise ValueError("Each cache_v head must be contiguous") + n_total_heads = n_q_heads + 2 * n_kv_heads + v_start = n_total_heads - n_kv_heads + k_start = n_q_heads + if out_q is None: + out_q = xq.new_empty(xq.shape) + else: + if out_q.shape != xq.shape: + raise ValueError("Unexpected shape of out_q") + out_q_stride = out_q.stride() + if out_q_stride[-1] != 1: + raise ValueError("Each out_q head must be contiguous") + + assert out_q is not None + + logical_bsz = len(attn_bias.q_seqinfo.seqstart_py) - 1 + + if first_seqpos is not None and seqpos is not None: + raise ValueError("seqpos and first_seqpos may not both be provided") + stride_seqpos = 0 + if first_seqpos is not None: + if first_seqpos.shape != (logical_bsz,): + shape = tuple(first_seqpos.shape) + raise ValueError( + f"first_seqpos.shape {shape} but ({logical_bsz},) expected." + ) + stride_seqpos = first_seqpos.stride(0) + elif seqpos is not None: + if seqpos.shape != (n_total_queries,): + shape = tuple(seqpos.shape) + raise ValueError(f"seqpos.shape {shape} but ({n_total_queries},) expected.") + stride_seqpos = seqpos.stride(0) + + # Less than 64KB per feature: enqueue fused kernel + MAX_FUSED_SIZE = 65536 // xq.element_size() + BLOCK_SIZE = min(MAX_FUSED_SIZE, triton.next_power_of_2(dim)) + BLOCK_SIZE = max(BLOCK_SIZE, 128) + BLOCK_SIZE = min(BLOCK_SIZE, 4096) + # heuristics for number of warps + num_warps = min(max(BLOCK_SIZE // 256, 1), 8) + device = xq.device + seqstartq = attn_bias.q_seqinfo.seqstart + seqstartk = attn_bias.k_seqinfo.seqstart + seqlenk = attn_bias.k_seqinfo.seqlen + if ( + seqstartq.device != device + or seqstartk.device != device + or seqlenk.device != device + ): + raise ValueError("`attn_bias` must be on the same device as the other inputs") + assert internal_dtype in ["", "f32", "f64"] + # experiment with the order of dims here. + with torch.cuda.device(xq.device): + _rope_padded_kernel[ + (attn_bias.q_seqinfo.max_seqlen, logical_bsz, n_total_heads * n_groups) + ]( + xq, + xk, + xv, + out_q, + cache_k, + cache_v, + seqstartq, + seqstartk, + seqlenk, + theta, + linear_scale, + use_dynamic_scaling, + dynamic_old_context_len if use_dynamic_scaling else 0, + dynamic_scale_factor if use_dynamic_scaling else 0, + dynamic_low_freq_factor if use_dynamic_scaling else 0, + dynamic_high_freq_factor if use_dynamic_scaling else 0, + first_seqpos, + seqpos, + k_start, + v_start, + n_groups, + dim, + xq_stride[1], + xq_stride[2] if ndim == 5 else 0, + xq_stride[-2], + xk_stride[1], + xk_stride[2] if ndim == 5 else 0, + xk_stride[-2], + xv_stride[1], + xv_stride[2] if ndim == 5 else 0, + xv_stride[-2], + cache_k_stride[1], + cache_k_stride[2] if ndim == 5 else 0, + cache_k_stride[-2], + cache_v_stride[1], + cache_v_stride[2] if ndim == 5 else 0, + cache_v_stride[-2], + seqstartq.stride(0), + seqstartk.stride(0), + seqlenk.stride(0), + out_q_stride[1], + out_q_stride[2] if ndim == 5 else 0, + out_q_stride[-2], + stride_seqpos, + internal_dtype, + const_batch_strides=False, + cache_padding_length=0, + seqlenk_shift=0, + BLOCK_SIZE=BLOCK_SIZE, + adjacents=adjacents, + num_warps=num_warps, + ) + return out_q diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/seqpar.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/seqpar.py new file mode 100644 index 0000000000000000000000000000000000000000..b81eaf33042ae45754e67873d679ebf9d8aa6389 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/seqpar.py @@ -0,0 +1,365 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +from typing import Callable, List, Tuple + +import torch +from torch.distributed.distributed_c10d import _resolve_process_group + +from .differentiable_collectives import ( + gather_along_first_dim, + gather_along_first_dim_async, + reduce_scatter_along_first_dim, + reduce_scatter_along_first_dim_async, +) +from .sequence_parallel_fused_ops import ( + fused_allgather_and_anything, + fused_allgather_and_linear, + fused_anything_and_reducescatter, + fused_linear_and_reducescatter, +) +from .tiled_matmul import tiled_matmul, tiled_matmul_out + + +@torch.library.custom_op( + "xformers_python::sequence_parallel_leading_matmul_fwd", + mutates_args=(), + device_types="cuda", +) +def sequence_parallel_leading_matmul_fwd( + scattered_input: torch.Tensor, + weights: List[torch.Tensor], + fuse: bool, + process_group_name: str, +) -> List[torch.Tensor]: + process_group = _resolve_process_group(process_group_name) + + if fuse: + gathered_outputs = fused_allgather_and_linear( + scattered_input, [w.t() for w in weights], group=process_group + ) + else: + gathered_input = gather_along_first_dim( + scattered_input, process_group=process_group + ) + (gathered_outputs,) = tiled_matmul( + [[gathered_input]], + [[w for w in weights]], + ) + return gathered_outputs + + +@torch.library.register_fake("xformers_python::sequence_parallel_leading_matmul_fwd") +def sequence_parallel_leading_matmul_fwd_fake( + scattered_input: torch.Tensor, + weights: List[torch.Tensor], + fuse: bool, + process_group_name: str, +) -> List[torch.Tensor]: + mp_size = _resolve_process_group(process_group_name).size() + return [ + scattered_input.new_empty((scattered_input.shape[0] * mp_size, w.shape[1])) + for w in weights + ] + + +@torch.library.custom_op( + "xformers_python::sequence_parallel_leading_matmul_bwd", + mutates_args=(), + device_types="cuda", +) +def sequence_parallel_leading_matmul_bwd( + scattered_input: torch.Tensor, + weights: List[torch.Tensor], + grad_gathered_outputs: List[torch.Tensor], + fuse: bool, + process_group_name: str, +) -> Tuple[torch.Tensor, List[torch.Tensor]]: + process_group = _resolve_process_group(process_group_name) + mp_size = process_group.size() + + # torch.library.opcheck gives us gradients whose strides are zero. + # See https://github.com/pytorch/pytorch/issues/132857. + grad_gathered_outputs = [ + grad_go.clone() if any(s == 0 for s in grad_go.stride()) else grad_go + for grad_go in grad_gathered_outputs + ] + + if fuse: + grad_scattered_input = torch.empty_like(scattered_input) + grad_weights = [torch.zeros_like(w) for w in weights] + + grad_gathered_outputss = [ + grad_go.tensor_split(mp_size, dim=0) for grad_go in grad_gathered_outputs + ] + + def my_si_matmul( + grad_gathered_inputs: List[torch.Tensor], + dst_rank: int, + stream_factory: Callable[[], torch.cuda.Stream], + ) -> None: + (grad_gi,) = grad_gathered_inputs + with torch.cuda.stream(stream_factory()): + tiled_matmul_out( + [[grad_gos[dst_rank] for grad_gos in grad_gathered_outputss]], + [[w.t()] for w in weights], + out=[[grad_gi]], + ) + + fused_anything_and_reducescatter( + my_si_matmul, + [grad_scattered_input], + group=process_group, + ) + + # Each pair of shards of input and grad_output accumulates into the same + # grad_weight. Thus we need to make sure that the in-place addmms are + # sequenced correctly for each of the grad_weights. + events = [torch.cuda.Event() for _ in weights] + + def my_w_matmul( + gathered_inputs_shard: List[torch.Tensor], + src_rank: int, + stream_factory: Callable[[], torch.cuda.Stream], + ) -> None: + (gi_shard,) = gathered_inputs_shard + for grad_gos, grad_w, event in zip( + grad_gathered_outputss, grad_weights, events + ): + with torch.cuda.stream(stream_factory()): + event.wait() + grad_w.t().addmm_(grad_gos[src_rank].t(), gi_shard) + event.record() + + fused_allgather_and_anything( + [scattered_input], + my_w_matmul, + group=process_group, + ) + else: + gathered_input, handle = gather_along_first_dim_async( + scattered_input, process_group=process_group + ) + ((grad_gathered_input,),) = tiled_matmul( + [[grad_go for grad_go in grad_gathered_outputs]], + [[w.t()] for w in weights], + ) + if handle is not None: + handle.wait() + + grad_scattered_input, handle = reduce_scatter_along_first_dim_async( + grad_gathered_input, process_group=process_group + ) + + grad_weights_tuples = tiled_matmul( + [[grad_go.t()] for grad_go in grad_gathered_outputs], + [[gathered_input]], + ) + if handle is not None: + handle.wait() + + grad_weights = [grad_w.t() for (grad_w,) in grad_weights_tuples] + + return grad_scattered_input, grad_weights + + +@torch.library.register_fake("xformers_python::sequence_parallel_leading_matmul_bwd") +def sequence_parallel_leading_matmul_bwd_fake( + scattered_input: torch.Tensor, + weights: List[torch.Tensor], + grad_gathered_outputs: List[torch.Tensor], + fuse: bool, + process_group_name: str, +) -> Tuple[torch.Tensor, List[torch.Tensor]]: + return (torch.empty_like(scattered_input), [torch.empty_like(w) for w in weights]) + + +def sequence_parallel_leading_matmul_setup_context(ctx, inputs, output): + scattered_input, weights, fuse, process_group_name = inputs + ctx.save_for_backward(scattered_input, *weights) + ctx.fuse = fuse + ctx.process_group_name = process_group_name + + +def sequence_parallel_leading_matmul_bwd_bridge(ctx, grad_gathered_outputs): + scattered_input, *weights = ctx.saved_tensors + ( + grad_scattered_input, + grad_weights, + ) = sequence_parallel_leading_matmul_bwd( + scattered_input, + list(weights), + list(grad_gathered_outputs), + ctx.fuse, + ctx.process_group_name, + ) + return grad_scattered_input, grad_weights, None, None + + +torch.library.register_autograd( + "xformers_python::sequence_parallel_leading_matmul_fwd", + sequence_parallel_leading_matmul_bwd_bridge, + setup_context=sequence_parallel_leading_matmul_setup_context, +) + + +def sequence_parallel_leading_matmul( + x: torch.Tensor, + ws: List[torch.Tensor], + *, + fuse: bool, + process_group: torch.distributed.ProcessGroup, +) -> List[torch.Tensor]: + os = sequence_parallel_leading_matmul_fwd( + x.flatten(0, -2), ws, fuse, process_group.group_name + ) + return [o.view(-1, *x.shape[1:-1], w.shape[1]) for o, w in zip(os, ws)] + + +@torch.library.custom_op( + "xformers_python::sequence_parallel_trailing_matmul_fwd", + mutates_args=(), + device_types="cuda", +) +def sequence_parallel_trailing_matmul_fwd( + gathered_input: torch.Tensor, + weight: torch.Tensor, + fuse: bool, + process_group_name: str, +) -> torch.Tensor: + process_group = _resolve_process_group(process_group_name) + + if fuse: + scattered_output = fused_linear_and_reducescatter( + gathered_input, weight.t(), group=process_group + ) + else: + gathered_output = torch.matmul(gathered_input, weight) + scattered_output = reduce_scatter_along_first_dim( + gathered_output, process_group=process_group + ) + return scattered_output + + +@torch.library.register_fake("xformers_python::sequence_parallel_trailing_matmul_fwd") +def sequence_parallel_trailing_matmul_fwd_fake( + gathered_input: torch.Tensor, + weight: torch.Tensor, + fuse: bool, + process_group_name: str, +) -> torch.Tensor: + mp_size = _resolve_process_group(process_group_name).size() + return gathered_input.new_empty( + (gathered_input.shape[0] // mp_size, weight.shape[1]) + ) + + +@torch.library.custom_op( + "xformers_python::sequence_parallel_trailing_matmul_bwd", + mutates_args=(), + device_types="cuda", +) +def sequence_parallel_trailing_matmul_bwd( + gathered_input: torch.Tensor, + weight: torch.Tensor, + grad_scattered_output: torch.Tensor, + fuse: bool, + process_group_name: str, +) -> Tuple[torch.Tensor, torch.Tensor]: + process_group = _resolve_process_group(process_group_name) + mp_size = process_group.size() + + # torch.library.opcheck gives us gradients whose strides are zero. + # See https://github.com/pytorch/pytorch/issues/132857. + if any(s == 0 for s in grad_scattered_output.stride()): + grad_scattered_output = grad_scattered_output.clone() + + if fuse: + grad_gathered_input = torch.empty_like(gathered_input) + grad_weight = torch.zeros_like(weight) + + gathered_inputs = gathered_input.tensor_split(mp_size, dim=0) + grad_gathered_inputs = grad_gathered_input.tensor_split(mp_size, dim=0) + + def my_gi_and_w_matmul( + grad_gathered_outputs_shard: List[torch.Tensor], + src_rank: int, + stream_factory: Callable[[], torch.cuda.Stream], + ) -> None: + (grad_go_shard,) = grad_gathered_outputs_shard + with torch.cuda.stream(stream_factory()): + torch.matmul( + grad_go_shard, weight.t(), out=grad_gathered_inputs[src_rank] + ) + with torch.cuda.stream(stream_factory()): + grad_weight.t().addmm_(grad_go_shard.t(), gathered_inputs[src_rank]) + + fused_allgather_and_anything( + [grad_scattered_output], + my_gi_and_w_matmul, + group=process_group, + ) + else: + grad_gathered_output = gather_along_first_dim( + grad_scattered_output, process_group=process_group + ) + grad_gathered_input = torch.matmul(grad_gathered_output, weight.t()) + grad_weight = torch.matmul(grad_gathered_output.t(), gathered_input).t() + + return grad_gathered_input, grad_weight + + +@torch.library.register_fake("xformers_python::sequence_parallel_trailing_matmul_bwd") +def sequence_parallel_trailing_matmul_bwd_fake( + gathered_input: torch.Tensor, + weight: torch.Tensor, + grad_scattered_output: torch.Tensor, + fuse: bool, + process_group_name: str, +) -> Tuple[torch.Tensor, torch.Tensor]: + return (torch.empty_like(gathered_input), torch.empty_like(weight)) + + +def sequence_parallel_trailing_matmul_setup_context(ctx, inputs, output): + gathered_input, weight, fuse, process_group_name = inputs + ctx.save_for_backward(gathered_input, weight) + ctx.fuse = fuse + ctx.process_group_name = process_group_name + + +def sequence_parallel_trailing_matmul_bwd_bridge(ctx, grad_scattered_output): + gathered_input, weight = ctx.saved_tensors + ( + grad_gathered_input, + grad_weight, + ) = sequence_parallel_trailing_matmul_bwd( + gathered_input, + weight, + grad_scattered_output, + ctx.fuse, + ctx.process_group_name, + ) + return grad_gathered_input, grad_weight, None, None + + +torch.library.register_autograd( + "xformers_python::sequence_parallel_trailing_matmul_fwd", + sequence_parallel_trailing_matmul_bwd_bridge, + setup_context=sequence_parallel_trailing_matmul_setup_context, +) + + +def sequence_parallel_trailing_matmul( + x: torch.Tensor, + w: torch.Tensor, + *, + fuse: bool, + process_group: torch.distributed.ProcessGroup, +) -> torch.Tensor: + o = sequence_parallel_trailing_matmul_fwd( + x.flatten(0, -2), w, fuse, process_group.group_name + ) + return o.view(-1, *x.shape[1:-1], w.shape[1]) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/sequence_parallel_fused_ops.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/sequence_parallel_fused_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..1f766673820fe19aee3c8544de1cf87bc81ab65c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/sequence_parallel_fused_ops.py @@ -0,0 +1,847 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import os +from typing import Callable, Dict, List, Optional, overload, Sequence, Union + +import torch +import torch.distributed as dist +import torch.multiprocessing.reductions +from torch.distributed._symmetric_memory import get_symm_mem_workspace + +OP_FINISHED_CHANNEL = 0 +COMMS_READY_CHANNEL = 1 + +MS_IN_S = 1_000 + + +def _is_fp8_dtype(dt: torch.dtype): + # Detect if it's float8_e4m3fn or float8_e5m2 without mentioning them in + # order to support old versions of PyTorch that don't define them. + return dt.is_floating_point and torch.finfo(dt).bits == 8 + + +class _FusedSequenceParallel: + """Set up a communication ring and perform fused ops on it + + Stores the persistent state needed to support a ring of connections between + processes, and the logic that can do fused comms + matmuls on it. + + We want to achieve overlap between: + - a computation which reads from the data we received from a remote GPU + - and the communication where we send some data to another GPU + And in order to do that we need some staging buffers and a way to + synchronize access to them across processes. + + To perform the communication over NVLink we make the processes exchange + their staging buffers using IPC (Inter-Process Communication) handles, which + "mounts"/"mmaps" an allocation on one GPU into the virtual address space of + another GPU: the memory remains backed by the original GPU but the other GPU + can access it as if it were local. We exchange these IPC handles using + multiprocessing Connections (and the "reductions" provided by PyTorch), + which we establish over UNIX domain sockets, whose addresses we exchange by + using a ProcessGroup. + + To synchronize accesses we use a set of counters/sequence numbers that are + also allocated in memory shared over IPC handles. Processes signal that they + completed an operation by launching a kernel that increases that value, and + they wait for anoher process to complete an operation by launching a kernel + that busy-waits for that value to increase. Currently we implement these + kernels manually, but on recent CUDA drivers (515.43.04+, corresponding to + CUDA 11.7) we could use standard stream memory operations (see + https://docs.nvidia.com/cuda/archive/11.7.0/cuda-driver-api/group__CUDA__MEMOP.html). + + We prefer to use these kernels (or the stream memory ops) over IPC events + because IPC events require signaling between processes at launch time to + ensure that the wait on one process occurs after the record on another + process. This signaling means that _launching_ our fused operation becomes a + synchronization barrier, which can increase the launch overhead. It would + also behave differently from NCCL, where launching is async and all the + synchronization happens on device in the kernels. A previous version of this + code which uses IPC events can be found here: + https://github.com/fairinternal/xformers/pull/504. + + """ + + def __init__( + self, + device: torch.device, + group: dist.ProcessGroup, + ): + self.my_device = device + self.my_rank = group.rank() + self.world_size = group.size() + self.group = group + + self.second_stream = torch.cuda.Stream() + # CUDA can schedule the matmul and the memcpy at the same time, but it + # tends to run the matmul first and delay the memcpy, which causes a + # domino effect. We thus "encourage" it to prioritize the memcpy. + self.memcpy_stream = torch.cuda.Stream(priority=-1) + # Use dedicated streams to run the wait kernels in the background. + self.compute_wait_stream = torch.cuda.Stream(priority=-1) + self.memcpy_wait_stream = torch.cuda.Stream(priority=-1) + + self.next_stream_idx = 0 + + def make_stream_factory( + self, current_stream: torch.cuda.Stream + ) -> Callable[[], torch.cuda.Stream]: + def result(): + stream = [current_stream, self.second_stream][self.next_stream_idx] + self.next_stream_idx += 1 + self.next_stream_idx %= 2 + return stream + + return result + + def allgather_and_linear( + self, + scattered_inputs: List[torch.Tensor], + my_matmul: Callable[ + [List[torch.Tensor], int, Callable[[], torch.cuda.Stream]], None + ], + timeout_s: int, + _wait: bool = True, + _memcpy: bool = True, + ): + """Perform a fused all-gather followed by a linear layer""" + + dtype = scattered_inputs[0].dtype + assert all(si.device == self.my_device for si in scattered_inputs) + assert all(si.dtype == dtype for si in scattered_inputs) + + scattered_input_numels = [si.numel() for si in scattered_inputs] + total_scattered_input_numel = sum(scattered_input_numels) + + with torch.cuda.device(self.my_device): + symm_mem = get_symm_mem_workspace( + self.group.group_name, + self.world_size * total_scattered_input_numel * dtype.itemsize, + ) + # FIXME Do something about random_init if _memcpy is True. + buffers = [ + [ + s.view((self.world_size,) + si.shape) + for s, si in zip( + symm_mem.get_buffer( + rank, [self.world_size, total_scattered_input_numel], dtype + ).split(scattered_input_numels, dim=-1), + scattered_inputs, + ) + ] + for rank in range(self.world_size) + ] + + current_stream = torch.cuda.current_stream() + + # Signal to buddy that we have read from the data (in previous iter) so + # it can overwrite it (this write matches up with wait [B] below). + for iter_ in range(1, self.world_size): + src_rank = (self.my_rank - iter_) % self.world_size + if _wait: + with torch.cuda.stream(current_stream): + symm_mem.put_signal(src_rank, OP_FINISHED_CHANNEL) + + self.second_stream.wait_stream(current_stream) + self.compute_wait_stream.wait_stream(current_stream) + self.memcpy_wait_stream.wait_stream(current_stream) + stream_factory = self.make_stream_factory(current_stream) + + for iter_ in range(1, self.world_size): + dst_rank = (self.my_rank + iter_) % self.world_size + + # Wait for buddy to signal that it read from the data before we + # overwrite it (this wait matches up with write [B] above). + if _wait: + with torch.cuda.stream(self.memcpy_wait_stream): + symm_mem.wait_signal( + dst_rank, + OP_FINISHED_CHANNEL, + timeout_ms=timeout_s * MS_IN_S, # type: ignore[call-arg] + ) + + self.memcpy_stream.wait_stream(self.memcpy_wait_stream) + + if _memcpy: + with torch.cuda.stream(self.memcpy_stream): + for bs, si in zip(buffers[dst_rank], scattered_inputs): + bs[self.my_rank].copy_(si) + + # Signal to buddy that we have written into the data so it can + # read from it (this write matches up with wait [A] below). + if _wait: + with torch.cuda.stream(self.memcpy_stream): + symm_mem.memset32( + symm_mem.get_signal_pad(dst_rank), # type: ignore[attr-defined] + self.world_size * COMMS_READY_CHANNEL + self.my_rank, + val=1, + count=1, + ) + + my_matmul(scattered_inputs, self.my_rank, stream_factory) + + for iter_ in range(1, self.world_size): + src_rank = (self.my_rank - iter_) % self.world_size + + # Wait for buddy to signal that it wrote into the data before we + # read from it (this wait matches up with write [A] above). + if _wait: + with torch.cuda.stream(self.compute_wait_stream): + symm_mem.wait_signal( + src_rank, + COMMS_READY_CHANNEL, + timeout_ms=timeout_s * MS_IN_S, # type: ignore[call-arg] + ) + + current_stream.wait_stream(self.compute_wait_stream) + self.second_stream.wait_stream(self.compute_wait_stream) + + my_matmul( + [s[src_rank] for s in buffers[self.my_rank]], src_rank, stream_factory + ) + + current_stream.wait_stream(self.second_stream) + current_stream.wait_stream(self.memcpy_stream) + + def linear_and_reducescatter( + self, + my_matmul: Callable[ + [List[torch.Tensor], int, Callable[[], torch.cuda.Stream]], None + ], + gathered_outputs: List[torch.Tensor], + scattered_outputs: List[torch.Tensor], + timeout_s: int, + _wait: bool = True, + _memcpy: bool = True, + ): + """Perform a fused linear layer followed by a reduce-scatter""" + + dtype = gathered_outputs[0].dtype + assert all(go.device == self.my_device for go in gathered_outputs) + assert all(go.dtype == dtype for go in gathered_outputs) + assert all(so.device == self.my_device for so in scattered_outputs) + assert all(so.dtype == dtype for so in scattered_outputs) + + scattered_output_numels = [so.numel() for so in scattered_outputs] + total_scattered_output_numel = sum(scattered_output_numels) + + with torch.cuda.device(self.my_device): + symm_mem = get_symm_mem_workspace( + self.group.group_name, + self.world_size * total_scattered_output_numel * dtype.itemsize, + ) + # FIXME Do something about random_init if _memcpy is True. + buffers = [ + [ + s.view((self.world_size,) + so.shape) + for s, so in zip( + symm_mem.get_buffer( + rank, [self.world_size, total_scattered_output_numel], dtype + ).split(scattered_output_numels, dim=-1), + scattered_outputs, + ) + ] + for rank in range(self.world_size) + ] + + current_stream = torch.cuda.current_stream() + + # Signal to buddy that we have read from the data (in previous iter) + # so it can overwrite it (this write matches up with wait [2] below). + for iter_ in range(1, self.world_size): + src_rank = (self.my_rank - iter_) % self.world_size + if _wait: + with torch.cuda.stream(current_stream): + symm_mem.put_signal(src_rank, OP_FINISHED_CHANNEL) + + self.second_stream.wait_stream(current_stream) + self.compute_wait_stream.wait_stream(current_stream) + self.memcpy_wait_stream.wait_stream(current_stream) + stream_factory = self.make_stream_factory(current_stream) + + for iter_ in range(1, self.world_size): + dst_rank = (self.my_rank + iter_) % self.world_size + + # Wait for buddy to signal that it read from the data before we + # overwrite it (this wait matches up with write [2] above). + if _wait: + with torch.cuda.stream(self.compute_wait_stream): + symm_mem.wait_signal( + dst_rank, + OP_FINISHED_CHANNEL, + timeout_ms=timeout_s * MS_IN_S, # type: ignore[call-arg] + ) + + current_stream.wait_stream(self.compute_wait_stream) + self.second_stream.wait_stream(self.compute_wait_stream) + + my_matmul( + [s[dst_rank] for s in buffers[self.my_rank]], dst_rank, stream_factory + ) + + # Deduce which stream contains the last kernel launched. + final_stream = [current_stream, self.second_stream][ + (self.next_stream_idx - 1) % 2 + ] + final_stream.wait_stream(current_stream) + final_stream.wait_stream(self.second_stream) + + # Signal to buddy that we have written into the data so it can + # read from it (this write matches up with wait [1] below). + if _wait: + with torch.cuda.stream(final_stream): + symm_mem.memset32( + symm_mem.get_signal_pad(dst_rank), # type: ignore[attr-defined] + self.world_size * COMMS_READY_CHANNEL + self.my_rank, + val=1, + count=1, + ) + + my_matmul( + [o[self.my_rank] for o in gathered_outputs], + self.my_rank, + stream_factory, + ) + + for iter_ in range(1, self.world_size): + src_rank = (self.my_rank - iter_) % self.world_size + + # Wait for buddy to signal that it wrote into the data before we + # read from it (this wait matches up with write [1] above). + if _wait: + with torch.cuda.stream(self.memcpy_wait_stream): + symm_mem.wait_signal( + src_rank, + COMMS_READY_CHANNEL, + timeout_ms=timeout_s * MS_IN_S, # type: ignore[call-arg] + ) + + self.memcpy_stream.wait_stream(self.memcpy_wait_stream) + + if _memcpy: + with torch.cuda.stream(self.memcpy_stream): + for go, bs in zip(gathered_outputs, buffers[src_rank]): + go[src_rank].copy_(bs[self.my_rank]) + + current_stream.wait_stream(self.second_stream) + current_stream.wait_stream(self.memcpy_stream) + + for go, so in zip(gathered_outputs, scattered_outputs): + torch.sum(go, dim=0, out=so) + + +# We'd store this as an attribute on the PG object itself, but some PGs are +# pybind-bound classes and thus don't support it, so we simulate this as an +# external cache. +CACHE: Dict[int, Optional[_FusedSequenceParallel]] = {} + + +def _can_ranks_communicate_all_to_all_over_nvlink(group: dist.ProcessGroup) -> bool: + # FIXME This is currently overly simplistic, must be improved. The following + # should be enough: + # - ensure that all ranks are running on the same machine (by exchanging + # their /proc/sys/kernel/random/boot_id value) + # - ensure there's P2P between all pairs of ranks (can_device_access_peer + # could help here but it's unclear what happens if target devices aren't + # visible? maybe just trying to exchange IPC handles and catching errors + # would work? note that in any case some ranks might succeed while some + # might fail so we need a barrier to have them all make the same decision) + return group.size() <= 8 + + +def _lazy_init( + device: torch.device, group: dist.ProcessGroup +) -> Optional[_FusedSequenceParallel]: + world_size = group.size() + try: + obj = CACHE[id(group)] + except KeyError: + if int(os.environ.get("DISABLE_FUSED_SEQUENCE_PARALLEL", "0")): + obj = None + elif world_size == 1: + obj = None + elif not _can_ranks_communicate_all_to_all_over_nvlink(group): + obj = None + else: + obj = _FusedSequenceParallel(device, group) + CACHE[id(group)] = obj + return obj + + +def _default_stream_factory() -> torch.cuda.Stream: + return torch.cuda.current_stream() + + +@overload +def fused_allgather_and_linear( + scattered_input: torch.Tensor, + weight: torch.Tensor, + *, + group: dist.ProcessGroup, + out: Optional[torch.Tensor] = None, + timeout_s: int = 60 * 60, + scale_scattered_input: Optional[torch.Tensor] = None, + scale_weight: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None, + out_dtype: Optional[torch.dtype] = None, + **private_args_DO_NOT_USE, +) -> torch.Tensor: ... + + +@overload +def fused_allgather_and_linear( + scattered_input: torch.Tensor, + weight: List[torch.Tensor], + *, + group: dist.ProcessGroup, + out: Optional[List[torch.Tensor]] = None, + timeout_s: int = 60 * 60, + scale_scattered_input: Optional[torch.Tensor] = None, + scale_weight: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None, + out_dtype: Optional[torch.dtype] = None, + **private_args_DO_NOT_USE, +) -> List[torch.Tensor]: ... + + +def fused_allgather_and_linear( + scattered_input: torch.Tensor, + weight: Union[torch.Tensor, List[torch.Tensor]], + *, + group: dist.ProcessGroup, + out: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None, + timeout_s: int = 60 * 60, + scale_scattered_input: Optional[torch.Tensor] = None, + scale_weight: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None, + out_dtype: Optional[torch.dtype] = None, + **private_args_DO_NOT_USE, +) -> Union[torch.Tensor, List[torch.Tensor]]: + """Performs a fused all-gather followed by a linear op + + It is equivalent to the following plain PyTorch code: + + # like scattered_input but with first dim multiplied by group's world size + gathered_input = scattered_input.new_empty(...) + dist.all_gather_into_tensor(gathered_input, scattered_input, group=group) + return torch.nn.functional.linear(gathered_input, weight) + + It achieves this by breaking down the matmul into smaller partial ops (as + many as the world size), each needing as input a different "contribution" + to the all-gather (by a different rank), and writing to a different chunk of + the output. Then, on one stream, it sends the local contribution to all + other ranks (first one rank over, then two, ...) while, on another stream, + it launches the sub-matmuls in the order in which the remote contributions + (which are the sub-matmuls' inputs) are supposed to arrive, so that ideally + none of the sub-matmuls will ever have to wait. + + The idea comes from this paper: https://arxiv.org/abs/2302.05442 + + This method uses a staging buffer, which persists across calls, of the same + size as the all-gathered input tensor (i.e., the input's size times the + world size). If multiple inputs of multiple sizes are used, the staging + buffer will be the maximum needed by any of them. Each call, when it starts, + must first wait for the previous call to finish using the staging buffer. In + normal conditions, where there's some other operation between two calls, + this isn't an issue. + + Supports FP8 gemm for tensor-wise quantized weight and input tensors. + To enable FP8 gemm: + 1. pass scattered_input and weight as quantized FP8 datatype + 2. pass scale_scattered_input and scale_weight, the scales used to + quantize input and weight, respectively. + 3. set out_dtype, if not specified, will be inferred from scattered_input type. + + """ + world_size = group.size() + weights = weight if isinstance(weight, list) else [weight] + assert (scale_scattered_input is None) == (scale_weight is None) + if scale_weight is not None: + assert isinstance(weight, list) == isinstance(scale_weight, list) + scales_weights: Sequence[Optional[torch.Tensor]] = ( + scale_weight if isinstance(scale_weight, list) else [scale_weight] + ) + assert len(weights) == len(scales_weights) + assert _is_fp8_dtype(scattered_input.dtype) + assert all(_is_fp8_dtype(w.dtype) for w in weights) + assert out_dtype is not None, "output_dtype is required with FP8" + else: + scales_weights = [None] * len(weights) + assert all(w.ndim == 2 for w in weights) + assert scattered_input.ndim >= 2 + assert all(scattered_input.shape[-1] == w.shape[-1] for w in weights) + assert scattered_input.is_contiguous() + gathered_input_shape = (world_size,) + scattered_input.shape + gathered_output_shapes = [gathered_input_shape[:-1] + w.shape[:-1] for w in weights] + if out is not None: + assert isinstance(out, list) == isinstance(weight, list) + gathered_outputs = out if isinstance(out, list) else [out] + assert len(gathered_outputs) == len(gathered_output_shapes) + assert all( + go.shape == gos for go, gos in zip(gathered_outputs, gathered_output_shapes) + ) + assert all(go.is_contiguous() for go in gathered_outputs) + if out_dtype is not None: + if isinstance(out, list): + for o in out: + assert o.dtype == out_dtype + else: + assert out.dtype == out_dtype + else: + gathered_outputs = [ + scattered_input.new_empty( + gos, + dtype=out_dtype if out_dtype is not None else scattered_input.dtype, + ) + for gos in gathered_output_shapes + ] + + torch.ops.xformers_python._fused_allgather_and_linear_impl( + scattered_input, + weights, + group.group_name, + gathered_outputs, + timeout_s=timeout_s, + _wait=private_args_DO_NOT_USE.get("_wait", True), + _memcpy=private_args_DO_NOT_USE.get("_memcpy", True), + scale_scattered_input=scale_scattered_input, + scales_weights=scales_weights, + ) + + if isinstance(weight, list): + return [go.flatten(0, 1) for go in gathered_outputs] + else: + return gathered_outputs[0].flatten(0, 1) + + +@torch.library.custom_op( + "xformers_python::_fused_allgather_and_linear_impl", + mutates_args={"gathered_outputs"}, + device_types="cuda", +) +def _fused_allgather_and_linear_custom_op( + scattered_input: torch.Tensor, + weights: List[torch.Tensor], + process_group_name: str, + gathered_outputs: List[torch.Tensor], + timeout_s: int, + _wait: bool, + _memcpy: bool, + scale_scattered_input: torch.Tensor, + scales_weights: Sequence[Optional[torch.Tensor]], +) -> None: + process_group = dist.distributed_c10d._resolve_process_group(process_group_name) + + def my_matmul( + inputs: List[torch.Tensor], + src_rank: int, + stream_factory: Callable[[], torch.cuda.Stream], + ) -> None: + for w, scale_weight, go in zip(weights, scales_weights, gathered_outputs): + with torch.cuda.stream(stream_factory()): + if scale_scattered_input is not None and scale_weight is not None: + torch._scaled_mm( + inputs[0], + w.t(), + out_dtype=go[src_rank].dtype, + scale_a=scale_scattered_input, + scale_b=scale_weight, + out=go[src_rank], + ) + else: + torch.matmul(inputs[0], w.t(), out=go[src_rank]) + + fused_allgather_and_anything( + [scattered_input], + my_matmul, + group=process_group, + timeout_s=timeout_s, + _wait=_wait, + _memcpy=_memcpy, + ) + + +def fused_allgather_and_anything( + scattered_inputs: List[torch.Tensor], + my_matmul: Callable[ + [List[torch.Tensor], int, Callable[[], torch.cuda.Stream]], None + ], + *, + group: dist.ProcessGroup, + timeout_s: int = 60 * 60, + **private_args_DO_NOT_USE, +) -> None: + world_size = group.size() + + if len(scattered_inputs) == 0: + for src_rank in range(world_size): + my_matmul([], src_rank, _default_stream_factory) + return + + assert all(si.is_contiguous() for si in scattered_inputs) + assert all(si.device == scattered_inputs[0].device for si in scattered_inputs) + assert all(si.dtype == scattered_inputs[0].dtype for si in scattered_inputs) + + gathered_input_shapes = [(world_size,) + si.shape for si in scattered_inputs] + + obj = _lazy_init(scattered_inputs[0].device, group) + + if world_size == 1: + my_matmul(scattered_inputs, 0, _default_stream_factory) + + # Fallback + elif obj is None: + gathered_inputs = [ + si.new_empty(gis) + for si, gis in zip(scattered_inputs, gathered_input_shapes) + ] + for si, gi in zip(scattered_inputs, gathered_inputs): + dist.all_gather_into_tensor(output_tensor=gi, input_tensor=si, group=group) + for src_rank in range(world_size): + my_matmul( + [gi[src_rank] for gi in gathered_inputs], + src_rank, + _default_stream_factory, + ) + + # Fast path + else: + assert scattered_inputs[0].device == obj.my_device + obj.allgather_and_linear( + scattered_inputs, + my_matmul, + timeout_s=timeout_s, + _wait=private_args_DO_NOT_USE.get("_wait", True), + _memcpy=private_args_DO_NOT_USE.get("_memcpy", True), + ) + + +@overload +def fused_linear_and_reducescatter( + gathered_input: torch.Tensor, + weight: torch.Tensor, + *, + group: dist.ProcessGroup, + out: Optional[torch.Tensor] = None, + timeout_s: int = 60 * 60, + scale_gathered_input: Optional[torch.Tensor] = None, + scale_weight: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None, + out_dtype: Optional[torch.dtype] = None, + **private_args_DO_NOT_USE, +) -> torch.Tensor: ... + + +@overload +def fused_linear_and_reducescatter( + gathered_input: torch.Tensor, + weight: List[torch.Tensor], + *, + group: dist.ProcessGroup, + out: Optional[List[torch.Tensor]] = None, + timeout_s: int = 60 * 60, + scale_gathered_input: Optional[torch.Tensor] = None, + scale_weight: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None, + out_dtype: Optional[torch.dtype] = None, + **private_args_DO_NOT_USE, +) -> List[torch.Tensor]: ... + + +def fused_linear_and_reducescatter( + gathered_input: torch.Tensor, + weight: Union[torch.Tensor, List[torch.Tensor]], + *, + group: dist.ProcessGroup, + out: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None, + timeout_s: int = 60 * 60, + scale_gathered_input: Optional[torch.Tensor] = None, + scale_weight: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None, + out_dtype: Optional[torch.dtype] = None, + **private_args_DO_NOT_USE, +) -> Union[torch.Tensor, List[torch.Tensor]]: + """Performs a fused linear op followed by a reduce-scatter + + It is equivalent to the following plain PyTorch code: + + gathered_output = torch.nn.functional.linear(gathered_input, weight) + # like gathered_output but with first dim divided by group's world size + scattered_output = gathered_output.new_empty(...) + dist.reduce_scatter_tensor(scattered_output, gathered_output, group=group) + + Supports FP8 gemm with tensor-wise quantized weights. To enable FP8 gemm: + 1. pass weight and gathered_input as FP8 tensors + 2. Set `scale_gathered_input` and `scale_weight` to the scales used to quantize + inputs and weight, respectively. + 3. Set out_dtype to the desired output dtype. If not specified, it will be inferred from + gathered_input datatype. + """ + world_size = group.size() + weights = weight if isinstance(weight, list) else [weight] + assert (scale_gathered_input is None) == (scale_weight is None) + if scale_weight is not None: + assert isinstance(weight, list) == isinstance(scale_weight, list) + scales_weights: Sequence[Optional[torch.Tensor]] = ( + scale_weight if isinstance(scale_weight, list) else [scale_weight] + ) + assert len(weights) == len(scales_weights) + assert _is_fp8_dtype(gathered_input.dtype) + assert all(_is_fp8_dtype(w.dtype) for w in weights) + assert out_dtype is not None, "output_dtype is required with FP8" + else: + scales_weights = [None] * len(weights) + assert all(w.ndim == 2 for w in weights) + assert gathered_input.ndim >= 2 + assert all(gathered_input.shape[-1] == w.shape[-1] for w in weights) + assert gathered_input.is_contiguous() + assert gathered_input.shape[0] % world_size == 0 + gathered_input = gathered_input.view( + (world_size, gathered_input.shape[0] // world_size) + gathered_input.shape[1:] + ) + gathered_output_shapes = [gathered_input.shape[:-1] + w.shape[:-1] for w in weights] + scattered_output_shapes = [gos[1:] for gos in gathered_output_shapes] + if out is not None: + assert isinstance(out, list) == isinstance(weight, list) + scattered_outputs = out if isinstance(out, list) else [out] + assert len(scattered_outputs) == scattered_output_shapes + assert all(so.device == gathered_input.device for so in scattered_outputs) + assert all(so.dtype == gathered_input.dtype for so in scattered_outputs) + assert all( + so.shape == sos + for so, sos in zip(scattered_outputs, scattered_output_shapes) + ) + if out_dtype is not None: + if isinstance(out, list): + for o in out: + assert o.dtype == out_dtype + else: + assert out.dtype == out_dtype + else: + scattered_outputs = [ + gathered_input.new_empty( + sos, + dtype=out_dtype if out_dtype is not None else gathered_input.dtype, + ) + for sos in scattered_output_shapes + ] + + torch.ops.xformers_python._fused_linear_and_reducescatter_impl( + gathered_input, + weights, + group.group_name, + scattered_outputs, + timeout_s=timeout_s, + _wait=private_args_DO_NOT_USE.get("_wait", True), + _memcpy=private_args_DO_NOT_USE.get("_memcpy", True), + scale_gathered_input=scale_gathered_input, + scales_weights=scales_weights, + ) + + if isinstance(weight, list): + return scattered_outputs + else: + return scattered_outputs[0] + + +@torch.library.custom_op( + "xformers_python::_fused_linear_and_reducescatter_impl", + mutates_args={"scattered_outputs"}, + device_types="cuda", +) +def _fused_linear_and_reducescatter_custom_op( + gathered_input: torch.Tensor, + weights: List[torch.Tensor], + process_group_name: str, + scattered_outputs: List[torch.Tensor], + timeout_s: int, + _wait: bool, + _memcpy: bool, + scale_gathered_input: torch.Tensor, + scales_weights: Sequence[Optional[torch.Tensor]], +) -> None: + process_group = dist.distributed_c10d._resolve_process_group(process_group_name) + + def my_matmul( + outputs: List[torch.Tensor], + dst_rank: int, + stream_factory: Callable[[], torch.cuda.Stream], + ) -> None: + for w, scale_weight, o in zip(weights, scales_weights, outputs): + with torch.cuda.stream(stream_factory()): + if scale_gathered_input is not None and scale_weight is not None: + torch._scaled_mm( + gathered_input[dst_rank], + w.t(), + out_dtype=o.dtype, + scale_a=scale_gathered_input, + scale_b=scale_weight, + out=o, + ) + else: + torch.matmul(gathered_input[dst_rank], w.t(), out=o) + + fused_anything_and_reducescatter( + my_matmul, + scattered_outputs, + group=process_group, + timeout_s=timeout_s, + _wait=_wait, + _memcpy=_memcpy, + ) + + +def fused_anything_and_reducescatter( + my_matmul: Callable[ + [List[torch.Tensor], int, Callable[[], torch.cuda.Stream]], None + ], + scattered_outputs: List[torch.Tensor], + *, + group: dist.ProcessGroup, + timeout_s: int = 60 * 60, + **private_args_DO_NOT_USE, +) -> None: + world_size = group.size() + + if len(scattered_outputs) == 0: + for dst_rank in range(world_size): + my_matmul([], dst_rank, _default_stream_factory) + return + + assert all(so.is_contiguous() for so in scattered_outputs) + assert all(so.device == scattered_outputs[0].device for so in scattered_outputs) + assert all(so.dtype == scattered_outputs[0].dtype for so in scattered_outputs) + + gathered_output_shapes = [(world_size,) + so.shape for so in scattered_outputs] + + obj = _lazy_init(scattered_outputs[0].device, group) + + if world_size == 1: + my_matmul(scattered_outputs, 0, _default_stream_factory) + + # Fallback + elif obj is None: + gathered_outputs = [ + so.new_empty(gos) + for so, gos in zip(scattered_outputs, gathered_output_shapes) + ] + for dst_rank in range(world_size): + my_matmul( + [go[dst_rank] for go in gathered_outputs], + dst_rank, + _default_stream_factory, + ) + for go, so in zip(gathered_outputs, scattered_outputs): + dist.reduce_scatter_tensor(output=so, input=go, group=group) + + # Fast path + else: + assert scattered_outputs[0].device == obj.my_device + gathered_outputs = [ + scattered_outputs[0].new_empty(gos) for gos in gathered_output_shapes + ] + obj.linear_and_reducescatter( + my_matmul, + gathered_outputs, + scattered_outputs, + timeout_s=timeout_s, + _wait=private_args_DO_NOT_USE.get("_wait", True), + _memcpy=private_args_DO_NOT_USE.get("_memcpy", True), + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/sp24.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/sp24.py new file mode 100644 index 0000000000000000000000000000000000000000..439ef9151dfdebc3a34cd96958e2612928eb9b15 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/sp24.py @@ -0,0 +1,823 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import contextlib +import os +import time +from functools import partial +from typing import Any, Callable, cast, Dict, List, Optional, Tuple, TypeVar + +import torch + +from .common import BaseOperator, get_operator, get_xformers_operator, register_operator + + +@register_operator +class SparsifyBothWays(BaseOperator): + OPERATOR = get_xformers_operator("sparse24_sparsify_both_ways") + OPERATOR_CATEGORY = "sp24" + NAME = "sparse24_sparsify_both_ways" + + +@register_operator +class SparsifyApply(BaseOperator): + OPERATOR = get_xformers_operator("sparse24_apply") + OPERATOR_CATEGORY = "sp24" + NAME = "sparse24_apply" + + +@register_operator +class SparsifyApplyDenseOutput(BaseOperator): + OPERATOR = get_xformers_operator("sparse24_apply_dense_output") + OPERATOR_CATEGORY = "sp24" + NAME = "sparse24_apply_dense_output" + + +@register_operator +class Sp24Gemm(BaseOperator): + OPERATOR = get_xformers_operator("_sparse24_gemm") + OPERATOR_CATEGORY = "sp24" + NAME = "_sparse24_gemm" + + +def _get_cusparselt_torch_version() -> Tuple[int, int, int]: + """ + Returns the version of the cusparselt.so library used by pytorch + """ + if not torch.backends.cusparselt.is_available(): + return (0, 0, 0) + version: Optional[int] = torch.backends.cusparselt.version() + if version is None: + return (0, 0, 0) + return ((version // 10000) % 100, (version // 100) % 100, version % 100) + + +_cusplt_version = _get_cusparselt_torch_version() +_cusplt_version_str = ".".join(str(v) for v in _cusplt_version) + + +@register_operator +class Sp24GemmCuspltSearch(BaseOperator): + OPERATOR = get_operator("aten", "_cslt_sparse_mm_search") + OPERATOR_CATEGORY = "sp24" + NAME = f"_cslt_sparse_mm_search@{_cusplt_version_str}" + + +@register_operator +class Sp24GemmCusplt(BaseOperator): + OPERATOR = get_operator("aten", "_cslt_sparse_mm") + OPERATOR_CATEGORY = "sp24" + NAME = f"_cslt_sparse_mm@{_cusplt_version_str}" + + +def _has_cusparseLt() -> bool: + available = _cusplt_version >= (0, 5, 0) + if not available: + return False + + # Sm90 added in 6.0 + compute_capability = (0, 0) + if torch.cuda.is_available(): + compute_capability = torch.cuda.get_device_capability("cuda") + if _cusplt_version < (6, 0, 0): + if compute_capability >= (9, 0): + return False + return available + + +def sparse24_pointwise_op( + func, types, args=(), kwargs=None, allow_sparsify_args_list=() +): + self = None + for tensor in args: + if isinstance(tensor, Sparse24Tensor): + self = tensor + assert self is not None + args_updated = [] + for i, tensor in enumerate(args): + if isinstance(tensor, torch.Tensor): + if not isinstance(tensor, Sparse24Tensor): + if i in allow_sparsify_args_list: + tensor = sparsify24_like(tensor, self) + else: + raise ValueError( + f"Operation {func.__module__}.{func.__name__} on Sparse24Tensor requires all operands to " + f"be Sparse24Tensors, but operand {i} is a {type(tensor)}" + ) + if ( + tensor.threads_masks is None + or self.threads_masks is None + or tensor.threads_masks.data_ptr() != self.threads_masks.data_ptr() + or tensor.threads_masks.stride() != self.threads_masks.stride() + ): + raise ValueError( + f"Operation {func.__module__}.{func.__name__} on Sparse24Tensor requires all operands to be " + "Sparse24Tensors with the same sparsity pattern" + ) + args_updated.append(tensor) + assert isinstance( + self, Sparse24TensorCutlass + ), "Only implemented for CUTLASS tensors" + return Sparse24TensorCutlass( + self.shape, + func( + *[(x.packed if isinstance(x, Sparse24Tensor) else x) for x in args_updated] + ), + self.meta, + func( + *[ + (x.packed_t if isinstance(x, Sparse24Tensor) else x) + for x in args_updated + ] + ), + self.meta_t, + self.threads_masks, + ) + + +def sparse24_mm(func, types, args=(), kwargs=None) -> torch.Tensor: + assert len(args) == 2 + A, B = args + if A.ndim != 2 or B.ndim != 2: + raise NotImplementedError( + "`Sparse24Tensor` matmul: Broadcasting is not implemented" + ) + if isinstance(A, Sparse24Tensor): + return A._mm(B) + else: + B_t = B.t() + assert isinstance(B_t, Sparse24Tensor) + return B_t._mm(A.t(), prefer_col_major_output=True).t() + + +def sparse24_addmm(func, types, args=(), kwargs=None) -> torch.Tensor: + assert len(args) == 3 + bias, A, B = args + if A.ndim != 2 or B.ndim != 2: + raise NotImplementedError( + "`Sparse24Tensor` matmul: Broadcasting is not implemented" + ) + if bias.ndim != 1: + raise NotImplementedError( + f"`Sparse24Tensor` matmul: only bias dim=1 supported. Shape={bias.shape}" + ) + if isinstance(A, Sparse24Tensor): + raise NotImplementedError( + "`Sparse24Tensor` matmul: only operand B of `addmm` can be sparse" + ) + B_t = B.t() + assert isinstance(B_t, Sparse24Tensor) + return B_t._mm(A.t(), bias=bias, prefer_col_major_output=True).t() + + +def sparse24_linear(func, types, args=(), kwargs=None) -> torch.Tensor: + assert len(args) in [2, 3] + A, B = args[:2] + bias = args[2] if len(args) == 3 else None + if bias is None: + return A @ B.t() + return sparse24_addmm( + func=None, + types=None, + args=[bias, A, B.t()], + ) + + +def sparse24_t(func, types, args=(), kwargs=None) -> torch.Tensor: + assert len(args) == 1 + self = args[0] + assert isinstance(self, Sparse24Tensor) + assert len(self.shape) == 2 + return self.__class__( + (self.shape[-1], self.shape[0]), + packed=self.packed_t, + meta=self.meta_t, + packed_t=self.packed, + meta_t=self.meta, + threads_masks=self.threads_masks.transpose(0, 1), + ) + + +def sparse24_view(func, types, args=(), kwargs=None) -> torch.Tensor: + assert len(args) == 2 + self, shape = args + if tuple(shape) != self.shape: + raise NotImplementedError( + f"`view` is not implemented for Sparse24Tensor, except for the dummy case (shape={shape})" + ) + return self + + +def sparse24_detach(func, types, args, kwargs) -> torch.Tensor: + assert len(args) == 1 + self = args[0] + return self.__class__( + shape=self.shape, + packed=self.packed, + meta=self.meta, + packed_t=self.packed_t, + meta_t=self.meta_t, + threads_masks=self.threads_masks, + requires_grad=False, + ) + + +@contextlib.contextmanager +def no_dispatch(): + guard = torch._C._DisableTorchDispatch() + try: + yield + finally: + del guard + + +def fallback_dispatcher(func, types, args, kwargs): + with no_dispatch(): + return func(*args) + + +SPARSE24_DISPATCH_CUTLASS = { + torch.ops.aten.is_same_size: fallback_dispatcher, + torch.ops.aten.detach_: fallback_dispatcher, + torch.ops.aten.detach: sparse24_detach, + torch.ops.aten.relu: sparse24_pointwise_op, + torch.ops.aten.gelu: sparse24_pointwise_op, + torch.ops.aten.silu: sparse24_pointwise_op, + torch.ops.aten.mul: partial( + # `mul` BW in swiglu + sparse24_pointwise_op, + allow_sparsify_args_list=( + 0, + 1, + ), + ), + torch.ops.aten.add: sparse24_pointwise_op, + # Note: for these ops, we allow the gradient to come in as a `torch.Tensor` + # and we will run the sparsification right before calling the BW aten func + torch.ops.aten.gelu_backward: partial( + sparse24_pointwise_op, allow_sparsify_args_list=(0,) + ), + torch.ops.aten.silu_backward: partial( + sparse24_pointwise_op, allow_sparsify_args_list=(0, 1) + ), + torch.ops.aten.threshold_backward: partial( # relu BW + sparse24_pointwise_op, + allow_sparsify_args_list=(0,), + ), + torch.ops.aten.mm: sparse24_mm, + torch.ops.aten.matmul: sparse24_mm, + torch.ops.aten.t: sparse24_t, + torch.ops.aten.view: sparse24_view, + torch.ops.aten.linear: sparse24_linear, +} + +SPARSE24_DISPATCH_CUSPARSELT = { + torch.ops.aten.is_same_size: fallback_dispatcher, + torch.ops.aten.detach_: fallback_dispatcher, + torch.ops.aten.detach: sparse24_detach, + torch.ops.aten.t: sparse24_t, + torch.ops.aten.view: sparse24_view, + torch.ops.aten.mm: sparse24_mm, + torch.ops.aten.matmul: sparse24_mm, + torch.ops.aten.addmm: sparse24_addmm, + torch.ops.aten.linear: sparse24_linear, +} + + +class Sparse24Tensor(torch.Tensor): + packed: torch.Tensor + meta: torch.Tensor + packed_t: torch.Tensor + meta_t: torch.Tensor + threads_masks: torch.Tensor + __slots__ = ["packed", "meta", "packed_t", "meta_t", "threads_masks"] + + # We need to update the new method here to tell PyTorch what should be + # the Tensor corresponding to the wrapper object + @staticmethod + def __new__( + cls, + shape, + packed: torch.Tensor, + meta: torch.Tensor, + packed_t: torch.Tensor, + meta_t: torch.Tensor, + threads_masks: torch.Tensor, + *, + requires_grad=False, + ): + assert isinstance(packed, torch.Tensor) + tensor = torch.Tensor._make_wrapper_subclass( # type: ignore[attr-defined] + cls, + shape, + device=packed.device, + dtype=packed.dtype, + requires_grad=requires_grad, + ) + tensor.packed = packed + tensor.meta = meta + tensor.packed_t = packed_t + tensor.meta_t = meta_t + tensor.threads_masks = threads_masks + return tensor + + def __repr__(self): + return f"{self.__class__.__name__}(shape={self.shape})" + + def _sp24_to_dense(self) -> torch.Tensor: + # Multiply by identity + # WARN: This is not efficient at all + e = torch.eye( + self.shape[1], self.shape[1], device=self.device, dtype=self.dtype + ) + return self @ e + + def _mm( + self, + B: torch.Tensor, + *, + prefer_col_major_output: bool = False, + bias: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + raise NotImplementedError() + + __torch_function__ = torch._C._disabled_torch_function_impl + + def __tensor_flatten__(self): + return self.__slots__, (self.shape, self.requires_grad) + + @classmethod + def __tensor_unflatten__( + cls, inner_tensors, flatten_spec, outer_size, outer_stride + ): + shape, requires_grad = flatten_spec + return cls( + shape, + **inner_tensors, + requires_grad=requires_grad, + ) + + +class Sparse24TensorCutlass(Sparse24Tensor): + def _mm( + self, + B: torch.Tensor, + *, + bias: Optional[torch.Tensor] = None, + prefer_col_major_output: bool = False, + ) -> torch.Tensor: + if isinstance(B, Sparse24Tensor): + raise ValueError( + "`Sparse24Tensor @ Sparse24Tensor` is not supported by the hardware" + ) + if bias is not None: + raise NotImplementedError( + f"`Sparse24Tensor` with backend='{BACKEND_CUTLASS}' does not support matmul with bias. " + f"Remove the bias, or use backend='{BACKEND_CUSPARSELT}'" + ) + if self.ndim != 2 or B.ndim != 2: + raise NotImplementedError( + f"`{self.__class__.__name__}` matmul: Broadcasting is not implemented" + ) + if self.shape[1] != B.shape[0]: + raise NotImplementedError( + f"`{self.__class__.__name__}` matmul: invalid shapes \ + ({self.shape[0]}, {self.shape[1]}) @ ({B.shape[0]}, {B.shape[1]})" + ) + return Sp24Gemm.OPERATOR(self.packed, B, self.meta)[: self.shape[0]] + + @classmethod + def __torch_dispatch__(cls, func, types, args=(), kwargs=None): + if func._overloadpacket not in SPARSE24_DISPATCH_CUTLASS: + raise NotImplementedError( + f"{cls.__name__} only supports a specific set of operations, " + f"can't perform requested op ({func.__name__})" + ) + return SPARSE24_DISPATCH_CUTLASS[func._overloadpacket]( + func, types, args, kwargs + ) + + +_CUSPLT_ALG_CACHE: Dict[Tuple[int, int, int, str, torch.dtype, bool], int] = {} +# Disabled by default, as there is a correctness issue on cusparselt +# when using some algorithms: +# https://github.com/pytorch/pytorch/issues/155333 +_CUSPLT_TUNE = os.environ.get("XFORMERS_CUSPARSELT_TUNE", "0") == "1" + + +def _cusplt_find_alg( + shape: List[int], + packed: torch.Tensor, + B: torch.Tensor, + bias: Optional[torch.Tensor], + transpose_result: bool, +) -> int: + """ + cuSPARSELt has multiple algorithms (that correspond to different kernels) + to run a given GEMM, because the optimal kernel depends on the GEMM dimensions. + This function attempts to find the most efficient one by benchmarking all + of them. + NOTE: cuSPARSELt also provides a function to search the best algorithm + (exposed via `aten:_cslt_sparse_mm_search`) but it often fails to find the best + algorithm, so we need this workaround. + """ + if not _CUSPLT_TUNE: + return 0 + M, K = shape + N = B.shape[1] + fmt = "r" + fmt += "r" if B.stride(-1) <= 1 else "c" + fmt += "c" if transpose_result else "r" + h = (M, N, K, fmt, B.dtype, bias is not None) + if h in _CUSPLT_ALG_CACHE: + return _CUSPLT_ALG_CACHE[h] + + REPEAT = 10 + TIME_ALGO = [] + for algo in range(70): + has_error = False + for i in range(REPEAT): + try: + Sp24GemmCusplt.OPERATOR( + packed, B, bias=bias, transpose_result=transpose_result, alg_id=algo + ) + except RuntimeError: + has_error = True + break + if i == 1: # 1 iteration of warmup + torch.cuda.synchronize() + t = time.monotonic() + if has_error: + break + torch.cuda.synchronize() + dt = time.monotonic() - t + TIME_ALGO.append((dt, algo)) + TIME_ALGO.sort() + _CUSPLT_ALG_CACHE[h] = TIME_ALGO[0][1] + return _CUSPLT_ALG_CACHE[h] + + +@torch.library.custom_op("xformers::_cusplt_mm", mutates_args=(), device_types=["cuda"]) +def _cusplt_mm( + shape: List[int], + packed: torch.Tensor, + B: torch.Tensor, + bias: Optional[torch.Tensor], + transpose_result: bool, +) -> torch.Tensor: + """ + This operator wraps find_algo + gemm. This is because we don't want find_algo + to be visible by torch compile, otherwise it will remove it from the graph. + """ + alg_id = _cusplt_find_alg( + shape, packed, B, bias=bias, transpose_result=transpose_result + ) + return Sp24GemmCusplt.OPERATOR( + packed, B, bias=bias, transpose_result=transpose_result, alg_id=alg_id + ) + + +@torch.library.register_fake("xformers::_cusplt_mm") +def _cusplt_mm_meta( + shape: List[int], + packed: torch.Tensor, + B: torch.Tensor, + bias: Optional[torch.Tensor], + transpose_result: bool, +) -> torch.Tensor: + M, K = shape + N = B.shape[1] + if transpose_result: + return torch.empty([N, M], dtype=B.dtype, device=B.device) + return torch.empty([M, N], dtype=B.dtype, device=B.device) + + +class Sparse24TensorCuSparseLt(Sparse24Tensor): + def _mm( + self, + B: torch.Tensor, + *, + prefer_col_major_output: bool = False, + bias: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + if isinstance(B, Sparse24Tensor): + raise ValueError( + "`Sparse24Tensor @ Sparse24Tensor` is not supported by the hardware" + ) + if self.ndim != 2 or B.ndim != 2: + raise NotImplementedError( + f"`{self.__class__.__name__}` matmul: Broadcasting is not implemented" + ) + if self.shape[1] != B.shape[0]: + raise NotImplementedError( + f"`{self.__class__.__name__}` matmul: invalid shapes \ + ({self.shape[0]}, {self.shape[1]}) @ ({B.shape[0]}, {B.shape[1]})" + ) + if B.shape[1] % 8 != 0: + raise NotImplementedError( + f"`{self.__class__.__name__}` matmul: trying to do `A={tuple(self.shape)} @ B={tuple(B.shape)}`. " + "The dense matrix B should have the second dimension aligned to 8." + ) + if B.dtype != self.dtype: + raise NotImplementedError( + f"`{self.__class__.__name__}` matmul: trying to do `A={tuple(self.shape)} @ B={tuple(B.shape)}`, " + f"with A.dtype={self.dtype} and B.dtype={B.dtype}. " + "This operation is only supported when A and B have the same data type." + ) + if bias is not None and bias.dtype != self.dtype: + raise NotImplementedError( + f"`{self.__class__.__name__}` matmul: trying to do `A={tuple(self.shape)} @ B={tuple(B.shape)} + C`, " + f"with A.dtype=B.dtype={self.dtype} and C.dtype={B.dtype}. " + "This operation is only supported when A, B and C have the same data type." + ) + assert _has_cusparseLt() + out = torch.ops.xformers._cusplt_mm( + self.shape, + self.packed, + B, + bias=bias, + transpose_result=prefer_col_major_output, + ) + if prefer_col_major_output: + out = out.t() + return out[: self.shape[0]] + + @classmethod + def __torch_dispatch__(cls, func, types, args=(), kwargs=None): + if func._overloadpacket not in SPARSE24_DISPATCH_CUSPARSELT: + raise NotImplementedError( + f"{cls.__name__} only supports a specific set of operations, " + f"can't perform requested op ({func.__name__})" + ) + return SPARSE24_DISPATCH_CUSPARSELT[func._overloadpacket]( + func, types, args, kwargs + ) + + +torch._dynamo.allow_in_graph(Sparse24TensorCuSparseLt) +torch._dynamo.allow_in_graph(Sparse24TensorCutlass) + +GRADIENT_SP24 = "24sparse" +GRADIENT_DENSE = "24dense" +GRADIENT_STE = "ste" # Straight-Through Estimator + +BACKEND_CUTLASS = "cutlass" +BACKEND_CUSPARSELT = "cusparselt" +BACKEND_DENSE = "dense" + + +def _sparsify24_forward(x: torch.Tensor, *, algo: str, backend: str) -> Sparse24Tensor: + assert backend in [ + BACKEND_CUTLASS, + BACKEND_CUSPARSELT, + ], f"Invalid backend: {backend}" + if isinstance(x, Sparse24Tensor): + if x.threads_masks is None: + raise ValueError("Input to `sparsify24` is already sparse") + return x + + (packed, meta, packed_t, meta_t, threads_masks) = SparsifyBothWays.OPERATOR( + x, algorithm=algo, backend=backend + ) + cls = ( + Sparse24TensorCutlass + if backend == BACKEND_CUTLASS + else Sparse24TensorCuSparseLt + ) + return cls( + x.shape, + packed=packed, + meta=meta, + packed_t=packed_t, + meta_t=meta_t, + threads_masks=threads_masks, + requires_grad=False, + ) + + +class _Sparsify24Func(torch.autograd.Function): + @staticmethod + def forward(ctx, x: torch.Tensor, algo: str, gradient: str, backend: str): # type: ignore[override] + if gradient not in [GRADIENT_SP24, GRADIENT_DENSE, GRADIENT_STE]: + raise ValueError( + f"Invalid gradient type: '{gradient}'. " + f"Expected '{GRADIENT_SP24}' or '{GRADIENT_DENSE}' or '{GRADIENT_STE}" + ) + out = _sparsify24_forward(x, algo=algo, backend=backend) + ctx.threads_masks = out.threads_masks + ctx.meta = out.meta + ctx.meta_t = out.meta_t + ctx.dtype = out.dtype + ctx.gradient = gradient + return out + + @staticmethod + def backward(ctx, grad_out: torch.Tensor): # type: ignore[override] + if isinstance(grad_out, Sparse24Tensor) or ctx.gradient == GRADIENT_STE: + return grad_out, None, None, None + assert not isinstance(grad_out, Sparse24Tensor) + assert grad_out.dtype == ctx.dtype + if ctx.gradient == GRADIENT_SP24: + packed, _, packed_t, _ = SparsifyApply.OPERATOR(grad_out, ctx.threads_masks) + grad_in: torch.Tensor = Sparse24TensorCutlass( + grad_out.shape, + packed, + ctx.meta, + packed_t, + ctx.meta_t, + ctx.threads_masks, + requires_grad=grad_out.requires_grad, + ) + elif ctx.gradient == GRADIENT_DENSE: + assert ctx.threads_masks.is_contiguous() + grad_in = SparsifyApplyDenseOutput.OPERATOR(grad_out, ctx.threads_masks) + else: + assert False, f"Unsupported gradient type: {ctx.gradient}" + return ( + grad_in, + None, + None, + None, + ) + + +class _Sparsify24STEFunc(torch.autograd.Function): + @staticmethod + def forward( + ctx, + x: torch.Tensor, + algo: str, + backend: str, + bw_mul0: float, + bw_mul1: float, + ): # type: ignore[override] + out = _sparsify24_forward(x, algo=algo, backend=backend) + ctx.threads_masks = out.threads_masks + ctx.bw_mul0 = bw_mul0 + ctx.bw_mul1 = bw_mul1 + return out + + @staticmethod + def backward(ctx, grad_out: torch.Tensor): # type: ignore[override] + assert not isinstance(grad_out, Sparse24Tensor) + if ctx.bw_mul0 == 1.0 and ctx.bw_mul1 == 1.0: + grad_in = grad_out + else: + grad_in = SparsifyApplyDenseOutput.OPERATOR( + grad_out, ctx.threads_masks, mul0=ctx.bw_mul0, mul1=ctx.bw_mul1 + ) + return ( + grad_in, + None, # algo + None, # backend + None, # bw_mul0 + None, # bw_mul1 + ) + + +class _Sparsify24LikeFunc(torch.autograd.Function): + @staticmethod + def forward(ctx, x: torch.Tensor, pattern: Sparse24Tensor, gradient: str, backend: str): # type: ignore[override] + if not isinstance(pattern, Sparse24Tensor): + raise NotImplementedError( + "`sparsify24_like`: `pattern` must be a sparse tensor" + ) + if not pattern.threads_masks.is_contiguous(): + raise NotImplementedError( + "`sparsify24_like` is not implemented when `pattern` is transposed" + ) + if gradient not in [GRADIENT_DENSE, GRADIENT_SP24, GRADIENT_STE]: + raise ValueError(f'`sparsify24_like`: invalid gradient type "{gradient}"') + ctx.threads_masks = pattern.threads_masks + ctx.meta = pattern.meta + ctx.meta_t = pattern.meta_t + ctx.dtype = pattern.dtype + ctx.gradient = gradient + if backend == BACKEND_DENSE: + assert ctx.threads_masks.is_contiguous() + return SparsifyApplyDenseOutput.OPERATOR(x, ctx.threads_masks) + packed, meta, packed_t, meta_t = SparsifyApply.OPERATOR( + x, ctx.threads_masks, backend=backend + ) + if backend == BACKEND_CUTLASS: + return Sparse24TensorCutlass( + x.shape, + packed, + ctx.meta, + packed_t, + ctx.meta_t, + ctx.threads_masks, + requires_grad=x.requires_grad, + ) + assert backend == BACKEND_CUSPARSELT, f"Invalid backend: {backend}" + meta.copy_(pattern.meta) + meta_t.copy_(pattern.meta_t) + return Sparse24TensorCuSparseLt( + x.shape, + packed, + meta, + packed_t, + meta_t, + ctx.threads_masks, + requires_grad=x.requires_grad, + ) + + @staticmethod + def backward(ctx, grad_out: torch.Tensor): # type: ignore[override] + if ctx.gradient == GRADIENT_STE or isinstance(grad_out, Sparse24Tensor): + return grad_out, None, None, None + assert not isinstance(grad_out, Sparse24Tensor) + assert grad_out.dtype == ctx.dtype + + if ctx.gradient == GRADIENT_DENSE: + assert ctx.threads_masks.is_contiguous() + return ( + SparsifyApplyDenseOutput.OPERATOR(grad_out, ctx.threads_masks), + None, + None, + None, + ) + assert ctx.gradient == GRADIENT_SP24 + + packed, _, packed_t, _ = SparsifyApply.OPERATOR( + grad_out, ctx.threads_masks, backend=BACKEND_CUTLASS + ) + return ( + Sparse24TensorCutlass( + grad_out.shape, + packed, + ctx.meta, + packed_t, + ctx.meta_t, + ctx.threads_masks, + requires_grad=grad_out.requires_grad, + ), + None, + None, + None, + ) + + +# We want to use `torch._dynamo.allow_in_graph` as a decorator +# (see https://fburl.com/workplace/uimiz0mf) but it breaks mypy. +# This is a hack to work around this +F = TypeVar("F", bound=Callable[..., Any]) + + +def allow_in_graph(func: F) -> F: + return cast(F, torch._dynamo.allow_in_graph(func)) + + +@allow_in_graph +def sparsify24( + x: torch.Tensor, + algo: str = "", + gradient: str = GRADIENT_SP24, + backend: str = BACKEND_CUTLASS, +) -> Sparse24Tensor: + return _Sparsify24Func.apply(x, algo, gradient, backend) + + +@allow_in_graph +def sparsify24_ste( + x: torch.Tensor, + algo: str = "", + backend: str = BACKEND_CUTLASS, + bw_mul0: float = 1.0, + bw_mul1: float = 1.0, +) -> Sparse24Tensor: + """ + 2:4 sparsification, with Straight Through Estimator for the + backward pass (eg the gradient is *not* sparsified). + Optionally, `bw_mul[0-1]` provide the option to rescale the gradient + differently for pruned (`bw_mul0`) and kept values (`bw_mul1`). + """ + return _Sparsify24STEFunc.apply(x, algo, backend, bw_mul0, bw_mul1) + + +@allow_in_graph +def sparsify24_like( + x: torch.Tensor, + pattern: torch.Tensor, + gradient: str = GRADIENT_SP24, + backend: str = "", + out_dense: Optional[bool] = None, # <-- TODO: Deprecate this in favor of "gradient" +) -> Sparse24Tensor: + if out_dense is not None and out_dense: + backend = BACKEND_DENSE + if backend == "": + backend = ( + BACKEND_CUSPARSELT + if isinstance(pattern, Sparse24TensorCuSparseLt) + else BACKEND_CUTLASS + ) + if not isinstance(pattern, Sparse24Tensor): + raise ValueError( + f"`pattern` must be a `Sparse24Tensor` but got a {type(pattern)}" + ) + # Handle transposed case + if not pattern.threads_masks.is_contiguous(): + return _Sparsify24LikeFunc.apply(x.t(), pattern.t(), gradient, backend).t() + return _Sparsify24LikeFunc.apply(x, pattern, gradient, backend) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/swiglu_op.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/swiglu_op.py new file mode 100644 index 0000000000000000000000000000000000000000..a4fcb7c26b05f8f94f70904dc9efb8adfec4ad2f --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/swiglu_op.py @@ -0,0 +1,554 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +from dataclasses import dataclass +from typing import Dict, Optional, Sequence, Tuple, Union + +import torch +import torch.nn.functional as F +from torch import nn +from torch.amp import custom_bwd, custom_fwd + +from .common import BaseOperator, get_xformers_operator, register_operator +from .unbind import stack_or_none, unbind + +if torch.version.hip: + + @torch.library.register_kernel("xformers::dual_gemm_silu_identity_mul", "cuda") # type: ignore + def dual_gemm_silu_identity_mul_cuda( + x: torch.Tensor, + w1: torch.Tensor, + b1: Optional[torch.Tensor], + w2: torch.Tensor, + b2: Optional[torch.Tensor], + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + x1 = x @ w1.T + if b1 is not None: + x1 += b1 + + x2 = x @ w2.T + if b2 is not None: + x2 += b2 + + x4 = F.silu(x1) * x2 + return x1, x2, x4 + + +@register_operator +class DualGemmSiluOp(BaseOperator): + OPERATOR = get_xformers_operator("dual_gemm_silu_identity_mul") + OPERATOR_CATEGORY = "swiglu" + NAME = "dual_gemm_silu" + + +@register_operator +class GemmFusedSumOp(BaseOperator): + OPERATOR = get_xformers_operator("gemm_fused_operand_sum") + OPERATOR_CATEGORY = "swiglu" + NAME = "gemm_fused_operand_sum" + + +class _SwiGLUDecomposedFunc(torch.autograd.Function): + """ + This is just an example implementation with all + operations explicited. This implementation is worse + than pytorch, because pytorch is able to fuse some operations + (eg the linear forward ...) that are decomposed here. + + The time measurements were made on the ViT-Giant setting: + - A100/f16 + - input: [4440, 1536] + - hidden: [4440, 4096] + """ + + NAME = "decomposed" + FORCE_BW_F32 = False + + def _silu_backward(dy, x): + # https://github.com/pytorch/pytorch/blob/563b065f5a4b4055fa6b025c2514b566d5fd9439/aten/src/ATen/native/Activation.cpp#L483 + sigm = 1 / (1 + torch.exp(-x.float())) + return (dy.float() * sigm * (1 + x.float() * (1 - sigm))).to(x.dtype) + + # 952us + @classmethod + def forward(cls, ctx, x, w1, b1, w2, b2, w3, b3): + x1 = x @ w1.transpose(-2, -1) + b1 # 275us + x2 = x @ w2.transpose(-2, -1) + b2 # 275us + x3 = F.silu(x1) # 62us + x4 = x3 * x2 # 90us + x5 = x4 @ w3.transpose(-2, -1) + b3 # 250us + + ctx.save_for_backward(x, w1, b1, w2, b2, w3, b3, x1, x2, x3, x4, x5) + return x5 + + # 1900us + @classmethod + def backward(cls, ctx, dx5): + saved_tensors = ctx.saved_tensors + if cls.FORCE_BW_F32: + dx5 = dx5.float() + saved_tensors = [t.float() for t in ctx.saved_tensors] + x, w1, b1, w2, b2, w3, b3, x1, x2, x3, x4, x5 = saved_tensors + dx4 = dx5 @ w3 # 255us (nn) + dw3 = dx5.transpose(-2, -1) @ x4 # 247us (nt) + db3 = dx5.sum(0) # 25us + dx3 = dx4 * x2 # 88us + dx2 = dx4 * x3 # 88us + dx1 = cls._silu_backward(dx3, x1) # 90us + dx = dx2 @ w2 # 260us (nn) + dw2 = dx2.transpose(-2, -1) @ x # 245us (nt) + db2 = dx2.sum(0) # 50us + dx += dx1 @ w1 # 260us (nn) + dw1 = dx1.transpose(-2, -1) @ x # 245us (nt) + db1 = dx1.sum(0) # 50us + return (dx, dw1, db1, dw2, db2, dw3, db3) + + +class _SwiGLUFusedFunc(torch.autograd.Function): + NAME = "fused.py" + + @classmethod + @custom_fwd(device_type="cuda") + def forward(cls, ctx, x, w1, b1, w2, b2, w3, b3): + x1, x2, x4 = DualGemmSiluOp.OPERATOR(x, w1, b1, w2, b2) + + x5 = F.linear(x4, w3, b3) + ctx.save_for_backward(x, w1, w2, w3, x1, x2) + ctx.bias = [b1 is not None, b2 is not None, b3 is not None] + return x5 + + @staticmethod + def _linear_bw( + dy: torch.Tensor, x: torch.Tensor, bias: bool + ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: + if not bias: + return (dy.transpose(-2, -1) @ x), None + dw, db = GemmFusedSumOp.OPERATOR(dy.transpose(-2, -1), x) + return dw, db + + @classmethod + @custom_bwd(device_type="cuda") + def backward(cls, ctx, dx5): + x, w1, w2, w3, x1, x2 = ctx.saved_tensors + w1w2 = stack_or_none([w1, w2], dim=0) + + dx4 = dx5 @ w3 # 255us (nn) + dx1dx2, x4 = torch.ops.xformers.silu_bw_fused(x1, x2, dx4) + dx1, dx2 = dx1dx2.unbind(1) + del x1, x2, dx4 + + dw3, db3 = cls._linear_bw(dx5, x4, bias=ctx.bias[2]) + del x4, dx5 + if w1w2 is not None: + assert dx1dx2.is_contiguous() + assert w1w2.is_contiguous() + w1w2 = w1w2.view([w1.shape[0] * 2, w1.shape[1]]) + dx = dx1dx2.view([dx1.shape[0], 2 * dx1.shape[1]]) @ w1w2 + + # backward of linear1 + linear2 - packed + dw1dw2 = dx1dx2.view([dx1.shape[0], 2 * dx1.shape[1]]).transpose(-2, -1) @ x + dw1dw2, db1db2 = cls._linear_bw( + dx1dx2.view([dx1.shape[0], 2 * dx1.shape[1]]), x, bias=ctx.bias[0] + ) + dw1, dw2 = dw1dw2.view([2, *w1.shape]).unbind(0) + if ctx.bias[0]: + db1db2 = db1db2.view([2, dx1.shape[1]]) + db1, db2 = torch.unbind(db1db2, dim=0) + else: + db1 = db2 = None + else: + dx = dx2 @ w2 # 260us (nn) + torch.addmm( + dx, dx1, w1.to(dx1.dtype), beta=1, alpha=1, out=dx + ) # dx += dx1 @ w1 + dw2, db2 = cls._linear_bw(dx2, x, bias=ctx.bias[1]) + dw1, db1 = cls._linear_bw(dx1, x, bias=ctx.bias[0]) + return (dx, dw1, db1, dw2, db2, dw3, db3) + + +class SwiGLUOp: + """Base class for any swiglu operator in :attr:`xformers.ops.swiglu`""" + + def __init__(self, op, packed_weights: bool, name: str, constraints): + self.NAME = name + self.PACKED_WEIGHTS = packed_weights + self.op = op + self.constraints = constraints + + def supports(self, op: "SwiGLUOpDispatch") -> bool: + if self.PACKED_WEIGHTS and not op.packed_weights: + return False + return all(c(op) for c in self.constraints) + + def __call__(self, *args: Optional[torch.Tensor]) -> torch.Tensor: + raise NotImplementedError() + + def __str__(self) -> str: + return f"SwiGLUOp:{self.NAME}" + + +class _ForwardToPythonAutogradFunc(SwiGLUOp): + def supports(self, op: "SwiGLUOpDispatch") -> bool: + return super().supports(op) + + def __call__(self, *args, **kwargs): + return self.op.apply(*args, **kwargs) + + +class _ForwardToFunc(SwiGLUOp): + def __call__(self, *args, **kwargs): + return self.op(*args, **kwargs) + + def info(self): + if self.op.__name__ == "no_such_operator": + return "not built" + return "available" + + +def _eager_functional_swiglu( + x: torch.Tensor, + w1: torch.Tensor, + b1: Optional[torch.Tensor], + w2: torch.Tensor, + b2: Optional[torch.Tensor], + w3: torch.Tensor, + b3: Optional[torch.Tensor], +) -> torch.Tensor: + x1 = F.linear(x, w1, b1) + x2 = F.linear(x, w2, b2) + hidden = F.silu(x1) * x2 + return F.linear(hidden, w3, b3) + + +@dataclass +class SwiGLUOpDispatch: + """Dispatcher to automatically select + the best operator in :attr:`xformers.ops.swiglu` + """ + + device: Union[torch.device, str] + dtype: torch.dtype + dtype_autocast_gpu: Optional[torch.dtype] + packed_weights: bool + bias_enabled: bool + + @property + def op(self) -> SwiGLUOp: + """Computes the best operator + + Returns: + SwiGLUOp: The best operator for the configuration + """ + priorities: Sequence[SwiGLUOp] = [ + SwiGLUPackedFusedOp, + SwiGLUFusedOp, + ] + for op in priorities: + if op.supports(self): + return op + return SwiGLUEagerOp + + @staticmethod + def from_arguments( + x: torch.Tensor, + w1: torch.Tensor, + b1: Optional[torch.Tensor], + w2: torch.Tensor, + b2: Optional[torch.Tensor], + w3: torch.Tensor, + b3: Optional[torch.Tensor], + ) -> "SwiGLUOpDispatch": + return SwiGLUOpDispatch( + device=x.device, + dtype=x.dtype, + packed_weights=stack_or_none((w1, w2), dim=0) is not None, + dtype_autocast_gpu=( + torch.get_autocast_gpu_dtype() + if torch.is_autocast_enabled() + else w1.dtype + ), + bias_enabled=b1 is not None and b2 is not None and b3 is not None, + ) + + +def _only_sm80(op: SwiGLUOpDispatch) -> bool: + device_type = op.device if isinstance(op.device, str) else op.device.type + return device_type == "cuda" and torch.cuda.get_device_capability(op.device)[0] >= 8 + + +def _only_half_or_autocast(op: SwiGLUOpDispatch) -> bool: + HALF_DTYPES = [torch.half, torch.bfloat16] + return op.dtype in HALF_DTYPES or ( + op.dtype_autocast_gpu is not None and op.dtype_autocast_gpu in HALF_DTYPES + ) + + +def _bias_enabled(op: SwiGLUOpDispatch) -> bool: + return op.bias_enabled + + +_SwiGLUDecomposedOp = _ForwardToPythonAutogradFunc( + _SwiGLUDecomposedFunc, False, "decomposed", constraints=[_bias_enabled] +) +SwiGLUFusedOp = _ForwardToPythonAutogradFunc( + _SwiGLUFusedFunc, False, "fused", constraints=[_only_sm80, _only_half_or_autocast] +) +SwiGLUPackedFusedOp = _ForwardToFunc( + get_xformers_operator("swiglu_packedw"), + True, + "fused.p.cpp", + constraints=[_only_sm80, _only_half_or_autocast], +) +SwiGLUEagerOp = _ForwardToFunc( + _eager_functional_swiglu, + False, + "eager", + constraints=[], +) + + +def _info() -> Dict[str, str]: + return {op.NAME: op.info() for op in [SwiGLUPackedFusedOp]} + + +def swiglu( + x: torch.Tensor, + w1: torch.Tensor, + b1: Optional[torch.Tensor], + w2: torch.Tensor, + b2: Optional[torch.Tensor], + w3: torch.Tensor, + b3: Optional[torch.Tensor], + *, + op: Optional[SwiGLUOp] = None, +) -> torch.Tensor: + """ + Computes a SwiGLU block given the weights/bias of the 3 + linear layers. + + - It is recommended to keep ``op=None`` so the best implementation \ + available for the inputs will be used. + + + :Equivalent pytorch code: + + .. code-block:: python + + x1 = F.linear(x, w1, b1) + x2 = F.linear(x, w2, b2) + hidden = F.silu(x1) * x2 + return F.linear(hidden, w3, b3) + + :Packing weights: + + To allow faster implementations, it's recommended to have w1/w2 come from the same storage, as in: + .. code-block:: python + + w1, w2 = xformers.ops.unbind(w12, 0) + + :Supported hardware: + + This operator is only optimized on A100+ on ``torch.half`` or ``torch.bfloat16`` \ + (autocast is supported), and will fallback to a functional pytorch \ + implementation otherwise. + """ + + batch_shape = x.shape[:-1] + x = x.reshape([-1, x.shape[-1]]) + if w1.ndim != 2 or w1.shape != w2.shape: + raise ValueError(f"Invalid shapes for w1: {w1.shape} / w2: {w2.shape}") + if b1 is not None: + if b1.ndim != 1 or b1.shape[0] != w1.shape[0]: + raise ValueError(f"Invalid shapes for b1: {b1.shape}") + if b2 is not None: + if b2.ndim != 1 or b2.shape[0] != w2.shape[0]: + raise ValueError(f"Invalid shapes for b2: {b2.shape}") + if w3.ndim != 2 or w3.shape[1] != w2.shape[0]: + raise ValueError(f"Invalid shape for w3: {w3.shape}") + if b3 is not None: + if b3.ndim != 1 or b3.shape[0] != w3.shape[0]: + raise ValueError(f"Invalid shapes for w3: {w3.shape} / b3: {b3.shape}") + + if op is None: + op = SwiGLUOpDispatch.from_arguments(x, w1, b1, w2, b2, w3, b3).op + + if not op.PACKED_WEIGHTS: + return op(x, w1, b1, w2, b2, w3, b3).reshape([*batch_shape, -1]) + w1w2 = stack_or_none((w1, w2), dim=0) + if b1 is not None and b2 is not None: + b1b2: Optional[torch.Tensor] = stack_or_none((b1, b2), dim=0) + if b1b2 is None: + raise NotImplementedError("b1/b2 needs to be properly packed") + else: + b1b2 = None + assert b1 is None and b2 is None + + if w1w2 is None: + raise NotImplementedError("w1/w2 needs to be properly packed") + return op(x, w1w2, b1b2, w3, b3).reshape([*batch_shape, -1]) + + +def swiglu_packed( + x: torch.Tensor, + w1w2: torch.Tensor, + b1b2: Optional[torch.Tensor], + w3: torch.Tensor, + b3: Optional[torch.Tensor], + *, + op: SwiGLUOp, +) -> torch.Tensor: + """ + Computes a SwiGLU block given the weights/bias of the 3 + linear layers. + + :Equivalent pytorch code: + + .. code-block:: python + + x1 = F.linear(x, w1, b1) + x2 = F.linear(x, w2, b2) + hidden = F.silu(x1) * x2 + return F.linear(hidden, w3, b3) + + :Supported hardware: + + This operator is only optimized on A100+ on ``torch.half`` or ``torch.bfloat16`` \ + (autocast is supported), and will fallback to a functional pytorch \ + implementation otherwise. + """ + batch_shape = x.shape[:-1] + x = x.reshape([-1, x.shape[-1]]) + + if b3 is not None: + if b3.ndim != 1 or b3.shape[0] != w3.shape[0]: + raise ValueError(f"Invalid shapes for w3: {w3.shape} / b3: {b3.shape}") + + assert op.PACKED_WEIGHTS, "Not implemented PACKED_WEIGHTS" + + return op(x, w1w2, b1b2, w3, b3).reshape([*batch_shape, -1]) + + +class SwiGLU(nn.Module): + """ + A Module that encapsulates the call to :attr:`xformers.ops.swiglu`, + and holds the weights for the 3 linear layers + """ + + def __init__( + self, + in_features: int, + hidden_features: int, + out_features: Optional[int] = None, + bias: bool = True, + *, + _pack_weights: bool = True, + ) -> None: + """Create a SwiGLU module + + Args: + in_features (int): Number of features of the input + hidden_features (int): Number of hidden features + out_features (Optional[int], optional): Number of features of the input. Defaults to None. + bias (bool, optional): Whether linear layers also include a bias. Defaults to True. + """ + super().__init__() + out_features = out_features or in_features + hidden_features = hidden_features or in_features + + self.w12: Optional[nn.Linear] + if _pack_weights: + self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias) + else: + self.w12 = None + self.w1 = nn.Linear(in_features, hidden_features, bias=bias) + self.w2 = nn.Linear(in_features, hidden_features, bias=bias) + self.w3 = nn.Linear(hidden_features, out_features, bias=bias) + + self.hidden_features = hidden_features + self.out_features = out_features + self.in_features = in_features + self.op: Optional[SwiGLUOp] = None + + def forward(self, x: torch.Tensor) -> torch.Tensor: + """Computes :attr:`swiglu` with the module's weights + + Args: + x (torch.Tensor): A Tensor of shape ``[..., in_features]`` + + Returns: + torch.Tensor: A Tensor of shape ``[..., out_features]`` + """ + if self.w12 is not None: + if self.op is not None: + assert ( + self.op.PACKED_WEIGHTS + ), "_pack_weights and self.op.PACKED_WEIGHTS should match" + return swiglu_packed(x, *self._packed_ordered_params(), op=self.op) + + return swiglu(x, *self._ordered_params(), op=self.op) + + def _ordered_params( + self, + ) -> Tuple[ + torch.Tensor, + Optional[torch.Tensor], + torch.Tensor, + Optional[torch.Tensor], + torch.Tensor, + Optional[torch.Tensor], + ]: + """Used for testing - returns ordered arguments for operators""" + b1: Optional[torch.Tensor] + b2: Optional[torch.Tensor] + if self.w12 is not None: + w1w2 = self.w12.weight + b1b2 = self.w12.bias + w1, w2 = unbind( + w1w2.view([2, w1w2.shape[0] // 2, w1w2.shape[1]]), + dim=0, + ) + if b1b2 is not None: + b1, b2 = unbind(b1b2.view([2, b1b2.shape[0] // 2]), dim=0) + else: + b1, b2 = None, None + else: + w1, w2 = self.w1.weight, self.w2.weight + b1, b2 = self.w1.bias, self.w2.bias + + return ( + w1, + b1, + w2, + b2, + self.w3.weight, + self.w3.bias, + ) + + def _packed_ordered_params( + self, + ) -> Tuple[ + torch.Tensor, + Optional[torch.Tensor], + torch.Tensor, + Optional[torch.Tensor], + ]: + assert self.w12 is not None, "Packed weights are only available when using w12" + + """Used for testing - returns ordered arguments for packed operators""" + w1w2 = self.w12.weight + b1b2_param = self.w12.bias + + w1w2 = w1w2.view([2, w1w2.shape[0] // 2, w1w2.shape[1]]) + + b1b2: Optional[torch.Tensor] = None + if b1b2_param is not None: + b1b2 = b1b2_param.view([2, b1b2_param.shape[0] // 2]) + + return ( + w1w2, + b1b2, + self.w3.weight, + self.w3.bias, + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/tiled_matmul.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/tiled_matmul.py new file mode 100644 index 0000000000000000000000000000000000000000..d3e77061248ba308c15ebcaead78af886e7191b0 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/tiled_matmul.py @@ -0,0 +1,318 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import os +from typing import List, Tuple + +import torch + +from .. import _is_triton_available + + +# Copied over from the sequence parallel fused ops. +def _should_use_triton(device: torch.device, dtype: torch.dtype) -> bool: + if not int(os.getenv("XFORMERS_TILED_MATMUL_ENABLE_TRITON", "1")): + return False + if not _is_triton_available(): + return False + device_capability = torch.cuda.get_device_capability(device) + # Triton seems to be having issues on P100 and V100 GPUs, such as + # https://github.com/openai/triton/issues/1609 + # https://github.com/openai/triton/issues/1610 + # https://github.com/openai/triton/issues/1257#issuecomment-1532616965 + # and, in recent Triton versions (Jan 2024), returning wrong values. + if device_capability < (8, 0): + return False + return True + + +def check_inputs( + a: List[List[torch.Tensor]], + b: List[List[torch.Tensor]], +) -> Tuple[List[int], List[int], List[int]]: + assert len(a) >= 1 and len(a[0]) >= 1 and all(len(row) == len(a[0]) for row in a), ( + "the first operand must be a non-empty two-dimensional regular list of lists " + "of tenors" + ) + assert len(b) >= 1 and len(b[0]) >= 1 and all(len(row) == len(b[0]) for row in b), ( + "the second operand must be a non-empty two-dimensional regular list of lists " + "of tenors" + ) + + m_tiles = len(a) + k_tiles = len(a[0]) + assert len(b) == k_tiles, ( + "the first operand's inner dimension must match the second operand's outer " + f"dimension, got {k_tiles} and {len(b)}" + ) + n_tiles = len(b[0]) + + ms = [a[tile_m][0].shape[0] for tile_m in range(m_tiles)] + ns = [b[0][tile_n].shape[1] for tile_n in range(n_tiles)] + aks = [a[0][tile_k].shape[1] for tile_k in range(k_tiles)] + bks = [b[tile_k][0].shape[0] for tile_k in range(k_tiles)] + + for tile_m in range(m_tiles): + for tile_k in range(k_tiles): + assert a[tile_m][tile_k].shape[0] == ms[tile_m], ( + f"the tensors on row {tile_m} of the first operand must all have the " + f"same size along the m dimension, got {ms[tile_m]} at position 0 and " + f"{a[tile_m][tile_k].shape[0]} at position {tile_k}" + ) + assert a[tile_m][tile_k].shape[1] == aks[tile_k], ( + f"the tensors on column {tile_k} of the first operand must all have " + f"the same size along the k dimension, got {aks[tile_k]} at position 0 " + f"and {a[tile_m][tile_k].shape[1]} at position {tile_m}" + ) + + for tile_n in range(n_tiles): + for tile_k in range(k_tiles): + assert b[tile_k][tile_n].shape[0] == bks[tile_k], ( + f"the tensors on row {tile_k} of the second operand must all have the " + f"same size along the k dimension, got {bks[tile_k]} at position 0 and " + f"{b[tile_k][tile_n].shape[0]} at position {tile_n}" + ) + assert b[tile_k][tile_n].shape[1] == ns[tile_n], ( + f"the tensors on column {tile_n} of the second operand must all have " + f"the same size along the n dimension, got {ns[tile_n]} at position 0 " + f"and {b[tile_k][tile_n].shape[1]} at position {tile_k}" + ) + + for tile_k in range(k_tiles): + assert aks[tile_k] == bks[tile_k], ( + f"the tensors on column {tile_k} of the first operand and those on row " + f"{tile_k} of the second operand must have the same size along the k " + f"dimension, got {aks[tile_k]} and {bks[tile_k]}" + ) + ks = aks + + return ms, ns, ks + + +def check_output(out: List[List[torch.Tensor]], ms: List[int], ns: List[int]) -> None: + m_tiles, n_tiles = len(ms), len(ns) + assert ( + len(out) >= 1 + and len(out[0]) >= 1 + and all(len(row) == len(out[0]) for row in out) + ), "out must be a non-empty two-dimensional regular list of lists of tenors" + assert len(out) == m_tiles + assert len(out[0]) == n_tiles + cms = [out[tile_m][0].shape[0] for tile_m in range(m_tiles)] + cns = [out[0][tile_n].shape[1] for tile_n in range(n_tiles)] + for tile_m in range(m_tiles): + for tile_n in range(n_tiles): + assert out[tile_m][tile_n].shape[0] == cms[tile_m], ( + f"the tensors on row {tile_m} of out must all have the same size " + f"along the m dimension, got {cms[tile_m]} at position 0 and " + f"{out[tile_m][tile_n].shape[0]} at position {tile_n}" + ) + assert out[tile_m][tile_n].shape[1] == cns[tile_n], ( + f"the tensors on column {tile_n} of out must all have the same " + f"size along the k dimension, got {cns[tile_n]} at position 0 and " + f"{out[tile_m][tile_n].shape[1]} at position {tile_m}" + ) + for tile_m in range(m_tiles): + assert cms[tile_m] == ms[tile_m], ( + f"the tensors on row {tile_m} of out and those on row {tile_m} of the " + f"first operand must have the same size along the m dimension, got " + f"{cms[tile_m]} and {ms[tile_m]}" + ) + for tile_n in range(n_tiles): + assert cns[tile_n] == ns[tile_n], ( + f"the tensors on column {tile_n} of out and those on column {tile_n} " + f"of the second operand must have the same size along the n dimension, " + f"got {cns[tile_n]} and {ns[tile_n]}" + ) + + +# Using out= args in PyTorch is complicated, especially with custom_ops and +# torch.compile (we need to declare our side-effects with mutates_args, which +# then requires a functionalization step, ...). Thus this out= variant of the +# operator is exposed as a PLAIN PYTHON function, and is not compilable nor +# differentiable. It needs to be invoked from within a custom_op elsewhere. +def tiled_matmul_out( + a: List[List[torch.Tensor]], + b: List[List[torch.Tensor]], + out: List[List[torch.Tensor]], +) -> None: + ms, ns, ks = check_inputs(a, b) + check_output(out, ms, ns) + + # TODO We can try merging tiles that come from contiguous memory, using + # stack_or_none, to further improve performance. + + # Because the Triton kernel is hardcoded for maximum three tiles. + # Because, in turn, we aimed this at the fusion of wq/wk/wv. + if ( + len(ms) <= 3 + and len(ks) <= 3 + and len(ns) <= 3 + and _should_use_triton(a[0][0].device, a[0][0].dtype) + ): + from ._triton.tiled_matmul_kernels import _launch_triton_matmul + + _launch_triton_matmul(a, b, out, ms, ns, ks) + else: + for tile_m in range(len(ms)): + for tile_n in range(len(ns)): + torch.mm(a[tile_m][0], b[0][tile_n], out=out[tile_m][tile_n]) + for tile_k in range(1, len(ks)): + out[tile_m][tile_n].addmm_(a[tile_m][tile_k], b[tile_k][tile_n]) + + +def _flatten(x: List[List[torch.Tensor]], rows: int, cols: int) -> List[torch.Tensor]: + assert len(x) == rows + assert all(len(row) == cols for row in x) + flat_x = [elem for row in x for elem in row] + assert len(flat_x) == rows * cols + return flat_x + + +def _unflatten( + flat_x: List[torch.Tensor], rows: int, cols: int +) -> List[List[torch.Tensor]]: + assert len(flat_x) == cols * rows + x = [ + flat_x[row_offset : row_offset + cols] + for row_offset in range(0, rows * cols, cols) + ] + assert len(x) == rows + assert all(len(row) == cols for row in x) + return x + + +def _flattened_transpose( + flat_x: List[torch.Tensor], rows: int, cols: int +) -> List[torch.Tensor]: + x = _unflatten(flat_x, rows, cols) + transposed_x = [[elem.t() for elem in col] for col in zip(*x)] + flat_transposed_x = _flatten(transposed_x, cols, rows) + return flat_transposed_x + + +# PyTorch (custom_op and torch.compile, but also the dispatcher in general) +# have a hard time with Tensor[][] args. Thus we flatten them into Tensor[] to +# pass them into and out of this operator. +# See: https://github.com/pytorch/pytorch/issues/113022 +@torch.library.custom_op( + "xformers_python::tiled_matmul_fwd", + mutates_args=(), + device_types="cuda", +) +def tiled_matmul_fwd( + flat_a: List[torch.Tensor], + flat_b: List[torch.Tensor], + ms: List[int], + ns: List[int], + ks: List[int], +) -> List[torch.Tensor]: + a = _unflatten(flat_a, len(ms), len(ks)) + b = _unflatten(flat_b, len(ks), len(ns)) + + c = [[a[0][0].new_empty((m, n)) for n in ns] for m in ms] + tiled_matmul_out(a, b, out=c) + + return _flatten(c, len(ms), len(ns)) + + +@torch.library.register_fake("xformers_python::tiled_matmul_fwd") +def tiled_matmul_fwd_fake( + flat_a: List[torch.Tensor], + flat_b: List[torch.Tensor], + ms: List[int], + ns: List[int], + ks: List[int], +) -> List[torch.Tensor]: + c = [[flat_a[0][0].new_empty((m, n)) for n in ns] for m in ms] + return _flatten(c, len(ms), len(ks)) + + +def tiled_matmul_setup_context(ctx, inputs, output): + flat_a, flat_b, ctx.ms, ctx.ns, ctx.ks = inputs + ctx.save_for_backward(*flat_a, *flat_b) + + +def tiled_matmul_bwd(ctx, flat_grad_c): + assert len(ctx.saved_tensors) == len(ctx.ms) * len(ctx.ks) + len(ctx.ks) * len( + ctx.ns + ) + flat_a = ctx.saved_tensors[: len(ctx.ms) * len(ctx.ks)] + flat_b = ctx.saved_tensors[-len(ctx.ks) * len(ctx.ns) :] + + flat_transposed_a = _flattened_transpose(flat_a, len(ctx.ms), len(ctx.ks)) + flat_transposed_b = _flattened_transpose(flat_b, len(ctx.ks), len(ctx.ns)) + + flat_grad_a = tiled_matmul_fwd( + flat_grad_c, flat_transposed_b, ctx.ms, ctx.ks, ctx.ns + ) + flat_grad_b = tiled_matmul_fwd( + flat_transposed_a, flat_grad_c, ctx.ks, ctx.ns, ctx.ms + ) + + return flat_grad_a, flat_grad_b, None, None, None + + +torch.library.register_autograd( + "xformers_python::tiled_matmul_fwd", + tiled_matmul_bwd, + setup_context=tiled_matmul_setup_context, +) + + +def tiled_matmul( + a: List[List[torch.Tensor]], + b: List[List[torch.Tensor]], +) -> List[List[torch.Tensor]]: + """Multiply two matrices given as grids of tiles + + It performs the matmul between A and B, which are given as two-dimensional + grids of tiles (i.e., blocks), represented as lists of lists of tensors. + The output will itself be a matrix in such a form. Formally: + + out[m][n] = sum(a[m][k] @ b[k][n] for k in range(...)) + + with the obvious constraints needed to make it work, in terms of number of + tiles and sizes of each tile. + + The interest of this operator is to improve performance by avoding wave + quantization effects when doing independent matrix multiplications in + series. Sometimes, when these matmuls have one operand in common, this can + also be addressed by concatenating the other operands into a single matrix, + and issuing a single matmul. However this isn't always possible (e.g., might + break the checkpoint format) and it's an anti-pattern, as it obscures the + logic (e.g., changing the modelling code out of performance reasons). This + tiled matmul performs the same computation as if the matrices were merged, + without merging them, simply through a smarter memory addressing scheme. + + The tiled matmul is less generic than a grouped matmul, which can also help + with wave quantization, and doesn't need the matmuls to have the same lhs + or rhs operand. However, a grouped matmul will write the result of each + matmul to a separate output matrix, whereas the tiled matmul allows to add + them together into a single output. This is needed during the backward pass + of a linear layer, and it's the reason we wrote this instead of using a + grouped matmul. + + The tiled matmul is implemented using a custom Triton kernel, which puts + constraints on the strides of the tiles. All rows of A must have the same + K stride, all columns of A must have the same M stride, and so on. + + Currently the tiled matmul supports at most three tiles on each dimension, + although fewer can also be given. This is because we needed it to fuse the + query, key and value weights of an attention layer. This limit can be + increased if needed. + + This operator is differentiable. + + """ + # Inputs are checked inside the op, but we check them as well to make sure + # that they are "regular" and can be flattened. + ms, ns, ks = check_inputs(a, b) + flat_a = _flatten(a, len(ms), len(ks)) + flat_b = _flatten(b, len(ks), len(ns)) + flat_c = tiled_matmul_fwd(flat_a, flat_b, ms, ns, ks) + c = _unflatten(flat_c, len(ms), len(ns)) + return c diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/tree_attention.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/tree_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..35635754a9453cb6122baa842a013e2a0ec4096e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/tree_attention.py @@ -0,0 +1,695 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import itertools +from dataclasses import dataclass +from functools import lru_cache +from typing import List, Optional, Sequence, Tuple, Type + +import torch + +from xformers.ops import fmha + +from .fmha import ( + flash, + flash3, + memory_efficient_attention_forward_requires_grad, + memory_efficient_attention_partial, + merge_attentions, + triton_splitk, +) +from .fmha.attn_bias import ( + AttentionBias, + PagedBlockDiagonalGappyKeysMask, + PagedBlockDiagonalPaddedKeysMask, +) +from .fmha.common import AttentionFwOpBase +from .fmha.dispatch import _get_use_fa3, fa3_available + + +@dataclass +class TreeAttnMetadata: + """ + tree_choices: definition of the tree, tuples sorted by length, each corresponding + to a node. See the docstring of TreeAttnMetadata.from_tree_choices. + attention_bias: Medusa-style tree attention bias as an explicit tensor + of shape (tree_size, tree_size), where tree_size is the total number + of nodes in the tree. It can be used as a spec_attn_bias ("right" + or "suffix" attention part) in tree_attention. + See tree_attention_with_sync for a usage example. + tree_indices: 1D tensor of size tree_size which maps tree nodes to draft tokens. + Tree nodes are assumed to be in the same order as in tree_choices + (see TreeAttnMetadata.from_tree_choices). + retrieval_indices: a tensor of shape (number of leaves, depth + 1), where one + row corresponds to one path, and contains indices of the tree nodes + on that path. Paths are padded with -1 from the right. + The paths (row dim) are unsorted. + path_lengths: real lengths for each of the paths. + tree_seq_position_ids: 1D tensor of size tree_size which indicates which head + a node belongs to. Equivalently, it shows the sequence position of the + node within the corresponding path. + parent_node_indices: 1D tensor of size tree_size which for each node contains + position of its parent + 1. For root node(s) it contains 0. + child_node_indices: a tensor of shape (tree_size, max_num_children_per_node), + in which each row contains indices of children of the corresponding node. + Rows corresponding to nodes which have less than max_num_children_per_node + children are padded by repeating the last child index. + For leaf nodes the values are meaningless and filled with 0. + num_children_per_node: 1D tensor of size tree_size which contains the number of + children for each node. + candidate_idx: 1D tensor of size tree_size, contains index of each node among its "siblings". + Takes values from 0 to the number of children of the parent node minus 1. + num_nodes_per_level: 1D tensor of the number of nodes at each level (including root). + num_children_per_node_at_level: List of 1D tensors, each containing the number of children at the tree level. + subtree_size: List of integers, each containing the number of nodes in the subtree at the tree level. + Example: + Tree choices + `[(0,), (0, 0), (0, 1), (0, 2), (1,), (1, 0), (1, 1), (1, 2), (2,), (2, 0), (2, 1), (2, 2)]` + represents a tree that looks like this: + 0 + |-- 1 + | |-- 4 + | |-- 5 + | |-- 6 + | + |-- 2 + | |-- 7 + | |-- 8 + | |-- 9 + | + |-- 3 + |-- 10 + |-- 11 + |-- 12 + + with TreeAttnMetadata + tree_indices=tensor([0, 1, 2, 3, 4, 5, 6, 4, 5, 6, 4, 5, 6]) + retrieval_indices=tensor([[ 0, 1, 5], + [ 0, 2, 9], + [ 0, 3, 11], + [ 0, 1, 4], + [ 0, 2, 8], + [ 0, 3, 10], + [ 0, 1, 6], + [ 0, 2, 7], + [ 0, 3, 12]]) + path_lengths=[3, 3, 3, 3, 3, 3, 3, 3, 3] + tree_seq_position_ids=tensor([0, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2]) + child_node_indices=tensor([[ 0, 1, 2], + [ 3, 4, 5], + [ 6, 7, 8], + [ 9, 10, 11], + [ 0, 0, 0], + ... + [ 0, 0, 0]]) + num_children_per_node=tensor([3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0]) + candidate_idx=tensor([0, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]) + num_nodes_per_level=tensor([1, 3, 3]) + num_children_per_node_at_level=[tensor([3]), tensor([3, 3, 3]), tensor([0, 0, 0, 0, 0, 0, 0, 0, 0])] + subtree_sizes=[1, 4, 13] + """ + + tree_choices: Sequence[Tuple[int, ...]] + attention_bias: torch.Tensor + tree_indices: torch.Tensor + retrieval_indices: torch.Tensor + path_lengths: List[int] + tree_seq_position_ids: torch.Tensor + parent_node_indices: torch.Tensor + child_node_indices: torch.Tensor + num_children_per_node: torch.Tensor + candidate_idx: torch.Tensor + num_nodes_per_level: torch.Tensor + num_nodes_per_level_cpu: torch.Tensor + num_children_per_node_at_level: List[torch.Tensor] + num_children_per_node_at_level_cpu: List[torch.Tensor] + subtree_sizes: List[int] + + @classmethod + @lru_cache + def from_tree_choices_cached( + cls, + tree_choices: Tuple[Tuple[int, ...]], + dtype: Optional[torch.dtype] = None, + device: Optional[torch.device] = None, + ) -> "TreeAttnMetadata": + return cls.from_tree_choices(tree_choices, dtype, device) + + @classmethod + def from_tree_choices( + cls, + tree_choices: Sequence[Tuple[int, ...]], + dtype: Optional[torch.dtype] = None, + device: Optional[torch.device] = None, + ) -> "TreeAttnMetadata": + """ + Args: + tree_choices: tree description in the style of + https://github.com/FasterDecoding/Medusa/blob/5e9805386/medusa/model/medusa_choices.py + A typical tree description would look like: + [(node0, node1, ...), (node0, node2), (node0, node3), (node1, node3), ..., (node0, node2, ..., nodeN)] + Every tuple is corresponds to one node in the tree, encoded as a path from one of the root nodes to the + node in question. + For example, a node encoded as (1, 0, 3, ..., 2) is understood as: + list all the root nodes and take node number 1 + list all children of that node and take node number 0 + list all children of that node and take node number 3 + ... + list all children of that node and take node number 2 - that's the node encoded by this tuple. + + dtype: data type of the output mask tensor. + device: device of the output tensors. + Returns: + TreeAttnMetadata object with all the fields. + """ + # from https://github.com/SafeAILab/EAGLE/blob/e98fc7c/model/utils.py#L89C1-L117C1 + sorted_tree_choices = sorted(tree_choices, key=lambda x: (len(x), x)) + tree_len = len(sorted_tree_choices) + 1 + + depth_counts = _get_depth_counts(sorted_tree_choices) + tree_indices = _prepare_tree_indices(sorted_tree_choices, depth_counts, device) + retrieval_indices, path_lengths = _prepare_retrieval_indices( + sorted_tree_choices, device + ) + tree_seq_position_ids = _prepare_tree_position_ids( + depth_counts, tree_len, device + ) + tree_attn_mask = _prepare_tree_attn_bias( + sorted_tree_choices, depth_counts, dtype, device + ) + parent_node_indices = _prepare_parent_node_indices(sorted_tree_choices, device) + child_node_indices, num_children_per_node = _prepare_child_node_indices( + sorted_tree_choices, device + ) + candidate_idx = _prepare_candidate_idx(sorted_tree_choices, device) + + num_nodes_per_level = _get_num_nodes_per_level(depth_counts, device) + num_nodes_per_level_cpu = num_nodes_per_level.cpu() + ( + subtree_sizes, + num_children_per_node_at_level, + ) = _get_subtree_size_and_num_children_per_node_at_level( + num_nodes_per_level, num_children_per_node, device + ) + num_children_per_node_at_level_cpu = [ + row.cpu() for row in num_children_per_node_at_level + ] + return TreeAttnMetadata( + sorted_tree_choices, + tree_attn_mask, + tree_indices, + retrieval_indices, + path_lengths, + tree_seq_position_ids, + parent_node_indices, + child_node_indices, + num_children_per_node, + candidate_idx, + num_nodes_per_level, + num_nodes_per_level_cpu, + num_children_per_node_at_level, + num_children_per_node_at_level_cpu, + subtree_sizes, + ) + + +def _get_subtree_size_and_num_children_per_node_at_level( + num_nodes_per_level: torch.Tensor, + num_children_per_node: torch.Tensor, + device: Optional[torch.device] = None, +) -> Tuple[List[int], List[torch.Tensor]]: + depth: int = len(num_nodes_per_level) + subtree_sizes: List[int] = [ + 1, + ] + num_children_per_node_at_level: List[torch.Tensor] = [ + num_children_per_node[0].unsqueeze(0) + ] + for i in range(1, depth): + subtree_sizes.append(int(torch.sum(num_nodes_per_level[: (i + 1)]))) + num_children_per_node_at_level.append( + num_children_per_node[subtree_sizes[i - 1] : subtree_sizes[i]] + ) + return subtree_sizes, num_children_per_node_at_level + + +def _get_depth_counts(sorted_tree_choices: List[Tuple[int, ...]]) -> List[int]: + # Initialize depth_counts to keep track of how many choices have a particular depth + depth_counts = [] + prev_depth = 0 + for path in sorted_tree_choices: + depth = len(path) + if depth != prev_depth: + depth_counts.append(0) + depth_counts[depth - 1] += 1 + prev_depth = depth + return depth_counts + + +def _get_num_nodes_per_level( + depth_counts: List[int], device: Optional[torch.device] +) -> torch.Tensor: + depth_counts_tensor: torch.Tensor = torch.tensor([1] + depth_counts, device=device) + return depth_counts_tensor[depth_counts_tensor != 0] + + +def _prepare_tree_attn_bias( + sorted_tree_choices: List[Tuple[int, ...]], + depth_counts: List[int], + dtype: Optional[torch.dtype], + device: Optional[torch.device], +) -> torch.Tensor: + """ + Construct a Medusa-style tree attention bias as an explicit tensor. + It can be used as a spec_attn_bias ("right" or "suffix" attention part) + in tree_attention. See run_tree_attention_inner in test for a usage example. + Args: + sorted_tree_choices: tree description in the style of + https://github.com/FasterDecoding/Medusa/blob/5e9805386/medusa/model/medusa_choices.py + A typical tree description would look like: + [(node0, node1, ...), (node0, node2), (node0, node3), (node1, node3), ..., (node0, node2, ..., nodeN)] + Every tuple is corresponds to one node in the tree, encoded as a path from one of the root nodes to the + node in question. Passed in sorted order. + For example, a node encoded as (1, 0, 3, ..., 2) is understood as: + list all the root nodes and take node number 1 + list all children of that node and take node number 0 + list all children of that node and take node number 3 + ... + list all children of that node and take node number 2 - that's the node encoded by this tuple + depth_counts: a list of integers, where the i-th element is the number of choices with depth i. + dtype: data type of the output tensor. + device: device of the output tensor. + Returns: + attention bias of shape (tree_size, tree_size), + where tree_size is the total number of nodes in the tree. + """ + # +1 comes from the addtional root node + tree_len = len(sorted_tree_choices) + 1 + tree_attn_mask = torch.full( + (tree_len, tree_len), -torch.inf, device=device, dtype=dtype + ) + + mask_val = 0 + for i in range(tree_len): + tree_attn_mask[i, i] = mask_val + + tree_attn_mask[:, 0] = mask_val + start = 0 + for i in range(len(depth_counts)): + for j in range(depth_counts[i]): + cur_tree_choice = sorted_tree_choices[start + j] + # retrieve ancestor position + if len(cur_tree_choice) == 1: + continue + ancestor_idx = [] + for c in range(len(cur_tree_choice) - 1): + ancestor_idx.append( + sorted_tree_choices.index(cur_tree_choice[: c + 1]) + 1 + ) + tree_attn_mask[j + start + 1, ancestor_idx] = mask_val + start += depth_counts[i] + return tree_attn_mask + + +def _prepare_tree_indices( + sorted_tree_choices: List[Tuple[int, ...]], + depth_counts: List[int], + device: Optional[torch.device], +) -> torch.Tensor: + """ + Construct an index tensor for choices in the tree and their corresponding index in the draft tokens. + Args: + sorted_tree_choices: sorted from tree_choices input of prepare_tree_attn_metadata function + depth_counts: a list of integers, where the i-th element is the number of choices with depth i. + device: device of the output tensor. + Returns: + tree indices of shape (tree_len,). See docstring of TreeAttnMetadata for details. + """ + # Generate tree indices for the tree_choices structure + # add root node from main head prediction to the tree_len + tree_len = len(sorted_tree_choices) + 1 + tree_indices = torch.zeros(tree_len, device=device, dtype=torch.long) + tree_indices[0] = 0 + start, max_idx_prev_level = 0, 0 + for i in range(len(depth_counts)): + cur_offset = max_idx_prev_level + for j in range(depth_counts[i]): + cur_tree_choice = sorted_tree_choices[start + j] + tree_idx = cur_tree_choice[-1] + cur_offset + 1 + tree_indices[start + j + 1] = tree_idx + max_idx_prev_level = max(tree_idx, max_idx_prev_level) + start += depth_counts[i] + return tree_indices + + +def _prepare_retrieval_indices( + tree_choices: List[Tuple[int, ...]], device: Optional[torch.device] +) -> Tuple[torch.Tensor, List[int]]: + """ + Convert tree definition from the format used by Medusa and EAGLE (tree_choices, see docstring of + TreeAttnMetadata.from_tree_choices) to a list of paths: + [ + (node_index0_path0, node_index1_path0, ...), + (node_index0_path1, node_index1_path1, ...), + ... + ] + where each value is an index of a node inside the corresponding level of a tree. + Returns: + retrieval indices of shape (number of leaves, depth + 1) + length of each path. + """ + tree_depth = max(len(node) for node in tree_choices) + 1 if tree_choices else 1 + + leaves = set(tree_choices) + + for node in tree_choices[::-1]: + if node[:-1] in leaves: + leaves.remove(node[:-1]) + + paths, path_lengths = [], [] + for leaf in leaves: + path = [0] + [ + tree_choices.index(leaf[:level]) + 1 for level in range(1, len(leaf) + 1) + ] + path_lengths.append(len(path)) + paths.append(path + [-1] * (tree_depth - len(path))) + paths_tensor = torch.tensor(paths, dtype=torch.long, device=device) + return paths_tensor, path_lengths + + +def _prepare_tree_position_ids( + depth_counts: List[int], tree_len: int, device: Optional[torch.device] +) -> torch.Tensor: + """ + Construct sequence position of each node within its path, can be used for positional embedding. + Args: + depth_counts: number of nodes at each of the levels of the tree. + tree_len: total number of nodes in the tree including the root. + device: device of the output tensor. + Returns: + tree position ids of shape (tree_len,). See docstring of TreeAttnMetadata for details. + """ + tree_position_ids = torch.zeros(tree_len, dtype=torch.int32, device=device) + start = 0 + for i in range(len(depth_counts)): + tree_position_ids[start + 1 : start + depth_counts[i] + 1] = i + 1 + start += depth_counts[i] + + return tree_position_ids + + +def _prepare_parent_node_indices( + sorted_tree_choices: List[Tuple[int, ...]], device: Optional[torch.device] +) -> torch.Tensor: + ancestor_idx = [] + for cur_medusa_choice in sorted_tree_choices: + try: + ancestor_idx.append(sorted_tree_choices.index(cur_medusa_choice[:-1]) + 1) + except ValueError: + ancestor_idx.append(0) + return torch.tensor(ancestor_idx, dtype=torch.long, device=device) + + +def _prepare_child_node_indices( + tree_choices: List[Tuple[int, ...]], device: Optional[torch.device] +) -> Tuple[torch.Tensor, torch.Tensor]: + res = [] + num_children_per_node = [] + for x in [()] + tree_choices: + curr_children = [ + i + for i, y in enumerate(tree_choices) + if len(x) + 1 == len(y) and y[:-1] == x + ] + num_children_per_node.append(len(curr_children)) + if curr_children: + res.append(curr_children) + else: + res.append([0]) + + # pad all children lists by repeating the last element + max_num_children = max(len(x) for x in res) + res = [x + x[-1:] * (max_num_children - len(x)) for x in res] + + # Check that all nodes have the same number of children. + assert all(len(x) == len(res[0]) for x in res) + return ( + torch.tensor(res, dtype=torch.long, device=device), + torch.tensor(num_children_per_node, dtype=torch.long, device=device), + ) + + +def _prepare_candidate_idx( + tree_choices: List[Tuple[int, ...]], device: Optional[torch.device] +) -> torch.Tensor: + candidate_idx = [ + sum( + curr_node[:-1] == another_node[:-1] + for another_node in tree_choices[:curr_node_idx] + ) + for curr_node_idx, curr_node in enumerate(tree_choices) + ] + return torch.tensor(candidate_idx, dtype=torch.long, device=device) + + +def use_triton_splitk_for_prefix(B: int, G: int, tree_size: int) -> bool: + """ + Heuristic to decide whether to use Triton Split-k or default (Flash Attention) for prefix attention. + """ + return ( + (B * G <= 128 and tree_size <= 64) + or (B * G < 4 and tree_size < 100) + or B * G < 2 + ) + + +def select_prefix_op( + B: int, + G: int, + tree_size: int, + autotune: bool, + attn_bias: AttentionBias, + kv_cache_dtype: torch.dtype, +) -> Optional[Type[AttentionFwOpBase]]: + """ + Heuristic to decide whether to use Triton Split-k or default (Flash Attention) for prefix attention. + """ + triton_splitk_op = SplitKAutotune if autotune else triton_splitk.FwOp + if torch.version.hip: + # TODO: further tune heuristics once CK splitK is ready + return triton_splitk_op + + # Triton Split-k is not present in the dispatcher list for some shapes. + # However, we need to dispatch to it if no other op is available. + # FA3 splitKV doesn't yet support gappy or paged biases. + fa3_splitkv_supported = isinstance( + attn_bias, flash3.FwOp_KVSplit.SUPPORTED_ATTN_BIAS_TYPES # type: ignore + ) + fa3_supported = isinstance(attn_bias, flash3.FwOp.SUPPORTED_ATTN_BIAS_TYPES) # type: ignore + flash2_supported = isinstance(attn_bias, flash.FwOp.SUPPORTED_ATTN_BIAS_TYPES) # type: ignore + if not (fa3_splitkv_supported or fa3_supported or flash2_supported): + return triton_splitk_op + + assert torch.version.cuda + use_fa3 = _get_use_fa3() and fa3_available() + # override heuristics for quantized kv cache for decode + if kv_cache_dtype == torch.uint8: + return triton_splitk_op + # select FA3 when bs >= 64 + if B >= 64 and use_fa3: + if fa3_splitkv_supported: + return flash3.FwOp_KVSplit + return flash3.FwOp + elif use_triton_splitk_for_prefix(B, G, tree_size): + return triton_splitk_op + else: + # use default heuristics from xformers + return None + + +def tree_attention( + q: torch.Tensor, + spec_k: torch.Tensor, + spec_v: torch.Tensor, + cache_k: torch.Tensor, + cache_v: torch.Tensor, + spec_attn_bias: torch.Tensor, + prefix_attn_bias: AttentionBias, + prefix_op: Optional[Type[AttentionFwOpBase]] = None, + suffix_op: Optional[Type[AttentionFwOpBase]] = None, + autotune: bool = False, + quantized_kv_scales: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, +) -> torch.Tensor: + """ + Compute Medusa/EAGLE/Hydra-style tree attention. + Notice that this function takes as arguments biases for the left (prefix) + and right (speculative suffix) parts of the attention. + This way we avoid creating these biases on the fly, and + allow this function to be used in performance-critical decoding + jobs, including in CUDA graph mode. In the latter case one should + construct the biases once, and update prefix_attn_bias with + current seqlens before every graph replay; spec_attn_bias stays static, + as it's determined by the tree structure. + Args: + q: query from speculative tokens, of shape (B, tree_size_q, (G), H, D) + spec_k, spec_v: keys/values from speculative tokens, each of shape (B, tree_size_kv, (G), H, D). + If tree_size_q < tree_size_kv, we assume the end of the query sequence aligns with end the k/v sequence, + like in "from-bottom-right" attention masks. Such rectangular attention masks can be used when we are + adding new nodes to the tree, and want to avoid recomputing attention for the existing nodes. For example, + this can be used during draft token generation in EAGLE. + cache_k/cache_v: queries/keys/values from the existing context, each of shape (B, Mk, (G), H, D) + spec_attn_bias: attention bias of the "right" part of the attention (tree_size_q x spec tokens). + This would typically be a an explicit tensor mask, precomputed once and not changing during decoding + prefix_attn_bias: attention bias of the "left" part of the attention (tree_size_q x existing context). + This bias would typically be block-diagonal padded non-causal (BlockDiagonalPaddedKeysMask), and it + changes at every decoding step as K/V sequence lengths grow during decoding. + prefix_op: attention backend which will be passed to memory_efficient_attention to compute prefix attention. + If None, will use Triton Split-K or Flash Attention depending on the heuristics. + suffix_op: same as prefix_op, but for the suffix. + autotune: If True, Triton Split-K will use autotuning when chosen + as a default backend for prefix/suffix attention. + Returns: + attention output of shape (B, tree_size_q, (G), H, D) + + :Usage example: + + See also tree_attention_with_sync in tests/test_tree_attention.py + + .. code-block:: python + + # Create an attention bias for the prefix part of the attention + prefix_attn_bias = BlockDiagonalPaddedKeysMask.from_seqlens( + q_seqlen=[tree_size_q for _ in range(B)], kv_seqlen=kv_lens, kv_padding=Mk + ) + # Create an explit attention bias for the speculative part of the attention + spec_attn_bias = TreeAttnMetadata.from_tree_choices(tree_choices, q.dtype, q.device).attention_bias + attn_output = tree_attention( + q, spec_k, spec_v, cache_k, cache_v, spec_attn_bias, prefix_attn_bias + ) + """ + + is_bmhk = q.ndim == 4 + if is_bmhk: + q = q.unsqueeze(2) + spec_k, spec_v = spec_k.unsqueeze(2), spec_v.unsqueeze(2) + cache_k, cache_v = cache_k.unsqueeze(2), cache_v.unsqueeze(2) + + B, tree_size_q, G, H, D = q.shape + Bkv, Mk, G1, H1, D1 = cache_k.shape + tree_size_q1, tree_size_kv = spec_attn_bias.shape + if isinstance( + prefix_attn_bias, + (PagedBlockDiagonalPaddedKeysMask, PagedBlockDiagonalGappyKeysMask), + ): + assert Bkv == 1 + else: + assert Bkv == B + + assert H == H1 and D == D1 and G == G1 + assert cache_k.shape == cache_v.shape + assert ( + tree_size_q1 == tree_size_q <= tree_size_kv + ), f"{tree_size_q1=} {tree_size_q=} {tree_size_kv=}" + assert ( + q.shape[2:] == spec_k.shape[2:] == spec_v.shape[2:] + ), f"{q.shape=} {spec_k.shape=} {spec_v.shape=}" + + spec_attn_bias = spec_attn_bias.expand(B, G, H, tree_size_q, tree_size_kv) + + triton_splitk_op = SplitKAutotune if autotune else triton_splitk.FwOp + + # TODO: improve this heuristic + if prefix_op is None: + prefix_op = select_prefix_op( + B, G, tree_size_kv, autotune, prefix_attn_bias, cache_k.dtype + ) + if cache_k.dtype == torch.uint8: + assert quantized_kv_scales is not None + assert prefix_op is triton_splitk.FwOp + fp8_inp = triton_splitk.InputsFp8( + query=q.view(1, B * tree_size_q, G, H, D), + key=cache_k.view(1, Bkv * Mk, G, H, D).view(torch.int32), + value=cache_v.view(1, Bkv * Mk, G, H, D).view(torch.int32), + attn_bias=prefix_attn_bias, + k_fp8_scale_shift=quantized_kv_scales[0].view(1, Bkv * Mk, G, H), + v_fp8_scale_shift=quantized_kv_scales[1].view(1, Bkv * Mk, G, H), + is_partial=True, + ) + out, ctx = fmha._memory_efficient_attention_forward_requires_grad( + fp8_inp, + op=prefix_op, + ) + attn_prefix, lse_prefix = out, ctx.lse + else: + attn_prefix, lse_prefix = memory_efficient_attention_partial( + q.view(1, B * tree_size_q, G, H, D), + cache_k.view(1, Bkv * Mk, G, H, D), + cache_v.view(1, Bkv * Mk, G, H, D), + attn_bias=prefix_attn_bias, + op=prefix_op, + ) + attn_prefix = attn_prefix.view(B, tree_size_q, G, H, D) + lse_prefix = lse_prefix.view(G, H, B, tree_size_q).permute(2, 0, 1, 3) + + # attn_suffix ~ (B, tree_size_q, G, H, D) + # lse_suffix ~ (B, G, H, tree_size_q) + attn_suffix, lse_suffix = memory_efficient_attention_forward_requires_grad( + q, + spec_k, + spec_v, + attn_bias=spec_attn_bias, + op=suffix_op or triton_splitk_op, + ) + + # attn_output ~ [B, tree_size_q, G, H, D] + # attn input [B, M, G, H, Kq] + # lse input [B, G, H, M] + attn_output, _ = merge_attentions( + [attn_prefix, attn_suffix], + [lse_prefix, lse_suffix], + output_dtype=q.dtype, + ) + + if is_bmhk: + attn_output = attn_output.squeeze(2) + return attn_output + + +class SplitKAutotune(triton_splitk.FwOp): + AUTOTUNE = True + + +@lru_cache +def construct_full_tree_choices( + tree_depth: int, branching: int +) -> List[Tuple[int, ...]]: + """ + Construct a full tree of a given depth where each node (except for leaves) has a given number of children. + The format is compatible with that used by Medusa and EAGLE: + https://github.com/FasterDecoding/Medusa/blob/5e98053/medusa/model/medusa_choices.py + For detailed description, see docstring of + xformers.ops.tree_attention.TreeAttnMetadata.from_tree_choices . + """ + return construct_tree_choices(branching=[branching] * tree_depth) + + +def construct_tree_choices( + branching: List[int], +) -> List[Tuple[int, ...]]: + """ + Construct a tree based on given branching factor for each non-root level. + """ + choices: List[Tuple[int, ...]] = [] + for i in range(len(branching)): + choices.extend(itertools.product(*[range(branching[k]) for k in range(i + 1)])) + return choices + + +def get_full_tree_size(tree_depth: int, branching: int) -> int: + """ + Number of nodes in a full tree of a given depth (including the root node) and branching factor. + """ + return sum(branching**i for i in range(tree_depth)) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/unbind.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/unbind.py new file mode 100644 index 0000000000000000000000000000000000000000..4e22ae0574c7d785c9137677181a249fdaa489aa --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/ops/unbind.py @@ -0,0 +1,129 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +from typing import List, Optional, Sequence, Tuple, Union + +import torch + +from .common import _get_storage_base + + +def get_stack_strides( + tensors: Sequence[torch.Tensor], dim: int +) -> Optional[Tuple[Union[int, torch.SymInt], ...]]: + """ + If the tensors are already stacked on dimension :code:`dim`, \ + returns the strides of the stacked tensors. \ + Otherwise returns :code:`None`. + """ + if len(tensors) <= 1 or dim > tensors[0].ndim: + return None + + final_stride = [] + for i in range(tensors[0].ndim + 1): + if i == dim: + # PyTorch 2.5 messed up the type annotations for SymInt, but 2.6 will fix it + # https://github.com/pytorch/pytorch/issues/138478 + final_stride.append( + tensors[1].storage_offset() - tensors[0].storage_offset() # type: ignore[operator] + ) + continue + if i > dim: + i -= 1 + final_stride.append(tensors[0].stride(i)) + + storage_data_ptr: Optional[int] = None + for i, x in enumerate(tensors[1:]): + # Sanity checks + if x.shape != tensors[0].shape: + return None + if x.stride() != tensors[0].stride(): + return None + # PyTorch 2.5 messed up the type annotations for SymInt, but 2.6 will fix it + # https://github.com/pytorch/pytorch/issues/138478 + if ( + x.storage_offset() + != tensors[0].storage_offset() + (i + 1) * final_stride[dim] # type: ignore[operator] + ): + return None + if storage_data_ptr is None: + storage_data_ptr = _get_storage_base(tensors[0]) + # Actual storage check + if _get_storage_base(x) != storage_data_ptr: + return None + return tuple(final_stride) + + +def _stack_or_none_fw( + tensors: Union[Tuple[torch.Tensor, ...], List[torch.Tensor]], + dim: int, +) -> Optional[torch.Tensor]: + strides = get_stack_strides(tensors, dim) + if strides is not None: + input_shape = list(tensors[0].shape) + input_shape.insert(dim, len(tensors)) + return tensors[0].as_strided(input_shape, strides) + return None + + +def _stack_fw( + tensors: Union[Tuple[torch.Tensor, ...], List[torch.Tensor]], + dim: int, +) -> torch.Tensor: + out = _stack_or_none_fw(tensors, dim) + if out is None: + out = torch.stack(tensors, dim=dim) + return out + + +class _Unbind(torch.autograd.Function): + """ + See function `unbind` + """ + + @staticmethod + # type: ignore + def forward(ctx, x: torch.Tensor, dim: int): + ctx.dim = dim + return x.unbind(dim) + + @classmethod + # type: ignore + def backward(cls, ctx, *tensors: torch.Tensor): + return _stack_fw(tensors, ctx.dim), None + + +class _StackOrNone(torch.autograd.Function): + """ + See function `stack_or_none` + """ + + @staticmethod + # type: ignore + def forward(ctx, dim: int, *tensors: torch.Tensor): + ctx.dim = dim + return _stack_or_none_fw(tensors, dim=dim) + + @classmethod + # type: ignore + def backward(cls, ctx, grad: torch.Tensor): + return (None, *grad.unbind(dim=ctx.dim)) + + +def unbind(x: torch.Tensor, dim: int) -> Tuple[torch.Tensor, ...]: + """ + Does exactly the same as :attr:`torch.unbind` for the forward. + In backward, avoids a :attr:`torch.cat` if the gradients + are already multiple views of the same storage + """ + return _Unbind.apply(x, dim) + + +def stack_or_none(tensors: Sequence[torch.Tensor], dim: int) -> torch.Tensor: + """ + Does exactly the same as :attr:`torch.stack` if the tensors can be concatenated + without any memory operation. Otherwise returns None. + """ + return _StackOrNone.apply(dim, *tensors) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe9d0a492624968258c8d5b9180658e3b2fb113b --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__init__.py @@ -0,0 +1,15 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +from .api import profile, step +from .profiler import MemSnapshotsProfiler, NsightProfiler, PyTorchProfiler + +__all__ = [ + "profile", + "step", + "MemSnapshotsProfiler", + "PyTorchProfiler", + "NsightProfiler", +] diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7914d4c24c26b111585194839055345389b8730 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/api.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7c120caa0828833be8511020052713c61c38e26 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/api.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/device_limits.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/device_limits.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a6040ee1d66742d75299ffb001e21cbd9f9e443 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/device_limits.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/find_slowest.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/find_slowest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6b4fd15a47fc5b3db5ae562c00df19056da9f17e Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/find_slowest.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/profile_analyzer.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/profile_analyzer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab7b59628aa0205300ec8454a0812a9154472a05 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/profile_analyzer.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/profiler.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/profiler.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9721ff8912feabf446e2e50c7f25ac5229b5b7c4 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/profiler.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/profiler_dcgm.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/profiler_dcgm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4175fc1d068de5eae1464aa638c6de42b8fb6341 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/profiler_dcgm.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/profiler_dcgm_impl.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/profiler_dcgm_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5e617d39f4b04efae572e329106bf1e8a854381 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/__pycache__/profiler_dcgm_impl.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/api.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/api.py new file mode 100644 index 0000000000000000000000000000000000000000..619bd4fda8f08902d27b41c09ec883430ec8f487 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/api.py @@ -0,0 +1,92 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Any, Optional, Sequence, Tuple + +import torch.nn as nn + +from .profiler import ( + _Profiler, + MemSnapshotsProfiler, + NsightProfiler, + PyTorchProfiler, + PyTorchProfiler_CUDAOnly, +) +from .profiler_dcgm import DCGMProfiler # noqa: F401 + +DEFAULT_SCHEDULE = ( + (MemSnapshotsProfiler, 0, 2), + (NsightProfiler, 4, 6), + (PyTorchProfiler, 6, 7), + (PyTorchProfiler_CUDAOnly, 7, 8), + # TODO: Found issues where this can take minutes to + # start, as it flushes previous values + # (DCGMProfiler, 9, 11), +) + + +def profile( + output_dir: str, + module: Optional[nn.Module] = None, + schedule: Sequence[Tuple[Any, int, int]] = DEFAULT_SCHEDULE, +): + """ + A pre-configured profiler that will run on the first ~20 steps of the training + It will provide multiple traces that can be exploited later. + Use it in a context manager around your training loop, and call `xformers.profiler.step` + before starting the next iteration. + + :Examples: + + .. code-block:: python + + import torch + import timm.models + import xformers.profiler + + dtype = torch.bfloat16 + device = "cuda" + model = timm.models.vit_large_patch16_224().to(device).to(dtype) + inp = torch.zeros([64, 3, 224, 224], device=device, dtype=dtype) + optim = torch.optim.Adam(model.parameters()) + + with xformers.profiler.profile( + output_dir="profile_data", + module=model, + schedule=[ + (MemSnapshotsProfiler, 0, 2), + (NsightProfiler, 4, 6), + (PyTorchProfiler, 6, 20), + ] + ): + for i in range(20): + model(inp).sum().backward() + optim.step() + optim.zero_grad() + xformers.profiler.step() + + # alternatively, use the profiler without context and with ``.start()`` / `.stop()` + # calls. + + xprofiler = xformers.profiler.profile(...) + xprofiler.start() + + for i in range(20): + model(inp).sum().backward() + optim.step() + optim.zero_grad() + xprofiler.step() + + xprofiler.stop() + """ + return _Profiler(output_dir=output_dir, schedule=schedule, module=module) + + +def step() -> None: + """See `xformers.profiler.profile`""" + # Silently return if no profiler is enabled + if _Profiler._CURRENT_PROFILER is None: + return + _Profiler._CURRENT_PROFILER.step() diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/device_limits.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/device_limits.py new file mode 100644 index 0000000000000000000000000000000000000000..7d35022303733889fb4280cfae1f2f493559d5a2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/device_limits.py @@ -0,0 +1,113 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import math +from dataclasses import dataclass, field +from typing import Mapping, Optional, Tuple + +import torch + + +@dataclass +class DeviceLimit: + name: str = "default" # pattern to match from `torch.cuda.get_device_name()` + source: str = "" + sm: Tuple[int, int] = (0, 0) + # bytes/s + gmem_bandwidth: float = math.inf + # dtype -> TFlop/s + gemm_tflops: Mapping[torch.dtype, float] = field(default_factory=dict) + + +# For f32, we assume we can use tf32 +DEVICE_LIMITS: Tuple[DeviceLimit, ...] = ( + DeviceLimit( + "H100", + "https://resources.nvidia.com/en-us-tensor-core/nvidia-tensor-core-gpu-datasheet", # noqa: E501 + sm=(9, 0), + gmem_bandwidth=3.35 * (1024**4), # NOTE: PCIe is 2 TB/s + gemm_tflops={ + torch.float64: 67, + # NOTE: NVIDIA gives all numbers "with 2:4 sparsity" + # but we want the full GEMM numbers + torch.float32: 989 // 2, + torch.float16: 1979 // 2, + torch.bfloat16: 1979 // 2, + torch.int8: 3958 // 2, + }, + ), + DeviceLimit( + "A100", + "https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a100/pdf/nvidia-a100-datasheet-us-nvidia-1758950-r4-web.pdf", # noqa: E501 + sm=(8, 0), + gmem_bandwidth=2 * (1024**4), # NOTE: PCIe is 1.5 TB/s + gemm_tflops={ + torch.float64: 19.5, + torch.float32: 156, + torch.float16: 312, + torch.bfloat16: 312, + torch.int8: 624, + }, + ), + DeviceLimit( + "A30", + "https://www.nvidia.com/content/dam/en-zz/Solutions/data-center/products/a30-gpu/pdf/a30-datasheet.pdf", + sm=(8, 0), + gmem_bandwidth=933 * (1024**3), + gemm_tflops={ + torch.float64: 10.3, + torch.float32: 82, + torch.float16: 165, + torch.bfloat16: 165, + torch.int8: 330, + }, + ), + DeviceLimit( + "T4", + "https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/tesla-t4/t4-tensor-core-datasheet-951643.pdf", + sm=(7, 5), + gmem_bandwidth=300 * (1024**3), + gemm_tflops={ + torch.float32: 8.1, + torch.float16: 65, + torch.int8: 130, + }, + ), + # Assuming SXM2 + DeviceLimit( + "V100", + "https://images.nvidia.com/content/technologies/volta/pdf/tesla-volta-v100-datasheet-letter-fnl-web.pdf", + sm=(7, 0), + gmem_bandwidth=900 * (1024**3), + gemm_tflops={ + torch.float64: 7.8, + torch.float32: 15.7, + torch.float16: 125, + }, + ), + DeviceLimit( + "P100", + "https://images.nvidia.com/content/tesla/pdf/nvidia-tesla-p100-datasheet.pdf", + sm=(6, 0), + gmem_bandwidth=732 * (1024**3), + gemm_tflops={ + torch.float64: 5.3, + torch.float32: 10.6, + torch.float16: 21.2, + }, + ), +) + + +def get_device_limits(device) -> Optional[DeviceLimit]: + """Currently only implemented for GPUs""" + if device is not None and device.type == "cuda": + device_sm = torch.cuda.get_device_capability(device) + device_name = torch.cuda.get_device_name(device) + for lim in DEVICE_LIMITS: + if lim.sm == device_sm: + if lim.name in device_name: + return lim + return None diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/find_slowest.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/find_slowest.py new file mode 100644 index 0000000000000000000000000000000000000000..423e29c8a4bead81220b18a10fb0ba6c8ffa5ac6 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/find_slowest.py @@ -0,0 +1,157 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import argparse +import concurrent.futures +import glob +import os +import subprocess +from shlex import quote +from typing import Dict, List + +import pandas as pd + + +def print_json_as_dataframe(json_list): + if not json_list: + print("Empty list") + return + + # Extract the headers from the keys of the first dictionary + headers = list(json_list[0].keys()) + + # Determine the width of each column + col_widths = {header: max(len(header), 10) for header in headers} + for row in json_list: + for header in headers: + col_widths[header] = max(col_widths[header], len(str(row[header]))) + + # Create the header row + header_row = " ".join(f"{header:<{col_widths[header]}}" for header in headers) + print(header_row) + print("-" * len(header_row)) + + # Create each data row + for row in json_list: + data_row = " ".join( + f"{str(row[header]):<{col_widths[header]}}" for header in headers + ) + print(data_row) + + +def compute_std_dev_of_event_durations_over_ranks(events, top=5): + grouped_sorted_events = list( + events.filter(items=["name", "log_name", "dur"]) + .groupby(["name", "log_name"]) + .sum() + .groupby(["name"]) + .std() + .sort_values(["dur"], ascending=False) + .iterrows() + ) + + return [ + {"name": idx, "std_dev": f"{row.dur / 1000:.2f} ms"} + for idx, row in grouped_sorted_events[:top] + ] + + +def sort_nccl_events( + nccl_events, top_k: int = 3, last_k: int = 3 +) -> List[Dict[str, str]]: + grouped_sorted_events = list( + nccl_events.filter(items=["log_name", "dur"]) + .groupby(["log_name"]) + .sum() + .sort_values(["dur"]) + .iterrows() + ) + + return [ + {"log_name": idx, "nccl_ms": f"{row.dur / 1000:.2f} ms"} + for idx, row in ( + grouped_sorted_events[:top_k] + grouped_sorted_events[-last_k:] + ) + ] + + +def parse_one_file(profile_trace_path): + jq_pipe = '.traceEvents[] | select(.cat == "kernel") | [.name, .dur] | @csv' + if profile_trace_path.endswith(".gz"): + cmd = ( + f"gunzip -c {quote(profile_trace_path)} | jq --raw-output {quote(jq_pipe)}" + ) + else: + cmd = f"jq --raw-output {quote(jq_pipe)} {quote(profile_trace_path)}" + + subp = subprocess.Popen( + cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL + ) + try: + kernel_events = pd.read_csv(subp.stdout, names=["name", "dur"]) + except Exception: + subp.terminate() + raise + finally: + assert subp.wait() == 0 + + kernel_events["log_name"] = os.path.basename(profile_trace_path) + + communication_kernels = kernel_events[kernel_events.name.str.startswith("nccl")] + computation_kernels = kernel_events[~(kernel_events.name.str.startswith("nccl"))] + + return communication_kernels, computation_kernels + + +def print_profiling_info(cuda_profile_dir: str): + cuda_profile_path_name = f"{cuda_profile_dir}/*trace.json.gz" + profile_files = glob.glob(cuda_profile_path_name) + + if len(profile_files) == 0: + cuda_profile_path_name = f"{cuda_profile_dir}/*.json" + profile_files = glob.glob(cuda_profile_path_name) + + if len(profile_files) == 0: + raise Exception( + f"Couldnt find any profiling trace in the specified directory: {cuda_profile_dir}" + ) + + # Extract detailed NCCL event durations for all logs + communication_kernels = [] + computation_kernels = [] + with concurrent.futures.ThreadPoolExecutor(max_workers=32) as executor: + for index, (comm_ks, comp_ks) in enumerate( + executor.map(parse_one_file, profile_files) + ): + print( + f"Processed file {index + 1}/{len(profile_files)}", end="\r", flush=True + ) + communication_kernels.append(comm_ks) + computation_kernels.append(comp_ks) + communication_kernels = pd.concat(communication_kernels) + computation_kernels = pd.concat(computation_kernels) + print() + + print("The longest and shortest communication_kernels:") + print_json_as_dataframe(sort_nccl_events(communication_kernels)) + print("\n\n") + + std_df = compute_std_dev_of_event_durations_over_ranks(communication_kernels) + print("The standard deviation of nccl kernels durations across ranks:") + print_json_as_dataframe(std_df) + print("\n\n") + + std_df = compute_std_dev_of_event_durations_over_ranks(computation_kernels) + print("The standard deviation of computation kernels durations across ranks:") + print_json_as_dataframe(std_df) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Process CUDA profile directory.") + parser.add_argument("cuda_profile_dir", type=str, help="The CUDA profile directory") + + args = parser.parse_args() + + print_profiling_info(args.cuda_profile_dir) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/profile_analyzer.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/profile_analyzer.py new file mode 100644 index 0000000000000000000000000000000000000000..276abc331b8703a2b43df8666fbefc4a20e6efbd --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/profile_analyzer.py @@ -0,0 +1,235 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import math +from collections import defaultdict +from dataclasses import dataclass +from typing import Any, cast, Dict, List, Optional, Sequence + +import torch + + +class FakeKinetoEvent: + def __init__(self, e: torch._C._autograd._KinetoEvent) -> None: + for attr in dir(e): + if attr.startswith("_"): + continue + setattr(self, attr, getattr(e, attr)) + self._kineto_event = e + + +def _attention_flops(queries, values, causal: bool, fmt: str = "BHMK") -> int: + assert isinstance(causal, bool) + assert fmt in ["BMHK", "BHMK"] + if fmt == "BMHK": + queries, values = [[x[0], x[2], x[1], x[3]] for x in [queries, values]] + *B, N, K = queries + *B, Nv, Kv = values + if causal: # NOTE: Causal from bottom right + # non-causal part + flops = 2 * N * max(Nv - N, 0) * K + 2 * max(Nv - N, 0) * max(Nv - N, 0) * Kv + # causal part + flops += ( + 2 * min(N, Nv) * min(N, Nv) * K + 2 * min(N, Nv) * min(N, Nv) * Kv + ) // 2 + else: + flops = 2 * N * Nv * K + 2 * N * Nv * Kv + for b in B: + flops *= b + return int(flops) + + +def _get_arg_idx(op, *arg_names: str) -> int: + for i, arg in enumerate(op.default._schema.arguments): + if arg.name in arg_names: + return i + raise ValueError(f"No such argument {arg_names} found in {op.default._schema}") + + +def _replace_if_needed( + e: torch._C._autograd._KinetoEvent, +) -> torch._C._autograd._KinetoEvent: + """ + Adds a flops amount for operators that don't have this information in Kineto already + This mostly applies for the attention for now, as GEMMs are already calculated by Kineto + and other operations are negligible. + """ + if e.device_type().name != "CPU": + return e + op_name = e.name() + flops = None + + FMT_BMHK = dict(fmt="BMHK") + ATTN_OPS = { + getattr(lib, op).default.name(): (getattr(lib, op), is_bwd, kwargs) + for lib, op, is_bwd, kwargs in [ + (torch.ops.aten, "scaled_dot_product_attention", False, {}), + (torch.ops.xformers_flash, "flash_fwd", False, FMT_BMHK), + ( + torch.ops.xformers, + "efficient_attention_forward_cutlass", + False, + FMT_BMHK, + ), + (torch.ops.aten, "_efficient_attention_forward", False, FMT_BMHK), + (torch.ops.aten, "_scaled_dot_product_flash_attention_backward", True, {}), + ( + torch.ops.aten, + "_scaled_dot_product_efficient_attention_backward", + True, + {}, + ), + (torch.ops.xformers_flash, "flash_bwd", True, FMT_BMHK), + ( + torch.ops.xformers, + "efficient_attention_backward_cutlass", + True, + FMT_BMHK, + ), + (torch.ops.aten, "_efficient_attention_backward", True, FMT_BMHK), + (torch.ops.aten, "_scaled_dot_product_cudnn_attention_backward", True, {}), + ] + if hasattr(lib, op) + } + if op_name in ATTN_OPS.keys(): + op, is_bwd, kwargs = ATTN_OPS[op_name] + shapes = e.shapes() + concrete_inputs = e.concrete_inputs() + try: + is_causal = concrete_inputs[_get_arg_idx(op, "causal", "is_causal")] + except ValueError: + is_causal = concrete_inputs[_get_arg_idx(op, "custom_mask_type")] != 0 + flops = _attention_flops( + shapes[_get_arg_idx(op, "query")], + shapes[_get_arg_idx(op, "value")], + is_causal, + **kwargs, + ) + if is_bwd: + flops = flops * 5 // 2 + if flops is not None: + new_e = FakeKinetoEvent(e) + new_e.flops = lambda: flops # type: ignore + e = cast(torch._C._autograd._KinetoEvent, new_e) + return e + + +@dataclass +class AnalyzedTrace: + operations_per_dtype_fw: Dict[torch.dtype, float] + operations_per_dtype_bw: Dict[torch.dtype, float] + total_time_s: float + + def compute_num_ops( + self, dtype: torch.dtype, fw: bool = True, bw: bool = True + ) -> float: + ops = 0.0 + if fw: + ops += self.operations_per_dtype_fw.get(dtype, 0.0) + if bw: + ops += self.operations_per_dtype_bw.get(dtype, 0.0) + return ops + + def compute_hfu(self, hardware_flops: Dict[torch.dtype, float]) -> float: + hfu_seconds = 0.0 + for dtype, hw_flops in hardware_flops.items(): + hfu_seconds += self.compute_num_ops(dtype) / hw_flops + return hfu_seconds / self.total_time_s + + def compute_mfu(self, hardware_flops: Dict[torch.dtype, float]) -> float: + # Estimated by considering the bw flops should be exactly 2x the fw flops + # The reason MFU!=HFU is because of recomputation in the BW pass + hfu_seconds = 0.0 + for dtype, hw_flops in hardware_flops.items(): + hfu_seconds += ( + min( + 3 * self.compute_num_ops(dtype, bw=False), + self.compute_num_ops(dtype), + ) + / hw_flops + ) + return hfu_seconds / self.total_time_s + + @staticmethod + def _find_all_root_events_with_flops( + all_events: Sequence[torch._C._autograd._KinetoEvent], + ) -> Sequence[torch._C._autograd._KinetoEvent]: + # Filters-out non-dispatch ops + # Or operations without flop counted + all_ops_with_flops = [ + e + for e in all_events + if ( + e.device_type().name == "CPU" + and (e.dtypes() or e.shapes()) + and e.flops() > 0 + ) + ] + events_per_group: Dict[Any, List[torch._C._autograd._KinetoEvent]] = ( + defaultdict(list) + ) + for e in all_ops_with_flops: + events_per_group[(e.start_thread_id(), e.device_type())].append(e) + root_events: List[torch._C._autograd._KinetoEvent] = [] + for events in events_per_group.values(): + # We assume that 2 events are either non-overlapping, + # or one is contained entirely within the other + events.sort(key=lambda e: (e.start_ns(), -e.duration_ns())) + current_root: Optional[torch._C._autograd._KinetoEvent] = None + for e in events: + if ( + current_root is None + or e.start_ns() + > current_root.start_ns() + current_root.duration_ns() + ): + current_root = e + root_events.append(e) + return root_events + + @staticmethod + def from_profile( + events: Sequence[torch._C._autograd._KinetoEvent], + ) -> "AnalyzedTrace": + events = [_replace_if_needed(e) for e in events] + root_ops = AnalyzedTrace._find_all_root_events_with_flops(events) + + operations_per_dtype_fw: Dict[torch.dtype, float] = defaultdict(float) + operations_per_dtype_bw: Dict[torch.dtype, float] = defaultdict(float) + # We detect BW pass ops based on their thread id + all_bw_threads = {e.start_thread_id() for e in events if e.fwd_thread_id() > 0} + # Find total dt + ATEN_DTYPES = [ + # NOTE: A single torch.dtype per number of bits + # (eg so we map bf16 --> b16) + ("double", torch.float64), + ("float", torch.float), + ("c10::Half", torch.float16), + ("c10::BFloat16", torch.float16), + ("c10::Int8", torch.int8), + ] + begin_ns, end_ns = math.inf, 0 + for op in root_ops: + dtype = None + for aten_dtype, torch_dtype in ATEN_DTYPES: + if aten_dtype in op.dtypes(): + dtype = torch_dtype + break + if dtype is None: # ??? + continue + if op.start_thread_id() in all_bw_threads: + operations_per_dtype_bw[dtype] += op.flops() + else: + operations_per_dtype_fw[dtype] += op.flops() + for op in events: + if op.device_type().name != "CUDA": + continue + begin_ns = min(begin_ns, op.start_ns()) + end_ns = max(end_ns, op.start_ns() + op.duration_ns()) + + return AnalyzedTrace( + operations_per_dtype_fw=operations_per_dtype_fw, + operations_per_dtype_bw=operations_per_dtype_bw, + total_time_s=(end_ns - begin_ns) / (10**9), + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/profiler.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..838778179f88e83844cd04134f92ddbab6989084 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/profiler.py @@ -0,0 +1,357 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import logging +import os +import queue +import socket +import time +import weakref +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence, Tuple + +import torch.cuda.memory +import torch.cuda.nvtx +import torch.distributed as dist +import torch.nn as nn +import torch.profiler + +from .device_limits import get_device_limits +from .profile_analyzer import AnalyzedTrace + +logger = logging.getLogger(__name__) + + +class NsightProfiler: + """Profiler that triggers start of NSight profiler. + + NOTE: you need to ensure that the script running this code actually is running with + ``nsys profile`` and also has a flag ``--capture-range=cudaProfilerApi`` so the + capturing is performed by this profiler during certain steps. + """ + + def __init__(self, main_profiler: "_Profiler") -> None: + self.main_profiler = main_profiler + # TODO figure out if there is a way to know if nsys is launched at this point + + def __enter__(self): + torch.cuda.profiler.start() + + def __exit__(self, exc_type, exc_val, exc_tb): + torch.cuda.profiler.stop() + + def step(self) -> None: + pass + + +class PyTorchProfiler: + """Profiler which relies on native Pytorch profiling. Current setting of the profiler + captures traces, memory footprint and other info that could be read via TensorBoard. + """ + + ACTIVITIES = [ + torch.profiler.ProfilerActivity.CPU, + torch.profiler.ProfilerActivity.CUDA, + ] + + def __init__(self, main_profiler: "_Profiler") -> None: + self.main_profiler = main_profiler + self.num_steps = 0 + self.pytorch_profiler = torch.profiler.profile( + on_trace_ready=self._on_trace, + profile_memory=True, + record_shapes=True, + with_stack=True, + with_flops=True, + activities=self.ACTIVITIES, + ) + + def _on_trace(self, prof: torch.profiler.profiler.profile) -> None: + activities_str = "_".join(a.name for a in self.ACTIVITIES) + dir_name = str( + self.main_profiler.output_dir + / f"profile_{activities_str}_{self.main_profiler.done_steps:06}" + ) + worker_name = self.main_profiler.worker_name + if worker_name == "": + worker_name = f"{socket.gethostname()}_{os.getpid()}" + if dist.is_available() and dist.is_initialized(): + # Left-pad rank with zeros to make them all of the same length + rank = f"{dist.get_rank()}".zfill(len(f"{dist.get_world_size() - 1}")) + worker_name = f"rank{rank}_{worker_name}" + os.makedirs(dir_name, exist_ok=True) + file_name = f"{worker_name}.{time.time_ns()}.pt.trace.json.gz" + prof.export_chrome_trace(os.path.join(dir_name, file_name)) + try: + self._analyze_trace(prof) + except Exception as exc: + self.main_profiler.summary.append(("TraceAnalysis", "Error")) + logger.warning("Exception analyzing kineto trace", exc_info=exc) + + def _analyze_trace(self, prof: torch.profiler.profiler.profile) -> None: + if prof.profiler is None or prof.profiler.kineto_results is None: + return + results = AnalyzedTrace.from_profile(prof.profiler.kineto_results.events()) + limits = get_device_limits(torch.device("cuda")) + hw_flops: Dict[torch.dtype, float] = {} + if limits is not None: + for dtype, tflops in limits.gemm_tflops.items(): + hw_flops[dtype] = tflops * (1000**4) + total_hfu = results.compute_hfu(hw_flops) + total_mfu = results.compute_mfu(hw_flops) + total_flop = sum( + results.compute_num_ops(dtype) + for dtype in results.operations_per_dtype_fw.keys() + ) + s = self.main_profiler.summary + s.append( + ("Step time (ms)", f"{int(results.total_time_s * 1000 / self.num_steps)}") + ) + s.append(("TFlop/step", f"{total_flop / (self.num_steps * 1000**4):0.1f}")) + s.append(("TFlops", f"{total_flop / (results.total_time_s * 1000**4):0.1f}")) + s.append(("HFU", f"{total_hfu:0.3f}")) + s.append(("MFU", f"{total_mfu:0.3f}")) + + def __enter__(self): + torch.cuda.synchronize() + self.pytorch_profiler.__enter__() + + def __exit__(self, exc_type, exc_val, exc_tb): + torch.cuda.synchronize() + self.pytorch_profiler.__exit__(exc_type, exc_val, exc_tb) + + def step(self) -> None: + self.pytorch_profiler.step() + self.num_steps += 1 + + +class PyTorchProfiler_CUDAOnly(PyTorchProfiler): + # This profiler does not profile the CPU-side of things + # so we expect it to have almost no overhead + ACTIVITIES = [torch.profiler.ProfilerActivity.CUDA] + + def _analyze_trace(self, prof: torch.profiler.profiler.profile) -> None: + # Can't analyze trace without CPU trace for operator shapes etc... + pass + + +class MemSnapshotsProfiler: + """Profiler that captures memory traces for allocation and deallocation of memory for + tensors. + """ + + def __init__(self, main_profiler: "_Profiler") -> None: + self.main_profiler = main_profiler + self.enabled = False + + @property + def _has_trace_plot(self) -> bool: + return hasattr(torch.cuda._memory_viz, "trace_plot") + + def __enter__(self): + if not self._has_trace_plot: + return + self.enabled = True + # TODO: This does not show the previous memory allocations + # We could at least have a placeholder with how much + # memory was allocated before + torch.cuda.memory._record_memory_history( + True, + # keep 100,000 alloc/free events from before the snapshot + trace_alloc_max_entries=100000, + # record stack information for the trace events + trace_alloc_record_context=True, + ) + + def __exit__(self, exc_type, exc_val, exc_tb): + if not self._has_trace_plot: + self.main_profiler.summary.append( + ("MemTrace", "(not available with your Pytorch version)") + ) + return + assert self.enabled + snapshot = torch.cuda.memory._snapshot() + torch.cuda.memory._record_memory_history(False) + # No data was recorded - avoids a `ValueError` in `trace_plot` + if all(len(t) == 0 for t in snapshot["device_traces"]): + self.main_profiler.summary.append(("MemTrace", "(no allocation recorded)")) + return + # Dump to disk + filename = self.main_profiler._create_output_filename("memory_trace_plot.html") + self.main_profiler.summary.append(("MemTrace", filename)) + with open(filename, "w+") as fd: + fd.write( + torch.cuda._memory_viz.trace_plot( + snapshot, device=None, plot_segments=False + ) + ) + + def step(self) -> None: + pass + + +@dataclass +class _ProfilerState: + cls: Any + iter_begin: int + iter_end: int + object: Any = None + + +class _Profiler: + _CURRENT_PROFILER = None + + def __init__( + self, + output_dir: str, + schedule: Sequence[Tuple[Any, int, int]], + module: Optional[nn.Module], + ) -> None: + self.check_schedule(schedule) + self.schedule = schedule + self.done_steps = 0 + self.output_dir = Path(output_dir).absolute() + self.output_dir.mkdir(exist_ok=True, parents=True) + self.worker_name = "" + if dist.is_available() and dist.is_initialized(): + # Left-pad rank with zeros to make them all of the same length + rank = f"{dist.get_rank()}".zfill(len(f"{dist.get_world_size() - 1}")) + self.worker_name = f"rank{rank}_{socket.gethostname()}_{os.getpid()}" + + self.module = weakref.ref(module if module is not None else nn.Module()) + self.init_schedule() + + def init_schedule(self, offset: int = 0) -> None: + self.profilers: List[_ProfilerState] = sorted( + [ + _ProfilerState(cls, begin + offset, end + offset) + for cls, begin, end in self.schedule + ], + key=lambda x: x.iter_begin, + ) + self.last_step = self.profilers[-1].iter_end if self.profilers else 0 + self.summary: List[Tuple[str, str]] = [] + + def check_schedule(self, schedule: Sequence[Tuple[Any, int, int]]) -> None: + if len(schedule) == 0: + logger.warning( + "You specified empty schedule for profiling. No data will be captured." + ) + + pq: Any = queue.PriorityQueue() + for cls, begin, end in schedule: + assert ( + begin >= 0 + ), f"Begin step of profiler must be non-negative, found: {begin}" + assert end > 0, f"End step of profiler must be positive, found: {end}" + assert ( + begin < end + ), f"Start must be before the end, found: begin={begin} and end={end}" + + pq.put((begin, end)) + + prev_end = -1 + for begin, end in pq.queue: + assert begin >= prev_end, ( + "There is some overlapping in profiler scheduling. Please do not" + + " overlap profilers by step as they may affect each other. Schedule:" + + f" {schedule}" + ) + prev_end = end + + def update_profilers_on_step(self) -> None: + for p in self.profilers: + if p.iter_begin <= self.done_steps and self.done_steps < p.iter_end: + if p.object is None: + o = p.cls(self) + logging.info(f"Starting {p.cls.__name__} profiler...") + o.__enter__() + p.object = o + else: + p.object.step() + else: + if p.object is not None: + o = p.object + p.object = None + logging.info(f"Shutting down {p.cls.__name__} profiler...") + # Make sure the profiler's `step` function is called + # $N times when we do $N steps with this profiler. + o.step() + o.__exit__(None, None, None) + + def _create_output_filename(self, filename: str) -> Path: + """ + Returns where to write a file with desired filename. + Handles the case where we are in distributed settings, or when + we need to output the same file multiple times (eg if a profiler + runs for several steps) + """ + if self.worker_name != "": + file = Path(filename) + folder = self.output_dir / file.stem + folder.mkdir(parents=True, exist_ok=True) + return folder / f"{self.done_steps:06}_{self.worker_name}{file.suffix}" + return self.output_dir / f"{self.done_steps:06}_{filename}" + + def start(self): + self.__enter__() + + def stop(self, exc_type=None, exc_val=None, exc_tb=None): + self.__exit__(exc_type, exc_val, exc_tb) + + def __enter__(self): + if _Profiler._CURRENT_PROFILER is not None: + raise ValueError("Only one xformers profiler can be active at a time") + _Profiler._CURRENT_PROFILER = self + self.update_profilers_on_step() + + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + _Profiler._CURRENT_PROFILER = None + + for p in self.profilers: + if p.object is not None: + p.object.__exit__(exc_type, exc_val, exc_tb) + + def step(self) -> None: + """Signals the profiler that the next profiling step has started.""" + self.done_steps += 1 + + if self.done_steps <= self.last_step: + self.update_profilers_on_step() + if self.done_steps == self.last_step: + logger.info("xFormers profiler done. %s", self.format_summary()) + + # Check if we triggered a manual profile step + CHECK_TRIGGER_EVERY = 10 + if ( + self.done_steps > self.last_step + and (self.done_steps % CHECK_TRIGGER_EVERY) == 0 + ): + try: + (self.output_dir / "trigger").unlink() + ( + self.output_dir + / f"trigger.{self.done_steps + CHECK_TRIGGER_EVERY:09}" + ).write_text(self.worker_name) + except FileNotFoundError: + pass + step_trigger = self.output_dir / f"trigger.{self.done_steps:09}" + if step_trigger.exists(): + logger.info( + "xFormers profiler manually triggered at step %d", self.done_steps + ) + self.init_schedule(offset=self.done_steps + 1) + + def format_summary(self) -> str: + if len(self.summary) == 0: + return "" + pad_titles = max(len(title) for title, value in self.summary) + return "summary:\n" + "\n".join( + [f" {title.ljust(pad_titles)}: {value}" for title, value in self.summary] + ) diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/profiler_dcgm.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/profiler_dcgm.py new file mode 100644 index 0000000000000000000000000000000000000000..389cadd2ca13b8f102b22d35310bdfbebd64dbe5 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/profiler_dcgm.py @@ -0,0 +1,45 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import sys + +from .profiler import _Profiler, logger + +DCGM_PROFILER_AVAILABLE = False +try: + DCGM_PYTHON_PATH: str = "/usr/local/dcgm/bindings/python3" + sys.path.insert(0, DCGM_PYTHON_PATH) + from .profiler_dcgm_impl import DCGMProfiler + + DCGM_PROFILER_AVAILABLE = True +except ModuleNotFoundError: + + class DCGMProfiler: # type: ignore + """The dummy DCGM Profiler.""" + + def __init__( + self, + main_profiler: "_Profiler", + gpus_to_profile=None, + field_ids_to_profile=None, + updateFreq=None, + ) -> None: + pass + + def __enter__(self) -> None: + logger.warning( + f"Unable to find python bindings at {DCGM_PYTHON_PATH}. " + "No data will be captured." + ) + + def __exit__(self, exc_type, exc_val, exc_tb) -> None: + pass + + def step(self) -> None: + pass + + +del sys.path[0] diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/profiler_dcgm_impl.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/profiler_dcgm_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..41bb32767dedef9975ff5b1826bd25f1aacb708e --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/profiler/profiler_dcgm_impl.py @@ -0,0 +1,216 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +from typing import List, Optional, Set, Tuple, Union + +import dcgm_fields +import torch +from dcgm_fields import DcgmFieldGetById +from dcgm_structs import DCGM_GROUP_EMPTY, DCGM_OPERATION_MODE_AUTO +from pydcgm import DcgmFieldGroup, DcgmGroup, DcgmHandle + +from .profiler import _Profiler, logger + + +class DCGMProfiler: + """Profiler that triggers start of DCGM profiler.""" + + def __init__( + self, + main_profiler: "_Profiler", + gpus_to_profile: Optional[Tuple[int, ...]] = None, + field_ids_to_profile=( + dcgm_fields.DCGM_FI_PROF_SM_ACTIVE, + dcgm_fields.DCGM_FI_PROF_SM_OCCUPANCY, + dcgm_fields.DCGM_FI_PROF_PIPE_TENSOR_ACTIVE, + dcgm_fields.DCGM_FI_PROF_DRAM_ACTIVE, + dcgm_fields.DCGM_FI_PROF_PCIE_TX_BYTES, + dcgm_fields.DCGM_FI_PROF_PCIE_RX_BYTES, + dcgm_fields.DCGM_FI_PROF_NVLINK_TX_BYTES, + dcgm_fields.DCGM_FI_PROF_NVLINK_RX_BYTES, + ), + updateFreq: int = 5000, # in microseconds + ) -> None: + """ + Args: + main_profiler: The main profiler object. + gpus_to_profile: A tuple of integers representing the GPUs to profile. If `None`, + then the "default" GPU is used. + field_ids_to_profile: + See https://github.com/NVIDIA/DCGM/blob/master/testing/python3/dcgm_fields.py#L436 + for a full list of available fields. Note that not all fields are profilable. + updateFreq: The interval of two consecutive updates of each field. Defaults to 5000 microseconds. + This is a good tradeoff between performance and accuracy. + An even smaller updateFreq is not supported well by A100. + If the step to profile takes more than 5000 microseconds, then a larger updateFreq could also be used. + """ + self.main_profiler = main_profiler + self.updateFreq = updateFreq + + self.dcgmHandle = DcgmHandle( + ipAddress="127.0.0.1", opMode=DCGM_OPERATION_MODE_AUTO + ) + + if gpus_to_profile is None: + default_gpu: int = torch.empty([], device="cuda").device.index + self.dcgmGroup = self.create_dcgm_group((default_gpu,)) + else: + self.dcgmGroup = self.create_dcgm_group(gpus_to_profile) + + self.dcgmFieldGroup = self.create_profiling_field_group(field_ids_to_profile) + + def create_dcgm_group( + self, gpus_to_profile: Union[Tuple[int], Tuple[int, ...]] + ) -> Optional[DcgmGroup]: + if self.dcgmHandle is None: + return None + + dcgmSystem = self.dcgmHandle.GetSystem() + supportedGPUs = dcgmSystem.discovery.GetAllSupportedGpuIds() + + valid_gpus_to_profile: List[int] = [ + gpu for gpu in gpus_to_profile if gpu in supportedGPUs + ] + if len(valid_gpus_to_profile) < 1: + logger.warning( + f"The provided GPUs are not supported on this system: " + f"provided {gpus_to_profile}, supported {supportedGPUs}. " + f"No data will be captured." + ) + return None + + dcgmGroup = DcgmGroup( + self.dcgmHandle, + groupName="DCGMProfiler", + groupType=DCGM_GROUP_EMPTY, + ) + + for gpu in valid_gpus_to_profile: + dcgmGroup.AddGpu(gpu) + + return dcgmGroup + + def get_profilable_fields(self) -> Set[int]: + assert self.dcgmGroup is not None + + dcgmMetricGroups = self.dcgmGroup.profiling.GetSupportedMetricGroups() + profilableFieldIds = set() + for group_idx in range(dcgmMetricGroups.numMetricGroups): + metric_group = dcgmMetricGroups.metricGroups[group_idx] + for field_id in metric_group.fieldIds[: metric_group.numFieldIds]: + profilableFieldIds.add(field_id) + return profilableFieldIds + + def create_profiling_field_group( + self, + fieldIdsToProfile: Optional[Tuple[int, ...]], + ) -> Optional[DcgmFieldGroup]: + if self.dcgmGroup is None: + return None + + # Get all field ids that can be profiled. + profilableFieldIds = self.get_profilable_fields() + + # Check which of the provided field ids are valid and invalid. + if fieldIdsToProfile is None: + validFieldIds = list(profilableFieldIds) + invalidFieldIds = [] + else: + validFieldIds = [ + field_id + for field_id in fieldIdsToProfile + if field_id in profilableFieldIds + ] + invalidFieldIds = [ + field_id + for field_id in fieldIdsToProfile + if field_id not in profilableFieldIds + ] + + if not validFieldIds: + logger.warning( + "None of the provided field ids could be profiled.\n" + f" Provided: {fieldIdsToProfile}\n" + f" Supported: {profilableFieldIds}\n" + "No data will be captured." + ) + return None + + if invalidFieldIds: + logger.warning( + f"The following field ids cannot be profiled: {invalidFieldIds}. " + f"Profiling {validFieldIds} only." + ) + dcgmFieldGroup = DcgmFieldGroup( + self.dcgmHandle, name="Profiling", fieldIds=validFieldIds + ) + return dcgmFieldGroup + + def __enter__(self) -> None: + if self.dcgmGroup is not None and self.dcgmFieldGroup is not None: + self.dcgmGroup.samples.WatchFields( + self.dcgmFieldGroup, self.updateFreq, 3600, 0 + ) + + # Start collecting the profiling results run in background. + self.profiling_results = self.dcgmGroup.samples.GetAllSinceLastCall( + None, self.dcgmFieldGroup + ) + + # It is necessary to call GetAllSinceLastCall and EmptyValues twice + # to clear old data from previous profilings + # (otherwise the new profiling data is appended to the old data from previous profiling). + self.dcgmGroup.samples.GetAllSinceLastCall( + self.profiling_results, self.dcgmFieldGroup + ) + self.profiling_results.EmptyValues() + + self.dcgmGroup.samples.GetAllSinceLastCall( + self.profiling_results, self.dcgmFieldGroup + ) + self.profiling_results.EmptyValues() + + def __exit__(self, exc_type, exc_val, exc_tb) -> None: + if self.dcgmGroup is not None and self.dcgmFieldGroup is not None: + self.dcgmGroup.samples.UnwatchFields(self.dcgmFieldGroup) + + # Delete the group. + self.dcgmGroup.Delete() + del self.dcgmGroup + self.dcgmGroup = None + + # Disconnect from the hostengine by deleting the DcgmHandle object. + del self.dcgmHandle + self.dcgmHandle = None + + def step(self) -> None: + if self.dcgmGroup is not None and self.dcgmFieldGroup is not None: + # Collect the profiling results. + self.dcgmGroup.samples.GetAllSinceLastCall( + self.profiling_results, self.dcgmFieldGroup + ) + + # Save profiling results to log. + for gpu_id in self.profiling_results.values.keys(): + for field_id in self.profiling_results.values[gpu_id].keys(): + field_name = DcgmFieldGetById(field_id).tag + + field_avg_val = 0.0 + num_vals = 0 + for gpu_field_time in self.profiling_results.values[gpu_id][ + field_id + ]: + if gpu_field_time.value is not None: + field_avg_val = ( + field_avg_val * num_vals + gpu_field_time.value + ) / (num_vals + 1) + num_vals += 1 + self.main_profiler.summary.append( + (f"GPU {gpu_id}, {field_name}({field_id})", f"{field_avg_val}") + ) + + # Clear the profiling results to get ready for the next collection. + self.profiling_results.EmptyValues() diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7238f5be0142089cbcf25a72f26559c6a9ee0da2 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__init__.py @@ -0,0 +1,7 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +from .blocksparse_tensor import BlockSparseTensor # noqa: F401 +from .csr_tensor import SparseCSRTensor # noqa: F401 diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6735bdf61112aae29d59627009f5fa6261bbfbd Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__pycache__/_csr_ops.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__pycache__/_csr_ops.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83d1c93be6554127e3135c4f247eded9dce1d217 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__pycache__/_csr_ops.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__pycache__/blocksparse_tensor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__pycache__/blocksparse_tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eb6e2023f007ed934820af53da3532f6a7fd5aa1 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__pycache__/blocksparse_tensor.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__pycache__/csr_tensor.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__pycache__/csr_tensor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d0fedfeeb940f72ea96ac144d339fd43f5cd5fb Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__pycache__/csr_tensor.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__pycache__/utils.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65c62641d3c7fd047af2b40aeef02de19d939b32 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/__pycache__/utils.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/_csr_ops.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/_csr_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..3b3115ee1ca58e238b6bb3c68082d453f7ec7b9c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/_csr_ops.py @@ -0,0 +1,166 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import torch + +from .utils import _csr_to_coo, _transpose_with_info + + +def _should_use_coo(a, sparsity): + if not a.is_cuda: + return False + B, M, K = a.shape + # amortize overhead of converting from csr to coo + if B < 32 and M < 4096: + return False + if sparsity > 0.995: + return False + if sparsity < 0.9: + return False + if K > 64: + return False + # let's be overly cautious here for now + return sparsity > 0.97 + + +def _should_use_csr_ge(a, sparsity): + if not a.is_cuda: + return False + return sparsity > 0.99 + + +def _sddmm_func(a, b, row_indices, row_offsets, column_indices): + sparsity = 1 - column_indices.shape[0] / (a.shape[1] * b.shape[1]) + if _should_use_coo(a, sparsity): + m = a.shape[-2] + n = b.shape[-2] + # converting from csr to coo has a constant overhead of ~150us + # so only dispatch to it for reasonably large problem sizes + ro, ci = _csr_to_coo(m, n, row_offsets, column_indices) + return torch.ops.xformers.coo_sddmm(a, b, row_indices, ro, ci) + elif _should_use_csr_ge(a, sparsity): + return torch.ops.xformers.csr_sddmm( + a, b, row_indices, row_offsets, column_indices + ) + return torch.ops.xformers.sddmm_sputnik( + a, b, row_indices, row_offsets, column_indices + ) + + +class _SparseSoftmax(torch.autograd.Function): + @staticmethod + def forward(ctx, m, n, row_indices, values, row_offsets, column_indices): + out = torch.ops.xformers.sparse_softmax_sputnik( + m, n, row_indices, values, row_offsets, column_indices + ) + # note: save out and not values, as an optimization step + ctx.save_for_backward(row_indices, out, row_offsets, column_indices) + ctx.size = (m, n) + return out + + @staticmethod + def backward(ctx, grad): + row_indices, out, row_offsets, column_indices = ctx.saved_tensors + m, n = ctx.size + + # gradients w.r.t. values + grad = grad.contiguous() + ga = torch.ops.xformers.sparse_softmax_backward_sputnik( + m, n, row_indices, out, grad, row_offsets, column_indices + ) + + return None, None, None, ga, None, None + + +class _sddmm(torch.autograd.Function): + @staticmethod + def forward(ctx, a, b, row_indices, row_offsets, column_indices, _transp_info): + out = _sddmm_func(a, b, row_indices, row_offsets, column_indices) + + ctx.save_for_backward( + a, b, row_indices, row_offsets, column_indices, *_transp_info + ) + return out + + @staticmethod + def backward(ctx, grad): + ( + a, + b, + row_indices, + row_offsets, + column_indices, + *_transp_info, + ) = ctx.saved_tensors + m, n = a.shape[1], b.shape[1] + + # gradients w.r.t. values + grad = grad.contiguous() + a = a.contiguous() + b = b.contiguous() + + a_grad = torch.ops.xformers.spmm_sputnik( + b, row_indices, grad, row_offsets, column_indices, m + ) + + ( + row_indices_t, + grad_t, + row_offsets_t, + column_indices_t, + ) = _transpose_with_info(grad, _transp_info) + + b_grad = torch.ops.xformers.spmm_sputnik( + a, row_indices_t, grad_t, row_offsets_t, column_indices_t, n + ) + + return a_grad, b_grad, None, None, None, None + + +class _spmm(torch.autograd.Function): + @staticmethod + def forward( + ctx, b, row_indices, values, row_offsets, column_indices, m, _transp_info + ): + b = b.contiguous() + out = torch.ops.xformers.spmm_sputnik( + b, row_indices, values, row_offsets, column_indices, m + ) + + ctx.save_for_backward( + b, row_indices, values, row_offsets, column_indices, *_transp_info + ) + return out + + @staticmethod + def backward(ctx, grad): + ( + b, + row_indices, + values, + row_offsets, + column_indices, + *_transp_info, + ) = ctx.saved_tensors + k = b.shape[1] + + # gradients w.r.t. values + grad = grad.contiguous() + + grad_sparse = _sddmm_func(grad, b, row_indices, row_offsets, column_indices) + + ( + row_indices_t, + values_t, + row_offsets_t, + column_indices_t, + ) = _transpose_with_info(values, _transp_info) + + grad_dense = torch.ops.xformers.spmm_sputnik( + grad, row_indices_t, values_t, row_offsets_t, column_indices_t, k + ) + + return grad_dense, None, grad_sparse, None, None, None, None diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/blocksparse_tensor.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/blocksparse_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..a3b9db039b25a4b494591aed9bd425b0d4eeac3c --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/blocksparse_tensor.py @@ -0,0 +1,278 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import logging + +import torch + +from xformers.ops import masked_matmul + +logger = logging.getLogger("xformers") + + +# TODO: This is all now deprecated because PyTorch has its own blocksparse ops +def _spmm(b, layout, values): + N, nnz, _, block_size = values.shape + br = b.reshape( + b.shape[0], b.shape[1], b.shape[2] // block_size, block_size, b.shape[3] + ) + # perform matmul on blocks + h, r, c = layout.nonzero(as_tuple=True) + temp = values @ br[:, h, c, :] + + linear_idx = h * (b.shape[2] // block_size) + r + out = torch.zeros( + N, + b.shape[1] * layout.shape[-2], + block_size, + b.shape[3], + dtype=b.dtype, + device=b.device, + ) + # now aggregate the results of the different blocks + out.index_add_(1, linear_idx.to(b.device), temp) + out = out.reshape(N, b.shape[1], -1, b.shape[3]) + return out + + +def _softmax(layout, values): + h, r, c = layout.nonzero(as_tuple=True) + norms = torch.logsumexp(values, dim=-1, keepdim=True) + linear_idx = h * layout.shape[1] + r + + out_t = torch.zeros( + norms.shape[0], + layout.shape[0] * layout.shape[1], + norms.shape[2], + norms.shape[3], + dtype=norms.dtype, + device=norms.device, + ) + max_val = norms.max() + out_t.index_add_( + 1, linear_idx.to(values.device), (norms - max_val).exp() + ).clamp_min_(1e-24).log_().add_(max_val) + out = torch.exp(values - out_t[:, linear_idx]) + return out + + +def _sddmm(a, b, layout): + block_size = a.shape[-2] // layout.shape[-2] + a = a.reshape( + a.shape[0], a.shape[1], a.shape[2] // block_size, block_size, a.shape[3] + ) + b = b.reshape( + b.shape[0], b.shape[1], b.shape[2] // block_size, block_size, b.shape[3] + ) + + h, r, c = layout.nonzero(as_tuple=True) + + out = torch.einsum("nhik,nhjk->nhij", a[:, h, r, :, :], b[:, h, c, :, :]) + return out + + +class BlockSparseTensor(torch.Tensor): + @staticmethod + def __new__(cls, values, layout): + kwargs = {} + kwargs["device"] = values.device + kwargs["dtype"] = values.dtype + kwargs["layout"] = values.layout + kwargs["requires_grad"] = values.requires_grad + assert values.ndim == 4 + B, _, block_size, _ = values.shape + C, h, w = layout.shape + # TODO validate shape of layout vs values + shape = (B, C, block_size * h, block_size * w) + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) + + def __init__(self, values, layout): + assert values.shape[-2] == values.shape[-1] + assert ( + values.device == layout.device + ), "Both values and layout need to reside on the same device" + block_size = values.shape[-1] + # TODO: make this check conditioned on the use of Triton + assert block_size >= 16, "Minimum block size is 16, for now at least" + + # Pure blocksparse data + self.__values = values + self.__layout = layout + + def __repr__(self): + return f"block_sparse_tensor(shape={self.shape}, values={self.__values})" + + def values(self): + return self.__values + + @classmethod + def _raw_wrap(cls, values, layout): + matrix = cls.__new__(cls, values, layout) + matrix.__values = values + matrix.__layout = layout + return matrix + + @classmethod + def _wrap(cls, values, bmat): + matrix = cls.__new__(cls, values, bmat.__layout) + matrix.__values = values + matrix.__layout = bmat.__layout + return matrix + + @classmethod + def _bmm(cls, arg0, arg1): + if not (isinstance(arg0, cls) and type(arg1) is torch.Tensor): + return NotImplemented + res = _spmm(arg1, arg0.__layout, arg0.__values) + return res + + @classmethod + def _masked_matmul(cls, a, b, mask): + if not (type(a) is torch.Tensor and type(b) is torch.Tensor): + return NotImplemented + b = b.transpose(-2, -1) + assert b.is_contiguous() + res = _sddmm(a, b, mask.__layout) + return cls._wrap(res, mask) + + @classmethod + def _softmax(cls, arg0, dim): + if not (dim == -1 or dim == 2): + return NotImplemented + res = _softmax(arg0.__layout, arg0.__values) + return cls._wrap(res, arg0) + + @classmethod + def _to(cls, arg0, device): + if isinstance(device, str): + device = torch.device(device) + assert isinstance(device, torch.device) + return cls( + arg0.__values.to(device=device), + arg0.__layout, + ) + + @classmethod + def _copy(cls, arg0, arg1): + if not (isinstance(arg0, cls) and isinstance(arg1, cls)): + return NotImplemented + assert arg0.shape == arg1.shape + av0, av1 = arg0.__values, arg1.__values + av0.resize_as_(av1).copy_(av1) + av0, av1 = arg0.__layout, arg1.__layout + av0.resize_as_(av1).copy_(av1) + return arg0 + + @classmethod + def _equal(cls, arg0, arg1): + if not (isinstance(arg0, cls) and isinstance(arg1, cls)): + return NotImplemented + if arg0.shape != arg1.shape: + return False + if not torch.equal(arg0.__values, arg1.__values): + return False + if not torch.equal(arg0.__layout, arg1.__layout): + return False + return True + + @classmethod + def _to_dense(cls, arg0): + # out = torch.zeros(arg0.shape, dtype=arg0.dtype, device=arg0.device, requires_grad=arg0.requires_grad) + out = torch.zeros(arg0.shape, dtype=arg0.dtype, device=arg0.device) + values = arg0.__values + layout = arg0.__layout + block_size = values.shape[-1] + blocks_i = layout.shape[-2] + blocks_j = layout.shape[-1] + + out_r = out.reshape( + arg0.shape[0], arg0.shape[1], blocks_i, block_size, blocks_j, block_size + ) + + for idx, (h, i, j) in enumerate(zip(*layout.nonzero(as_tuple=True))): + out_r[:, h, i, :, j, :] = values[:, idx, :, :] + + return out + + @classmethod + def __torch_function__(cls, func, types, args=(), kwargs=None): + if kwargs is None: + kwargs = {} + if func in [ + torch.Tensor.bmm, + torch.bmm, + torch.Tensor.__matmul__, + torch.matmul, + torch.Tensor.matmul, + ]: + assert len(args) == 2 + return cls._bmm(args[0], args[1]) + + if func in [torch.Tensor.softmax, torch.nn.functional.softmax, torch.softmax]: + return cls._softmax(args[0], kwargs["dim"]) + + if func == masked_matmul: + assert len(args) == 3 + return cls._masked_matmul(args[0], args[1], args[2]) + + if func in [torch.nn.functional.dropout, torch.dropout, torch.dropout_]: + x = args[0] + values = x.__values.clone() + values = func(values, *args[1:], **kwargs) + return cls._wrap(values, x) + + if func == torch.Tensor.to: + # print(args, kwargs) + assert len(args) >= 2 + return cls._to(args[0], args[1]) + # return cls._to(args[0], kwargs["device"]) + + if func in [torch.Tensor.copy_]: + assert len(args) == 2 + return cls._copy(args[0], args[1]) + + if func in [torch.Tensor.equal, torch.equal]: + assert len(args) == 2 + return cls._equal(args[0], args[1]) + + if func == torch.Tensor.to_dense: + assert len(args) == 1 + return cls._to_dense(args[0]) + + if func == torch.Tensor.detach: + x = args[0] + values = x.__values.clone() + values = func(values, *args[1:], **kwargs) + return cls._wrap(values, x) + + if func == torch.Tensor.__deepcopy__: + x = args[0] + memo = args[1] + return cls._raw_wrap( + x.__values.__deepcopy__(memo), + x.__layout.__deepcopy__(memo), + ) + + if func in [torch.Tensor.grad.__get__, torch.Tensor._grad.__get__]: + assert len(args) == 1 + assert len(kwargs) == 0 + x = args[0] + return cls._wrap(x.__values.grad, x) + + if func == torch.Tensor.requires_grad_: + func(args[0].__values) + + with torch._C.DisableTorchFunction(): + ret = func(*args, **kwargs) + # TODO: check this + if func in torch.overrides.get_default_nowrap_functions(): + return ret + return torch._tensor._convert(ret, cls) + + return NotImplemented + + @classmethod + def __torch_dispatch__(cls, func, types, args, kwargs): + return NotImplemented diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/csr_tensor.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/csr_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..5ec9846c39f204b42f057409fd2dc97787af33b6 --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/csr_tensor.py @@ -0,0 +1,437 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import torch + +from xformers.ops import masked_matmul +from xformers.sparse import _csr_ops +from xformers.sparse.utils import ( + _csr_to_coo, + _dense3d_to_sparse, + _diffsort, + _get_transpose_info, + _transpose_with_info, +) + + +class SparseCSRTensor(torch.Tensor): + @staticmethod + def __new__(cls, row_offsets, column_indices, values, shape): + kwargs = {} + kwargs["device"] = values.device + kwargs["dtype"] = values.dtype + kwargs["layout"] = values.layout + kwargs["requires_grad"] = values.requires_grad + assert len(shape) == 3 + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) + + def __init__(self, row_offsets, column_indices, values, shape): + assert row_offsets.ndim == 1 + assert column_indices.ndim == 1 + assert values.ndim == 2 + + self.__row_offsets = row_offsets.contiguous() + self.__row_indices = _diffsort(row_offsets).to(row_offsets.dtype) + self.__column_indices = column_indices.contiguous() + self.__values = values.contiguous() + + self.__transp_info = _get_transpose_info( + self.shape[1], + self.shape[2], + self.__row_indices, + self.__row_offsets, + self.__column_indices, + ) + + def __repr__(self): + return f"sparse_csr_tensor(shape={self.shape}, values={self.__values})" + + @classmethod + def from_dense(cls, matrix): + values, row_indices, row_offsets, column_indices = _dense3d_to_sparse( + matrix, matrix.device + ) + return cls(row_offsets, column_indices, values, matrix.shape) + + @classmethod + def from_sparse_coo(cls, arg0): + """ + assert arg0.is_sparse + x = arg0.coalesce() + rows, cols = x.indices().unbind(0) + vals = x.values() + _coo_to_csr() + """ + pass + + @classmethod + def _wrap( + cls, shape, values, row_indices, row_offsets, column_indices, _transp_info + ): + matrix = cls.__new__(cls, row_offsets, column_indices, values, shape) + matrix.__values = values + matrix.__row_indices = row_indices + matrix.__row_offsets = row_offsets + matrix.__column_indices = column_indices + matrix.__transp_info = _transp_info + return matrix + + def values(self): + return self.__values + + @property + def _csr_row_indices(self): + return self.__row_indices + + @property + def _csr_row_offsets(self): + return self.__row_offsets + + @property + def _csr_column_indices(self): + return self.__column_indices + + @property + def _csr_transp_info(self): + return self.__transp_info + + @classmethod + def _bmm(cls, arg0, arg1): + if not (isinstance(arg0, cls) and type(arg1) is torch.Tensor): + return NotImplemented + + assert arg0.ndim == 3 + assert arg1.ndim == 3 + + self = arg0 + b = arg1 + + _, m, n = self.shape + row_indices = self.__row_indices + values = self.__values + row_offsets = self.__row_offsets + column_indices = self.__column_indices + + out = _csr_ops._spmm.apply( + b, row_indices, values, row_offsets, column_indices, m, self.__transp_info + ) + return out + + @classmethod + def _softmax(cls, arg0, dim): + if not (dim == -1 or dim == 2): + return NotImplemented + + self = arg0 + _, m, n = self.shape + row_indices = self.__row_indices + values = self.__values + row_offsets = self.__row_offsets + column_indices = self.__column_indices + out = _csr_ops._SparseSoftmax.apply( + m, n, row_indices, values, row_offsets, column_indices + ) + return cls._wrap( + self.shape, + out, + row_indices, + row_offsets, + column_indices, + self.__transp_info, + ) + + @classmethod + def _transpose(cls, arg0, dim0, dim1): + # TODO: check if need to return this or not + if not (dim0 == 1 or dim0 == -2): + return NotImplemented + if not (dim1 == 2 or dim1 == -1): + return NotImplemented + + B, m, n = arg0.shape + values = arg0.__values + + ( + output_row_indices, + output_values, + output_row_offsets, + output_column_indices, + ) = _transpose_with_info(values, arg0.__transp_info) + new_transp_info = _get_transpose_info( + n, m, output_row_indices, output_row_offsets, output_column_indices + ) + + return cls._wrap( + (B, n, m), + output_values, + output_row_indices, + output_row_offsets, + output_column_indices, + new_transp_info, + ) + + @classmethod + def _masked_matmul(cls, a, b, mask): + if not (type(a) is torch.Tensor and type(b) is torch.Tensor): + return NotImplemented + assert mask.shape[1] == a.shape[1] + assert mask.shape[2] == b.shape[2] + row_indices = mask.__row_indices + row_offsets = mask.__row_offsets + column_indices = mask.__column_indices + a = a.contiguous() + out = _csr_ops._sddmm.apply( + a, + b.transpose(-2, -1).contiguous(), + row_indices, + row_offsets, + column_indices, + mask.__transp_info, + ) + # TODO add bias here + return cls._wrap( + mask.shape, + out, + row_indices, + row_offsets, + column_indices, + mask.__transp_info, + ) + + @classmethod + def _to(cls, arg0, device): + if isinstance(device, str): + device = torch.device(device) + assert isinstance(device, torch.device) + return cls._wrap( + arg0.shape, + arg0.__values.to(device=device), + arg0.__row_indices.to(device=device), + arg0.__row_offsets.to(device=device), + arg0.__column_indices.to(device=device), + tuple(t.to(device=device) for t in arg0.__transp_info), + ) + + @classmethod + def _copy(cls, arg0, arg1): + if not (isinstance(arg0, cls) and isinstance(arg1, cls)): + return NotImplemented + assert arg0.shape == arg1.shape + av0, av1 = arg0.__values, arg1.__values + av0.resize_as_(av1).copy_(av1) + av0, av1 = arg0.__row_indices, arg1.__row_indices + av0.resize_as_(av1).copy_(av1) + av0, av1 = arg0.__row_offsets, arg1.__row_offsets + av0.resize_as_(av1).copy_(av1) + av0, av1 = arg0.__column_indices, arg1.__column_indices + av0.resize_as_(av1).copy_(av1) + for v0, v1 in zip(arg0.__transp_info, arg1.__transp_info): + v0.resize_as_(v1).copy_(v1) + return arg0 + + @classmethod + def _equal(cls, arg0, arg1): + if not (isinstance(arg0, cls) and isinstance(arg1, cls)): + return NotImplemented + if arg0.shape != arg1.shape: + return False + if not torch.equal(arg0.__values, arg1.__values): + return False + if not torch.equal(arg0.__row_offsets, arg1.__row_offsets): + return False + if not torch.equal(arg0.__column_indices, arg1.__column_indices): + return False + return True + + @classmethod + def _to_dense(cls, arg0): + _, m, n = arg0.shape + shape = arg0.shape + matrix = torch.zeros(shape, dtype=arg0.dtype, device=arg0.device) + row_offsets = arg0.__row_offsets.long() + column_indices = arg0.__column_indices.long() + row_coo, _ = _csr_to_coo(m, n, row_offsets, column_indices) + b_idxs = torch.arange(len(arg0.__values), device=arg0.device)[:, None] + matrix[b_idxs, row_coo, column_indices] = arg0.__values + return matrix + + @classmethod + def _binary_op(cls, func, arg0, arg1): + if not ( + isinstance(arg0, (cls, int, float)) and isinstance(arg1, (cls, int, float)) + ): + return NotImplemented + v0, v1 = arg0, arg1 + if isinstance(arg0, cls): + v0 = arg0.__values + if isinstance(arg1, cls): + v1 = arg1.__values + # assert arg0.shape == arg1.shape + if isinstance(arg0, cls) and isinstance(arg1, cls): + msg = f"arg0 and arg1 need to have the same sparsity pattern in {func} (for now)" + if not arg0.__row_offsets.shape == arg1.__row_offsets.shape: + raise NotImplementedError(msg) + if not arg0.__column_indices.shape == arg1.__column_indices.shape: + raise NotImplementedError(msg) + if not arg0.__values.shape == arg1.__values.shape: + raise NotImplementedError(msg) + # TODO this is not always true, but is a fast approximation for now + if arg0.__row_offsets is not arg1.__row_offsets: + raise NotImplementedError(msg) + if arg0.__column_indices is not arg1.__column_indices: + raise NotImplementedError(msg) + out = func(v0, v1) + return cls._wrap( + arg0.shape, + out, + arg0.__row_indices, + arg0.__row_offsets, + arg0.__column_indices, + arg0.__transp_info, + ) + + @classmethod + def _binary_op_slow(cls, func, arg0, arg1): + # assert arg0.shape == arg1.shape + v0, v1 = arg0, arg1 + if isinstance(arg0, cls): + v0 = arg0.to_dense() + if isinstance(arg1, cls): + v1 = arg1.to_dense() + out = func(v0, v1) + return cls.from_dense(out) + + @classmethod + def __torch_function__(cls, func, types, args=(), kwargs=None): + if kwargs is None: + kwargs = {} + if func in [ + torch.Tensor.bmm, + torch.bmm, + torch.Tensor.__matmul__, + torch.matmul, + torch.Tensor.matmul, + ]: + assert len(args) == 2 + return cls._bmm(args[0], args[1]) + + if func in [torch.Tensor.softmax, torch.nn.functional.softmax, torch.softmax]: + return cls._softmax(args[0], kwargs["dim"]) + + if func in [torch.Tensor.transpose, torch.transpose]: + assert len(kwargs) == 0 + return cls._transpose(args[0], args[1], args[2]) + + if func == masked_matmul: + assert len(args) == 3 + return cls._masked_matmul(args[0], args[1], args[2]) + + if func in [ + torch.Tensor.add, + torch.add, + torch.Tensor.__add__, + ]: + assert len(args) == 2 + if not (isinstance(args[0], cls) and isinstance(args[1], cls)): + raise NotImplementedError( + f"{func} with {type(args[0])} and {type(args[1])} not implemented" + ) + return cls._binary_op(func, args[0], args[1]) + + if func in [ + torch.Tensor.mul, + torch.mul, + torch.Tensor.__mul__, + ]: + assert len(args) == 2 + return cls._binary_op(func, args[0], args[1]) + + if func in [torch.Tensor.logical_and, torch.logical_and, torch.Tensor.__and__]: + assert len(args) == 2 + return cls._binary_op_slow(func, args[0], args[1]) + + if func in [torch.nn.functional.dropout, torch.dropout, torch.dropout_]: + x = args[0] + values = x.__values.clone() + values = func(values, *args[1:], **kwargs) + return cls._wrap( + x.shape, + values, + x.__row_indices, + x.__row_offsets, + x.__column_indices, + x.__transp_info, + ) + + if func == torch.Tensor.to: + # print(args, kwargs) + assert len(args) >= 2 + return cls._to(args[0], args[1]) + # return cls._to(args[0], kwargs["device"]) + + if func in [torch.Tensor.copy_]: + assert len(args) == 2 + return cls._copy(args[0], args[1]) + + if func in [torch.Tensor.equal, torch.equal]: + assert len(args) == 2 + return cls._equal(args[0], args[1]) + + if func == torch.Tensor.to_dense: + assert len(args) == 1 + return cls._to_dense(args[0]) + + if func == torch.Tensor.detach: + x = args[0] + return cls._wrap( + x.shape, + x.__values.detach(), + x.__row_indices, + x.__row_offsets, + x.__column_indices, + x.__transp_info, + ) + + if func == torch.Tensor.__deepcopy__: + x = args[0] + memo = args[1] + return cls._wrap( + x.shape, + x.__values.__deepcopy__(memo), + x.__row_indices.__deepcopy__(memo), + x.__row_offsets.__deepcopy__(memo), + x.__column_indices.__deepcopy__(memo), + tuple(v.__deepcopy__(memo) for v in x.__transp_info), + ) + + if func in [torch.Tensor.grad.__get__, torch.Tensor._grad.__get__]: + assert len(args) == 1 + assert len(kwargs) == 0 + x = args[0] + return cls._wrap( + x.shape, + x.__values.grad, + x.__row_indices, + x.__row_offsets, + x.__column_indices, + x.__transp_info, + ) + + if func == torch.Tensor.requires_grad_: + func(args[0].__values) + + with torch._C.DisableTorchFunction(): + ret = func(*args, **kwargs) + # TODO: check this + if func in torch.overrides.get_default_nowrap_functions(): + return ret + return torch._tensor._convert(ret, cls) + + return NotImplemented + + @classmethod + def __torch_dispatch__(cls, func, types, args, kwargs): + return NotImplemented diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/utils.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ceb4e183d12d1b199e05ae2a20b76403b8306abc --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/sparse/utils.py @@ -0,0 +1,123 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + + +import torch + + +def _coo_to_csr(m, n, row_indices, column_indices): + # assumes coalesced coo + row_offsets = row_indices.bincount(minlength=m).cumsum(0, dtype=row_indices.dtype) + row_offsets = torch.nn.functional.pad(row_offsets, (1, 0)) + return row_offsets, column_indices + + +def _csr_to_coo(m, n, row_offsets, column_indices): + # convert from compressed rows to uncompressed + indices = torch.arange(m, dtype=row_offsets.dtype, device=row_offsets.device) + row_sizes = torch.diff(row_offsets) + row_coo = torch.repeat_interleave(indices, row_sizes.long()) + return row_coo, column_indices + + +def _diffsort(a): + return torch.argsort(torch.diff(a), dim=0, descending=True) + + +def _get_transpose_info(m, n, row_indices, row_offsets, column_indices): + # strategy: + # - uncompress the rows to have data in COO format + # - get permutation for stable sort of the columns to get the rows for the transposed matrix + # - compress the new rows and return the permutation to be applied on the values + + # convert from compressed rows to uncompressed + row_coo, _ = _csr_to_coo(m, n, row_offsets, column_indices) + + # get the permutation for the stable sort + row_offsets_t, perm = column_indices.sort(dim=0, stable=True) + column_indices_t = row_coo[perm] + + row_offsets_t, _ = _coo_to_csr(n, m, row_offsets_t, column_indices) + row_indices_t = _diffsort(row_offsets_t).int() + + return row_indices_t, row_offsets_t, column_indices_t, perm + + +def _transpose_with_info(values, _transpose_info): + row_indices_t, row_offsets_t, column_indices_t, perm = _transpose_info + values_t = values[:, perm] + return row_indices_t, values_t, row_offsets_t, column_indices_t + + +def _transpose(m, n, row_indices, values, row_offsets, column_indices): + _transpose_info = _get_transpose_info( + m, n, row_indices, row_offsets, column_indices + ) + return _transpose_with_info(values, _transpose_info) + + +def _nonzero_mask_to_sparse_csr_indices(mask, device): + """Converts dense 2d matrix to a csr sparse matrix.""" + + assert len(mask.shape) == 2 + index_dtype = torch.int32 + + # Calculate the offset of each row. + row_offsets = mask.sum(dim=-1, dtype=index_dtype).cumsum(dim=-1, dtype=index_dtype) + row_offsets = torch.nn.functional.pad(row_offsets, (1, 0)) + + # Create the row indices and sort them. + row_indices = _diffsort(row_offsets).to(index_dtype) + + # Extract the column indices for the nonzero values. + column_indices = torch.where(mask)[1].to(index_dtype).contiguous() + + row_indices = row_indices.to(device) + row_offsets = row_offsets.to(device) + column_indices = column_indices.to(device) + return row_indices, row_offsets, column_indices + + +def _dense_to_sparse(matrix, device): + """Converts dense 2d matrix to a csr sparse matrix.""" + + assert len(matrix.shape) == 2 + value_dtype = torch.float32 + + # Extract the nonzero values. + mask = matrix != 0 + values = matrix[mask].to(dtype=value_dtype, device=device) + + row_indices, row_offsets, column_indices = _nonzero_mask_to_sparse_csr_indices( + mask, device + ) + return values, row_indices, row_offsets, column_indices + + +def _round_nnz(mask, divisible_by=4): + nonzero = torch.where(mask) + nnz = nonzero[0].shape[0] + nonzero = tuple(n[: (nnz - nnz % divisible_by)] for n in nonzero) + nm = torch.zeros_like(mask) + nm[nonzero] = True + return nm + + +def _dense3d_to_sparse(matrix, device): + assert len(matrix.shape) == 3 + mask = matrix != 0 + if not torch.all(mask == mask[0]): + raise ValueError("Expected the same sparsity pattern over the batch dimension") + + # for now, our kernels assume that we have the number of + # nnz to be divisible by 4 + mask = _round_nnz(mask[0], divisible_by=4) + mask = mask[None].expand(matrix.shape) + + values = matrix[mask].reshape(matrix.shape[0], -1).to(device) + row_indices, row_offsets, column_indices = _nonzero_mask_to_sparse_csr_indices( + mask[0], device + ) + return values, row_indices, row_offsets, column_indices diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/__init__.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6677db08c0dcd87f7570a3249f61cc3eabe0532a --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/__init__.py @@ -0,0 +1,4 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/__pycache__/__init__.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..972beb431523329cd9a9f4459e043714a57b7918 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/__pycache__/__init__.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/__pycache__/importing.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/__pycache__/importing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..807521de668868f810b6593e9f8e5a14e8d6bc7f Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/__pycache__/importing.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/__pycache__/vararg_kernel.cpython-312.pyc b/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/__pycache__/vararg_kernel.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff663d3eadb367fff884288ca2689c26cff8fe41 Binary files /dev/null and b/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/__pycache__/vararg_kernel.cpython-312.pyc differ diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/importing.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/importing.py new file mode 100644 index 0000000000000000000000000000000000000000..903c38a0e9c97970e3308b7c2c0f248f020086df --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/importing.py @@ -0,0 +1,31 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import importlib.util + + +def libdevice_find(name): + """ + rsqrt = libdevice_find("rsqrt") + + is a triton-version-friendly way to say + + from triton.language.extra.libdevice import rsqrt + """ + locs = ( + "triton.language.extra.libdevice", + "triton.language.extra.cuda.libdevice", + "triton.language.math", + "triton.language.libdevice", + ) + + for loc in locs: + if spec := importlib.util.find_spec(loc): + module = importlib.util.module_from_spec(spec) + assert spec.loader is not None + spec.loader.exec_module(module) + return getattr(module, name) + + raise ImportError(f"Could not find a library to import {name}") diff --git a/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/vararg_kernel.py b/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/vararg_kernel.py new file mode 100644 index 0000000000000000000000000000000000000000..7aa30a7a25cb1e835be4706ee84b99be769955de --- /dev/null +++ b/tool_server/.venv/lib/python3.12/site-packages/xformers/triton/vararg_kernel.py @@ -0,0 +1,260 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import ast +import copy +import functools +import linecache +import os +import sys +import tempfile +from enum import Enum +from typing import Any, Dict, List + +import triton + + +class _ForLoopUnroller(ast.NodeTransformer): + def __init__(self, target, inline_variables, loop_iter): + self.loop_iter = loop_iter + self.target = target + self.inline_variables = inline_variables + + def visit_Name(self, node): + if node.id != self.target: + return node + return ast.Name(str(self.loop_iter)) + + def visit_Subscript(self, node): + # Pattern-matching `value[slice]` + if ( + isinstance(node.slice, ast.Name) + and node.slice.id == self.target + and isinstance(node.value, ast.Name) + and node.value.id in self.inline_variables + ): + return ast.Name(f"{node.value.id}{self.loop_iter}") + return node + + +class _VisitorVarargKernel(ast.NodeTransformer): + def __init__(self, N): + self.inline_variables = set() + self.N = N + + def visit_AnnAssign(self, node): + # Pattern-matching: + # var_name: "VAR_ARGS_ARRAY" + if ( + node.value is None + and node.simple == 1 + and isinstance(node.target, ast.Name) + and isinstance(node.annotation, ast.Constant) + and node.annotation.value == "VAR_ARGS_ARRAY" + ): + self.inline_variables.add(node.target.id) + return [] + if node.value is not None: + node.value = self.visit(node.value) + if node.annotation is not None: + node.annotation = self.visit(node.annotation) + if node.target is not None: + node.target = self.visit(node.target) + return node + + def visit_arguments(self, node): + # Replace `args` annotated with `VAR_ARGS_ARRAY` + new_args = [] + for arg in node.args: + if ( + arg.annotation is not None + and isinstance(arg.annotation, ast.Constant) + and arg.annotation.value == "VAR_ARGS_ARRAY" + ): + self.inline_variables.add(arg.arg) + new_args += [ast.arg(f"{arg.arg}{i}") for i in range(self.N)] + continue + new_args.append(arg) + if node.vararg is not None: + self.inline_variables.add(node.vararg.arg) + new_args += [ast.arg(f"{node.vararg.arg}{i}") for i in range(self.N)] + node.vararg = None + new_args += node.kwonlyargs + node.kwonlyargs = [] + node.args = new_args + return node + + +class _VisitorUnrollKernel(_VisitorVarargKernel): + def visit_For(self, node): + if ( + not isinstance(node.iter, ast.Call) + or node.iter.func.id != "range" + or len(node.iter.args) != 1 + or not isinstance(node.iter.args[0], ast.Call) + or node.iter.args[0].func.id != "len" + or len(node.iter.args[0].args) != 1 + or node.iter.args[0].args[0].id not in self.inline_variables + ): + node.body = [self.visit(x) for x in node.body] + return node + # We know we have to modify this loop + new_nodes = [] + for i in range(self.N): + unroller = _ForLoopUnroller( + target=node.target.id, + inline_variables=self.inline_variables, + loop_iter=i, + ) + for body in node.body: + body = copy.deepcopy(body) + new_node = ast.fix_missing_locations(unroller.visit(body)) + new_node = self.visit(new_node) + new_nodes.append(new_node) + return new_nodes + + +class _VisitorConditionalKernel(_VisitorVarargKernel): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.extra_nodes = None + + def visit_Subscript(self, node): + if isinstance(node.value, ast.Subscript): + node.value = self.visit_Subscript(node.value) + return node + if node.value.id in self.inline_variables and isinstance(node.slice, ast.Name): + # given `a[i]`, replace with `res`, where `res` is: + # a0 if i == 0 else a1 if i== 1 else a2 if i == 2 ... + if_statements = [None] * self.N + if_statements[-1] = ast.Name(f"{node.value.id}{self.N - 1}") + + for i in reversed(range(self.N - 1)): + test = ast.Compare(node.slice, [ast.Eq()], [ast.Constant(i)]) + body = ast.Name(f"{node.value.id}{i}") + if_statements[i] = ast.IfExp( + test=test, + body=body, + orelse=if_statements[i + 1], + ) + + return if_statements[0] + return node + + def visit_Call(self, node): + if ( + isinstance(node.func, ast.Name) + and node.func.id == "len" + and len(node.args) == 1 + and isinstance(node.args[0], ast.Name) + and node.args[0].id in self.inline_variables + ): + return ast.Constant(self.N) + self.generic_visit(node) + return node + + +# Hackfix to get access to get source-code for +# `exec`-created functions - see https://stackoverflow.com/a/69668999 +_getlines_orig = None +_FILENAME_TO_SRC: Dict[str, List[str]] = {} + +# Materializing the codegen to disk can be useful for external tools, e.g. ncu +# Disabled by default because writing to disk at module import time is unexpected and error-prone. +_should_materialize_codegen = os.environ.get("XFORMERS_MATERIALIZE_CODEGEN") == "1" +_should_keep_materialized_source = os.environ.get("XFORMERS_KEEP_CODEGEN") == "1" +_tmp_dir = None + + +def _monkey_patched_getlines(filename, module_globals=None): + if filename in _FILENAME_TO_SRC: + return _FILENAME_TO_SRC[filename] + else: + return _getlines_orig(filename, module_globals) # type: ignore + + +class VarargMode(Enum): + UNROLL = "unroll" + CONDITIONAL = "conditional" + + +@functools.lru_cache(None) +def unroll_varargs(kernel, N: int, mode: VarargMode = VarargMode.UNROLL): + """ + Specializes a triton kernel with variable number of inputs + to a specific number of inputs `N`. + + `mode` can either be `UNROLL` or `CONDITIONAL`. Both options + implement the same functionality, but have different implementations + and can have different performance. In `UNROLL` mode, any loops that + loop over the varargs will be unrolled. In `CONDITIONAL` mode, + indexing into the list of varargs is replaced with conditional + statements like `a0 if i==0 else a1 if i==1 else a2...`. + `CONDITIONAL` mode is generally better if `N` is large, because it + generates a smaller triton kernel that should fit in the + instruction cache and will compile faster. + + NOTE: Because it's quite costly to call `triton.jit`, + we cache the returned value with `lru_cache` + """ + global _FILENAME_TO_SRC, _getlines_orig, _tmp_dir + + k = triton.JITFunction(kernel.fn) + parsed = ast.parse(k.src) + if mode == VarargMode.UNROLL: + nodeVisitor: _VisitorVarargKernel = _VisitorUnrollKernel(N=N) + elif mode == VarargMode.CONDITIONAL: + nodeVisitor = _VisitorConditionalKernel(N=N) + parsed = nodeVisitor.visit(parsed) + parsed = ast.fix_missing_locations(parsed) + + # NOTE: `ast.unparse` requires python 3.9+ + if (sys.version_info.major, sys.version_info.minor) <= (3, 8): + raise RuntimeError("Error: This functionality requires python 3.9 or above") + new_src = ast.unparse(parsed) # type: ignore + + # Now we want to `eval` the function, but we need all this + # boilerplate code to make sure triton can run `inspect.getsource` + + fn_basename = f"unroll_varargs-{kernel.fn.__name__}-{mode.value}-{N}" + if _should_materialize_codegen: + if not _tmp_dir: + _tmp_dir = tempfile.TemporaryDirectory() + fn_filename = os.path.join(_tmp_dir.name, f"{fn_basename}.py") + if _should_keep_materialized_source: + # destroy the TemporaryDirectory object + _tmp_dir = None + # create path if not exists + os.makedirs(os.path.dirname(fn_filename), exist_ok=True) + with open(fn_filename, "w") as f: + f.write(new_src) + else: + # Patch `getlines` only the first time + if not _FILENAME_TO_SRC: + _getlines_orig = linecache.getlines + linecache.getlines = _monkey_patched_getlines + fn_filename = f"<{fn_basename}>" + _FILENAME_TO_SRC[fn_filename] = new_src.splitlines(keepends=True) + + # Create function given source + code = compile(new_src, fn_filename, "exec") + + _locals: Dict[str, Any] = {} + exec(code, kernel.fn.__globals__, _locals) + assert len(_locals) == 1, len(_locals) + fn = next(iter(_locals.values())) + + jitted_fn = triton.jit(fn) + if hasattr(jitted_fn, "_unsafe_update_src"): + jitted_fn._unsafe_update_src(new_src) + jitted_fn.hash = None + else: + jitted_fn.src = new_src + return jitted_fn + + +# Note: just import this to make mypy happy +# when annotating variables with `VAR_ARGS_ARRAY` +VAR_ARGS_ARRAY = List[Any]