diff --git a/deps/benchee/.fetch b/deps/benchee/.fetch new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/deps/benchee/.formatter.exs b/deps/benchee/.formatter.exs new file mode 100644 index 0000000000000000000000000000000000000000..18d7eda3a8ca5a6f20e675c34d72547a71b2a830 --- /dev/null +++ b/deps/benchee/.formatter.exs @@ -0,0 +1,5 @@ +# Used by "mix format" +[ + plugins: [DoctestFormatter], + inputs: ["{mix,.formatter}.exs", "{config,lib,test,samples,mix}/**/*.{ex,exs}"] +] diff --git a/deps/benchee/.hex b/deps/benchee/.hex new file mode 100644 index 0000000000000000000000000000000000000000..853ada2e55950d11d92d30803ac7db5cdd46ce8a Binary files /dev/null and b/deps/benchee/.hex differ diff --git a/deps/benchee/CHANGELOG.md b/deps/benchee/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..44e56eeb7fac04c3a996934e202c18849f53bb96 --- /dev/null +++ b/deps/benchee/CHANGELOG.md @@ -0,0 +1,459 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## 1.5.0 (2025-10-21) +Finally `max_sample_size` is here to alleviate a variety of woes resulting from gathering too many samples! +Also finally, Benchee lets you exclude outliers! + +## Features (User Facing) +* Introduce `max_sample_size` which guides how many samples will be gathered at most for a given scenario. +This avoids a variety of issues when scenarios gather too many samples (memory consumption, statistics taking long to calculate, formatters hanging/not working). +Defaults to `1_000_000`, setting it to `nil` gathers unlimited samples again (behavior before this version). +* Introduce `exclude_outliers` option which when set to `true` will automatically exclude outliers from the samples gathered. +Especially important for run time, you can remove samples caused by garbage collection or external factors. +Defaults to `false`. +Shout out to [@NickNeck](https://github.com/NickNeck) who implemented this long wished for feature over in `Statistex`. +* Display `input_name` entries in Livebook/`Table.Reader` protocol. Thanks [@madlep](https://github.com/madlep)! + +### Bugfixes (User Facing) +* fixed a bug where if times were supplied as `0` instead of `0.0` we'd sometimes gather a single measurement +* elixir `1.19` compilation warnings have been fixed + +### Features (Plugins) +* The `%Benchee.Statistics{}` struct now comes with values to accompany the outlier exclusion feature: + * outliers - if outlier exclusion was enabled, may include any samples of outliers that were found, empty list otherwise + * lower_outlier_bound - value below which values are considered an outlier + * upper_outlier_bound - value above which values are considered an outlier + +## 1.4.0 (2025-04-14) + +Some nice features (`pre_check: :all_same` is cool) along with adding support for some new stuff (`tprof`) and fixing some bugs. + +### Features (User Facing) +* `pre_check` now accepts the option `:all_same` - which raises if any job returns a value different from another for the same input. Useful when benchmarking multiple variants of the same function. Thanks to [@sabiwara](https://github.com/sabiwara)! +* Enable the [`tprof`](https://www.erlang.org/doc/apps/tools/tprof.html) profiler that shipped with OTP 27, requires OTP 27+ and elixir 1.17+. + +## Bugfixes (User Facing) +* Make gathering of system data more resilient, if the commands we ran didn't exist it may have crashed previously. Most notably, occurring on Windows 11 due to te removal of the tool we use to gather processor information. Now "N/A" is returned. +* An incompatibility with the upcoming OTP 28 that'd emit a warning on newer elixir versions was removed. Thanks [TBK145](https://github.com/TBK145)! + +## 1.3.1 (2024-06-05) + +Small release to remove warnings for the upcoming elixir 1.17 as well as add proper solaris support. + +### Features (User Facing) +* Solaris systems will now correctly be identified and have their CPU and memory parsed. Thanks to [@brianewell](https://github.com/brianewell)! + +### Bugfixes (User Facing) +* warnings on elixir-main/1.17-rc have been removed. Thanks to [@mhanberg](https://github.com/mhanberg) & [@alco](https://github.com/alco)! + +## 1.3.0 (2023-12-22) +A big swath of bug fixes and improvements. The highlights certainly are fixes and conveniences around saved benchmarks and loading them again via the new `Benchee.report/1`. The other big one is saving a lot of memory (and time!) when processing big inputs. Sadly the latter comes with some breaking changes for plugins, but they are well justified and shouldn't actually affect any plugin in practice. + +There's also a **known issue** for elixir 1.14.0 to 1.16.0-rc.0 - [read up about it](https://github.com/bencheeorg/benchee#known-issues). + +### Features (User Facing) +* System information now includes whether or not the JIT is enabled ([erlang docs](https://www.erlang.org/doc/apps/erts/beamasm)). +* Benchee now let's you know when it's calculating statistics or running the formatters. Helps when you wonder what's taking so long or blows up memory. +* `Benchee.report/1` introduced if you just want to load saved benchmarks and report on them (---> run formatters). +* Configuration times will now be displayed in a more human friendly format (1 min 12 s vs. 1.2 min). Thanks to [@drobnyd](https://github.com/drobnyd). + +### Bugfixes (User Facing) +* Memory usage should be massively reduced when dealing with larger sets of data in inputs or benchmarking functions. They were needlessly sent to processes calculating statistics or formatters which could lead to memory blowing up. +* Similarly, inputs and benchmarking functions will no longer be saved when using the `:save` option, this makes it immensely faster and depending on the size of the data a lot slower (I have an example with a factor 200x for the size). The side effect of this is that you also can't use `:load` and run the benchmarks saved again from just the file, this was never an intended use case though (as loading happens after benchmarking by default). You also still should have the benchmarking script so it's also not needed. +* Fix a bug where relative statistics would always rely on the inputs provided in the config, which can break when you load saved benchmarks but don't specify the `inputs` again. + +### Breaking Changes (Plugins) +Woopsie, didn't wanna do any of these in 1.x, sorry but there's good reason :( However, counting them as bugs. + +* Formatters have lost access to benchmarking functions and the inputs, this is to enable huge memory and run time savings when using a lot of data. I also believe they should not be needed for formatters, please get in touch if this is a problem so we can work it out. In detail this means: + * Each `Benchee.Scenario` struct in a formatter will have `:function` and `:input` set to `nil` + * The `inputs` list in `Configuration` retains the input names, but the values will be set to `:scrubbed_see_1_3_0_changelog`. It may be completely scrubbed in the future, use the newly introduced `input_names` instead if you need easy access to all the input names at once. + * Technically speaking formatters haven't generally lost access, only if they are processed in parallel - so not if it's the only formatter or if it's used via a function (`formatters: [fn suite -> MyFormatter.output(suite) end]`. Still, should not be used or relied upon. + +### Features (Plugins) +* `jit_enabled?` is exposed as part of the `suite.system` struct +* Yes, `Benchee.System` is now a struct so feel easier about relying on the fields +* `Configuration` now has an `input_names` key that holds the name of all inputs, for the reasoning, see above. +* The more human friendly formats are accessible via `Format.format_human/2` or `Duration.format_human/1` (& friends) + +## 1.2.0 (2023-11-09) + +Long time, huh? 😉 I'm not gonna repeat all that, but I'm happy benchee is in a place where it just works and doesn't need too much support. Biggest feature here is the implementation of the `Table.Reader` protocol for a better Livebook experience. + +### Features (User Facing) +* Trying to benchmark evaluated functions will now result in a warning. Thanks [@BrooklinJazz](https://github.com/BrooklinJazz), [@czrpb](https://github.com/czrpb), [@aar2dee2](https://github.com/aar2dee2),[@ReecesPeanutButterCodes](https://github.com/ReecesPeanutButterCodes). +* Add support for the [`Table.Reader`](https://hexdocs.pm/table/Table.html) protocol so that benchee works out of the box in Livebook. See [#369](https://github.com/bencheeorg/benchee/pull/369), big shoutout to [@akoutmos](https://github.com/akoutmos) and sorry for keeping it unreleased for so long. + +### Bugfixes (User Facing) +* Removed Elixir 1.16 compiler warnings around +0.0 and -0.0. Thanks [@tomciop](https://github.com/tomciopp). +* Building an escript and running it is fixed. See [#384](https://github.com/bencheeorg/benchee/issues/384) and thanks [@Munksgaard](https://github.com/Munksgaard)! + +## 1.1.0 (2022-03-08) + +Long time, huh? I'm sorry, combination of priorities, difficult to fix bugs, stress and arm problems kept me away too long. +This release brings major features long developed and now finally released (reduction measurements + profiler after run), along with a critical bugfix around measurement accuracy for very fast functions (nanoseconds). + +### Features (User Facing) +* Reduction counting/measurements was implemented. Basically, it's a rather stable unit of execution implemented by the BEAM that measures in more abstract manner how much work was done. It's helpful, as it shouldn't be affected by load on the system. Check out [the docs](https://github.com/bencheeorg/benchee#measuring-reductions). +* You can now dive straight into profiling from your benchmarks by using the profiling feature. See [the docs](https://github.com/bencheeorg/benchee#profiling-after-a-run) - thanks [@pablocostass](https://github.com/pablocostass) + +### Default Behavior Changes (User Facing) +* measuring function call overhead is now turned off by default, as it only helps with extreme nano benchmarks and has some potential for causing wrong results, so it should only be opt in. We now also print out the measured overhead for vsibility. + +### Bugfixes (User Facing) +* Benchee now correctly looks for the time resolution as reported by `:erlang.system_info(:os_monotonic_time_source)` to accommodate when determining if a measurement is "precise" enough. Benche also works around an erlang bug we discovered present in erlang <= 22.2. [Issue for reference](https://github.com/bencheeorg/benchee/issues/313). +* The annoying stacktrace warning has been removed - thanks [@mad42](https://github.com/mad42) + +### Noteworthy +* a new dependency `statistex` will show up - it's a part of continued efforts to extract reusable libraries from Benchee. + +## 1.0.1 (2019-04-09) + +### Bugfixes (User Facing) +* When memory measurements were actually different extended statistics was displayed although the option was not provided. Now correctly only displayed if the option is provided and values actually had variance. + +## 1.0.0 (2019-03-28) + +It's 0.99.0 without the deprecation warnings. Specifically: + +* Old way of passing formatters (`:formatter_options`) vs. new `:formatters` with modules, tuples or functions with one arg +* The configuration needs to be passed as the second argument to `Benchee.run/2` +* `Benchee.collect/1` replaces `Benchee.measure/1` +* `unit_scaling` is a top level configuration option, not for the console formatter +* the warning for memory measurements not working on OTP <= 18 will also be dropped (we already officially dropped OTP 18 support in 0.14.0) + +We're aiming to follow Semantic Versioning as we go forward. That means formatters should be safe to use `~> 1.0` (or even `>= 0.99.0 and < 2.0.0`). + +## 0.99.0 (2019-03-28) + +The "we're almost 1.0!" release - all the last small features, a bag of polish and deprecation warnings. If you run this release successfully without deprecation warnings you should be safe to upgrade to 1.0.0, if not - it's a bug :) + +### Breaking Changes (User Facing) +* changed official Elixir compatibility to `~> 1.6`, 1.4+ should still work but aren't guaranteed or tested against. + +### Features (User Facing) +* the console comparison now also displays the absolute difference in the average (like +12 ms) so that you have an idea to how much time that translates to in your applications not just that it's 100x faster +* Overhaul of README, documentation, update samples etc. - a whole lot of things have also been marked `@doc false` as they're considered internal + +### Bugfixes (User Facing) +* Remove double empty line after configuration display +* Fix some wrong type specs + +### Breaking Changes (Plugins) +* `Scenario` made it to the big leagues, it's no longer `Benchee.Benchmark.Scenario` but `Benchee.Scenario` - as it is arguably one of our most important data structures. +* The `Scenario` struct had some keys changed (last time before 2.0 I promise!) - instead of `:run_times`/`:run_time_statistics` you now have one `run_time_data` key that contains `Benchee.CollectionData` which has the keys `:samples` and `:statistics`. Same for `memory_usage`. This was done to be able to handle different kinds of measurements more uniformly as we will add more of them. + +### Features (Plugins) +* `Benchee.Statistics` comes with 3 new values: `:relative_more`, `:relative_less`, `:absolute_difference` so that you don't have to calculate these relative values yourself :) + +## 0.14.0 (2019-02-10) + +Highlights of this release are a new way to specify formatter options closer to the formatters themselves as well as maximum precision measurements. + +### Breaking Changes (User Facing) +* dropped support for Erlang 18.x +* Formatters no longer have an `output/1` method, instead use `Formatter.output/3` please +* Usage of `formatter_options` is deprecated, instead please use the new tuple way + +### Features (User Facing) +* Benchee now uses the maximum precision available to measure which on Linux and OSX is nanoseconds instead of microseconds. Somewhat surprisingly `:timer.tc/1` always cut down to microseconds although better precision is available. +* The preferred way to specify formatters and their options is to specify them as a tuple `{module, options}` instead of using `formatter_options`. +* New `Formatter.output/1` function that takes a suite and uses all configured formatters to output their results +* Add the concept of a benchmarking title that formatters can pick up +* the displayed percentiles can now be adjusted +* inputs option can now be an ordered list of tuples, this way you can determine their order +* support FreeBSD properly (system metrics) - thanks @[kimshrier](/kimshrier) + +### Bugfixes (User Facing) +* Remove extra double quotes in operating system report line - thanks @[kimshrier](/kimshrier) + +### Breaking Changes (Plugins) +* all reported times are now in nanoseconds instead of microseconds +* formatter methods `format` and `write` now take 2 arguments each where the additional arguments is the options specified for this formatter so that you have direct access to it without peeling it from the suite +* You can no longer `use Benchee.Formatter` - just adopt the behaviour (no more auto generated `output/1` method, but `Formatter.output/3` takes that responsibility now) + +### Features (Plugins) +* An optional title is now available in the suite for you to display +* Scenarios are now sorted already sorted (first by run time, then memory usage) - no need to sort them yourself! +* Add `Scenario.data_processed?/2` to check if either run time or memory data has had statistics generated + +## 0.13.2 (2018-08-02) + +Mostly fixing memory measurement bugs and delivering them to you asap ;) + +### Bugfixes (User Facing) +* Remove race condition that caused us to sometimes miss garbage collection events and hence report even negative or N/A results +* restructure measuring code to produce less overhead (micro memory benchmarks should be much better now) +* make console formatter more resilient to faulty memory measurements aka don't crash + +## 0.13.1 (2018-05-02) + +Mostly fixing memory measurement bugs and related issues :) Enjoy a better memory measurement experience from now on! + +### Bugfixes (User Facing) +* Memory measurements now correctly take the old generation on the heap into account. In reality that means sometimes bigger results and no missing measurements. See [#216](https://github.com/bencheeorg/benchee/pull/216) for details. Thanks to @michalmuskala for providing an interesting sample. +* Formatters are now more robust (aka not crashing) when dealing with partially missing memory measurements. Although it shouldn't happen anymore with the item before fixed, Benchee shouldn't crash on you so we want to be on the safe side. +* It's now possible to run just memory measurements (i.e. `time: 0, warmup: 0, memory_time: 1`) +* even when you already have scenarios tagged with `-2` etc. it still correctly produces `-3`, `-4` etc. when saving again with the same "base tagged name" + +## 0.13.0 (2018-04-14) + +Memory Measurements are finally here! Please report problems if you experience them. + +### Features (User Facing) +* Memory measurements obviously ;) Memory measurement are currently limited to process your function will be run in - memory consumption of other processes will **not** be measured. More information can be found in the [README](https://github.com/bencheeorg/benchee#measuring-memory-consumption). Only usable on OTP 19+. Special thanks go to @devonestes and @michalmuskala +* new `pre_check` configuration option which allows users to add a dry run of all +benchmarks with each input before running the actual suite. This should save +time while actually writing the code for your benchmarks. + +### Bugfixes (User Facing) +* Standard Deviation is now calculated correctly for being a sample of the population (divided by `n - 1` and not just `n`) + +## 0.12.1 (2018-02-26) + +### Bugfixes (User Facing) +* Formatters that use `FileCreation.each` will no longer silently fail on file +creation and now also sanitizes `/` and other file name characters to be `_`. +Thanks @gfvcastro + +## 0.12.0 (2018-01-20) + +Adds the ability to save benchmarking results and load them again to compare +against. Also fixes a bug for running benchmarks in parallel. + +### Breaking Changes (User Facing) +* Dropped Support for elixir 1.3, new support is elixir 1.4+ + +### Features (User Facing) +* new `save` option specifying a path and a tag to save the results and tag them +(for instance with `"main"`) and a `load` option to load those results again +and compare them against your current results. +* runs warning free with elixir 1.6 + +### Bugfixes (User Facing) + +* If you were running benchmarks in parallel, you would see results for each +parallel process you were running. So, if you were running **two** jobs, and +setting your configuration to `parallel: 2`, you would see **four** results in the +formatter. This is now correctly showing only the **two** jobs. + +### Features (Plugins) +* `Scenario` has a new `name` field to be adopted for displaying the scenario names, +as it includes the tag name and potential future additions. + +## 0.11.0 (2017-11-30) + +A tiny little release with a bugfix and MOARE statistics for the console formatter. + +### Bugfixes (User Facing) + +* estimated run times should be correct again, they were too high when inputs were used + +### Features (User Facing) + +* the console formatter accepts a new `extended_statistics` options that shows you additional statistics such as `minimum`, `maximum`, `sample_size` and the `mode`. Thanks `@lwalter` + +## 0.10.0 (2017-10-24) + +This release focuses on 2 main things: the internal restructuring to use _scenarios_ and the new _hooks_ system. Other than that we also have some nice convenience features and formatters can be generated in parallel now. + +### Features (User Facing) +* Hooks system - basically you can now do something before/after a benchmarking scenario or the benchmarking function, too much to explain it in a Changelog, check the [README](https://github.com/bencheeorg/benchee#hooks-setup-teardown-etc) +* Don't show more precision than we have - i.e. 234.00 microseconds (measurements are in microseconds and .00 doesn't gain you anything) +* Limit precision of available memory displayed, you don't need to know 7.45678932 GB. Thanks to `@elpikel`. +* Display the 99th percentile runtime. Thanks to `@wasnotrice`. +* `:unit_scaling` is now a top level configuration option that can now also be used and picked up by formatters, like the HTML formatter +* formatters can now be specified as a module (which should implement the `Benchee.Formatter` behaviour) - this makes specifying them nice and now at least their `format/1` functions can be executed in parallel + +### Bugfixes (User Facing) +* Determining CPUs was too strict/too assuming of a specific pattern breaking in certain environments (like Semaphore CI). That is more relaxed now thanks to `@predrag-rakic`! +* Memory is now correctly converted using the binary (1024) interpretation, instead of the decimal one (1000) + + +### Features (Plugins) +* the statistics now also provide the mode of the samples as well as the 99th percentile +* There is a new `Benchee.Formatter` behaviour to adopt and enforce a uniform format for formatters, best to do `use Benchee.Formatter` + +### Breaking Changes (Plugins) +* `:run_times`, `:statistics` and `:jobs` have been removed and folded together into `:scenarios` - a scenario holds the benchmarking function, potentially the input, the raw run times measures and the computed statistics. With this data structure, all the relevant data for one scenario is one place although it takes a lot to change, this seems to be the best way going forward. Huge thanks to `@devonestes`! + +## 0.9.0 (2017-06-08) + +This release focuses on adding more system specific information like CPU etc. and for better Erlang compatibility if you wanna use Benchee from Erlang. There is an [example project](https://github.com/bencheeorg/benchee_erlang_try) but calling Elixir from Erlang hasn't been as easy as I hoped :) + +### Features (User Facing) +* Gather more system data like number of cores, Operating System, memory, cpu speed - thanks @devonestes and @OvermindDL1 +* the names for jobs in the map of `Benchee.run/2` or in `Benchee.benchmark/3` may now be given as strings or atoms - atoms will be converted to strings internally though for consistency and avoiding name duplicates +* the names of inputs in the Benchee configuration may now be given as strings or atoms - atoms will be converted to strings internally though for consistency and avoiding name duplicates +* Benchee is now also available _"Erlang Style"_ to be called on an atom like `:benchee.run(_, _)` for better Erlang compatibility + +## 0.8.0 (2017-05-07) + +Another smaller release that focuses on adding type specs and structs in appropriate places along with fixing a couple of small bugs. + +### Features (User Facing) +* Providing an unrecognized configuration option (say `runNtime` instead of `runtime`) will now raise an exception +* Durations in the configuration will now be scaled appropriately (minutes, microseconds etc) +* Major functions are type specced for your viewing pleasure in the docs and your dialyzer pleasure at type check time. + +### Bugfixes (User Facing) +* In 0.7.0 statistics generation might time out if Millions of run times were captured so that it takes longer than 5 seconds, this is fixed by waiting infinitely - thanks @devonestes for the [report](https://github.com/bencheeorg/benchee/issues/71). +* Unintended line break in the fast function warning removed +* All necessary dependencies added to `:applications` (deep_merge was missing) + +### Breaking Changes (User Facing) +* Dropped support for elixir 1.2, new support is elixir 1.3+ +* `Benchee.Config` was renamed to `Benchee.Configuration` (important when you use the more verbose API or used it in a Plugin) + +### Features (Plugins) +* Major public interfacing functions are now typespecced! +* A couple of major data structures are now proper structs e.g. `Benchee.Suite`, `Benchee.Configuration`, `Benchee.Statistics` + +### Breaking Changes (Plugins) +* The `config` key is now `configuration` to go along with the Configuration name change +* As `Benchee.Configuration` is a proper struct now, arbitrary keys don't end up in it anymore. Custom data for plugins should be passed in through `formatter_options` or `assigns`. Existing plugin keys (`csv`, `json`, `html` and `console`) are automatically put into the `formatter_options` key space for now. + +## 0.7.0 (April 23, 2017) + +Smaller convenience features in here - the biggest part of work went into breaking reports in [benchee_html](https://github.com/bencheeorg/benchee_html) apart :) + +### Features (User Facing) +* the print out of the Erlang version now is less verbose (just major/minor) +* the fast_warning will now also tell you how to disable it +* When `print: [benchmarking: false]` is set, information about which input is being benchmarked at the moment also won't be printed +* generation of statistics parallelized (thanks hh.ex - @nesQuick and @dszam) + +### Breaking Changes (User Facing) +* If you use the more verbose interface (`Benchee.init` and friends, e.g. not `Benchee.run`) then you have to insert a `Benchee.system` call before `Benchee.measure` (preferably right after `Benchee.init`) + +### Features (Plugins) +* `Benchee.Utility.FileCreation.interleave/2` now also accepts a list of inputs which are then all interleaved in the file name appropriately. See the doctests for more details. + +### Breaking Changes (Plugins) +* `Benchee.measure/1` now also needs to have the system information generated by `Benchee.system/1` present if configuration information should be printed. + +## 0.6.0 (November 30, 2016) + +One of the biggest releases yet. Great stuff in here - more elixir like API for `Benchee.run/2` with the jobs as the primary argument and the optional options as the second argument and now also as the more idiomatic keyword list! + +The biggest feature apart from that is the possibility to use multiple inputs - which you all should do now as quite many functions behave differently with bigger, smaller or differently shaped inputs. Apart from that a bulk of work has gone into making and supporting [benchee_html](https://github.com/bencheeorg/benchee_html)! + +### Features (User Facing) + +* New `:inputs` configuration key that allows you to specify a map from input name to input value so that each defined benchmarking job is then executed with this input. For this to work the benchmarking function is called with the appropriate `input` as an argument. See [`samples/multiple_inputs.exs`](https://github.com/bencheeorg/benchee/blob/main/samples/multiple_inputs.exs) for an example. [#21]( https://github.com/bencheeorg/benchee/issues/21) +* The highlevel `Benchee.run/2` is now more idiomatic elixir and takes the map of jobs as the first argument and a keyword list of options as the second (and last) argument. The old way of passing config as a map as the first argument and the jobs as the second argument still works, **but might be deprecated later on** [#47](https://github.com/bencheeorg/benchee/issues/47) +* Along with that `Benchee.init/1` now also accepts keyword lists of course + +### Breaking Changes (User Facing) + +* The old way of providing the jobs as a list of tuples now removed, please switch to using a map from string to functions + +### Features (Plugins) + +* `Benchee.Utility.FileCreation` module to help with creating files from a map of multiple inputs (or other descriptors) mapping to input and an `interleave` function that spits out the correct file names especially if the `:__no_input` marker is used +* `Benchee.System` is available to retrieve Elixir and Erlang versions but it's +also already added to the suite during `Benchee.run/2` + +### Breaking Changes (Plugins) + +* The structure of the output from `Benchee.Benchmark.measure/1` to `Benchee.Statistics.statistics/1` has changed to accommodate the new inputs feature there is now an additional level where in a map the input name then points to the appropriate results of the jobs. When there were no inputs the key is the value returned by `Benchee.Benchmark.no_input/0`. + +### Bugfixes + +* prewarming (discarding the first result due to some timer issues) during run time was removed, as it should already happen during the warmup period and would discard actual useful results especially for longer running macro benchmarks. +* when the execution time of the benchmarking job exceeds the given `:time` it will now execute exactly once (used to be 2) [#49](https://github.com/bencheeorg/benchee/issues/49) +* `run_times` are now in the order as recorded (used to be reverse) - important when wants to graph them/look at them to see if there are any anomalies during benchmarking +* Remove elixir 1.4.0-rc.0 warnings + +## 0.5.0 (October 13, 2016) + +This release focuses on scaling units to more appropriate sizes. Instead of always working with base one for counts and microseconds those values are scaled accordingly to thousands, milliseconds for better readability. This work was mostly done by new contributor @wasnotrice. + +### Features (User Facing) + +* Console output now scales units to be more friendly. Examples: + * instead of "44556677" ips, you would see "44.56 M" + * instead of "44556.77 μs" run time, you would see "44.56 ms" +* Console output for standard deviation omits the parentheses +* Scaling of console output can be configured with the 4 different strategies `:best`, `:largest`, `:smallest` and `:none`. Refer to the documentation for their different properties. +* Shortened the fast function warning and instead [linked to the wiki](https://github.com/bencheeorg/benchee/wiki/Benchee-Warnings#fast-execution-warning) + +### Features (Plugins) + +* The statistics module now computes the `minimum`, `maximum` and `sample_size` (not yet shown in the console formatter) +* you can rely on `Benchee.Conversion.Duration`, `Benchee.Conversion.Count` and `Benchee.Conversion.DeviationPercent` for help with formatting and scaling units + +### Breaking Changes (Plugins) + +* The `Benchee.Time`module is gone, if you relied on it for one reason or another it's succeeded by the more powerful `Benchee.Conversion.Duration` + +## 0.4.0 (September 11, 2016) + +Focuses on making what Benchee print out configurable to make it fit to your preferences :) + +### Features (User Facing) +* The configuration now has a `:print` key where it is possible to configure in a map what Benchee prints out during benchmarking. All options are enabled by default (true). Options are: + * `:benchmarking` - print when Benchee starts benchmarking a new job (Benchmarking name ..) + * `:configuration` - a summary of configured benchmarking options including estimated total run time is printed before benchmarking starts + * `:fast_warning` - warnings are displayed if functions are executed too fast leading to inaccurate measures +* There is also a new configuration option for the built-in console formatter. Which is also enabled by default: + * `:comparison` - if the comparison of the different benchmarking jobs (x times slower than) is shown +* The pre-benchmarking output of the configuration now also prints the currently used Erlang and Elixir versions (similar to `elixir -v`) +* Add a space between the benchmarked time and the unit (microseconds) + +## 0.3.0 (July 11, 2016) + +This release switches internal data structures from lists of tuples to maps, allows the configuration of formatters, aggregates all values and hands them down so formatters can access the whole configuration, prints general configuration information and much more great stuff :) + +### Breaking Changes (User Facing) +* The recommended data structure handed to `Benchee.run` was changed from a list of 2-element tuples to a map (`"Name" => benchmark_function`). However, **the old list of tuples still works but may be removed in future releases** (so it's not "breaking" _strictly_ speaking). +* You **can not have benchmark jobs with the same names anymore**, the last one wins here. This was the reason why previously the data structure was a list of tuples. However, having benchmarks with the same name is nonsensical as you can't discern their results in the output any way. + +### Breaking Changes (Plugins) +* main data structure to hold benchmarks and results was changed from a list of 2-element tuples to a map (`"Name" => values`). That is for the jobs, the run times as well as the statistics. However, if you used something like `Enum.each(data, fn({name, value}) -> .. end)` you are still fine though, cause Elixir is awesome :) + +### Features (User Facing) +* now takes a `parallel: number` configuration option and will then execute each job in parallel in as many parallel processes as specified in `number`. This way you can gather more samples in the same time and also simulate a system more under load. This is tricky, however. One of the use cases is also stress testing a system. Thanks @ldr +* the name column width is now determined based on the longest name. Thanks @alvinlindstam +* Print general configuration information at the start of the benchmark, including warmup, time, parallel and an estimated total run time +* New method `Benchee.Formatters.Console.output/1` that immediately prints to the console +* now takes a `formatters: [&My.Format.function/1, &Benchee.Formatters.console.output/1]` configuration option with which multiple formatters for the same benchmarking run can be configured when using `Benchee.run/2`. E.g. you can print results to the console and create a csv from that same run. Defaults to the builtin Console formatter. + +### Features (Plugins) +* All previous configuration options are preserved after `Benchee.Statistics.statistics/1`, meaning there is access to raw run times as well as custom options etc. E.g. you could grab custom options like `%{csv: %{file: "my_file_name.csv"}}` to use. + +### Bugfixes +* name columns are no longer truncated after 30 characters. Thanks @alvinlindstam + +## 0.2.0 (June 11, 2016) + +This release introduces warmup for benchmarks, nicer console output and the new `Benchee.measure` that runs the benchmarks previously defined instead of running them instantly. + +### Breaking Changes (User Facing) +* `Benchee.benchmark/3` now doesn't run the benchmark anymore but simply adds it to `:jobs` in the config. The whole benchmark suite is then run via `Benchee.measure/1`. This only affects you if you used the more verbose way of defining benchmarks, `Benchee.run/2` still work as before. + +### Breaking Changes (Plugins) +* the defined benchmarking are now preserved after running the benchmark under the `:jobs` key of the suite. Run times are added to the `:run_times` key of the suite (important for alternative statistics implementations) + +### Features (User Facing) + +* configuring a warmup time to run functions before measurements are taken can be configured via the `warmup` key in the config defaulting to 2 (seconds) + +* statistics in console output are aligned right now for better comparisons +* last blank line of console output removed + +### Features (Plugins) +* additionally supply the total standard deviation of iterations per second as `std_dev_ips` after `Benchee.Statistics.statistics` + +### Bugfixes + +* if no time/warmup is specified the function won't be called at all + +## 0.1.0 (June 5, 2016) + +Initial release diff --git a/deps/benchee/LICENSE.md b/deps/benchee/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..c9ece1998ffac157bc6418b60286eda5e2909539 --- /dev/null +++ b/deps/benchee/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2016 Tobias Pfeiffer + +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/deps/benchee/README.md b/deps/benchee/README.md new file mode 100644 index 0000000000000000000000000000000000000000..24c7cc5834e49b6d3e241e35ee9912d8dd2e9002 --- /dev/null +++ b/deps/benchee/README.md @@ -0,0 +1,1144 @@ +# Benchee [![Hex Version](https://img.shields.io/hexpm/v/benchee.svg)](https://hex.pm/packages/benchee) [![Hex Docs](https://img.shields.io/badge/docs-hexpm-blue.svg)](https://hexdocs.pm/benchee/) [![CI](https://github.com/bencheeorg/benchee/workflows/CI/badge.svg)](https://github.com/bencheeorg/benchee/actions?query=branch%3Amain) [![Coverage Status](https://coveralls.io/repos/github/bencheeorg/benchee/badge.svg?branch=main)](https://coveralls.io/github/bencheeorg/benchee?branch=main) [![Total Download](https://img.shields.io/hexpm/dt/benchee.svg)](https://hex.pm/packages/benchee) [![License](https://img.shields.io/hexpm/l/benchee.svg)](https://github.com/bencheeorg/benchee/blob/main/LICENSE) + +Library for easy and nice (micro) benchmarking in Elixir. Benchee allows you to compare the performance of different pieces of code at a glance. It is also versatile and extensible, relying only on functions. There are also a bunch of [plugins](#plugins) to draw pretty graphs and more! + +Benchee runs each of your functions for a given amount of time after an initial warmup, it then measures their run time and optionally memory consumption. It then shows different statistical values like average, standard deviation etc. See [features](#features). + +Benchee has a nice and concise main interface, its behavior can be altered through lots of [configuration options](#configuration): + +```elixir +list = Enum.to_list(1..10_000) +map_fun = fn i -> [i, i * i] end + +Benchee.run( + %{ + "flat_map" => fn -> Enum.flat_map(list, map_fun) end, + "map.flatten" => fn -> list |> Enum.map(map_fun) |> List.flatten() end + }, + time: 10, + memory_time: 2 +) +``` + +Produces the following output on the console: + +``` +Operating System: Linux +CPU Information: AMD Ryzen 9 5900X 12-Core Processor +Number of Available Cores: 24 +Available memory: 31.26 GB +Elixir 1.19.0 +Erlang 28.1 +JIT enabled: true + +Benchmark suite executing with the following configuration: +warmup: 2 s +time: 10 s +memory time: 2 s +reduction time: 0 ns +parallel: 1 +inputs: none specified +Estimated total run time: 28 s +Excluding outliers: false + +Benchmarking flat_map ... +Benchmarking map.flatten ... +Calculating statistics... +Formatting results... + +Name ips average deviation median 99th % +flat_map 3.96 K 252.74 μs ±15.64% 247.61 μs 321.85 μs +map.flatten 1.84 K 543.57 μs ±44.18% 414.16 μs 1223.92 μs + +Comparison: +flat_map 3.96 K +map.flatten 1.84 K - 2.15x slower +290.83 μs + +Memory usage statistics: + +Name Memory usage +flat_map 624.97 KB +map.flatten 781.25 KB - 1.25x memory usage +156.28 KB + +**All measurements for memory usage were the same** +``` + +The aforementioned [plugins](#plugins) like [benchee_html](https://github.com/bencheeorg/benchee_html) make it possible to generate nice looking [HTML reports](http://www.pragtob.info/benchee/README/results.html), where individual graphs can also be exported as PNG images: + +![report](http://www.pragtob.info/benchee/images/report.png) + +## Table of Contents + +- [Table of Contents](#table-of-contents) +- [Features](#features) + - [Statistics](#statistics) +- [Installation](#installation) +- [Usage](#usage) + - [Configuration](#configuration) + - [Metrics to measure](#metrics-to-measure) + - [Measuring time](#measuring-time) + - [A note on time measurement accuracy](#a-note-on-time-measurement-accuracy) + - [Measuring Memory Consumption](#measuring-memory-consumption) + - [Measuring Reductions](#measuring-reductions) + - [Inputs](#inputs) + - [Formatters](#formatters) + - [Console Formatter options](#console-formatter-options) + - [Profiling after a run](#profiling-after-a-run) + - [Remove Outliers](#remove-outliers) + - [Saving, loading and comparing previous runs](#saving-loading-and-comparing-previous-runs) + - [Hooks (Setup, Teardown etc.)](#hooks-setup-teardown-etc) + - [Suite hooks](#suite-hooks) + - [Scenario hooks](#scenario-hooks) + - [What is a scenario?](#what-is-a-scenario) + - [before\_scenario](#before_scenario) + - [after\_scenario](#after_scenario) + - [Benchmarking function hooks](#benchmarking-function-hooks) + - [before\_each](#before_each) + - [after\_each](#after_each) + - [Hook arguments and return values](#hook-arguments-and-return-values) + - [Hook configuration: global versus local](#hook-configuration-global-versus-local) + - [When does a hook happen? (Complete Example)](#when-does-a-hook-happen-complete-example) + - [More verbose usage](#more-verbose-usage) + - [Usage from Erlang](#usage-from-erlang) +- [Known Issues](#known-issues) +- [Plugins](#plugins) +- [Contributing ](#contributing-) +- [Development](#development) +- [Copyright and License](#copyright-and-license) + +## Features + +* first runs the functions for a given warmup time without recording the results, to simulate a _"warm"/running_ system +* [measures memory usage](#measuring-memory-consumption) +* provides you with lots of [statistics](#statistics) +* plugin/extensible friendly architecture so you can use different formatters to display benchmarking results as [HTML, markdown, JSON and more](#plugins) +* measure not only [time](#measuring-time), but also measure [memory](#measuring-memory-consumption) and [reductions](#measuring-reductions) +* [profile](#profiling-after-a-run) right after benchmarking +* as precise as it can get, measure with up to nanosecond precision (Operating System dependent) +* nicely formatted console output with units scaled to appropriately (nanoseconds to minutes) +* (optionally) measures the overhead of function calls so that the measured/reported times really are the execution time of _your_code_ without that overhead. +* (optionally) [removes outliers](#remove-outliers) +* [hooks](#hooks-setup-teardown-etc) to execute something before/after a benchmarking invocation, without it impacting the measured time +* execute benchmark jobs in parallel to gather more results in the same time, or simulate a system under load +* well documented & well tested + +### Statistics + +Provides you with the following **statistical data**: + +* **average** - average execution time/memory usage (the lower the better) +* **ips** - iterations per second, aka how often can the given function be executed within one second (the higher the better - good for graphing), only for run times +* **deviation** - standard deviation (how much do the results vary), given as a percentage of the average (raw absolute values also available) +* **median** - when all measured values are sorted, this is the middle value. More stable than the average and somewhat more likely to be a typical value you see, for the most typical value see mode. (the lower the better) +* **99th %** - 99th percentile, 99% of all measured values are less than this - worst case performance-ish + +In addition, you can optionally output an extended set of statistics: + +* **minimum** - the smallest value measured for the job (fastest/least consumption) +* **maximum** - the biggest run time measured for the job (slowest/most consumption) +* **sample size** - the number of measurements taken +* **mode** - the measured values that occur the most. Often one value, but can be multiple values if they occur exactly as often. If no value occurs at least twice, this value will be `nil`. + +Benchee can also [remove outliers](#remove-outliers). + +## Installation + +Add `:benchee` to your list of dependencies in `mix.exs`: + +```elixir +defp deps do + [ + {:benchee, "~> 1.0", only: :dev} + ] +end +``` + +Install via `mix deps.get` and then happy benchmarking as described in [Usage](#usage) :) + +Elixir versions supported/tested against are 1.7+. It _should_ theoretically still work with 1.4, 1.5 & 1.6 but we don't actively test/support it as installing them on current CI systems is not supported out of the box. + +## Usage + +After installing just write a little Elixir benchmarking script: + +```elixir +list = Enum.to_list(1..10_000) +map_fun = fn i -> [i, i * i] end + +Benchee.run( + %{ + "flat_map" => fn -> Enum.flat_map(list, map_fun) end, + "map.flatten" => fn -> list |> Enum.map(map_fun) |> List.flatten() end + } +) +``` + +(names can also be specified as `:atoms` if you want to) + +This produces the following output: + +``` +tobi@speedy:$ mix run samples/run_defaults.exs +Operating System: Linux +CPU Information: Intel(R) Core(TM) i7-4790 CPU @ 3.60GHz +Number of Available Cores: 8 +Available memory: 15.61 GB +Elixir 1.8.1 +Erlang 21.2.7 + +Benchmark suite executing with the following configuration: +warmup: 2 s +time: 5 s +memory time: 0 ns +parallel: 1 +inputs: none specified +Estimated total run time: 14 s + +Benchmarking flat_map... +Benchmarking map.flatten... + +Name ips average deviation median 99th % +flat_map 2.34 K 427.78 μs ±16.02% 406.29 μs 743.01 μs +map.flatten 1.22 K 820.87 μs ±19.29% 772.61 μs 1286.35 μs + +Comparison: +flat_map 2.34 K +map.flatten 1.22 K - 1.92x slower +393.09 μs +``` + +See [Features](#features) for a description of the different statistical values and what they mean. + +If you're looking to see how to make something specific work, please refer to the [samples](https://github.com/bencheeorg/benchee/tree/main/samples) directory. Also, especially when wanting to extend Benchee, check out the [hexdocs](https://hexdocs.pm/benchee/api-reference.html). + +### Configuration + +Benchee takes a wealth of configuration options, however those are entirely optional. Benchee ships with sensible defaults for all of these. + +In the most common `Benchee.run/2` interface configuration options are passed as the second argument in the form of an keyword list: + +```elixir +Benchee.run(%{"some function" => fn -> magic end}, print: [benchmarking: false]) +``` + +The available options are the following (also documented in [hexdocs](https://hexdocs.pm/benchee/Benchee.Configuration.html#init/1)). + +* `warmup` - the time in seconds for which a benchmarking job should be run without measuring anything before "real" measurements start. This simulates a _"warm"/running_ system. Defaults to 2. +* `time` - the time in seconds for how long each individual scenario (benchmarking job x input) should be run for measuring the execution times (run time performance). Defaults to 5. +* `memory_time` - the time in seconds for how long [memory measurements](#measuring-memory-consumption) should be conducted. Defaults to 0 (turned off). +* `reduction_time` - the time in seconds for how long [reductions are measured](#measuring-memory-reductions) should be conducted. Defaults to 0 (turned off). +* `inputs` - a map or list of two element tuples. If a map, the keys are descriptive input names and values are the actual input values. If a list of tuples, the first element in each tuple is the input name, and the second element in each tuple is the actual input value. Your benchmarking jobs will then be run with each of these inputs. For this to work your benchmarking function gets the current input passed in as an argument into the function. Defaults to `nil`, aka no input specified and functions are called without an argument. See [Inputs](#inputs). +* `formatters` - list of formatters either as a module implementing the formatter behaviour, a tuple of said module and options it should take or formatter functions. They are run when using `Benchee.run/2` or you can invoke them through `Benchee.Formatter.output/1`. Functions need to accept one argument (which is the benchmarking suite with all data) and then use that to produce output. Used for plugins & configuration. Also allows the configuration of the console formatter to print extended statistics. Defaults to the builtin console formatter `Benchee.Formatters.Console`. See [Formatters](#formatters). +* `measure_function_call_overhead` - Measure how long an empty function call takes and deduct this from each measured run time. This overhead should be negligible for all but the most micro benchmarks. Defaults to false. +* `pre_check` - whether or not to run each job with each input - including all given before or after scenario or each hooks - before the benchmarks are measured to ensure that your code executes without error. This can save time while developing your suites. Defaults to `false`. Possible values are: + * `false` - no pre check is run + * `true` - each scenario is run but the return value is ignored + * `:all_same` - raises if all scenarios are not returning the same value for + each input. This is useful when benchmarking alternative implementations of a + deterministic function. +* `parallel` - the function of each benchmarking job will be executed in `parallel` number processes. If `parallel: 4` then 4 processes will be spawned that all execute the _same_ function for the given time. When `time` seconds have passed, 4 new processes will be spawned for the next scenario (meaning a new input or another function to be benchmarked). This gives you more data in the same time, but also puts load on the system interfering with benchmark results. For more on the pros and cons of parallel benchmarking [check the wiki](https://github.com/bencheeorg/benchee/wiki/Parallel-Benchmarking). Defaults to 1 (no parallel execution). +* `save` - specify a `path` where to store the results of the current benchmarking suite, tagged with the specified `tag`. See [Saving & Loading](#saving-loading-and-comparing-previous-runs). +* `load` - load saved suite or suites to compare your current benchmarks against. Can be a string or a list of strings or patterns. See [Saving & Loading](#saving-loading-and-comparing-previous-runs). +* `print` - a map or keyword list from atoms to `true` or `false` to configure if the output identified by the atom will be printed during the standard Benchee benchmarking process. All options are enabled by default (true). Options are: + * `:benchmarking` - print when Benchee starts benchmarking a new job (`Benchmarking name ...`) as well as when statistics are being calculated or formatting begins. + * `:configuration` - a summary of configured benchmarking options including estimated total run time is printed before benchmarking starts + * `:fast_warning` - warnings are displayed if functions are executed too fast leading to inaccurate measures +* `:unit_scaling` - the strategy for choosing a unit for durations, + counts & memory measurements. May or may not be implemented by a given formatter (The console formatter implements it). + When scaling a value, Benchee finds the "best fit" + unit (the largest unit for which the result is at least 1). For example, + 1_200_000 scales to `1.2 M`, while `800_000` scales to `800 K`. The + `unit_scaling` strategy determines how Benchee chooses the best fit unit for + an entire list of values, when the individual values in the list may have + different best fit units. There are four strategies, defaulting to `:best`: + * `:best` - the most frequent best fit unit will be used, a tie + will result in the larger unit being selected. + * `:largest` - the largest best fit unit will be used + * `:smallest` - the smallest best fit unit will be used + * `:none` - no unit scaling will occur. +* `:before_scenario`/`after_scenario`/`before_each`/`after_each` - read up on them in the [hooks section](#hooks-setup-teardown-etc) +* `profile_after` - accepts any of the following options: + * a boolean - `true` will enable profiling with the default profiler (`:eprof`) and `false` will disable profiling. Defaults to `false`. + * a profiler - either as a tuple of `{profiler, opts}` (e.g., `{:fprof, [sort: :own]}`) or just the profiler (e.g., `:fprof`), + which is equivalent to `{profiler, []}`. The accepted built-in profilers are: + [`:cprof`](https://hexdocs.pm/mix/Mix.Tasks.Profile.Cprof.html), + [`:eprof`](https://hexdocs.pm/mix/Mix.Tasks.Profile.Eprof.html) + [`:fprof`](https://hexdocs.pm/mix/Mix.Tasks.Profile.Fprof.html) and + [`:tprof`](https://hexdocs.pm/mix/Mix.Tasks.Profile.Tprof.html) (requires elixir >= 1.17 and erlang >= 27). +* `max_sample_size` - the maximum number of samples collected per scenario. Defaults to `1_000_000`. + This is used to limit memory consumption and unnecessary processing - 1 Million samples is plenty. + This limit also applies to number of iterations done during warmup. + You can set your own number or set it to `nil` if you don't want any limit. +* `exclude_outliers` - whether or not statistical outliers should be removed for the calculated statistics. +Defaults to `false`. +This means that values that are far outside the usual range (as determined by the percentiles/quantiles) will +be removed from the gathered samples and the calculated statistics. You might want to enable this if you +don't want things like the garbage collection triggering to influence your results as much. + +### Metrics to measure + +Benchee can't only measure [execution time](#measuring-time), but also [memory consumption](#measuring-memory-consumption) and [reductions](#measuring-reductions)! + +You can measure one of these metrics, or all at the same time. The choice is up to you. Warmup will only occur once though, the time for measuring the metrics are governed by `time`, `memory_time` and `reduction_time` configuration values respectively. + +By default only execution time is measured, memory and reductions need to be opted in by specifying a non 0 time amount. + +#### Measuring time + +This is the default, which you'll most likely want to use as you want to measure how fast your system processes something or responds to a request. Benchee does its best to measure time as accurately and as scoped to your function as possible. + +```elixir +Benchee.run( + %{ + "something_great" => fn -> cool_stuff end + }, + warmup: 1, + time: 5, + memory_time: 2, + reduction_time: 2 +) +``` + +##### A note on time measurement accuracy + +From system to system the resolution of the clock [can vary](https://www.erlang.org/doc/apps/erts/time_correction.html). + +Generally speaking we have seen accuracies down to 1 nanosecond on Linux and ~1 microsecond onb both OSX and Windows. We have also seen accuracy as low as 10ms on Windows in a CI environment. +These numbers are not a limitation of Benchee, but of the Operating System (or at the very least how erlang makes it available). + +If your benchmark takes 100s of microseconds this likely has no/little impact, but **if you want to do extremely nano benchmarks we recommend doing them on Linux**. + +So, what happens if a function executes too fast for Benchee to measure? If Benchee recognizes this (not always possible) it will automatically take the function and repeat it multiple times. This way a function that takes 2 microseconds will take ~20 microseconds and differences can be measured even with microsecond accuracy. Naturally, this comes at several disadvantages: + +* The looping/repetition code is now measured alongside the function +* essentially every single measurement is now an average across 10 runs making lots of statistics less meaningful + +Benchee will print a big warning when this happens. + +#### Measuring Memory Consumption + +Starting with version 0.13, users can now get measurements of how much memory their benchmarked scenarios use. The measurement is **limited to the process that Benchee executes your provided code in** - i.e. other processes (like worker pools)/the whole BEAM isn't taken into account. + +This measurement is **not** the actual effect on the size of the BEAM VM size, but the total amount of memory that was allocated during the execution of a given scenario. This includes all memory that was garbage collected during the execution of that scenario. + +This measurement of memory does not affect the measurement of run times. + +In cases where all measurements of memory consumption are identical, which happens very frequently, the full statistics will be omitted from the standard console formatter. If your function is deterministic, this should always be the case. Only in functions with some amount of randomness will there be variation in memory usage. + +Memory measurement is disabled by default, you can choose to enable it by passing `memory_time: your_seconds` option to `Benchee.run/2`: + +```elixir +Benchee.run( + %{ + "something_great" => fn -> cool_stuff end + }, + memory_time: 2 +) +``` + +Memory time can be specified separately as it will often be constant - so it might not need as much measuring time. + +A full example, including an example of the console output, can be found +[here](samples/measure_memory.exs). + +#### Measuring Reductions + +Starting in versions 1.1.0 Benchee can measure reductions - but what are reductions? + +In short, it's not very well defined but a "unit of work". The BEAM uses them to keep track of how long a process has run. As [the Beam Book puts it as follows](https://blog.stenmans.org/theBeamBook/#_scheduling_non_preemptive_reduction_counting): + +>BEAM solves this by keeping track of how long a process has been running. This is done by counting reductions. The term originally comes from the mathematical term beta-reduction used in lambda calculus. +> +>The definition of a reduction in BEAM is not very specific, but we can see it as a small piece of work, which shouldn’t take too long. Each function call is counted as a reduction. BEAM does a test upon entry to each function to check whether the process has used up all its reductions or not. If there are reductions left the function is executed otherwise the process is suspended. + +Now, why would you want to measure this? Well, apart from BIFs & NIFs, which are not accurately tracked through this, it gives an impression of how much work the BEAM is doing. And the great thing is, this is independent of the load the system is under as well as the hardware. Hence, it gives you a way to check performance that is less volatile so suitable for CI for instance. + +It can slightly differ between elixir & erlang versions, though. + +**Like memory measurements, this only tracks reductions directly in the function given to benchee, not processes spawned by it or other processes it uses.** + +Reduction measurement is disabled by default, you can choose to enable it by passing `reduction_time: your_seconds` option to `Benchee.run/2`: + +```elixir +Benchee.run( + %{ + "something_great" => fn -> cool_stuff end + }, + reduction_time: 2 +) +``` + +Also like memory measurements, reduction measurements will often be constant unless something changes about the execution of the benchmarking function. + +### Inputs + +`:inputs` is a very useful configuration that allows you to run the same benchmarking jobs with different inputs. We call this combination a _"scenario"_. You specify the inputs as either a map from name (String or atom) to the actual input value or a list of tuples where the first element in each tuple is the name and the second element in the tuple is the value. + +Why do this? Functions can have different performance characteristics on differently shaped inputs - be that structure or input size. One of such cases is comparing tail-recursive and body-recursive implementations of `map`. More information in the [repository with the benchmark](https://github.com/PragTob/elixir_playground/blob/main/bench/tco_blog_post_focussed_inputs.exs) and the [blog post](https://pragtob.wordpress.com/2016/06/16/tail-call-optimization-in-elixir-erlang-not-as-efficient-and-important-as-you-probably-think/). + +As a little sample: + +```elixir +map_fun = fn i -> [i, i * i] end + +Benchee.run( + %{ + "flat_map" => fn input -> Enum.flat_map(input, map_fun) end, + "map.flatten" => fn input -> input |> Enum.map(map_fun) |> List.flatten() end + }, + inputs: %{ + "Small" => Enum.to_list(1..1_000), + "Medium" => Enum.to_list(1..10_000), + "Bigger" => Enum.to_list(1..100_000) + } +) +``` + +This means each function will be benchmarked with each input that is specified in the inputs. Then you'll get the output divided by input so you can see which function is fastest for which input, like so: + +``` +tobi@speedy:~/github/benchee(readme-overhaul)$ mix run samples/multiple_inputs.exs + +(... general information ...) + +##### With input Bigger ##### +Name ips average deviation median 99th % +flat_map 150.81 6.63 ms ±12.65% 6.57 ms 8.74 ms +map.flatten 114.05 8.77 ms ±16.22% 8.42 ms 12.76 ms + +Comparison: +flat_map 150.81 +map.flatten 114.05 - 1.32x slower +2.14 ms + +##### With input Medium ##### +Name ips average deviation median 99th % +flat_map 2.28 K 437.80 μs ±10.72% 425.63 μs 725.09 μs +map.flatten 1.78 K 561.18 μs ±5.55% 553.98 μs 675.98 μs + +Comparison: +flat_map 2.28 K +map.flatten 1.78 K - 1.28x slower +123.37 μs + +##### With input Small ##### +Name ips average deviation median 99th % +flat_map 26.31 K 38.01 μs ±15.47% 36.69 μs 67.08 μs +map.flatten 18.65 K 53.61 μs ±11.32% 52.79 μs 70.17 μs + +Comparison: +flat_map 26.31 K +map.flatten 18.65 K - 1.41x slower +15.61 μs +``` + +Therefore, we **highly recommend** using this feature and checking different realistically structured and sized inputs for the functions you benchmark! + +### Formatters + +Among all the configuration options, one that you probably want to use are the formatters. They format and print out the results of the benchmarking suite. + +The `:formatters` option is specified a list of: +* modules implementing the `Benchee.Formatter` behaviour +* a tuple of a module specified above and options for it `{module, options}` +* functions that take one argument (the benchmarking suite with all its results) and then do whatever you want them to + +So if you are using the [HTML plugin](https://github.com/bencheeorg/benchee_html) and you want to run both the console formatter and the HTML formatter this looks like this (after you installed it of course): + +```elixir +list = Enum.to_list(1..10_000) +map_fun = fn i -> [i, i * i] end + +Benchee.run( + %{ + "flat_map" => fn -> Enum.flat_map(list, map_fun) end, + "map.flatten" => fn -> list |> Enum.map(map_fun) |> List.flatten end + }, + formatters: [ + {Benchee.Formatters.HTML, file: "samples_output/my.html"}, + Benchee.Formatters.Console + ] +) +``` + +#### Console Formatter options + +The console formatter supports 2 configuration options: + + * `:comparison` - if the comparison of the different benchmarking jobs (x times slower than) is shown. Enabled by default. + * `extended_statistics` - display more statistics, aka `minimum`, `maximum`, `sample_size` and `mode`. Disabled by default. + +So if you want to see more statistics you simple pass `extended_statistics: true` to the console formatter: + +```elixir +list = Enum.to_list(1..10_000) +map_fun = fn i -> [i, i * i] end + +Benchee.run( + %{ + "flat_map" => fn -> Enum.flat_map(list, map_fun) end, + "map.flatten" => fn -> list |> Enum.map(map_fun) |> List.flatten() end + }, + time: 10, + formatters: [{Benchee.Formatters.Console, extended_statistics: true}] +) +``` + +Which produces: + +``` +(... normal output ...) + +Extended statistics: + +Name minimum maximum sample size mode +flat_map 345.43 μs 1195.89 μs 23.73 K 405.64 μs +map.flatten 522.99 μs 2105.56 μs 12.03 K 767.83 μs, 768.44 μs +``` + +(Btw. notice how the modes of both are much closer and for `map.flatten` much less than the average of `766.99`, see `samples/run_extended_statistics`) + +### Profiling after a run + +Often time when benchmarking, you want to improve performance. However, Benchee only tells you how fast something is, it doesn't tell you what part of your code is slow. This is where profiling comes in. + +Benchee offers you the `profile_after` option to run a profiler of your choice after a benchmarking run to see what's slow. This will run every scenario once. + +By default it will run the `:eprof` profiler, different profilers with different options can be used - see [configuration](#configuration). + +```elixir +list = Enum.to_list(1..10_000) +map_fun = fn i -> [i, i * i] end + +Benchee.run( + %{ + "flat_map" => fn -> Enum.flat_map(list, map_fun) end, + "map.flatten" => fn -> list |> Enum.map(map_fun) |> List.flatten() end + }, + profile_after: true +) +``` + +After the normal benchmarking, this results prints profiles like: + +``` +Profiling flat_map with eprof... +Warmup... + + +Profile results of #PID<0.1885.0> +# CALLS % TIME µS/CALL +Total 30004 100.0 5665 0.19 +Enum.flat_map/2 1 0.00 0 0.00 +anonymous fn/2 in :elixir_compiler_1.__FILE__/1 1 0.00 0 0.00 +:erlang.apply/2 1 0.04 2 2.00 +:erlang.++/2 10000 18.38 1041 0.10 +anonymous fn/1 in :elixir_compiler_1.__FILE__/1 10000 28.12 1593 0.16 +Enum.flat_map_list/2 10001 53.47 3029 0.30 + +Profile done over 6 matching functions + +Profiling map.flatten with eprof... +Warmup... + + +Profile results of #PID<0.1887.0> +# CALLS % TIME µS/CALL +Total 60007 100.0 8649 0.14 +Enum.map/2 1 0.00 0 0.00 +anonymous fn/2 in :elixir_compiler_1.__FILE__/1 1 0.00 0 0.00 +List.flatten/1 1 0.00 0 0.00 +:lists.flatten/1 1 0.00 0 0.00 +:erlang.apply/2 1 0.02 2 2.00 +anonymous fn/1 in :elixir_compiler_1.__FILE__/1 10000 16.35 1414 0.14 +Enum."-map/2-lists^map/1-0-"/2 10001 26.38 2282 0.23 +:lists.do_flatten/2 40001 57.24 4951 0.12 +``` + +**Note about after_each hooks:** `after_each` hooks currently don't work when profiling a function, as they are not passed the return value of the function after the profiling run. It's already fixed on the elixir side and is waiting for release, likely in 1.14. It should then just work. + +### Remove Outliers + +Benchee can remove outliers from the gathered samples while calculating statistics. +That is, as determined by percentiles/quantiles (we follow [this approach](https://en.wikipedia.org/wiki/Interquartile_range#Outliers)). + +You might consider excluding outliers for extreme micro/nano-benchmarks where individual results can be skewed a lot by the Garbage Collection. + +You can simply pass `exclude_outliers: true` to Benchee to trigger the removal of outliers. + +```elixir +Benchee.run(jobs, exclude_outliers: true) +``` + +The outliers themselves (aka the samples that have been determined to be outliers) +as well as the lower/upper bound after which samples are considered outliers are accessible +in the `Benchee.Statistics` struct. + +The samples themselves still include the outliers, they are only removed for calculating statistics. + +Right now Benchee doesn't print the outliers yet, but you can inspect the resulting data structures if you're interested (or send a PR :) ) + +### Saving, loading and comparing previous runs + +Benchee can store the results of previous runs in a file and then load them again to compare them. For example this is useful to compare what was recorded on the main branch against a branch with performance improvements. You may also use this to benchmark across different exlixir/erlang versions. + +**Saving** is done through the `:save` configuration option. You can specify a `:path` where results are saved, or you can use the default option of`"benchmark.benchee"` if you don't pass a `:path`. You can also pass a `:tag` option which annotates these results (for instance with a branch name or elixir version number). The default option for the `:tag` is a timestamp of when the benchmark was run. + +**Loading** is done through the `:load` option specifying a path to the file to load (for instance `"benchmark.benchee"`). You can also specify multiple files to load through a list of paths (`["my.benchee", "main_save.benchee"]`) - each one of those can also be a glob expression to match even more files glob (`"save_number*.benchee"`). +In the more verbose API loading is triggered via `Benchee.load/1`. +If all you want to do is to use `:load` without running any benchmarks then you can use `Benchee.report/1` which will take a normal configuration with a `:load` key and just format the loaded saved results with the given formatters. + +```elixir +Benchee.run( + %{ + "something_great" => fn -> cool_stuff end + }, + save: [path: "save.benchee", tag: "first-try"] +) + +Benchee.report(load: "save.benchee") +``` + +### Hooks (Setup, Teardown etc.) + +Most of the time, it's best to keep your benchmarks as simple as possible: plain old immutable functions work best. But sometimes you need other things to happen. When you want to add before or after hooks to your benchmarks, we've got you covered! Before you dig into this section though remember one thing: **you usually don't need hooks!** + +Benchee has three types of hooks: + +* [Suite hooks](#suite-hooks) +* [Scenario hooks](#scenario-hooks) +* [Benchmarking function hooks](#benchmarking-function-hooks) + + +Of course, **hooks are not included in the measurements**. So they are there especially if you want to do something and want it to **not be included in the measurements**. Sadly there is the notable exception of _too_fast_functions_ (the ones that execute faster than we can measure in [_native_ resolution](#a-note-on-time-measurement-accuracy)). As we need to measure their repeated invocations to get halfway good measurements `before_each` and `after_each` hooks are included there. However, to the best of our knowledge this should only ever happen on Windows (because of the bad run time measurement accuracy). + +#### Suite hooks + +It is very easy in Benchee to do setup and teardown for the whole benchmarking suite (think: "before all" and "after all"). As Benchee is just plain old functions, just do your setup and teardown before/after you call Benchee: + +```elixir +your_setup() + +Benchee.run(%{"Awesome stuff" => fn -> magic end}) + +your_teardown() +``` + +_When might this be useful?_ + +* Seeding the database with data to be used by all benchmarking functions +* Starting/shutting down a server, process, other dependencies + +#### Scenario hooks + +For the following discussions, it's important to know what benchee considers a "benchmarking scenario". + +##### What is a scenario? + +A scenario is the combination of one benchmarking function and one input. So, given this benchmark: + +```elixir +Benchee.run( + %{ + "foo" => fn input -> ... end, + "bar" => fn input -> ... end + }, + inputs: %{ + "input 1" => 1, + "input 2" => 2 + } +) +``` + +there are 4 scenarios: + +1. foo with input 1 +2. foo with input 2 +3. bar with input 1 +4. bar with input 2 + +A scenario includes warmup and actual run time (+ other measurements like memory). + +##### before_scenario + +Is executed before every [scenario](#what-is-a-scenario) that it applies to (see [hook configuration](#hook-configuration-global-versus-local)). `before_scenario` hooks take the input of the scenario as an argument. + +Since the return value of a `before_scenario` becomes the input for next steps (see [hook arguments and return values](#hook-arguments-and-return-values)), there usually are 3 kinds of before scenarios: + +* you just want to invoke a side effect: in that case return the given input unchanged +* you want to alter the given input: in that case alter the given input +* you want to keep the given input but add some other data: in that case return a tuple like `{original_input, new_fancy_data}` + +For before scenario hooks, the _global_ hook is invoked first, then the _local_ (see [when does a hook happen?](#when-does-a-hook-happen-complete-example)). + +Usage: + +```elixir +Benchee.run( + %{ + "foo" => + { + fn {input, resource} -> foo(input, resource) end, + before_scenario: fn {input, resource} -> + resource = alter_resource(resource) + {input, resource} + end + }, + "bar" => + fn {input, resource} -> bar(input, resource) end + }, + inputs: %{"input 1" => 1}, + before_scenario: fn input -> + resource = start_expensive_resource() + {input, resource} + end +) +``` + +_When might this be useful?_ + +* Starting a process to be used in your scenario +* Recording the PID of `self()` for use in your benchmark (each scenario is executed in its own process, so scenario PIDs aren't available in functions running before the suite) +* Clearing the cache before a scenario + +##### after_scenario + +Is executed after a scenario has completed. After scenario hooks receive the return value of the last `before_scenario` that ran as an argument. The return value is discarded (see [hook arguments and return values](#hook-arguments-and-return-values)). + +For after scenario hooks, the _local_ hook is invoked first, then the _global_ (see [when does a hook happen?](#when-does-a-hook-happen-complete-example)). + +Usage: + +```elixir +Benchee.run( + %{ + "bar" => fn -> bar() end + }, + after_scenario: fn _input -> bust_my_cache() end +) +``` + +_When might this be useful?_ + +* Busting caches after a scenario completed +* Deleting all the records in the database that the scenario just created +* Terminating whatever was setup by `before_scenario` + +#### Benchmarking function hooks + +You can also schedule hooks to run before and after each invocation of a benchmarking function. + +##### before_each + +Is executed before each invocation of the benchmarking function (before every measurement). Before each hooks receive the return value of their `before_scenario` hook as their argument. The return value of a before each hook becomes the input to the benchmarking function (see [hook arguments and return values](#hook-arguments-and-return-values)). + +For before each hooks, the _global_ hook is invoked first, then the _local_ (see [when does a hook happen?](#when-does-a-hook-happen-complete-example)). + +Usage: + +```elixir +Benchee.run( + %{ + "bar" => fn record -> bar(record) end + }, + inputs: %{ "record id" => 1}, + before_each: fn input -> get_from_db(input) end +) +``` + +_When might this be useful?_ + +* Retrieving a record from the database and passing it on to the benchmarking function to do _something(tm)_ without the retrieval from the database adding to the benchmark measurement +* Busting caches so that all measurements are taken in an uncached state +* Picking a random value from a collection and passing it to the benchmarking function for measuring performance with a wider spread of values +* You could also use this to benchmark with random data generated by tools like [StreamData](https://github.com/whatyouhide/stream_data), Devon shows how it's done [here](https://devonestes.com/benchmarking-with-stream-data) + +##### after_each + +Is executed directly after the invocation of the benchmarking function. After each hooks receive the return value of the benchmarking function as their argument. The return value is discarded (see [hook arguments and return values](#hook-arguments-and-return-values)). + +For after each hooks, the _local_ hook is invoked first, then the _global_ (see [when does a hook happen?](#when-does-a-hook-happen-complete-example)). + +Usage: + +```elixir +Benchee.run( + %{ + "bar" => fn input -> bar(input) end + }, + inputs: %{ "input 1" => 1}, + after_each: fn result -> assert result == 42 end +) +``` + +_When might this be useful?_ + +* Running assertions that whatever your benchmarking function returns is truly what it should be (i.e. all "contestants" work as expected) +* Busting caches/terminating processes setup in `before_each` or elsewhere +* Deleting files created by the benchmarking function + +#### Hook arguments and return values + +Before hooks form a chain, where the return value of the previous hook becomes the argument for the next one. The first defined `before` hook receives the scenario input as an argument, and returns a value that becomes the argument of the next in the chain. The benchmarking function receives the value of the last `before` hook as its argument (or the scenario input if there are no `before` hooks). + +After hooks do not form a chain, and their return values are discarded. An `after_each` hook receives the return value of the benchmarking function as its argument. An `after_scenario` function receives the return value of the last `before_scenario` that ran (or the scenario's input if there is no `before_scenario` hook). + +If you haven't defined any inputs, the hook chain is started with the special input argument returned by `Benchee.Benchmark.no_input()`. + +#### Hook configuration: global versus local + +Hooks can be defined either _globally_ as part of the configuration or _locally_ for a specific benchmarking function. Global hooks will be executed for every scenario in the suite. Local hooks will only be executed for scenarios involving that benchmarking function. + +**Global hooks** + +Global hooks are specified as part of the general benchee configuration: + +```elixir +Benchee.run( + %{ + "foo" => fn input -> ... end, + "bar" => fn input -> ... end + }, + inputs: %{ + "input 1" => 1, + "input 2" => 2, + }, + before_scenario: fn input -> ... end +) +``` + +Here the `before_scenario` function will be executed for all 4 scenarios present in this benchmarking suite. + +**Local hooks** + +Local hooks are defined alongside the benchmarking function. To define a local hook, pass a tuple in the initial map, instead of just a single function. The benchmarking function comes first, followed by a keyword list specifying the hooks to run: + +```elixir +Benchee.run( + %{ + "foo" => {fn input -> ... end, before_scenario: fn input -> ... end}, + "bar" => fn input -> ... end + }, + inputs: %{ + "input 1" => 1, + "input 2" => 2 + } +) +``` + +Here `before_scenario` is only run for the 2 scenarios associated with `"foo"`, i.e. foo with input 1 and foo with input 2. It is _not_ run for any `"bar"` benchmarks. + + +#### When does a hook happen? (Complete Example) + +Yes the whole hooks system is quite a lot to take in. Here is an overview showing the order of hook execution, along with the argument each hook receives (see [hook arguments and return values](#hook-arguments-and-return-values)). The guiding principle whether _local_ or _global_ is run first is that _local_ always executes closer to the benchmarking function. + +Given the following code: + +```elixir + +suite_set_up() + +Benchee.run( + %{ + "foo" => + { + fn input -> foo(input) end, + before_scenario: fn input -> + local_before_scenario(input) + input + 1 + end, + before_each: fn input -> + local_before_each(input) + input + 1 + end, + after_each: fn value -> + local_after_each(value) + end, + after_scenario: fn input -> + local_after_scenario(input) + end + }, + "bar" => + fn input -> bar(input) end + }, + inputs: %{"input 1" => 1}, + before_scenario: fn input -> + global_before_scenario(input) + input + 1 + end, + before_each: fn input -> + global_before_each(input) + input + 1 + end, + after_each: fn value -> + global_after_each(value) + end, + after_scenario: fn input -> + global_after_scenario(input) + end +) + +suite_tear_down() +``` + +Keeping in mind that the order of foo and bar could be different, here is how the hooks are called: + +``` +suite_set_up + +# starting with the foo scenario +global_before_scenario(1) +local_before_scenario(2) # as before_scenario incremented it + +global_before_each(3) +local_before_each(4) +foo(5) # let's say foo(5) returns 6 +local_after_each(6) +global_after_each(6) + +global_before_each(3) +local_before_each(4) +foo(5) # let's say foo(5) returns 6 +local_after_each(6) +global_after_each(6) + +# ... this block is repeated as many times as benchee has time + +local_after_scenario(3) +global_after_scenario(3) + +# now it's time for the bar scenario, it has no hooks specified for itself +# so only the global hooks are run + +global_before_scenario(1) + +global_before_each(2) +bar(3) # let's say foo(3) returns 4 +global_after_each(4) + +global_before_each(2) +bar(3) # let's say foo(3) returns 4 +global_after_each(4) + +# ... this block is repeated as many times as benchee has time + +global_after_scenario(2) + +suite_tear_down +``` + +### More verbose usage + +It is important to note that the benchmarking code shown in the beginning is the convenience interface. The same benchmark in its more verbose form looks like this: + +```elixir +list = Enum.to_list(1..10_000) +map_fun = fn i -> [i, i * i] end + +[time: 3] +|> Benchee.init() +|> Benchee.system() +|> Benchee.benchmark("flat_map", fn -> Enum.flat_map(list, map_fun) end) +|> Benchee.benchmark( + "map.flatten", + fn -> list |> Enum.map(map_fun) |> List.flatten() end +) +|> Benchee.collect() +|> Benchee.statistics() +|> Benchee.relative_statistics() +|> Benchee.Formatter.output(Benchee.Formatters.Console) +# Instead of the last call you could also just use Benchee.Formatter.output() +# to just output all configured formatters +``` + +This is a take on the _functional transformation_ of data applied to benchmarks: + +1. Configure the benchmarking suite to be run +2. Gather System data +3. Define the functions to be benchmarked +4. Run benchmarks with the given configuration gathering raw run times per function +5. Calculate statistics based on the raw run times +6. Calculate statistics between the scenarios (faster/slower...) +7. Format the statistics in a suitable way and print them out + +This is also part of the **official API** and allows for more **fine grained control**. (It's also what Benchee does internally when you use `Benchee.run/2`). + +Do you just want to have all the raw run times? Just work with the result of `Benchee.collect/1`! Just want to have the calculated statistics and use your own formatting? Grab the result of `Benchee.statistics/1`! Or, maybe you want to write to a file or send an HTTP post to some online service? Just grab the complete suite after statistics were generated. + +It also allows you to alter behaviour, normally `Benchee.load/1` is called right before the formatters so that neither the benchmarks are run again or statistics are computed again. However, you might want to run the benchmarks again or recompute the statistics. Then you can call `Benchee.load/1` right at the start. + +This way Benchee should be flexible enough to suit your needs and be extended at will. Have a look at the [available plugins](#plugins). + +### Usage from Erlang + +Before you dig deep into this, it is inherently easier to setup a small elixir project, add a dependency to your erlang project and then run the benchmarks from elixir. The reason is easy - mix knows about rebar3 and knows how to work with it. The reverse isn't true so the road ahead is somewhat bumpy. + +There is an [example project](https://github.com/bencheeorg/benchee_erlang_try) to check out. + +You can use the [rebar3_elixir_compile](https://github.com/barrel-db/rebar3_elixir_compile) plugin. In your `rebar.config` you can do the following which should get you started: + +```erlang +deps, [ + {benchee, {elixir, "benchee", "0.9.0"}} +]}. + +{plugins, [ + { rebar3_elixir_compile, ".*", {git, "https://github.com/barrel-db/rebar3_elixir_compile.git", {branch, "main"}}} +]}. + +{provider_hooks, [ + {pre, [{compile, {ex, compile}}]}, + {pre, [{release, {ex, compile}}]} +]}. + +{elixir_opts, + [ + {env, dev} + ] +}. +``` + +Then benchee already provides a `:benchee` interface for erlang compatibility which you can use. Sadly couldn't get it to work in an escript yet. + +You can then invoke it like this (for instance): + +``` +tobi@comfy ~/github/benchee_erlang_try $ rebar3 shell +===> dependencies etc. +Erlang/OTP 18 [erts-7.3] [source] [64-bit] [smp:4:4] [async-threads:0] [hipe] [kernel-poll:false] + +Eshell V7.3 (abort with ^G) +1> benchee:run(#{myFunc => fun() -> lists:sort([8, 2, 3, 4, 2, 1, 3, 4, 9, 10, 11, 12, 13, 20, 1000, -4, -5]) end}, [{warmup, 0}, {time, 2}]). +Operating System: Linux +CPU Information: Intel(R) Core(TM) i5-7200U CPU @ 2.50GHz +Number of Available Cores: 4 +Available memory: 8.05 GB +Elixir 1.3.4 +Erlang 18.3 +Benchmark suite executing with the following configuration: +warmup: 0.0 μs +time: 2 s +parallel: 1 +inputs: none specified +Estimated total run time: 2 s + + +Benchmarking myFunc... + +Name ips average deviation median +myFunc 289.71 K 3.45 μs ±250.31% 3 μs +``` + +This doesn't seem to be too reliable right now, so suggestions and input are very welcome :) + +## Known Issues + +There is a known issue affecting elixir versions from 1.14.0 to 1.16.0-rc.0: Optimizations (SSA and bool passes, [see the original change](https://github.com/elixir-lang/elixir/pull/11420)) had been disabled affecting the performance of functions defined directly in the top level (i.e. outside of any module). The issue was fixed by re-enabling the optimization in [1.16.0-rc.1](https://github.com/elixir-lang/elixir/blob/v1.16/CHANGELOG.md#v1160-rc1-2023-12-12). +The issue is best show-cased by the following benchmark where we'd expect ~equal results: + +```elixir +list = Enum.to_list(1..10_000) + +defmodule Compiled do + def comprehension(list) do + for x <- list, rem(x, 2) == 1, do: x + 1 + end +end + +Benchee.run(%{ + "module (optimized)" => fn -> Compiled.comprehension(list) end, + "top_level (non-optimized)" => fn -> for x <- list, rem(x, 2) == 1, do: x + 1 end +}) +``` + +Which yields ~these results on an affected elixir version: + +``` +Comparison: +module (optimized) 18.24 K +top_level (non-optimized) 11.91 K - 1.53x slower +29.14 μs +``` + +So, how do you fix it/make sure a benchmark you ran is not affected? All of these work: + +* benchmark on an unaffected/fixed version of elixir (<= 1.13.4 or >= 1.16.0-rc.1) +* put the code you want to benchmark into a module (just like it is done in `Compiled` in the example above) +* you can also invoke benchee from within a module, such as: + +```elixir +defmodule Compiled do + def comprehension(list) do + for x <- list, rem(x, 2) == 1, do: x + 1 + end +end + +defmodule MyBenchmark do + def run do + list = Enum.to_list(1..10_000) + + Benchee.run(%{ + "module (optimized)" => fn -> Compiled.comprehension(list) end, + "top_level (non-optimized)" => fn -> for x <- list, rem(x, 2) == 1, do: x + 1 end + }) + end +end + +MyBenchmark.run() +``` + +Also note that even if all your examples are top level functions you should still follow these tips (on affected elixir versions), as the missing optimization might affect them differently. Further note, that even though your examples use top level functions they _may_ not be affected, as the specific disabled optimization may not impact them. Better safe than sorry though :) + +## Plugins + +Benchee only has small runtime dependencies that were initially extracted from it. Further functionality is provided through plugins that then pull in dependencies, such as HTML generation and CSV export. They help provide excellent visualization or interoperability. + +* [benchee_html](//github.com/bencheeorg/benchee_html) - generate HTML including a data table and many different graphs with the possibility to export individual graphs as PNG :) +* [benchee_csv](//github.com/bencheeorg/benchee_csv) - generate CSV from your benchee benchmark results so you can import them into your favorite spreadsheet tool and make fancy graphs +* [benchee_json](//github.com/bencheeorg/benchee_json) - export suite results as JSON to feed anywhere or feed it to your JavaScript and make magic happen :) +* [benchee_markdown](//github.com/hrzndhrn/benchee_markdown) - write markdown files containing your benchmarking results + +With the HTML plugin for instance you can get fancy graphs like this boxplot: + +![boxplot](http://www.pragtob.info/benchee/images/boxplot.png) + +Of course there also are normal bar charts including standard deviation: + +![flat_map_ips](http://www.pragtob.info/benchee/images/flat_map_ips.png) + +## Contributing [![Open Source Helpers](https://www.codetriage.com/pragtob/benchee/badges/users.svg)](https://www.codetriage.com/pragtob/benchee) + +Contributions to Benchee are **very welcome**! Bug reports, documentation, spelling corrections, whole features, feature ideas, bugfixes, new plugins, fancy graphics... all of those (and probably more) are much appreciated contributions! + +Keep in mind that the [plugins](#plugins) live in their own repositories with their own issue tracker and they also like to get contributions :) + +Please respect the [Code of Conduct](//github.com/bencheeorg/benchee/blob/main/CODE_OF_CONDUCT.md). + +In addition to contributing code, you can help to triage issues. This can include reproducing bug reports, or asking for vital information such as version numbers or reproduction instructions. If you would like to start triaging issues, one easy way to get started is to [subscribe to pragtob/benchee on CodeTriage](https://www.codetriage.com/pragtob/benchee). + +You can also look directly at the [open issues](https://github.com/bencheeorg/benchee/issues). There are `help wanted` and `good first issue` labels - those are meant as guidance, of course other issues can be tackled :) + +A couple of (hopefully) helpful points: + +* Feel free to ask for help and guidance on an issue/PR ("How can I implement this?", "How could I test this?", ...) +* Feel free to open early/not yet complete pull requests to get some early feedback +* When in doubt if something is a good idea open an issue first to discuss it +* In case I don't respond feel free to bump the issue/PR or ping me in other places + +If you're on the [elixir-lang slack](https://elixir-lang.slack.com) also feel free to drop by in `#benchee` and say hi! + +## Development + +Note that if the change includes adding new statistics you might need to introduce them to our statistics library [Statistex](https://github.com/bencheeorg/statistex) first! + +For an overview of benchee's architecture, check out [architecture](./architecture/README.md)! + +* `mix deps.get` to install dependencies +* `mix test` to run tests +* `mix dialyzer` to run dialyzer for type checking, might take a while on the first invocation (try building plts first with `mix dialyzer --plt`) +* `mix credo` to find code style problems +* or run `mix guard` to run all of them continuously on file change + + +## Copyright and License + +Copyright (c) 2016 Tobias Pfeiffer + +This work is free. You can redistribute it and/or modify it under the +terms of the MIT License. See the [LICENSE.md](./LICENSE.md) file for more details. diff --git a/deps/benchee/hex_metadata.config b/deps/benchee/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..fb6395426554ca85258ea2d31e22ef95734f131c --- /dev/null +++ b/deps/benchee/hex_metadata.config @@ -0,0 +1,70 @@ +{<<"links">>, + [{<<"Blog posts">>,<<"https://pragtob.wordpress.com/tag/benchee/">>}, + {<<"Changelog">>,<<"https://hexdocs.pm/benchee/changelog.html">>}, + {<<"GitHub">>,<<"https://github.com/bencheeorg/benchee">>}]}. +{<<"name">>,<<"benchee">>}. +{<<"version">>,<<"1.5.0">>}. +{<<"description">>, + <<"Versatile (micro) benchmarking that is extensible. Get statistics such as:\naverage, iterations per second, standard deviation and the median.">>}. +{<<"elixir">>,<<"~> 1.6">>}. +{<<"app">>,<<"benchee">>}. +{<<"licenses">>,[<<"MIT">>]}. +{<<"requirements">>, + [[{<<"name">>,<<"table">>}, + {<<"app">>,<<"table">>}, + {<<"optional">>,true}, + {<<"requirement">>,<<"~> 0.1.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"deep_merge">>}, + {<<"app">>,<<"deep_merge">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 1.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"statistex">>}, + {<<"app">>,<<"statistex">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 1.1">>}, + {<<"repository">>,<<"hexpm">>}]]}. +{<<"files">>, + [<<"lib">>,<<"lib/benchee">>,<<"lib/benchee/conversion.ex">>, + <<"lib/benchee/scenario.ex">>,<<"lib/benchee/suite.ex">>, + <<"lib/benchee/configuration.ex">>,<<"lib/benchee/formatter.ex">>, + <<"lib/benchee/system.ex">>,<<"lib/benchee/profile.ex">>, + <<"lib/benchee/conversion">>,<<"lib/benchee/conversion/memory.ex">>, + <<"lib/benchee/conversion/unit.ex">>, + <<"lib/benchee/conversion/duration.ex">>, + <<"lib/benchee/conversion/scale.ex">>,<<"lib/benchee/conversion/count.ex">>, + <<"lib/benchee/conversion/deviation_percent.ex">>, + <<"lib/benchee/conversion/format.ex">>,<<"lib/benchee/utility">>, + <<"lib/benchee/utility/deep_convert.ex">>, + <<"lib/benchee/utility/repeat_n.ex">>,<<"lib/benchee/utility/parallel.ex">>, + <<"lib/benchee/utility/erlang_version.ex">>, + <<"lib/benchee/utility/file_creation.ex">>, + <<"lib/benchee/scenario_loader.ex">>,<<"lib/benchee/statistics.ex">>, + <<"lib/benchee/collection_data.ex">>, + <<"lib/benchee/relative_statistics.ex">>,<<"lib/benchee/errors.ex">>, + <<"lib/benchee/benchmark.ex">>,<<"lib/benchee/output">>, + <<"lib/benchee/output/progress_printer.ex">>, + <<"lib/benchee/output/profile_printer.ex">>, + <<"lib/benchee/output/benchmark_printer.ex">>,<<"lib/benchee/formatters">>, + <<"lib/benchee/formatters/console">>, + <<"lib/benchee/formatters/console/run_time.ex">>, + <<"lib/benchee/formatters/console/helpers.ex">>, + <<"lib/benchee/formatters/console/memory.ex">>, + <<"lib/benchee/formatters/console/reductions.ex">>, + <<"lib/benchee/formatters/console.ex">>, + <<"lib/benchee/formatters/tagged_save.ex">>,<<"lib/benchee/benchmark">>, + <<"lib/benchee/benchmark/runner.ex">>, + <<"lib/benchee/benchmark/scenario_context.ex">>, + <<"lib/benchee/benchmark/collect.ex">>, + <<"lib/benchee/benchmark/repeated_measurement.ex">>, + <<"lib/benchee/benchmark/function_call_overhead.ex">>, + <<"lib/benchee/benchmark/collect">>, + <<"lib/benchee/benchmark/collect/memory.ex">>, + <<"lib/benchee/benchmark/collect/reductions.ex">>, + <<"lib/benchee/benchmark/collect/time.ex">>, + <<"lib/benchee/benchmark/hooks.ex">>, + <<"lib/benchee/benchmark/benchmark_config.ex">>,<<"lib/benchee.ex">>, + <<".formatter.exs">>,<<"mix.exs">>,<<"README.md">>,<<"LICENSE.md">>, + <<"CHANGELOG.md">>]}. +{<<"build_tools">>,[<<"mix">>]}. diff --git a/deps/benchee/lib/benchee.ex b/deps/benchee/lib/benchee.ex new file mode 100644 index 0000000000000000000000000000000000000000..dad63f81c06688907fb43919d91c994fe56c4bf6 --- /dev/null +++ b/deps/benchee/lib/benchee.ex @@ -0,0 +1,109 @@ +# Idea from this: +# credo:disable-for-next-line +# https://github.com/bencheeorg/benchee/commit/b3ddbc132e641cdf1eec0928b322ced1dab8553f#commitcomment-23381474 + +elixir_doc = """ +Top level module providing convenience access to needed functions as well +as the very high level `Benchee.run` API. + +Intended Elixir interface. +""" + +erlang_doc = """ +High-Level interface for more convenient usage from Erlang. Same as `Benchee`. +""" + +for {module, moduledoc} <- [{Benchee, elixir_doc}, {:benchee, erlang_doc}] do + defmodule module do + @moduledoc moduledoc + + alias Benchee.Formatter + + @doc """ + Run benchmark jobs defined by a map and optionally provide configuration + options. + + Benchmarks are defined as a map where the keys are a name for the given + function and the values are the functions to benchmark. Users can configure + the run by passing a keyword list as the second argument. For more + information on configuration see `Benchee.Configuration.init/1`. + + ## Examples + + Benchee.run( + %{ + "My Benchmark" => fn -> 1 + 1 end, + "My other benchmrk" => fn -> [1] ++ [1] end + }, + warmup: 2, + time: 3 + ) + """ + @spec run(map, keyword) :: Benchee.Suite.t() + def run(jobs, config \\ []) when is_list(config) do + config + |> Benchee.init() + |> Benchee.system() + |> add_benchmarking_jobs(jobs) + |> Benchee.collect() + |> Benchee.statistics() + |> Benchee.load() + |> Benchee.relative_statistics() + |> Formatter.output() + |> Benchee.profile() + end + + defp add_benchmarking_jobs(suite, jobs) do + Enum.reduce(jobs, suite, fn {key, function}, suite_acc -> + Benchee.benchmark(suite_acc, key, function) + end) + end + + @doc """ + A convenience function designed for loading saved benchmarks and running formatters on them. + + Basically takes the input of the map of jobs away from you and skips unnecessary steps with + that data missing (aka not running benchmarks, only running relative statistics). + + You can use config options as normal, but some options related to benchmarking won't take + effect (such as `:time`). The `:load` option however is mandatory to use, as you need to + load some benchmarks to report on them. + + ## Usage + + Benchee.report(load: ["benchmark-*.benchee"]) + """ + @spec report(keyword) :: Benchee.Suite.t() + def report(config) do + if !Access.get(config, :load), do: raise_missing_load() + + config + |> Benchee.init() + |> Benchee.system() + |> Benchee.load() + |> Benchee.relative_statistics() + |> Formatter.output() + end + + defp raise_missing_load do + raise ArgumentError, + "You need to provide at least a :load option for report/1 to make sense" + end + + defdelegate init(), to: Benchee.Configuration + defdelegate init(config), to: Benchee.Configuration + defdelegate system(suite), to: Benchee.System + defdelegate benchmark(suite, name, function), to: Benchee.Benchmark + @doc false + defdelegate benchmark(suite, name, function, printer), to: Benchee.Benchmark + defdelegate collect(suite), to: Benchee.Benchmark + @doc false + defdelegate collect(suite, printer), to: Benchee.Benchmark + defdelegate statistics(suite), to: Benchee.Statistics + @doc false + defdelegate statistics(suite, printer), to: Benchee.Statistics + defdelegate relative_statistics(suite), to: Benchee.RelativeStatistics + defdelegate load(suite), to: Benchee.ScenarioLoader + defdelegate profile(suite), to: Benchee.Profile + end +end diff --git a/deps/benchee/lib/benchee/benchmark.ex b/deps/benchee/lib/benchee/benchmark.ex new file mode 100644 index 0000000000000000000000000000000000000000..3ed49aa1f703c863d96d8c79a20e9766303db455 --- /dev/null +++ b/deps/benchee/lib/benchee/benchmark.ex @@ -0,0 +1,134 @@ +defmodule Benchee.Benchmark do + @moduledoc """ + Functions related to building and running benchmarking scenarios. + Exposes `benchmark/4` and `collect/3` functions. + """ + + alias Benchee.Benchmark.{BenchmarkConfig, Runner, ScenarioContext} + alias Benchee.Output.BenchmarkPrinter, as: Printer + alias Benchee.Scenario + alias Benchee.Suite + alias Benchee.Utility.DeepConvert + + @no_input :__no_input + @type no_input :: :__no_input + + @doc """ + Public access for the special key representing no input for a scenario. + """ + @spec no_input() :: no_input() + def no_input, do: @no_input + + @doc """ + Takes the current suite and adds a new benchmarking scenario (represented by a + %Scenario{} struct) with the given name and function to the suite's scenarios. + If there are inputs in the suite's config, a scenario will be added for the given + function for each input. + """ + @spec benchmark(Suite.t(), Suite.key(), Scenario.to_benchmark(), module) :: Suite.t() + def benchmark( + suite = %Suite{scenarios: scenarios}, + job_name, + to_be_benchmark, + printer \\ Printer + ) do + warn_if_evaluated(to_be_benchmark, job_name, printer) + + normalized_name = to_string(job_name) + + if duplicate?(scenarios, normalized_name) do + printer.duplicate_benchmark_warning(normalized_name) + suite + else + add_scenario(suite, normalized_name, to_be_benchmark) + end + end + + defp warn_if_evaluated(to_be_benchmark, job_name, printer) do + function = + case to_be_benchmark do + {function, _} -> function + function -> function + end + + if :erlang.fun_info(function, :module) == {:module, :erl_eval} do + printer.evaluated_function_warning(job_name) + end + end + + defp duplicate?(scenarios, job_name) do + Enum.any?(scenarios, fn scenario -> scenario.name == job_name end) + end + + defp add_scenario( + suite = %Suite{scenarios: scenarios, configuration: config}, + job_name, + function + ) do + new_scenarios = build_scenarios_for_job(job_name, function, config) + %Suite{suite | scenarios: List.flatten([scenarios | new_scenarios])} + end + + defp build_scenarios_for_job(job_name, function, %{inputs: nil}) do + [ + build_scenario(%{ + job_name: job_name, + function: function, + input: @no_input, + input_name: @no_input + }) + ] + end + + defp build_scenarios_for_job(job_name, function, %{inputs: inputs}) do + Enum.map(inputs, fn {input_name, input} -> + build_scenario(%{ + job_name: job_name, + function: function, + input: input, + input_name: input_name + }) + end) + end + + defp build_scenario(scenario_data = %{function: {function, options}}) do + scenario_data + |> Map.put(:function, function) + |> Map.merge(DeepConvert.to_map(options)) + |> build_scenario + end + + defp build_scenario(scenario_data) do + struct!(Scenario, add_scenario_name(scenario_data)) + end + + defp add_scenario_name(scenario_data) do + Map.put(scenario_data, :name, Scenario.display_name(scenario_data)) + end + + @doc """ + Kicks off the benchmarking of all scenarios defined in the given suite. + + Hence, this might take a while ;) Passes a list of scenarios and a scenario context to our + benchmark runner. For more information on how benchmarks are actually run, see the + `Benchee.Benchmark.Runner` code (API considered private). + """ + @spec collect(Suite.t(), module, module) :: Suite.t() + def collect( + suite = %Suite{scenarios: scenarios, configuration: config, system: system}, + printer \\ Printer, + runner \\ Runner + ) do + printer.configuration_information(suite) + benchmark_config = BenchmarkConfig.from(config) + + scenario_context = %ScenarioContext{ + config: benchmark_config, + printer: printer, + system: system + } + + scenarios = runner.run_scenarios(scenarios, scenario_context) + %Suite{suite | scenarios: scenarios} + end +end diff --git a/deps/benchee/lib/benchee/benchmark/benchmark_config.ex b/deps/benchee/lib/benchee/benchmark/benchmark_config.ex new file mode 100644 index 0000000000000000000000000000000000000000..ee624f7b68457b4f29ee261d8690e6e7975a6253 --- /dev/null +++ b/deps/benchee/lib/benchee/benchmark/benchmark_config.ex @@ -0,0 +1,55 @@ +defmodule Benchee.Benchmark.BenchmarkConfig do + @moduledoc """ + Benchmark Configuration, practically a sub set of `Benchee.Configuration` + + `Benchee.Configuration` holds too much data that we don't want to send into the benchmarking + processes - inputs being potentially huge. Hence, we take the sub set the benchmarks need and + put it in here. Since this is a benchmarking library, to no one's surprise these are a lot of + them. + See: https://github.com/bencheeorg/benchee/issues/412 + """ + + alias Benchee.Benchmark.Hooks + + @keys [ + :warmup, + :time, + :memory_time, + :reduction_time, + :pre_check, + :measure_function_call_overhead, + :before_each, + :after_each, + :before_scenario, + :after_scenario, + :parallel, + :print, + :max_sample_size + ] + + defstruct @keys + + @type t :: %__MODULE__{ + time: number, + warmup: number, + memory_time: number, + reduction_time: number, + pre_check: boolean, + measure_function_call_overhead: boolean, + print: map, + before_each: Hooks.hook_function() | nil, + after_each: Hooks.hook_function() | nil, + before_scenario: Hooks.hook_function() | nil, + after_scenario: Hooks.hook_function() | nil, + measure_function_call_overhead: boolean, + parallel: pos_integer(), + max_sample_size: pos_integer() + } + + alias Benchee.Configuration + + def from(config = %Configuration{}) do + values = Map.take(config, @keys) + struct!(__MODULE__, values) + end +end diff --git a/deps/benchee/lib/benchee/benchmark/collect.ex b/deps/benchee/lib/benchee/benchmark/collect.ex new file mode 100644 index 0000000000000000000000000000000000000000..daf4affec88eadd43399b87d1ef032c421267c77 --- /dev/null +++ b/deps/benchee/lib/benchee/benchmark/collect.ex @@ -0,0 +1,21 @@ +defmodule Benchee.Benchmark.Collect do + @moduledoc false + + # A thing that collects a data point about a function execution - like time + # or memory needed. + + @doc """ + Takes an anonymous 0 arity function to measure and returns the measurement + and the return value of the function in a tuple. + + The returned measurement may be `nil` if the measurement failed for some + reason - it will then be ignored and not counted. + """ + @type return_value :: {non_neg_integer | nil, any} + @type zero_arity_function :: (-> any) + @type opts :: any + @callback collect(zero_arity_function()) :: return_value() + @callback collect(zero_arity_function(), opts) :: return_value() + + @optional_callbacks collect: 2 +end diff --git a/deps/benchee/lib/benchee/benchmark/collect/memory.ex b/deps/benchee/lib/benchee/benchmark/collect/memory.ex new file mode 100644 index 0000000000000000000000000000000000000000..b29049463337562477f7e7d5bd9667d5a69a6f0c --- /dev/null +++ b/deps/benchee/lib/benchee/benchmark/collect/memory.ex @@ -0,0 +1,161 @@ +defmodule Benchee.Benchmark.Collect.Memory do + @moduledoc false + + # Measure memory consumption of a function. + # + # This is somewhat tricky and hence some resources can be recommended reading alongside + # this code: + # * description of the approach: https://devonestes.herokuapp.com/using-erlang-trace-3 + # * devon describing the journey that this feature put us through (includes remarks + # on why certain parts are very important: https://www.youtube.com/watch?v=aqLujfzvUgM) + # * erlang docs on the info data structure we use: + # http://erlang.org/doc/man/erlang.html#gc_minor_start + # + # Returns `{nil, return_value}` in case the memory measurement went bad. + + @behaviour Benchee.Benchmark.Collect + + defmacrop compatible_stacktrace do + if Version.match?(Version.parse!(System.version()), "~> 1.7") do + quote do + __STACKTRACE__ + end + else + quote do + System.stacktrace() + end + end + end + + @spec collect((-> any)) :: {nil | non_neg_integer, any} + def collect(fun) do + ref = make_ref() + Process.flag(:trap_exit, true) + start_runner(fun, ref) + await_results(nil, ref) + end + + defp await_results(return_value, ref) do + receive do + {^ref, memory_usage} -> + return_memory({memory_usage, return_value}) + + {^ref, :shutdown} -> + nil + + # we need a really basic pattern here because sending anything other than + # just what's returned from the function that we're benchmarking will + # involve allocating a new term, which will skew the measurements. + # We need to be very careful to always send the `ref` in every other + # message to this process. + new_result -> + await_results(new_result, ref) + end + end + + defp start_runner(fun, ref) do + parent = self() + + spawn_link(fn -> + tracer = start_tracer(self()) + + try do + _ = measure_memory(fun, tracer, parent) + word_size = :erlang.system_info(:wordsize) + memory_used = get_collected_memory(tracer) + send(parent, {ref, memory_used * word_size}) + catch + kind, reason -> + send(tracer, :done) + send(parent, {ref, :shutdown}) + stacktrace = compatible_stacktrace() + IO.puts(Exception.format(kind, reason, stacktrace)) + exit(:normal) + after + send(tracer, :done) + end + end) + end + + defp return_memory({memory_usage, return_value}) when memory_usage < 0, do: {nil, return_value} + defp return_memory(memory_usage_info), do: memory_usage_info + + defp measure_memory(fun, tracer, parent) do + :erlang.garbage_collect() + send(tracer, :begin_collection) + + receive do + :ready_to_begin -> nil + end + + return_value = fun.() + send(parent, return_value) + + :erlang.garbage_collect() + send(tracer, :end_collection) + + receive do + :ready_to_end -> nil + end + + # We need to reference these variables after we end our collection so + # these don't get GC'd and counted towards the memory usage of the function + # we're benchmarking. + {parent, fun} + end + + defp get_collected_memory(tracer) do + ref = Process.monitor(tracer) + send(tracer, {:get_collected_memory, self(), ref}) + + receive do + {:DOWN, ^ref, _, _, _} -> nil + {^ref, collected} -> collected + end + end + + defp start_tracer(pid) do + spawn(fn -> tracer_loop(pid, 0) end) + end + + defp tracer_loop(pid, acc) do + receive do + :begin_collection -> + :erlang.trace(pid, true, [:garbage_collection, tracer: self()]) + send(pid, :ready_to_begin) + tracer_loop(pid, acc) + + :end_collection -> + :erlang.trace(pid, false, [:garbage_collection]) + send(pid, :ready_to_end) + tracer_loop(pid, acc) + + {:get_collected_memory, reply_to, ref} -> + send(reply_to, {ref, acc}) + + {:trace, ^pid, :gc_minor_start, info} -> + listen_gc_end(pid, :gc_minor_end, acc, total_memory(info)) + + {:trace, ^pid, :gc_major_start, info} -> + listen_gc_end(pid, :gc_major_end, acc, total_memory(info)) + + :done -> + exit(:normal) + end + end + + defp listen_gc_end(pid, tag, acc, mem_before) do + receive do + {:trace, ^pid, ^tag, info} -> + mem_after = total_memory(info) + tracer_loop(pid, acc + mem_before - mem_after) + end + end + + defp total_memory(info) do + # `:heap_size` seems to only contain the memory size of the youngest + # generation `:old_heap_size` has the old generation. There is also + # `:recent_size` but that seems to already be accounted for. + Keyword.fetch!(info, :heap_size) + Keyword.fetch!(info, :old_heap_size) + end +end diff --git a/deps/benchee/lib/benchee/benchmark/collect/reductions.ex b/deps/benchee/lib/benchee/benchmark/collect/reductions.ex new file mode 100644 index 0000000000000000000000000000000000000000..eb431723b67a06ef6e14c5a98eb4fee5e7827d28 --- /dev/null +++ b/deps/benchee/lib/benchee/benchmark/collect/reductions.ex @@ -0,0 +1,24 @@ +defmodule Benchee.Benchmark.Collect.Reductions do + @moduledoc false + + @behaviour Benchee.Benchmark.Collect + + def collect(fun) do + parent = self() + + spawn_link(fn -> + start = get_reductions() + output = fun.() + send(parent, {:reductions, get_reductions() - start, output}) + end) + + receive do + {:reductions, reductions, output} -> {reductions, output} + end + end + + defp get_reductions do + {:reductions, reductions} = Process.info(self(), :reductions) + reductions + end +end diff --git a/deps/benchee/lib/benchee/benchmark/collect/time.ex b/deps/benchee/lib/benchee/benchmark/collect/time.ex new file mode 100644 index 0000000000000000000000000000000000000000..5fd58dff3a16d285c7304d1769c55742f65a4a75 --- /dev/null +++ b/deps/benchee/lib/benchee/benchmark/collect/time.ex @@ -0,0 +1,24 @@ +defmodule Benchee.Benchmark.Collect.Time do + @moduledoc false + + # Measure the time elapsed while executing a given function. + # + # In contrast to `:timer.tc/1` it always returns the result in nano seconds instead of micro + # seconds. This helps us avoid losing precision as both Linux and MacOSX seem to be able to + # measure in nano seconds. `:timer.tc/n` + # [forfeits this precision]( + # https://github.com/erlang/otp/blob/main/lib/stdlib/src/timer.erl#L164-L169). + + @behaviour Benchee.Benchmark.Collect + + @spec collect((-> any)) :: {non_neg_integer, any} + def collect(function) do + start = :erlang.monotonic_time() + result = function.() + finish = :erlang.monotonic_time() + + duration_nano_seconds = :erlang.convert_time_unit(finish - start, :native, :nanosecond) + + {duration_nano_seconds, result} + end +end diff --git a/deps/benchee/lib/benchee/benchmark/function_call_overhead.ex b/deps/benchee/lib/benchee/benchmark/function_call_overhead.ex new file mode 100644 index 0000000000000000000000000000000000000000..96c30d59cf2feccf7c857e6dede661f82604f820 --- /dev/null +++ b/deps/benchee/lib/benchee/benchmark/function_call_overhead.ex @@ -0,0 +1,55 @@ +defmodule Benchee.Benchmark.FunctionCallOverhead do + @moduledoc false + + alias Benchee.Benchmark.Collect.Time + alias Benchee.Conversion + + @overhead_determination_time Conversion.Duration.convert_value({0.01, :second}, :nanosecond) + + # Compute the function call overhead on the current system + # + # You might wonder why this isn't done simply through using our existing infrastructure + # and just run it with Scenario, Context etc. - in fact that's how it used to be, + # but it meant that we'd pass half-baked scenarios to functions causing dialyzer to complain, + # as well as running for a lot more code than we strictly need to like the + # `determine_n_times` code that we should rather not go through as it changes + # what this function does. + # This also gives us a way to make sure we definitely take at least one measurement. + @spec measure() :: non_neg_integer() + def measure do + # just the fastest function one can think of... + overhead_function = fn -> nil end + + _ = warmup(overhead_function) + run_times = run(overhead_function) + + Statistex.minimum(run_times) + end + + defp warmup(function) do + run_for(function, @overhead_determination_time / 2) + end + + defp run(function) do + run_for(function, @overhead_determination_time) + end + + defp run_for(function, run_time) do + end_time = current_time() + run_time + + do_run(function, [], end_time) + end + + @spec do_run((-> any), [number], number) :: [number, ...] + defp do_run(function, durations, end_time) do + {duration, _} = Time.collect(function) + + if current_time() < end_time do + do_run(function, [duration | durations], end_time) + else + durations + end + end + + defp current_time, do: :erlang.system_time(:nano_seconds) +end diff --git a/deps/benchee/lib/benchee/benchmark/hooks.ex b/deps/benchee/lib/benchee/benchmark/hooks.ex new file mode 100644 index 0000000000000000000000000000000000000000..540b4dc3e4cdf65434537bb7988e01115585eeea --- /dev/null +++ b/deps/benchee/lib/benchee/benchmark/hooks.ex @@ -0,0 +1,73 @@ +defmodule Benchee.Benchmark.Hooks do + @moduledoc """ + Internal module to support hooks functionality. + """ + + # Non Benchee code should not rely on this module. + + alias Benchee.Benchmark.ScenarioContext + alias Benchee.Scenario + + @type hook_function :: (any -> any) + + @spec run_before_scenario(Scenario.t(), ScenarioContext.t()) :: any + def run_before_scenario( + %Scenario{ + before_scenario: local_before_scenario, + input: input + }, + %ScenarioContext{ + config: %{before_scenario: global_before_scenario} + } + ) do + input + |> run_before_function(global_before_scenario) + |> run_before_function(local_before_scenario) + end + + defp run_before_function(input, nil), do: input + defp run_before_function(input, function), do: function.(input) + + @spec run_before_each(Scenario.t(), ScenarioContext.t()) :: any + def run_before_each( + %{ + before_each: local_before_each + }, + %{ + config: %{before_each: global_before_each}, + scenario_input: input + } + ) do + input + |> run_before_function(global_before_each) + |> run_before_function(local_before_each) + end + + @spec run_after_each(any, Scenario.t(), ScenarioContext.t()) :: any + def run_after_each( + return_value, + %{ + after_each: local_after_each + }, + %{ + config: %{after_each: global_after_each} + } + ) do + if local_after_each, do: local_after_each.(return_value) + if global_after_each, do: global_after_each.(return_value) + end + + @spec run_after_scenario(Scenario.t(), ScenarioContext.t()) :: any + def run_after_scenario( + %{ + after_scenario: local_after_scenario + }, + %{ + config: %{after_scenario: global_after_scenario}, + scenario_input: input + } + ) do + if local_after_scenario, do: local_after_scenario.(input) + if global_after_scenario, do: global_after_scenario.(input) + end +end diff --git a/deps/benchee/lib/benchee/benchmark/repeated_measurement.ex b/deps/benchee/lib/benchee/benchmark/repeated_measurement.ex new file mode 100644 index 0000000000000000000000000000000000000000..b562bb71820e1bf766e3185aa61266e4c708cb70 --- /dev/null +++ b/deps/benchee/lib/benchee/benchmark/repeated_measurement.ex @@ -0,0 +1,205 @@ +defmodule Benchee.Benchmark.RepeatedMeasurement do + @moduledoc false + + # This module is an internal implementation detail, and should absolutely not be relied upon + # from external clients. + # + # It is used when we can't conduct measurements precise enough with our measurement precision. + # I.e. we can measure in microseconds but we measure a function call to take 1 microsecond then + # most measurements will either be 1 or 2 microseconds which won't give us great results. + # Instead we repeat the function call n times until we measure at least ~10 (time unit) so + # that the difference between measurements can at least be ~10%. + # + # Today this is mostly only relevant on Windows & Mac OS as we have nanosecond precision on + # Linux and we've failed to produce a measurable function call that takes less than 10 nano + # seconds. + # + # That's also why this code lives in a separate module and not `Runner` - as it's rarely used + # and clutters that code + we need a way to test it even if we can't trigger it's conditions. + + # If a function executes way too fast measurements are too unreliable and + # with too high variance. Therefore determine an n how often it should be + # executed in the measurement cycle. + + alias Benchee.Benchmark.{Collect, Hooks, Runner, ScenarioContext} + alias Benchee.Scenario + alias Benchee.Utility.ErlangVersion + alias Benchee.Utility.RepeatN + + @minimum_execution_time 10 + @times_multiplier 10 + @nanosecond_resolution Benchee.Conversion.Duration.convert_value({1, :second}, :nanosecond) + + @spec determine_n_times(Scenario.t(), ScenarioContext.t(), boolean, module) :: + {pos_integer, number} + def determine_n_times( + scenario, + scenario_context = %ScenarioContext{system: system_info}, + print_fast_warning, + clock_info \\ :erlang.system_info(:os_monotonic_time_source), + collector \\ Collect.Time + ) do + resolution_adjustment = determine_resolution_adjustment(system_info, clock_info) + + do_determine_n_times( + scenario, + scenario_context, + print_fast_warning, + resolution_adjustment, + collector + ) + end + + # See ERL-1067 aka which was fixed here + # https://erlang.org/download/otp_src_22.2.readme + @fixed_erlang_vesion "22.2.0" + # MacOS usually measures in micro seconds so that's the best default to return when not given + @old_macos_value 1_000 + + defp determine_resolution_adjustment(system_info, clock_info) do + if trust_clock?(system_info) do + # If the resolution is 1_000_000 that means microsecond, while 1_000_000_000 is nanosecond. + # we then need to adjust our measured time by that value. I.e. if we measured "5000" here we + # do not want to let it pass as it is essentially just "5" for our measurement purposes. + {:ok, resolution} = Access.fetch(clock_info, :resolution) + + @nanosecond_resolution / resolution + else + @old_macos_value + end + end + + # Can't really trust the macOS clock on OTP before mentioned version, see tickets linked above + defp trust_clock?(%{os: :macOS, erlang: erlang_version}) do + ErlangVersion.includes_fixes_from?(erlang_version, @fixed_erlang_vesion) + end + + # If `suite.system` wasn't populated then we'll not mistrust it as well as all others + # (can happen if people call parts of benchee themselves without calling system first) + defp trust_clock?(_), do: true + + defp do_determine_n_times( + scenario, + scenario_context = %ScenarioContext{ + num_iterations: num_iterations, + printer: printer + }, + print_fast_warning, + resolution_adjustment, + collector + ) do + run_time = measure_iteration(scenario, scenario_context, collector) + resolution_adjusted_run_time = run_time / resolution_adjustment + + if resolution_adjusted_run_time >= @minimum_execution_time do + {num_iterations, report_time(run_time, num_iterations)} + else + if print_fast_warning, do: printer.fast_warning() + + new_context = %ScenarioContext{ + scenario_context + | num_iterations: num_iterations * @times_multiplier + } + + do_determine_n_times(scenario, new_context, false, resolution_adjustment, collector) + end + end + + # we need to convert the time here since we measure native time to see when we have enough + # repetitions but the first time is used in the actual samples + defp report_time(measurement, num_iterations) do + adjust_for_iterations(measurement, num_iterations) + end + + defp adjust_for_iterations(measurement, 1), do: measurement + defp adjust_for_iterations(measurement, num_iterations), do: measurement / num_iterations + + @spec collect(Scenario.t(), ScenarioContext.t(), module) :: number + def collect( + scenario, + scenario_context = %ScenarioContext{ + num_iterations: num_iterations + }, + collector + ) do + measurement = measure_iteration(scenario, scenario_context, collector) + + adjust_for_iterations(measurement, num_iterations) + end + + defp measure_iteration( + scenario, + scenario_context = %ScenarioContext{ + num_iterations: 1 + }, + collector + ) do + Runner.collect(scenario, scenario_context, collector) + end + + defp measure_iteration( + scenario, + scenario_context = %ScenarioContext{ + num_iterations: iterations + }, + collector + ) + when iterations > 1 do + # When we have more than one iteration, then the repetition and calling + # of hooks is already included in the function, for reference/reasoning see + # `build_benchmarking_function/2` + function = build_benchmarking_function(scenario, scenario_context) + + {measurement, _return_value} = collector.collect(function) + + measurement + end + + # Builds the appropriate function to benchmark. Takes into account the + # combinations of the following cases: + # + # * an input is specified - creates a 0-argument function calling the original + # function with that input + # * number of iterations - when there's more than one iteration we repeat the + # benchmarking function during execution and measure the the total run time. + # We only run multiple iterations if a function is so fast that we can't + # accurately measure it in one go. Hence, we can't split up the function + # execution and hooks anymore and sadly we also measure the time of the + # hooks. + defp build_benchmarking_function( + %Scenario{ + function: function, + before_each: nil, + after_each: nil + }, + %ScenarioContext{ + num_iterations: iterations, + scenario_input: input, + config: %{after_each: nil, before_each: nil} + } + ) + when iterations > 1 do + main = Runner.main_function(function, input) + # with no before/after each we can safely omit them and don't get the hit + # on run time measurements (See PR discussions for this for more info #127) + fn -> RepeatN.repeat_n(main, iterations) end + end + + defp build_benchmarking_function( + scenario = %Scenario{function: function}, + scenario_context = %ScenarioContext{num_iterations: iterations} + ) + when iterations > 1 do + fn -> + RepeatN.repeat_n( + fn -> + new_input = Hooks.run_before_each(scenario, scenario_context) + main = Runner.main_function(function, new_input) + return_value = main.() + Hooks.run_after_each(return_value, scenario, scenario_context) + end, + iterations + ) + end + end +end diff --git a/deps/benchee/lib/benchee/benchmark/runner.ex b/deps/benchee/lib/benchee/benchmark/runner.ex new file mode 100644 index 0000000000000000000000000000000000000000..d90471a81ec722498c935a0b35c471453096aada --- /dev/null +++ b/deps/benchee/lib/benchee/benchmark/runner.ex @@ -0,0 +1,380 @@ +defmodule Benchee.Benchmark.Runner do + @moduledoc """ + Internal module "running" a scenario, measuring all defined measurements. + """ + + # This module actually runs our benchmark scenarios, adding information about + # run time and memory usage to each scenario. + + alias Benchee.Benchmark + alias Benchee.Benchmark.BenchmarkConfig + alias Benchee.Scenario + alias Benchee.Utility.Parallel + + alias Benchmark.{ + Collect, + FunctionCallOverhead, + Hooks, + RepeatedMeasurement, + ScenarioContext + } + + @no_input Benchmark.no_input() + @zero_values [0, 0.0] + + @doc """ + Executes the benchmarks defined before by first running the defined functions + for `warmup` time without gathering results and them running them for `time` + gathering their run times. + + This means the total run time of a single benchmarking scenario is warmup + + time. + + Warmup is usually important for run times with JIT but it seems to have some + effect on the BEAM as well. + + There will be `parallel` processes spawned executing the benchmark job in + parallel. + """ + @spec run_scenarios([Scenario.t()], ScenarioContext.t()) :: [Scenario.t()] + def run_scenarios(scenarios, scenario_context = %ScenarioContext{}) do + case scenario_context.config.pre_check do + true -> Enum.each(scenarios, fn scenario -> pre_check(scenario, scenario_context) end) + false -> :ok + :all_same -> pre_check_all_same(scenarios, scenario_context) + end + + function_call_overhead = + if scenario_context.config.measure_function_call_overhead do + measure_and_report_function_call_overhead(scenario_context.printer) + else + 0 + end + + scenario_context = %ScenarioContext{ + scenario_context + | function_call_overhead: function_call_overhead + } + + Enum.map(scenarios, fn scenario -> parallel_benchmark(scenario, scenario_context) end) + end + + # This will run the given scenario exactly once, including the before and + # after hooks, to ensure the function can execute without raising an error. + defp pre_check(scenario, scenario_context) do + run_once(scenario, scenario_context) + end + + def run_once(scenario, scenario_context = %ScenarioContext{}) do + scenario_input = Hooks.run_before_scenario(scenario, scenario_context) + scenario_context = %ScenarioContext{scenario_context | scenario_input: scenario_input} + return_value = collect_return_value(scenario, scenario_context) + _ = Hooks.run_after_scenario(scenario, scenario_context) + return_value + end + + defp pre_check_all_same(scenarios, scenario_context) do + Enum.reduce(scenarios, %{}, fn %{input_name: input_name} = scenario, previous_runs -> + return_value = pre_check(scenario, scenario_context) + + case previous_runs do + %{^input_name => {previous_job, previous_value}} when return_value !== previous_value -> + raise Benchee.PreCheckError, + message: """ + all_same pre check failed#{pre_check_failed_input_message(input_name)}: + - #{previous_job} returned #{inspect(previous_value)} + - #{scenario.job_name} returned #{inspect(return_value)} + """ + + _ -> + Map.put_new(previous_runs, input_name, {scenario.job_name, return_value}) + end + end) + end + + defp pre_check_failed_input_message(@no_input), do: "" + defp pre_check_failed_input_message(input_name), do: " for input #{inspect(input_name)}" + + def measure_and_report_function_call_overhead(printer) do + overhead = FunctionCallOverhead.measure() + printer.function_call_overhead(overhead) + overhead + end + + defp parallel_benchmark( + scenario = %Scenario{job_name: job_name, input_name: input_name}, + scenario_context = %ScenarioContext{ + printer: printer, + config: config + } + ) do + printer.benchmarking(job_name, input_name, config) + + config + |> measure_scenario_parallel(scenario, scenario_context) + |> add_measurements_to_scenario(scenario) + end + + defp measure_scenario_parallel(config, scenario, scenario_context) do + Parallel.map(1..config.parallel, fn _ -> measure_scenario(scenario, scenario_context) end) + end + + defp add_measurements_to_scenario(measurements, scenario) do + run_times = Enum.flat_map(measurements, fn {run_times, _, _} -> run_times end) + memory_usages = Enum.flat_map(measurements, fn {_, memory_usages, _} -> memory_usages end) + reductions = Enum.flat_map(measurements, fn {_, _, reductions} -> reductions end) + + %{ + scenario + | run_time_data: %{scenario.run_time_data | samples: run_times}, + memory_usage_data: %{scenario.memory_usage_data | samples: memory_usages}, + reductions_data: %{scenario.reductions_data | samples: reductions} + } + end + + @spec measure_scenario(Scenario.t(), ScenarioContext.t()) :: {[number], [number], [number]} + defp measure_scenario(scenario, scenario_context = %ScenarioContext{}) do + scenario_input = Hooks.run_before_scenario(scenario, scenario_context) + scenario_context = %ScenarioContext{scenario_context | scenario_input: scenario_input} + + _ = run_warmup(scenario, scenario_context) + + run_times = + scenario + |> run_runtime_benchmark(scenario_context) + |> deduct_function_call_overhead(scenario_context.function_call_overhead) + + memory_usages = run_memory_benchmark(scenario, scenario_context) + + reductions = + scenario + |> run_reductions_benchmark(scenario_context) + |> deduct_reduction_overhead() + + Hooks.run_after_scenario(scenario, scenario_context) + + {run_times, memory_usages, reductions} + end + + defp run_warmup( + scenario, + scenario_context = %ScenarioContext{ + config: %BenchmarkConfig{warmup: warmup} + } + ) do + measure_runtimes(scenario, scenario_context, warmup, false) + end + + defp run_runtime_benchmark( + scenario, + scenario_context = %ScenarioContext{ + config: %{ + time: run_time, + print: %{fast_warning: fast_warning} + } + } + ) do + measure_runtimes(scenario, scenario_context, run_time, fast_warning) + end + + defp deduct_function_call_overhead(run_times, 0) do + run_times + end + + defp deduct_function_call_overhead(run_times, overhead) do + Enum.map(run_times, fn time -> + max(time - overhead, 0) + end) + end + + defp deduct_reduction_overhead([]), do: [] + + defp deduct_reduction_overhead(reductions) do + me = self() + ref = make_ref() + + spawn(fn -> + {offset, _} = Collect.Reductions.collect(fn -> nil end) + send(me, {ref, offset}) + end) + + offset = + receive do + {^ref, offset} -> offset + end + + Enum.map(reductions, &(&1 - offset)) + end + + defp run_reductions_benchmark(_, %ScenarioContext{config: %{reduction_time: time}}) + when time in @zero_values do + [] + end + + defp run_reductions_benchmark( + scenario, + scenario_context = %ScenarioContext{ + config: %{ + reduction_time: reduction_time + } + } + ) do + end_time = current_time() + reduction_time + + new_context = %ScenarioContext{ + scenario_context + | current_time: current_time(), + end_time: end_time + } + + do_benchmark(scenario, new_context, Collect.Reductions, []) + end + + defp run_memory_benchmark(_, %ScenarioContext{config: %{memory_time: time}}) + when time in @zero_values do + [] + end + + defp run_memory_benchmark( + scenario, + scenario_context = %ScenarioContext{ + config: %{ + memory_time: memory_time + } + } + ) do + end_time = current_time() + memory_time + + new_context = %ScenarioContext{ + scenario_context + | current_time: current_time(), + end_time: end_time + } + + do_benchmark(scenario, new_context, Collect.Memory, []) + end + + @spec measure_runtimes(Scenario.t(), ScenarioContext.t(), number, boolean) :: [number] + defp measure_runtimes(scenario, context, run_time, fast_warning) + defp measure_runtimes(_, _, time, _) when time in @zero_values, do: [] + + defp measure_runtimes(scenario, scenario_context = %ScenarioContext{}, run_time, fast_warning) do + end_time = current_time() + run_time + :erlang.garbage_collect() + + {num_iterations, initial_run_time} = + RepeatedMeasurement.determine_n_times(scenario, scenario_context, fast_warning) + + new_context = %ScenarioContext{ + scenario_context + | current_time: current_time(), + end_time: end_time, + num_iterations: num_iterations, + # we have the initial run time + sample_size: 1 + } + + do_benchmark(scenario, new_context, Collect.Time, [initial_run_time]) + end + + defp current_time, do: :erlang.system_time(:nano_seconds) + + # `run_times` is kept separately from the `Scenario` so that for the + # `parallel` execution case we can easily concatenate and flatten the results + # of all processes. That's why we add them to the scenario once after + # measuring has finished. `scenario` is still needed in general for the + # benchmarking function, hooks etc. + defp do_benchmark( + _scenario, + %ScenarioContext{ + current_time: current_time, + end_time: end_time, + sample_size: sample_size, + config: %BenchmarkConfig{ + max_sample_size: max_sample_size + } + }, + _collector, + measurements + ) + when (current_time > end_time or + (not is_nil(max_sample_size) and sample_size >= max_sample_size)) and + measurements != [] do + # restore correct order - important for graphing + Enum.reverse(measurements) + end + + defp do_benchmark(scenario, scenario_context = %ScenarioContext{}, collector, measurements) do + measurement = collect(scenario, scenario_context, collector) + + updated_context = %ScenarioContext{ + scenario_context + | current_time: current_time(), + sample_size: scenario_context.sample_size + 1 + } + + do_benchmark( + scenario, + updated_context, + collector, + updated_measurements(measurement, measurements) + ) + end + + # We return `nil` if memory measurement failed so keep it empty + @spec updated_measurements(number | nil, [number]) :: [number] + defp updated_measurements(nil, measurements), do: measurements + defp updated_measurements(measurement, measurements), do: [measurement | measurements] + + # Support functionality that just runs once via `run_once` and does not care about measurements. + # At the time of this writing that's pre checks and profilers. + defp collect_return_value(scenario, scenario_context) do + new_input = Hooks.run_before_each(scenario, scenario_context) + function = main_function(scenario.function, new_input) + + return_value = function.() + + Hooks.run_after_each(return_value, scenario, scenario_context) + return_value + end + + @doc """ + Takes one measure with the given collector. + + Correctly dispatches based on the number of iterations to perform. + """ + def collect( + scenario = %Scenario{function: function}, + scenario_context = %ScenarioContext{ + num_iterations: 1 + }, + collector + ) do + new_input = Hooks.run_before_each(scenario, scenario_context) + function = main_function(function, new_input) + + {measurement, return_value} = invoke_collector(collector, function) + + Hooks.run_after_each(return_value, scenario, scenario_context) + measurement + end + + def collect( + scenario, + scenario_context = %ScenarioContext{ + num_iterations: iterations + }, + collector + ) + when iterations > 1 do + RepeatedMeasurement.collect(scenario, scenario_context, collector) + end + + def main_function(function, @no_input), do: function + def main_function(function, input), do: fn -> function.(input) end + + defp invoke_collector({collector, collector_opts}, function), + do: collector.collect(function, collector_opts) + + defp invoke_collector(collector, function), do: collector.collect(function) +end diff --git a/deps/benchee/lib/benchee/benchmark/scenario_context.ex b/deps/benchee/lib/benchee/benchmark/scenario_context.ex new file mode 100644 index 0000000000000000000000000000000000000000..f3252773232416c32fc30195decbca86961c34d9 --- /dev/null +++ b/deps/benchee/lib/benchee/benchmark/scenario_context.ex @@ -0,0 +1,35 @@ +defmodule Benchee.Benchmark.ScenarioContext do + @moduledoc """ + Internal struct the runner & related modules deal with to run a scenario. + + Practically bundles information the runner needs to be aware of while running + a scenario such as the current_time, end_time, printer, input, function call + overhead etc. + """ + + # This struct holds the context in which any scenario is run. + + defstruct [ + :config, + :printer, + :system, + :current_time, + :end_time, + # before_scenario can alter the original input + :scenario_input, + num_iterations: 1, + function_call_overhead: 0, + sample_size: 0 + ] + + @type t :: %__MODULE__{ + config: Benchee.Benchmark.BenchmarkConfig.t(), + printer: module, + current_time: pos_integer | nil, + end_time: pos_integer | nil, + scenario_input: any, + num_iterations: pos_integer, + function_call_overhead: non_neg_integer, + sample_size: non_neg_integer() + } +end diff --git a/deps/benchee/lib/benchee/collection_data.ex b/deps/benchee/lib/benchee/collection_data.ex new file mode 100644 index 0000000000000000000000000000000000000000..fa82f1fd3934df8bbbbc7ba0f6c5f3876c5b4bf2 --- /dev/null +++ b/deps/benchee/lib/benchee/collection_data.ex @@ -0,0 +1,21 @@ +defmodule Benchee.CollectionData do + @moduledoc """ + The unified data structure for a given collection of data. + + Consists of the recorded `samples` and the statistics computed from them. + """ + + alias Benchee.Statistics + + defstruct statistics: %Statistics{}, samples: [] + + @typedoc """ + Samples and statistics. + + Statistics might only come later when they are computed. + """ + @type t :: %__MODULE__{ + samples: [float | non_neg_integer], + statistics: Statistics.t() + } +end diff --git a/deps/benchee/lib/benchee/configuration.ex b/deps/benchee/lib/benchee/configuration.ex new file mode 100644 index 0000000000000000000000000000000000000000..a5118d557c685fc07c569f3aa949a9ac6eeb1136 --- /dev/null +++ b/deps/benchee/lib/benchee/configuration.ex @@ -0,0 +1,400 @@ +defmodule Benchee.Configuration do + @moduledoc """ + Functions to handle the configuration of Benchee, exposes `init/1` function. + """ + + alias Benchee.{ + Benchmark.Hooks, + Configuration, + Conversion.Duration, + Conversion.Scale, + Formatters.Console, + Suite, + Utility.DeepConvert + } + + defstruct parallel: 1, + time: 5, + warmup: 2, + memory_time: 0.0, + reduction_time: 0.0, + pre_check: false, + formatters: [Console], + percentiles: [50, 99], + print: %{ + benchmarking: true, + configuration: true, + fast_warning: true + }, + inputs: nil, + input_names: [], + save: false, + load: false, + unit_scaling: :best, + # If you/your plugin/whatever needs it your data can go here + assigns: %{}, + before_each: nil, + after_each: nil, + before_scenario: nil, + after_scenario: nil, + measure_function_call_overhead: false, + title: nil, + profile_after: false, + # Why a million? Well, it's a nice number :P + # Seriously, though: That's usually enough samples to be significant enough as a + # result. + # At the same time, at least on my machine it takes less than one second for + # `Statistex` to calculate the statistics for a list that large. + # It also generates less than 1GB in data (some of which is garbage collected/ + # not necessarily all in RAM at the same time) - which seems reasonable enough. + # see `samples/statistics_performance.exs` and also maybe run it yourself. + max_sample_size: 1_000_000, + exclude_outliers: false + + @typedoc """ + The configuration supplied by the user as either a map or a keyword list + + Possible options are: + + Possible options: + + * `warmup` - the time in seconds for which a benchmarking job should be run + without measuring times before "real" measurements start. This simulates a + _"warm"_ running system. Defaults to 2. + * `time` - the time in seconds for how long each individual benchmarking job + should be run for measuring the execution times (run time performance). + Defaults to 5. + * `memory_time` - the time in seconds for how long memory measurements + should be conducted. Defaults to 0 (turned off). + * `inputs` - a map from descriptive input names to some different input, + your benchmarking jobs will then be run with each of these inputs. For this + to work your benchmarking function gets the current input passed in as an + argument into the function. Defaults to `nil`, aka no input specified and + functions are called without an argument. + * `title` - this option is purely cosmetic. If you would like to add a + title with some meaning to a given suite, you can do so by providing + a single string here. This is only for use by formatters. + * `formatters` - list of formatters either as a module implementing the formatter + behaviour, a tuple of said module and options it should take or formatter + functions. They are run when using `Benchee.run/2` or you can invoktem them + through `Benchee.Formatter.output/1`. Functions need to accept one argument (which + is the benchmarking suite with all data) and then use that to produce output. Used + for plugins. Defaults to the builtin console formatter + `Benchee.Formatters.Console`. See [Formatters](#formatters). + * `pre_check` - whether or not to run each job with each input - including all + given before or after scenario or each hooks - before the benchmarks are + measured to ensure that your code executes without error. This can save time + while developing your suites. Defaults to `false`. Possible values are: + * `false` - no pre check is run + * `true` - each scenario is run but the return value is ignored + * `:all_same` - raises if all scenarios are not returning the same value for + each input. This is useful when benchmarking alternative implementations of a + deterministic function. + * `parallel` - each the function of each job will be executed in + `parallel` number processes. If `parallel` is `4` then 4 processes will be + spawned that all execute the _same_ function for the given time. When these + finish/the time is up 4 new processes will be spawned for the next + job/function. This gives you more data in the same time, but also puts a + load on the system interfering with benchmark results. For more on the pros + and cons of parallel benchmarking [check the + wiki](https://github.com/bencheeorg/benchee/wiki/Parallel-Benchmarking). + Defaults to 1 (no parallel execution). + * `save` - specify a `path` where to store the results of the current + benchmarking suite, tagged with the specified `tag`. + * `load` - load saved suit or suits to compare your current benchmarks + against. Can be a string or a list of strings or patterns. + * `print` - a map from atoms to `true` or `false` to configure if the + output identified by the atom will be printed. All options are enabled by + default (true). Options are: + * `:benchmarking` - print when Benchee starts benchmarking a new job + (Benchmarking name ..) as well as when statistics are being calculated + or formatting begins. + * `:configuration` - a summary of configured benchmarking options + including estimated total run time is printed before benchmarking starts + * `:fast_warning` - warnings are displayed if functions are executed + too fast leading to inaccurate measures + * `console` - options for the built-in console formatter: + * `:comparison` - if the comparison of the different benchmarking jobs + (x times slower than) is shown (true/false). Enabled by default. + * `extended_statistics` - display more statistics, aka `minimum`, + `maximum`, `sample_size` and `mode`. Disabled by default. + * `percentiles` - if you are using extended statistics and want to see the + results for certain percentiles of results beyond just the median. + Defaults to [50, 99] to calculate the 50th and 99th percentiles. + * `:unit_scaling` - the strategy for choosing a unit for durations and + counts. May or may not be implemented by a given formatter (The console + formatter implements it). When scaling a value, Benchee finds the "best fit" + unit (the largest unit for which the result is at least 1). For example, + 1_200_000 scales to `1.2 M`, while `800_000` scales to `800 K`. The + `unit_scaling` strategy determines how Benchee chooses the best fit unit for + an entire list of values, when the individual values in the list may have + different best fit units. There are four strategies, defaulting to `:best`: + * `:best` - the most frequent best fit unit will be used, a tie + will result in the larger unit being selected. + * `:largest` - the largest best fit unit will be used (i.e. thousand + and seconds if values are large enough). + * `:smallest` - the smallest best fit unit will be used (i.e. + millisecond and one) + * `:none` - no unit scaling will occur. Durations will be displayed + in microseconds, and counts will be displayed in ones (this is + equivalent to the behaviour Benchee had pre 0.5.0) + * `:before_scenario`/`after_scenario`/`before_each`/`after_each` - read up on them in the hooks section in the README + * `:measure_function_call_overhead` - Measure how long an empty function call takes and deduct this from each measure run time. This overhead should be negligible for all but the most micro benchmarks. Defaults to false. + * `profile_after` - accepts any of the following options: + * a boolean - `true` will enable profiling with the default profiler + (`:eprof`) and `false` will disable profiling. Defaults to `false`. + * a profiler - either as a tuple of `{profiler, opts}` (e.g., `{:fprof, [sort: :own]}`) + or just the profiler (e.g., `:fprof`), which is equivalent to `{profiler, []}`. The accepted built-in profilers are: + [`:cprof`](https://hexdocs.pm/mix/Mix.Tasks.Profile.Cprof.html), + [`:eprof`](https://hexdocs.pm/mix/Mix.Tasks.Profile.Eprof.html) + [`:fprof`](https://hexdocs.pm/mix/Mix.Tasks.Profile.Fprof.html) and + [`:tprof`](https://hexdocs.pm/mix/Mix.Tasks.Profile.Tprof.html) (requires elixir >= 1.17 and erlang >= 27). + * `max_sample_size` - the maximum number of samples collected per scenario. Defaults to `1_000_000`. + This is used to limit memory consumption and unnecessary processing - 1 Million samples is plenty. + This limit also applies to number of iterations done during warmup. + You can set your own number or set it to `nil` if you don't want any limit. + * `exclude_outliers` - whether or not statistical outliers should be removed for the calculated statistics. + Defaults to `false`. + This means that values that are far outside the usual range (as determined by the percentiles/quantiles) will + be removed from the gathered samples and the calculated statistics. You might want to enable this if you + don't want things like the garbage collection triggering to influence your results as much. + """ + @type user_configuration :: map | keyword + + @typedoc """ + Generated configuration struct from the user supplied configuration options. + + Filled in with a lot of defaults. Also notably every option is already converted to + a map or struct at this point for easier handling in Benchee. + """ + @type t :: %__MODULE__{ + parallel: pos_integer, + time: number, + warmup: number, + memory_time: number, + reduction_time: number, + pre_check: boolean, + formatters: [(Suite.t() -> Suite.t()) | module | {module, user_configuration}], + print: map, + inputs: %{Suite.key() => any} | [{Suite.key(), any}] | nil, + input_names: [String.t()], + save: map | false, + load: String.t() | [String.t()] | false, + unit_scaling: Scale.scaling_strategy(), + assigns: map, + before_each: Hooks.hook_function() | nil, + after_each: Hooks.hook_function() | nil, + before_scenario: Hooks.hook_function() | nil, + after_scenario: Hooks.hook_function() | nil, + measure_function_call_overhead: boolean, + title: String.t() | nil, + profile_after: boolean | atom | {atom, keyword}, + max_sample_size: pos_integer(), + exclude_outliers: boolean() + } + + @time_keys [:time, :warmup, :memory_time, :reduction_time] + + @doc """ + Returns the initial benchmark configuration for Benchee, composed of defaults + and an optional custom configuration. + + Configuration times are given in seconds, but are converted to microseconds + internally. + + For a list of all possible options see `t:user_configuration/0` + + ## Examples + + iex> init() + %Benchee.Suite{ + configuration: %Benchee.Configuration{ + parallel: 1, + time: 5_000_000_000.0, + warmup: 2_000_000_000.0, + max_sample_size: 1_000_000, + inputs: nil, + input_names: [], + save: false, + load: false, + formatters: [Benchee.Formatters.Console], + print: %{ + benchmarking: true, + fast_warning: true, + configuration: true + }, + percentiles: [50, 99], + unit_scaling: :best, + assigns: %{}, + before_each: nil, + after_each: nil, + before_scenario: nil, + after_scenario: nil + }, + system: nil, + scenarios: [] + } + + iex> init(time: 1, warmup: 0.2) + %Benchee.Suite{ + configuration: %Benchee.Configuration{ + parallel: 1, + time: 1_000_000_000.0, + warmup: 200_000_000.0, + max_sample_size: 1_000_000, + inputs: nil, + input_names: [], + save: false, + load: false, + formatters: [Benchee.Formatters.Console], + print: %{ + benchmarking: true, + fast_warning: true, + configuration: true + }, + percentiles: [50, 99], + unit_scaling: :best, + assigns: %{}, + before_each: nil, + after_each: nil, + before_scenario: nil, + after_scenario: nil + }, + system: nil, + scenarios: [] + } + + iex> init( + ...> parallel: 2, + ...> time: 1, + ...> warmup: 0.2, + ...> max_sample_size: 500, + ...> formatters: [&IO.puts/1], + ...> print: [fast_warning: false], + ...> inputs: %{"Small" => 5, "Big" => 9999}, + ...> unit_scaling: :smallest + ...> ) + %Benchee.Suite{ + configuration: %Benchee.Configuration{ + parallel: 2, + time: 1_000_000_000.0, + warmup: 200_000_000.0, + max_sample_size: 500, + inputs: [{"Big", 9999}, {"Small", 5}], + input_names: ["Big", "Small"], + save: false, + load: false, + formatters: [&IO.puts/1], + print: %{ + benchmarking: true, + fast_warning: false, + configuration: true + }, + percentiles: [50, 99], + unit_scaling: :smallest, + assigns: %{}, + before_each: nil, + after_each: nil, + before_scenario: nil, + after_scenario: nil + }, + system: nil, + scenarios: [] + } + """ + @spec init(user_configuration) :: Suite.t() + def init(config \\ %{}) do + :ok = :timer.start() + + config = + config + |> standardized_user_configuration() + |> merge_with_defaults() + |> convert_time_to_nano_s() + |> save_option_conversion() + |> add_input_names() + + %Suite{configuration: config} + end + + defp standardized_user_configuration(config) do + config + |> DeepConvert.to_map([:formatters, :inputs]) + |> standardize_inputs() + end + + defp standardize_inputs(config = %{inputs: inputs}) do + standardized_inputs = + inputs + |> Enum.reduce([], &standardize_inputs/2) + |> Enum.reverse() + + %{config | inputs: standardized_inputs} + end + + defp standardize_inputs(config), do: config + + defp standardize_inputs({name, value}, acc) do + normalized_name = to_string(name) + + if List.keymember?(acc, normalized_name, 0) do + acc + else + [{normalized_name, value} | acc] + end + end + + defp add_input_names(config) do + input_names = + case config.inputs do + nil -> [] + inputs -> Enum.map(inputs, fn {name, _value} -> name end) + end + + %{config | input_names: input_names} + end + + defp merge_with_defaults(user_config) do + DeepMerge.deep_merge(%Configuration{}, user_config) + end + + defp convert_time_to_nano_s(config) do + Enum.reduce(@time_keys, config, fn key, new_config -> + {_, new_config} = + Map.get_and_update!(new_config, key, fn seconds -> + {seconds, Duration.convert_value({seconds, :second}, :nanosecond)} + end) + + new_config + end) + end + + defp save_option_conversion(config = %{save: false}), do: config + + defp save_option_conversion(config = %__MODULE__{save: save_values}) do + save_options = Map.merge(save_defaults(), save_values) + tagged_save_options = %{tag: save_options.tag, path: save_options.path} + formatters = config.formatters ++ [{Benchee.Formatters.TaggedSave, tagged_save_options}] + %__MODULE__{config | formatters: formatters} + end + + defp save_defaults do + now = DateTime.utc_now() + + %{ + tag: "#{now.year}-#{now.month}-#{now.day}--#{now.hour}-#{now.minute}-#{now.second}-utc", + path: "benchmark.benchee" + } + end +end + +defimpl DeepMerge.Resolver, for: Benchee.Configuration do + def resolve(_original, override = %{__struct__: Benchee.Configuration}, _) do + override + end + + def resolve(original, override, resolver) when is_map(override) do + merged = Map.merge(original, override, resolver) + struct!(Benchee.Configuration, Map.to_list(merged)) + end +end diff --git a/deps/benchee/lib/benchee/conversion.ex b/deps/benchee/lib/benchee/conversion.ex new file mode 100644 index 0000000000000000000000000000000000000000..4ca5798a82ce6e0203868c9f100721cb42ed4998 --- /dev/null +++ b/deps/benchee/lib/benchee/conversion.ex @@ -0,0 +1,76 @@ +defmodule Benchee.Conversion do + @moduledoc """ + Integration of the conversion of multiple units with Benchee. + + Can be used by plugins to use Benchee unit scaling logic. + """ + + alias Benchee.Conversion.{Count, Duration, Memory} + + @doc """ + Takes scenarios and a given scaling_strategy, returns the best units for the + given scaling strategy. The return value changes based on whether you want + units for run time or memory usage. + + The units can then be passed on to the appropriate `format` calls to format + the output of arbitrary values with the right unit. + + ## Examples + + iex> statistics = %Benchee.Statistics{average: 1_000_000.0, ips: 1000.0} + ...> + ...> scenario = %Benchee.Scenario{ + ...> run_time_data: %Benchee.CollectionData{statistics: statistics}, + ...> memory_usage_data: %Benchee.CollectionData{statistics: statistics}, + ...> reductions_data: %Benchee.CollectionData{statistics: statistics} + ...> } + ...> + ...> Benchee.Conversion.units([scenario], :best) + %{ + ips: %Benchee.Conversion.Unit{ + label: "K", + long: "Thousand", + magnitude: 1000, + name: :thousand + }, + run_time: %Benchee.Conversion.Unit{ + label: "ms", + long: "Milliseconds", + magnitude: 1_000_000, + name: :millisecond + }, + memory: %Benchee.Conversion.Unit{ + label: "KB", + long: "Kilobytes", + magnitude: 1024, + name: :kilobyte + }, + reduction_count: %Benchee.Conversion.Unit{ + label: "M", + long: "Million", + magnitude: 1_000_000, + name: :million + } + } + """ + def units(scenarios, scaling_strategy) do + run_time_measurements = measurements_for(scenarios, :run_time_data) + reductions_measurements = measurements_for(scenarios, :reductions_data) + memory_measurements = measurements_for(scenarios, :memory_usage_data) + + %{ + run_time: Duration.best(run_time_measurements.average, strategy: scaling_strategy), + ips: Count.best(run_time_measurements.ips, strategy: scaling_strategy), + memory: Memory.best(memory_measurements.average, strategy: scaling_strategy), + reduction_count: Count.best(reductions_measurements.average, strategry: scaling_strategy) + } + end + + defp measurements_for(scenarios, path) do + paths = [Access.key(path), Access.key(:statistics)] + + scenarios + |> Enum.flat_map(fn scenario -> scenario |> get_in(paths) |> Map.to_list() end) + |> Enum.group_by(fn {stat_name, _} -> stat_name end, fn {_, value} -> value end) + end +end diff --git a/deps/benchee/lib/benchee/conversion/count.ex b/deps/benchee/lib/benchee/conversion/count.ex new file mode 100644 index 0000000000000000000000000000000000000000..a627cabedbe6d4f7620ecce98945f959ba46dd91 --- /dev/null +++ b/deps/benchee/lib/benchee/conversion/count.ex @@ -0,0 +1,241 @@ +defmodule Benchee.Conversion.Count do + @moduledoc """ + Unit scaling for counts, such that 1000000 can be converted to 1 Million. + + Only Benchee plugins should use this code. + """ + + alias Benchee.Conversion.{Format, Scale, Unit} + + @behaviour Scale + @behaviour Format + + @one_billion 1_000_000_000 + @one_million 1_000_000 + @one_thousand 1_000 + + @units_map %{ + billion: %Unit{ + name: :billion, + magnitude: @one_billion, + label: "B", + long: "Billion" + }, + million: %Unit{ + name: :million, + magnitude: @one_million, + label: "M", + long: "Million" + }, + thousand: %Unit{ + name: :thousand, + magnitude: @one_thousand, + label: "K", + long: "Thousand" + }, + one: %Unit{ + name: :one, + magnitude: 1, + label: "", + long: "" + } + } + + @units Map.values(@units_map) + + @type unit_atoms :: :one | :thousand | :million | :billion + @type units :: unit_atoms | Unit.t() + + @doc """ + Scales a value representing a count in ones into a larger unit if appropriate + + ## Examples + + iex> {value, unit} = scale(4_321.09) + ...> value + 4.32109 + iex> unit.name + :thousand + + iex> {value, unit} = scale(0.0045) + ...> value + 0.0045 + iex> unit.name + :one + + """ + def scale(count) when count >= @one_billion do + scale_with_unit(count, :billion) + end + + def scale(count) when count >= @one_million do + scale_with_unit(count, :million) + end + + def scale(count) when count >= @one_thousand do + scale_with_unit(count, :thousand) + end + + def scale(count) do + scale_with_unit(count, :one) + end + + # Helper function for returning a tuple of {value, unit} + defp scale_with_unit(count, unit) do + {scale(count, unit), unit_for(unit)} + end + + @doc """ + Get a unit by its atom representation. If handed already a %Unit{} struct it + just returns it. + + ## Examples + + iex> unit_for(:thousand) + %Benchee.Conversion.Unit{ + name: :thousand, + magnitude: 1_000, + label: "K", + long: "Thousand" + } + + iex> unit_for(%Benchee.Conversion.Unit{ + ...> name: :thousand, + ...> magnitude: 1_000, + ...> label: "K", + ...> long: "Thousand" + ...> }) + %Benchee.Conversion.Unit{ + name: :thousand, + magnitude: 1_000, + label: "K", + long: "Thousand" + } + """ + def unit_for(unit) do + Scale.unit_for(@units_map, unit) + end + + def units do + @units + end + + @doc """ + Scales a value representing a count in ones into a specified unit + + ## Examples + + iex> scale(12345, :one) + 12345.0 + + iex> scale(12345, :thousand) + 12.345 + + iex> scale(12345, :billion) + 1.2345e-5 + + iex> scale(12345, :million) + 0.012345 + + """ + def scale(count, unit) do + Scale.scale(count, unit, __MODULE__) + end + + @doc """ + Converts a value for a specified %Unit or unit atom and converts it to the equivalent of another unit of measure. + + ## Examples + + iex> {value, unit} = convert({2500, :thousand}, :million) + ...> value + 2.5 + iex> unit.name + :million + """ + def convert(number_and_unit, desired_unit) do + Scale.convert(number_and_unit, desired_unit, __MODULE__) + end + + @doc """ + Finds the best unit for a list of counts. By default, chooses the most common + unit. In case of tie, chooses the largest of the most common units. + + Pass `[strategy: :smallest]` to always return the smallest unit in the list. + Pass `[strategy: :largest]` to always return the largest unit in the list. + + ## Examples + + iex> best([23, 23_000, 34_000, 2_340_000]).name + :thousand + + iex> best([23, 23_000, 34_000, 2_340_000, 3_450_000]).name + :million + + iex> best([23, 23_000, 34_000, 2_340_000], strategy: :smallest).name + :one + + iex> best([23, 23_000, 34_000, 2_340_000], strategy: :largest).name + :million + + """ + def best(list, opts \\ [strategy: :best]) + + def best(list, opts) do + Scale.best_unit(list, __MODULE__, opts) + end + + @doc """ + The raw count, unscaled. + + ## Examples + + iex> base_unit().name + :one + + """ + def base_unit, do: unit_for(:one) + + @doc """ + Formats a number as a string, with a unit label. + + To specify the unit, pass a tuple of `{value, unit_atom}` like `{1_234, :million}` + + ## Examples + + iex> format(45_678.9) + "45.68 K" + + iex> format(45.6789) + "45.68" + + iex> format({45.6789, :thousand}) + "45.68 K" + + iex> format( + ...> {45.6789, %Benchee.Conversion.Unit{long: "Thousand", magnitude: "1_000", label: "K"}} + ...> ) + "45.68 K" + """ + def format(count) do + Format.format(count, __MODULE__) + end + + @doc """ + Formats in a more "human" way separating by units. + + ## Examples + + iex> format_human(45_678.9) + "45 K 678.90" + + iex> format_human(1_000_000) + "1 M" + + iex> format_human(1_001_000) + "1 M 1 K" + """ + def format_human(count) do + Format.format_human(count, __MODULE__) + end +end diff --git a/deps/benchee/lib/benchee/conversion/deviation_percent.ex b/deps/benchee/lib/benchee/conversion/deviation_percent.ex new file mode 100644 index 0000000000000000000000000000000000000000..355a6b93c2d9b0ee307359ee9b2f08b09961649b --- /dev/null +++ b/deps/benchee/lib/benchee/conversion/deviation_percent.ex @@ -0,0 +1,46 @@ +defmodule Benchee.Conversion.DeviationPercent do + @moduledoc """ + Helps with formatting for the standard deviation ratio converting it into the + more common percent form. + + Only Benchee plugins should use this code. + """ + + alias Benchee.Conversion.Format + + @behaviour Format + + @doc """ + Formats the standard deviation ratio to an equivalent percent number including special signs. + + The ± is an important part of it as it shows that the deviation might be up but also might be + down. + + ## Examples + + iex> format(0.12345) + "±12.35%" + + iex> format(1) + "±100.00%" + """ + def format(std_dev_ratio) do + "~ts~.2f%" + |> :io_lib.format(["±", std_dev_ratio * 100.0]) + |> to_string + end + + @doc """ + Formats standard deviation percent, same as `format/1`. + + Implemented for consistency. + + ## Examples + + iex> format_human(0.1) + "±10.00%" + """ + def format_human(std_dev_ratio) do + format(std_dev_ratio) + end +end diff --git a/deps/benchee/lib/benchee/conversion/duration.ex b/deps/benchee/lib/benchee/conversion/duration.ex new file mode 100644 index 0000000000000000000000000000000000000000..278513351675f1a9584a9a7b2ca26c4a78425bb2 --- /dev/null +++ b/deps/benchee/lib/benchee/conversion/duration.ex @@ -0,0 +1,302 @@ +defmodule Benchee.Conversion.Duration do + @moduledoc """ + Unit scaling for duration converting from microseconds to minutes and others. + + Only Benchee plugins should use this code. + """ + + alias Benchee.Conversion.{Format, Scale, Unit} + + @behaviour Scale + @behaviour Format + + @nanoseconds_per_microsecond 1000 + @microseconds_per_millisecond 1000 + @milliseconds_per_second 1000 + @seconds_per_minute 60 + @minutes_per_hour 60 + + @nanoseconds_per_millisecond @nanoseconds_per_microsecond * @microseconds_per_millisecond + @nanoseconds_per_second @nanoseconds_per_millisecond * @milliseconds_per_second + @nanoseconds_per_minute @nanoseconds_per_second * @seconds_per_minute + @nanoseconds_per_hour @nanoseconds_per_minute * @minutes_per_hour + + @units_map %{ + hour: %Unit{ + name: :hour, + magnitude: @nanoseconds_per_hour, + label: "h", + long: "Hours" + }, + minute: %Unit{ + name: :minute, + magnitude: @nanoseconds_per_minute, + label: "min", + long: "Minutes" + }, + second: %Unit{ + name: :second, + magnitude: @nanoseconds_per_second, + label: "s", + long: "Seconds" + }, + millisecond: %Unit{ + name: :millisecond, + magnitude: @nanoseconds_per_millisecond, + label: "ms", + long: "Milliseconds" + }, + microsecond: %Unit{ + name: :microsecond, + magnitude: @nanoseconds_per_microsecond, + label: "μs", + long: "Microseconds" + }, + nanosecond: %Unit{ + name: :nanosecond, + magnitude: 1, + label: "ns", + long: "Nanoseconds" + } + } + + @units Map.values(@units_map) + + @doc """ + Scales a duration value in nanoseconds into a larger unit if appropriate + + ## Examples + + iex> {value, unit} = scale(1) + ...> value + 1.0 + iex> unit.name + :nanosecond + + iex> {value, unit} = scale(1_234) + ...> value + 1.234 + iex> unit.name + :microsecond + + iex> {value, unit} = scale(11_234_567_890_123) + ...> value + 3.1207133028119443 + iex> unit.name + :hour + """ + def scale(duration) when duration >= @nanoseconds_per_hour do + scale_with_unit(duration, :hour) + end + + def scale(duration) when duration >= @nanoseconds_per_minute do + scale_with_unit(duration, :minute) + end + + def scale(duration) when duration >= @nanoseconds_per_second do + scale_with_unit(duration, :second) + end + + def scale(duration) when duration >= @nanoseconds_per_millisecond do + scale_with_unit(duration, :millisecond) + end + + def scale(duration) when duration >= @nanoseconds_per_microsecond do + scale_with_unit(duration, :microsecond) + end + + def scale(duration) do + scale_with_unit(duration, :nanosecond) + end + + # Helper function for returning a tuple of {value, unit} + defp scale_with_unit(duration, unit) do + {scale(duration, unit), unit_for(unit)} + end + + @doc """ + Get a unit by its atom representation. If handed already a %Unit{} struct it + just returns it. + + ## Examples + + iex> unit_for(:hour) + %Benchee.Conversion.Unit{ + name: :hour, + magnitude: 3_600_000_000_000, + label: "h", + long: "Hours" + } + + iex> unit_for(%Benchee.Conversion.Unit{ + ...> name: :hour, + ...> magnitude: 3_600_000_000_000, + ...> label: "h", + ...> long: "Hours" + ...> }) + %Benchee.Conversion.Unit{ + name: :hour, + magnitude: 3_600_000_000_000, + label: "h", + long: "Hours" + } + """ + def unit_for(unit) do + Scale.unit_for(@units_map, unit) + end + + def units do + @units + end + + @doc """ + Scales a duration value in nanoseconds into a value in the specified unit + + ## Examples + + iex> scale(12345, :nanosecond) + 12345.0 + + iex> scale(12345, :microsecond) + 12.345 + + iex> scale(12345, :minute) + 2.0575e-7 + + """ + def scale(count, unit) do + Scale.scale(count, unit, __MODULE__) + end + + @doc """ + Converts a value for a specified %Unit or unit atom and converts it to the equivalent of another unit of measure. + + ## Examples + + iex> {value, unit} = convert({90, :minute}, :hour) + ...> value + 1.5 + iex> unit.name + :hour + """ + def convert(number_and_unit, desired_unit) do + Scale.convert(number_and_unit, desired_unit, __MODULE__) + end + + @doc """ + Converts a value of the given unit into the desired unit, returning only the value not the unit. + + ## Examples + + iex> convert_value({1.234, :second}, :microsecond) + 1_234_000.0 + + iex> convert_value({1.234, :minute}, :microsecond) + 7.404e7 + + iex> microseconds = convert_value({1.234, :minute}, :microsecond) + ...> {value, _} = convert({microseconds, :microsecond}, :minute) + ...> value + 1.234 + + """ + def convert_value({duration, unit}, desired_unit) do + {value, _} = convert({duration, unit}, desired_unit) + value + end + + @doc """ + Finds the best unit for a list of durations. By default, chooses the most common + unit. In case of tie, chooses the largest of the most common units. + + Pass `[strategy: :smallest]` to always return the smallest unit in the list. + Pass `[strategy: :largest]` to always return the largest unit in the list. + + ## Examples + + iex> best([23, 23_000, 34_000, 2_340_000]).name + :microsecond + + iex> best([23, 23_000, 34_000_000, 2_340_000_000, 3_450_000_000]).name + :second + + iex> best([23, 23_000, 34_000, 2_340_000], strategy: :smallest).name + :nanosecond + + iex> best([23, 23_000, 34_000, 2_340_000_000], strategy: :largest).name + :second + """ + def best(list, opts \\ [strategy: :best]) + + def best(list, opts) do + Scale.best_unit(list, __MODULE__, opts) + end + + @doc """ + The most basic unit in which measurements occur. + + ## Examples + + iex> base_unit().name + :nanosecond + + """ + def base_unit, do: unit_for(:nanosecond) + + @doc """ + Formats a number as a string, with a unit label. To specify the unit, pass + a tuple of `{value, unit_atom}` like `{1_234, :second}`. + + ## Examples + + iex> format(45_678.9) + "45.68 μs" + + iex> format(45.6789) + "45.68 ns" + + iex> format({45.6789, :millisecond}) + "45.68 ms" + + iex> format( + ...> {45.6789, + ...> %Benchee.Conversion.Unit{ + ...> long: "Milliseconds", + ...> magnitude: 1000, + ...> label: "ms" + ...> }} + ...> ) + "45.68 ms" + + """ + def format(duration) do + Format.format(duration, __MODULE__) + end + + @doc """ + Formats in a more "human" way - 1h 30min instead of 1.5h. + + ## Examples + + iex> format_human(5_400_000_000_000) + "1 h 30 min" + + iex> format_human(12.5) + "12.50 ns" + + iex> format_human(1000.555) + "1 μs 0.55 ns" + + iex> format_human(3_660_001_001_000) + "1 h 1 min 1 ms 1 μs" + + iex> format_human(0) + "0 ns" + + iex> format_human(2 * 1000 * 1000 * 1000) + "2 s" + """ + def format_human(duration) do + Format.format_human(duration, __MODULE__) + end +end diff --git a/deps/benchee/lib/benchee/conversion/format.ex b/deps/benchee/lib/benchee/conversion/format.ex new file mode 100644 index 0000000000000000000000000000000000000000..da3776b1905f9a306aa6aee74bd1495ad93dc0f5 --- /dev/null +++ b/deps/benchee/lib/benchee/conversion/format.ex @@ -0,0 +1,155 @@ +defmodule Benchee.Conversion.Format do + @moduledoc """ + Functions for formatting values and their unit labels. Different domains + handle this task differently, for example durations and counts. + + See `Benchee.Conversion.Count` and `Benchee.Conversion.Duration` for examples. + """ + + alias Benchee.Conversion.Unit + + @doc """ + Formats a number as a string, with a unit label. See `Benchee.Conversion.Count` + and `Benchee.Conversion.Duration` for examples + """ + @callback format(number) :: String.t() + + @doc """ + Formats in a more "human" way, one biggest unit at a time. + + So instead of 1.5h it says 1h 30min + """ + @callback format_human(number) :: String.t() + + # Generic formatting functions + + @doc """ + Formats a unit value with specified label and separator + """ + def format(number, label, separator) do + separator = separator(label, separator) + "#{number_format(number)}#{separator}#{label}" + end + + defp number_format(number) when is_float(number) do + number + |> :erlang.float_to_list(decimals: float_precision(number)) + |> to_string + end + + defp number_format(number) when is_integer(number) do + to_string(number) + end + + @doc """ + Formats a unit value in the domain described by `module`. The module should + provide a `units/0` function that returns a Map like + + %{ :unit_name => %Benchee.Conversion.Unit{ ... } } + + Additionally, `module` may specify a `separator/0` function, which provides a + custom separator string that will appear between the value and label in the + formatted output. If no `separator/0` function exists, the default separator + (a single space) will be used. + + iex> format({1.0, :kilobyte}, Benchee.Conversion.Memory) + "1 KB" + + """ + def format({number, unit = %Unit{}}) do + format(number, label(unit), separator()) + end + + def format({number, unit = %Unit{}}, _module) do + format({number, unit}) + end + + def format({number, unit_atom}, module) do + format({number, module.unit_for(unit_atom)}) + end + + def format(number, module) when is_number(number) do + number + |> module.scale() + |> format + end + + @doc """ + Human friendly duration format for time as a string. + + The output is a sequence of values and unit labels separated by a space. + Only units whose value is non-zero are included in the output. + The passed number is duration in the base unit - nanoseconds. + """ + def format_human(0, module) do + format(0, module) + end + + def format_human(+0.0, module) do + format(0, module) + end + + def format_human(number, module) when is_number(number) do + number + |> split_into_place_values(module) + |> Enum.map_join(" ", &format/1) + end + + # Returns a list of place vaules with corresponding units for the `number`. + # The output is sorted descending by magnitude of units and excludes tuples with place value 0. + # Place values are `non_neg_integer` for non-base units, + # however base unit may also be `float` becuase the decimals can't be split further. + @spec split_into_place_values(number, module) :: [{number, Unit.t()}] + defp split_into_place_values(number, module) do + descending_units = units_descending(module) + + place_values(number, descending_units) + end + + defp units_descending(module) do + Enum.sort(module.units(), &(&1.magnitude >= &2.magnitude)) + end + + @spec place_values(number, [Unit.t()]) :: [{number, Unit.t()}] + defp place_values(0, _units), do: [] + defp place_values(+0.0, _units), do: [] + + # smalles unit, carries the decimal + defp place_values(number, [base_unit = %Unit{magnitude: 1}]), do: [{number, base_unit}] + + defp place_values(number, [unit | units]) do + integer_number = trunc(number) + decimal_carry = number - integer_number + int_carry = rem(integer_number, unit.magnitude) + carry = decimal_carry + int_carry + + place_value = div(integer_number, unit.magnitude) + + case place_value do + 0 -> place_values(carry, units) + place_value -> [{place_value, unit} | place_values(carry, units)] + end + end + + @default_separator " " + # should we need it again, a customer separator could be returned + # per module here + defp separator do + @default_separator + end + + # Returns the separator, or an empty string if there isn't a label + defp separator(label, _separator) when label == "" or label == nil, do: "" + defp separator(_label, separator), do: separator + + # Fetches the label for the given unit + defp label(%Unit{label: label}) do + label + end + + defp float_precision(float) when trunc(float) == float, do: 0 + defp float_precision(float) when float < 0.01, do: 5 + defp float_precision(float) when float < 0.1, do: 4 + defp float_precision(float) when float < 0.2, do: 3 + defp float_precision(_float), do: 2 +end diff --git a/deps/benchee/lib/benchee/conversion/memory.ex b/deps/benchee/lib/benchee/conversion/memory.ex new file mode 100644 index 0000000000000000000000000000000000000000..9ab4b4c0089d0a0d051be9788826f020a77835f7 --- /dev/null +++ b/deps/benchee/lib/benchee/conversion/memory.ex @@ -0,0 +1,278 @@ +defmodule Benchee.Conversion.Memory do + @moduledoc """ + Unit scaling for memory converting from bytes to kilobytes and others. + + Only Benchee plugins should use this code. + """ + + alias Benchee.Conversion.{Format, Scale, Unit} + + @behaviour Scale + @behaviour Format + + @bytes_per_kilobyte 1024 + @bytes_per_megabyte @bytes_per_kilobyte * @bytes_per_kilobyte + @bytes_per_gigabyte @bytes_per_megabyte * @bytes_per_kilobyte + @bytes_per_terabyte @bytes_per_gigabyte * @bytes_per_kilobyte + + @units_map %{ + terabyte: %Unit{ + name: :terabyte, + magnitude: @bytes_per_terabyte, + label: "TB", + long: "Terabytes" + }, + gigabyte: %Unit{ + name: :gigabyte, + magnitude: @bytes_per_gigabyte, + label: "GB", + long: "Gigabytes" + }, + megabyte: %Unit{ + name: :megabyte, + magnitude: @bytes_per_megabyte, + label: "MB", + long: "Megabytes" + }, + kilobyte: %Unit{ + name: :kilobyte, + magnitude: @bytes_per_kilobyte, + label: "KB", + long: "Kilobytes" + }, + byte: %Unit{ + name: :byte, + magnitude: 1, + label: "B", + long: "Bytes" + } + } + + @units Map.values(@units_map) + + @type unit_atom :: :byte | :kilobyte | :megabyte | :gigabyte | :terabyte + @type any_unit :: unit_atom | Unit.t() + + @doc """ + Converts a value for a specified %Unit or unit atom and converts it to the equivalent of another unit of measure. + + ## Examples + + iex> {value, unit} = convert({1024, :kilobyte}, :megabyte) + ...> value + 1.0 + iex> unit.name + :megabyte + + iex> current_unit = unit_for(:kilobyte) + ...> {value, unit} = convert({1024, current_unit}, :megabyte) + ...> value + 1.0 + iex> unit.name + :megabyte + """ + @spec convert({number, any_unit}, any_unit) :: Scale.scaled_number() + def convert(number_and_unit, desired_unit) do + Scale.convert(number_and_unit, desired_unit, __MODULE__) + end + + # Scaling functions + + @doc """ + Scales a memory value in bytes into a larger unit if appropriate + + ## Examples + + iex> {value, unit} = scale(1) + ...> value + 1.0 + iex> unit.name + :byte + + iex> {value, unit} = scale(1_234) + ...> value + 1.205078125 + iex> unit.name + :kilobyte + + iex> {value, unit} = scale(11_234_567_890.123) + ...> value + 10.463006692121736 + iex> unit.name + :gigabyte + + iex> {value, unit} = scale(1_111_234_567_890.123) + ...> value + 1.0106619519229962 + iex> unit.name + :terabyte + """ + def scale(memory) when memory >= @bytes_per_terabyte do + scale_with_unit(memory, :terabyte) + end + + def scale(memory) when memory >= @bytes_per_gigabyte do + scale_with_unit(memory, :gigabyte) + end + + def scale(memory) when memory >= @bytes_per_megabyte do + scale_with_unit(memory, :megabyte) + end + + def scale(memory) when memory >= @bytes_per_kilobyte do + scale_with_unit(memory, :kilobyte) + end + + def scale(memory) do + scale_with_unit(memory, :byte) + end + + # Helper function for returning a tuple of {value, unit} + defp scale_with_unit(nil, _) do + {nil, nil} + end + + defp scale_with_unit(memory, unit) do + {scale(memory, unit), unit_for(unit)} + end + + @doc """ + Get a unit by its atom representation. If handed already a %Unit{} struct it + just returns it. + + ## Examples + + iex> unit_for(:gigabyte) + %Benchee.Conversion.Unit{ + name: :gigabyte, + magnitude: 1_073_741_824, + label: "GB", + long: "Gigabytes" + } + + iex> unit_for(%Benchee.Conversion.Unit{ + ...> name: :gigabyte, + ...> magnitude: 1_073_741_824, + ...> label: "GB", + ...> long: "Gigabytes" + ...> }) + %Benchee.Conversion.Unit{ + name: :gigabyte, + magnitude: 1_073_741_824, + label: "GB", + long: "Gigabytes" + } + """ + def unit_for(unit) do + Scale.unit_for(@units_map, unit) + end + + def units do + @units + end + + @doc """ + Scales a memory value in bytes into a value in the specified unit + + ## Examples + + iex> scale(12345, :kilobyte) + 12.0556640625 + + iex> scale(12345, :megabyte) + 0.011773109436035156 + + iex> scale(123_456_789, :gigabyte) + 0.11497809458523989 + + """ + def scale(count, unit) do + Scale.scale(count, unit, __MODULE__) + end + + @doc """ + Finds the best unit for a list of memory units. By default, chooses the most common + unit. In case of tie, chooses the largest of the most common units. + + Pass `[strategy: :smallest]` to always return the smallest unit in the list. + Pass `[strategy: :largest]` to always return the largest unit in the list. + Pass `[strategy: :best]` to always return the most frequent unit in the list. + Pass `[strategy: :none]` to always return :byte. + + ## Examples + + iex> best([23, 23_000, 34_000, 2_340_000]).name + :kilobyte + + iex> best([23, 23_000, 34_000, 2_340_000, 3_450_000]).name + :megabyte + + iex> best([23, 23_000, 34_000, 2_340_000], strategy: :smallest).name + :byte + + iex> best([23, 23_000, 34_000, 2_340_000], strategy: :largest).name + :megabyte + """ + def best(list, opts \\ [strategy: :best]) + + def best(list, opts) do + Scale.best_unit(list, __MODULE__, opts) + end + + @doc """ + The most basic unit in which memory occur, byte. + + ## Examples + + iex> base_unit().name + :byte + + """ + def base_unit, do: unit_for(:byte) + + @doc """ + Formats a memory as a string, with a unit label. + + To specify the unit, pass a tuple of `{value, unit_atom}` like `{1_234, :kilobyte}`. + + ## Examples + + iex> format(45_678.9) + "44.61 KB" + + iex> format(45.6789) + "45.68 B" + + iex> format({45.6789, :kilobyte}) + "45.68 KB" + + iex> format( + ...> {45.6789, + ...> %Benchee.Conversion.Unit{ + ...> long: "Kilobytes", + ...> magnitude: 1024, + ...> label: "KB" + ...> }} + ...> ) + "45.68 KB" + + """ + def format(memory) do + Format.format(memory, __MODULE__) + end + + @doc """ + Formats in a more human way, where multiple units are used. + + ## Examples + + iex> format_human(45_678.9) + "44 KB 622.90 B" + + iex> format_human(1024 * 1024 * 1024) + "1 GB" + """ + def format_human(memory) do + Format.format_human(memory, __MODULE__) + end +end diff --git a/deps/benchee/lib/benchee/conversion/scale.ex b/deps/benchee/lib/benchee/conversion/scale.ex new file mode 100644 index 0000000000000000000000000000000000000000..783f8aa070738712298ff683b76e4cc1acfb6ef8 --- /dev/null +++ b/deps/benchee/lib/benchee/conversion/scale.ex @@ -0,0 +1,227 @@ +defmodule Benchee.Conversion.Scale do + @moduledoc """ + Functions for scaling values to other units. Different domains handle + this task differently, for example durations and counts. + + See `Benchee.Conversion.Count` and `Benchee.Conversion.Duration` for examples + """ + + alias Benchee.Conversion.Unit + + @type unit :: Unit.t() + @type unit_atom :: atom + @type any_unit :: unit | unit_atom + @type scaled_number :: {number, unit} + @type scaling_strategy :: :best | :largest | :smallest | :none + + @doc """ + Scales a number in a domain's base unit to an equivalent value in the best + fit unit. Results are a `{number, unit}` tuple. See `Benchee.Conversion.Count` and + `Benchee.Conversion.Duration` for examples. + """ + @callback scale(number) :: scaled_number + + @doc """ + Scales a number in a domain's base unit to an equivalent value in the + specified unit. + See `Benchee.Conversion.Count` and `Benchee.Conversion.Duration` for examples. + """ + @callback scale(number, any_unit) :: number + + @doc """ + Finds the best fit unit for a list of numbers in a domain's base unit. + "Best fit" is the most common unit, or (in case of tie) the largest of the + most common units. + """ + @callback best(list, keyword) :: unit + + @doc """ + Returns the base_unit in which Benchee takes its measurements, which in + general is the smallest supported unit. + """ + @callback base_unit :: unit + + @doc """ + Given the atom representation of a unit (`:hour`) return the appropriate + `Benchee.Conversion.Unit` struct. + """ + @callback unit_for(any_unit) :: unit + + @doc """ + List of all the units supported by this type. + """ + @callback units :: [unit] + + @doc """ + Takes a tuple of a number and a unit and a unit to be converted to, returning + the the number scaled to the new unit and the new unit. + """ + @callback convert({number, any_unit}, any_unit) :: scaled_number + + # Generic scaling functions + + @doc """ + Used internally by implemented units to handle their scaling with units and + without. + + ## Examples + + iex> scale(12345, :thousand, Benchee.Conversion.Count) + 12.345 + """ + def scale(value, unit = %Unit{}, _module) do + scale(value, unit) + end + + def scale(value, unit_atom, module) do + scale(value, module.unit_for(unit_atom)) + end + + @doc """ + Used internally for scaling but only supports scaling with actual units. + + ## Examples + + iex> unit = %Benchee.Conversion.Unit{magnitude: 1000} + ...> scale(12345, unit) + 12.345 + """ + def scale(value, %Unit{magnitude: magnitude}) do + value / magnitude + end + + @doc """ + Lookup a unit by its `atom` presentation for the representation of supported + units. Used by `Benchee.Conversion.Duration` and `Benchee.Conversion.Count`. + """ + def unit_for(_units, unit = %Unit{}), do: unit + def unit_for(units, unit), do: Map.fetch!(units, unit) + + @doc """ + Used internally to implement scaling in the modules without duplication. + """ + def convert({value, current_unit}, desired_unit, module) do + current_unit = module.unit_for(current_unit) + desired_unit = module.unit_for(desired_unit) + do_convert({value, current_unit}, desired_unit) + end + + defp do_convert( + {value, %Unit{magnitude: current_magnitude}}, + desired_unit = %Unit{magnitude: desired_magnitude} + ) do + multiplier = current_magnitude / desired_magnitude + {value * multiplier, desired_unit} + end + + @doc """ + Given a `list` of number values and a `module` describing the domain of the + values (e.g. Duration, Count), finds the "best fit" unit for the list as a + whole. + + The best fit unit for a given value is the smallest unit in the domain for + which the scaled value is at least 1. For example, the best fit unit for a + count of 1_000_000 would be `:million`. + + The best fit unit for the list as a whole depends on the `:strategy` passed + in `opts`: + + * `:best` - the most frequent best fit unit. In case of tie, the + largest of the most frequent units + * `:largest` - the largest best fit unit + * `:smallest` - the smallest best fit unit + * `:none` - the domain's base (unscaled) unit + + ## Examples + + iex> list = [1, 101, 1_001, 10_001, 100_001, 1_000_001] + ...> best_unit(list, Benchee.Conversion.Count, strategy: :best).name + :thousand + + iex> list = [1, 101, 1_001, 10_001, 100_001, 1_000_001] + ...> best_unit(list, Benchee.Conversion.Count, strategy: :smallest).name + :one + + iex> list = [1, 101, 1_001, 10_001, 100_001, 1_000_001] + ...> best_unit(list, Benchee.Conversion.Count, strategy: :largest).name + :million + + iex> list = [] + ...> best_unit(list, Benchee.Conversion.Count, strategy: :best).name + :one + + iex> list = [nil] + ...> best_unit(list, Benchee.Conversion.Count, strategy: :best).name + :one + + iex> list = [nil, nil, nil, nil] + ...> best_unit(list, Benchee.Conversion.Count, strategy: :best).name + :one + + iex> list = [nil, nil, nil, nil, 2_000] + ...> best_unit(list, Benchee.Conversion.Count, strategy: :best).name + :thousand + """ + def best_unit(measurements, module, options) do + do_best_unit(Enum.reject(measurements, &is_nil/1), module, options) + end + + defp do_best_unit([], module, _) do + module.base_unit() + end + + defp do_best_unit(list, module, opts) do + case Keyword.get(opts, :strategy, :best) do + :best -> best_unit(list, module) + :largest -> largest_unit(list, module) + :smallest -> smallest_unit(list, module) + :none -> module.base_unit() + end + end + + # Finds the most common unit in the list. In case of tie, chooses the + # largest of the most common + defp best_unit(list, module) do + list + |> Enum.map(fn n -> scale_unit(n, module) end) + |> Enum.group_by(fn unit -> unit end) + |> Enum.map(fn {unit, occurrences} -> {unit, length(occurrences)} end) + |> Enum.sort(fn unit, freq -> by_frequency_and_magnitude(unit, freq) end) + |> hd + |> elem(0) + end + + # Finds the smallest unit in the list + defp smallest_unit(list, module) do + list + |> Enum.map(fn n -> scale_unit(n, module) end) + |> Enum.min_by(fn unit -> magnitude(unit) end) + end + + # Finds the largest unit in the list + defp largest_unit(list, module) do + list + |> Enum.map(fn n -> scale_unit(n, module) end) + |> Enum.max_by(fn unit -> magnitude(unit) end) + end + + defp scale_unit(count, module) do + {_, unit} = module.scale(count) + unit + end + + # Fetches the magnitude for the given unit + defp magnitude(%Unit{magnitude: magnitude}) do + magnitude + end + + # Sorts two elements first by total, then by magnitude of the unit in case + # of tie + defp by_frequency_and_magnitude({unit_a, frequency}, {unit_b, frequency}) do + magnitude(unit_a) > magnitude(unit_b) + end + + defp by_frequency_and_magnitude({_, frequency_a}, {_, frequency_b}) do + frequency_a > frequency_b + end +end diff --git a/deps/benchee/lib/benchee/conversion/unit.ex b/deps/benchee/lib/benchee/conversion/unit.ex new file mode 100644 index 0000000000000000000000000000000000000000..b58695f7cc6dfb5e71fd558ce11e617624ccf42e --- /dev/null +++ b/deps/benchee/lib/benchee/conversion/unit.ex @@ -0,0 +1,26 @@ +defmodule Benchee.Conversion.Unit do + @moduledoc """ + A representation of the different units used in `Benchee.Conversion.Format` + and `Benchee.Conversion.Scale` as well as the modules implementing these + behaviours. + + A unit is characterized by: + + * name - an atom representation of the unit for easy access (`:microseconds`, + `thousand`) + * magnitude - compared to he base unit (the smallest unit) what's the factor + you had to multiply it by to get back to the base unit. E.g. the thousand + unit has a magnitude of `1_000`. + * label - a string that is used as a unit label (`"K"` for a thousand f.ex.) + * long - a string giving the long version of the label (`"Thousand"`) + """ + + defstruct [:name, :magnitude, :label, :long] + + @type t :: %Benchee.Conversion.Unit{ + name: atom, + magnitude: non_neg_integer, + label: String.t(), + long: String.t() + } +end diff --git a/deps/benchee/lib/benchee/errors.ex b/deps/benchee/lib/benchee/errors.ex new file mode 100644 index 0000000000000000000000000000000000000000..78645cca12f721edf2a1232b759f182a6c73541f --- /dev/null +++ b/deps/benchee/lib/benchee/errors.ex @@ -0,0 +1,7 @@ +defmodule Benchee.UnknownProfilerError do + defexception message: "error" +end + +defmodule Benchee.PreCheckError do + defexception message: "error" +end diff --git a/deps/benchee/lib/benchee/formatter.ex b/deps/benchee/lib/benchee/formatter.ex new file mode 100644 index 0000000000000000000000000000000000000000..4f70970d94b5f4534acb42a313334b54ffca1a0b --- /dev/null +++ b/deps/benchee/lib/benchee/formatter.ex @@ -0,0 +1,214 @@ +defmodule Benchee.Formatter do + @moduledoc """ + Defines a behaviour for formatters in Benchee, and functions to work with these. + + When implementing a Benchee formatter as a behaviour please adopt this + behaviour, as it helps with uniformity and also allows at least the `.format` + function of formatters to be run in parallel. + + The module itself then has functions to deal with formatters defined in this way + allowing for parallel output through `output/1` or just output a single formatter + through `output/3`. + """ + + alias Benchee.Output.ProgressPrinter + alias Benchee.{Scenario, Suite, Utility.Parallel} + alias Benchee.Utility.DeepConvert + + @typedoc """ + Options given to formatters, entirely defined by formatter authors. + """ + @type options :: any + + @typedoc """ + A suite scrubbed of heavy data. + + Type to bring awareness to the fact that `format/2` doesn't have access to + _all_ data in `Benchee.Suite` - please read the docs for `format/2` to learn + more. + """ + @type scrubbed_suite :: Suite.t() + + @doc """ + Takes a suite and returns a representation `write/2` can use. + + Takes the suite and returns whatever representation the formatter wants to use + to output that information. It is important that this function **needs to be + pure** (aka have no side effects) as Benchee will run `format/1` functions + of multiple formatters in parallel. The result will then be passed to + `write/2`. + + **Note:** Due to memory consumption issues in benchmarks with big inputs, the suite + passed to the formatters **is missing anything referencing big input data** to avoid + huge memory consumption and run time. Namely this constitutes: + * `Benchee.Scenario` will have `function` and `input` set to `nil` + * `Benchee.Configuration` will have `inputs`, but it won't have values only the names, + it may be removed in the future please use `input_names` instead if needed (or + `input_name` of `Benchee.Scenario`) + + Technically speaking this "scrubbing" of `Benchee.Suite` only occurs when formatters + are run in parallel, you still shouldn't rely on those values (and they should not + be needed). If you do need them for some reason, please get in touch/open an issue. + """ + @callback format(Suite.t(), options) :: any + + @doc """ + Takes the return value of `format/1` and then performs some I/O for the user + to actually see the formatted data (UI, File IO, HTTP, ...) + """ + @callback write(any, options) :: :ok | {:error, String.t()} + + @doc """ + Format and output all configured formatters and formatting functions. + + Expects a suite that already has been run through all previous functions so has the aggregated + statistics etc. that the formatters rely on. + + Works by invoking the `format/2` and `write/2` functions defined in this module. The `format/2` + functions are actually called in parallel (as they should be pure) - due to potential + interference the `write/2` functions are called serial. + + Also handles pure functions that will then be called with the suite. + + You can't rely on the formatters being called in pre determined order. + """ + @spec output(Suite.t()) :: Suite.t() + def output(suite = %{configuration: %{formatters: formatters}}) do + print_formatting(suite.configuration) + + {parallelizable, serial} = + formatters + |> Enum.map(&normalize_module_configuration/1) + |> Enum.split_with(&is_tuple/1) + + maybe_parallel_output(suite, parallelizable) + + Enum.each(serial, fn function -> function.(suite) end) + + suite + end + + # This is a bit of a hack, but we can't DI the printer like we usually do as we made the _great_ + # decisions to use both `output/1` and `output/2` as part of the public interface. Adding the + # printer to `output/1` would clash with `output/2` and its second parameter is _also_ a module. + # So, we're abusing the `assigns` in the config a bit. + defp print_formatting(config) do + printer = config.assigns[:test][:progress_printer] || ProgressPrinter + printer.formatting(config) + end + + defp normalize_module_configuration(formatter) when is_function(formatter, 1), do: formatter + + defp normalize_module_configuration({module, opts}) do + normalize_module_configuration(module, DeepConvert.to_map(opts)) + end + + defp normalize_module_configuration(module) when is_atom(module) do + normalize_module_configuration(module, %{}) + end + + defp normalize_module_configuration(module, opts) do + if formatter_module?(module) do + {module, opts} + else + raise_behaviour_not_implemented(module) + end + end + + defp formatter_module?(module) do + :attributes + |> module.module_info() + |> Keyword.get(:behaviour, []) + |> Enum.member?(Benchee.Formatter) + end + + @spec raise_behaviour_not_implemented(atom) :: no_return() + defp raise_behaviour_not_implemented(module) do + raise """ + The module you're attempting to use as a formatter - #{module} - does + not implement the `Benchee.Formatter` behaviour. + """ + end + + @doc """ + Output a suite with a given formatter and options. + + Replacement for the old `MyFormatter.output/1` - calls `format/2` and `write/2` one after another + to create the output defined by the given formatter module. For the given options please refer + to the documentation of the formatters you use. + """ + @spec output(Suite.t(), module, options) :: Suite.t() + def output(suite, formatter, options \\ %{}) do + :ok = + suite + |> formatter.format(options) + |> formatter.write(options) + + suite + end + + # Invokes `format/2` and `write/2` as defined by the `Benchee.Formatter` + # behaviour. The output for all formatters is generated in parallel, and then + # the results of that formatting are written in sequence. + # If there is only one parallelizable formatter (common case) we don't do it + # in parallel at all to avoid the cost of copying all the data to a new process + # (and of us scrubbing it so we don't need as much data) + defp maybe_parallel_output(suite, module_configurations) do + module_configurations + |> maybe_parallel_format(suite) + |> Enum.each(fn {module, options, output} -> module.write(output, options) end) + + suite + end + + # don't let it drop to the `Parallel` case so we don't do the scrubbing + # for nothing + defp maybe_parallel_format([], _suite), do: [] + + defp maybe_parallel_format(formatters = [_one_formatter], suite) do + Enum.map(formatters, fn {module, options} -> + {module, options, module.format(suite, options)} + end) + end + + defp maybe_parallel_format(formatters, suite) do + # suite only needs scrubbing for parallel processing due to data copying + scrubbed_suite = scrub_suite(suite) + + Parallel.map(formatters, fn {module, options} -> + {module, options, module.format(scrubbed_suite, options)} + end) + end + + # The actual benchmarking functions and the actual inputs should not be important for + # formatters (famous last words, I know) and processing them in parallel means that for + # benchmarks with a lot of data we end up doing a lot of copying with huge impact on run + # time and memory consumption. + # As the suite isn't actually returned from the formatters removing them also doesn't impact + # anyone negatively downstream. + # Hence, we scrub them away here. If you maintain a formatter plugin and rely on these please + # get in touch so we can work on a solution. + defp scrub_suite(suite) do + suite = + update_in(suite.scenarios, fn scenarios -> + Enum.map(scenarios, &scrub_scenario/1) + end) + + update_in(suite.configuration, &scrub_configuration/1) + end + + defp scrub_scenario(scenario = %Scenario{}) do + %Scenario{scenario | function: nil, input: nil} + end + + defp scrub_configuration(configuration) do + update_in(configuration.inputs, &scrub_inputs/1) + end + + defp scrub_inputs(nil), do: nil + # Feels somewhat hacky, but while people should not be relying on the input itself, they + # may be relying on the input names/order + defp scrub_inputs(inputs) do + Enum.map(inputs, fn {name, _value} -> {name, :scrubbed_see_1_3_0_changelog} end) + end +end diff --git a/deps/benchee/lib/benchee/formatters/console.ex b/deps/benchee/lib/benchee/formatters/console.ex new file mode 100644 index 0000000000000000000000000000000000000000..37660aef35b8f9abe37c92c9fcbb7d9310069485 --- /dev/null +++ b/deps/benchee/lib/benchee/formatters/console.ex @@ -0,0 +1,161 @@ +defmodule Benchee.Formatters.Console do + @moduledoc """ + Formatter to print out the results of benchmarking suite to the console. + + Example: + + Name ips average deviation median 99th % + flat_map 2.40 K 417.00 μs ±9.40% 411.45 μs 715.21 μs + map.flatten 1.24 K 806.89 μs ±16.62% 768.02 μs 1170.67 μs + + Comparison: + flat_map 2.40 K + map.flatten 1.24 K - 1.93x slower + + Memory usage statistics: + + Name Memory usage + flat_map 624.97 KB + map.flatten 781.25 KB - 1.25x memory usage + + **All measurements for memory usage were the same** + + Reduction count statistics: + + Name average deviation median 99th % + flat_map 417.00 ±9.40 411.45 715.21 + map.flatten 806.89 ±16.62 768.02 1170.67 + + Comparison: + flat_map 417.00 + map.flatten 806.89 - 1.93x more reductions + """ + + @behaviour Benchee.Formatter + + alias Benchee.Formatters.Console.{Memory, Reductions, RunTime} + alias Benchee.Suite + + @doc """ + Formats the benchmark statistics to a report suitable for output on the CLI. + + Returns a list of lists, where each list element is a group belonging to one + specific input. So if there only was one (or no) input given through `:inputs` + then there's just one list inside. + + ## Examples + + ``` + iex> scenarios = [ + ...> %Benchee.Scenario{ + ...> name: "My Job", + ...> input_name: "My input", + ...> run_time_data: %Benchee.CollectionData{ + ...> statistics: %Benchee.Statistics{ + ...> average: 200.0, + ...> ips: 5000.0, + ...> std_dev_ratio: 0.1, + ...> median: 190.0, + ...> percentiles: %{99 => 300.1}, + ...> sample_size: 200 + ...> } + ...> }, + ...> memory_usage_data: %Benchee.CollectionData{statistics: %Benchee.Statistics{}} + ...> }, + ...> %Benchee.Scenario{ + ...> name: "Job 2", + ...> input_name: "My input", + ...> run_time_data: %Benchee.CollectionData{ + ...> statistics: %Benchee.Statistics{ + ...> average: 400.0, + ...> ips: 2500.0, + ...> std_dev_ratio: 0.2, + ...> median: 390.0, + ...> percentiles: %{99 => 500.1}, + ...> sample_size: 200 + ...> } + ...> }, + ...> memory_usage_data: %Benchee.CollectionData{statistics: %Benchee.Statistics{}} + ...> } + ...> ] + ...> + ...> suite = %Benchee.Suite{ + ...> scenarios: scenarios, + ...> configuration: %Benchee.Configuration{ + ...> unit_scaling: :best + ...> } + ...> } + ...> + ...> format(suite, %{comparison: false, extended_statistics: false}) + [ + [ + "\n##### With input My input #####", + "\nName ips average deviation median 99th %\n", + "My Job 5 K 200 ns ±10.00% 190 ns 300.10 ns\n", + "Job 2 2.50 K 400 ns ±20.00% 390 ns 500.10 ns\n" + ] + ] + + ``` + + """ + @impl true + @spec format(Suite.t(), map) :: [any] + def format(%Suite{scenarios: scenarios, configuration: config}, options \\ %{}) do + config = + config + |> Map.take([:unit_scaling, :title]) + |> Map.merge(options) + + scenarios + |> Enum.reduce([], &update_grouped_list/2) + |> Enum.map(fn {input, scenarios} -> + generate_output(scenarios, config, input) + end) + end + + # Normally one would prepend to lists and not append. In this case this lead to 2 + # `Enum.reverse` scattered around. As these lists are usually very small (mostly less + # than 10 elements) I opted for `++` here. + defp update_grouped_list(scenario, grouped_scenarios) do + case List.keyfind(grouped_scenarios, scenario.input_name, 0) do + {_, group} -> + new_tuple = {scenario.input_name, group ++ [scenario]} + List.keyreplace(grouped_scenarios, scenario.input_name, 0, new_tuple) + + _ -> + grouped_scenarios ++ [{scenario.input_name, [scenario]}] + end + end + + @doc """ + Takes the output of `format/1` and writes that to the console. + """ + @impl true + @spec write(any, map) :: :ok | {:error, String.t()} + def write(output, _options \\ %{}) do + IO.write(output) + rescue + _ -> {:error, "Unknown Error"} + end + + defp generate_output(scenarios, config, input) do + [ + suite_header(input, config) + | RunTime.format_scenarios(scenarios, config) ++ + Memory.format_scenarios(scenarios, config) ++ + Reductions.format_scenarios(scenarios, config) + ] + end + + defp suite_header(input, config) do + "#{title_header(config)}#{input_header(input)}" + end + + defp title_header(%{title: nil}), do: "" + defp title_header(%{title: title}), do: "\n*** #{title} ***\n" + + @no_input_marker Benchee.Benchmark.no_input() + defp input_header(input) when input == @no_input_marker, do: "" + defp input_header(input), do: "\n##### With input #{input} #####" +end diff --git a/deps/benchee/lib/benchee/formatters/console/helpers.ex b/deps/benchee/lib/benchee/formatters/console/helpers.ex new file mode 100644 index 0000000000000000000000000000000000000000..225b494b0625852cdaa1c1990dae9dec57841eb7 --- /dev/null +++ b/deps/benchee/lib/benchee/formatters/console/helpers.ex @@ -0,0 +1,101 @@ +defmodule Benchee.Formatters.Console.Helpers do + @moduledoc false + + # These are common functions shared between the formatting of the run time and + # memory usage statistics. + + alias Benchee.Conversion.{Count, DeviationPercent, Format, Scale, Unit} + alias Benchee.Scenario + alias Benchee.Statistics + + @type unit_per_statistic :: %{atom => Unit.t()} + + # Length of column header + @default_label_width 4 + + @spec mode_out(Statistics.mode(), Benchee.Conversion.Unit.t()) :: String.t() + def mode_out(modes, _run_time_unit) when is_nil(modes) do + "None" + end + + def mode_out(modes, run_time_unit) when is_list(modes) do + Enum.map_join(modes, ", ", fn mode -> unit_output(mode, run_time_unit) end) + end + + def mode_out(mode, run_time_unit) when is_number(mode) do + unit_output(mode, run_time_unit) + end + + defp unit_output(value, unit) do + Format.format({Scale.scale(value, unit), unit}) + end + + @spec label_width([Scenario.t()]) :: number + def label_width(scenarios) do + max_label_width = + scenarios + |> Enum.map(fn scenario -> String.length(scenario.name) end) + |> Stream.concat([@default_label_width]) + |> Enum.max() + + max_label_width + 1 + end + + @spec count_output(number, Count.units()) :: binary + def count_output(count, unit) do + Count.format({Count.scale(count, unit), unit}) + end + + @spec deviation_output(number) :: binary + def deviation_output(std_dev_ratio) do + DeviationPercent.format(std_dev_ratio) + end + + @spec descriptor(String.t()) :: String.t() + def descriptor(header_str), do: "\n#{header_str}: \n" + + def format_comparison( + name, + statistics, + display_value, + comparison_name, + display_unit, + label_width, + column_width + ) do + "~*s~*s ~ts" + |> :io_lib.format([ + -label_width, + name, + column_width, + display_value, + comparison_display(statistics, comparison_name, display_unit) + ]) + |> to_string + end + + defp comparison_display(%Statistics{relative_more: nil, absolute_difference: nil}, _, _), do: "" + + defp comparison_display(statistics, comparison_name, unit) do + "- #{comparison_text(statistics, comparison_name)} #{absolute_difference_text(statistics, unit)}\n" + end + + defp comparison_text(%Statistics{relative_more: :infinity}, name), do: "∞ x #{name}" + defp comparison_text(%Statistics{relative_more: nil}, _), do: "N/A" + + defp comparison_text(statistics, comparison_name) do + "~.2fx ~s" + |> :io_lib.format([statistics.relative_more, comparison_name]) + |> to_string + end + + defp absolute_difference_text(statistics, unit) do + formatted_value = Format.format({Scale.scale(statistics.absolute_difference, unit), unit}) + + if statistics.absolute_difference >= 0 do + "+#{formatted_value}" + else + formatted_value + end + end +end diff --git a/deps/benchee/lib/benchee/formatters/console/memory.ex b/deps/benchee/lib/benchee/formatters/console/memory.ex new file mode 100644 index 0000000000000000000000000000000000000000..918b27b85129b4f926939b877225dec0357e828b --- /dev/null +++ b/deps/benchee/lib/benchee/formatters/console/memory.ex @@ -0,0 +1,321 @@ +defmodule Benchee.Formatters.Console.Memory do + @moduledoc false + + # This deals with just the formatting of the run time results. They are similar + # to the way the memory results are formatted, but different enough to where the + # abstractions start to break down pretty significantly, so I wanted to extract + # these two things into separate modules to avoid confusion. + + alias Benchee.{ + Conversion, + Conversion.Count, + Conversion.Memory, + Conversion.Unit, + Formatters.Console.Helpers, + Scenario, + Statistics + } + + @type unit_per_statistic :: %{atom => Unit.t()} + + # Length of column header + @average_width 15 + @deviation_width 11 + @median_width 15 + @percentile_width 15 + @minimum_width 15 + @maximum_width 15 + @sample_size_width 15 + @mode_width 25 + + @doc """ + Formats the memory statistics to a report suitable for output on the CLI. If + all memory measurements are the same and we have a standard deviation of 0.0 + for each scenario, we don't show the statistics and report just on the single + measured memory usage. + """ + @spec format_scenarios([Scenario.t()], map) :: [String.t(), ...] + def format_scenarios(scenarios, config) do + if memory_measurements_present?(scenarios) do + render(scenarios, config) + else + [] + end + end + + defp memory_measurements_present?(scenarios) do + Enum.any?(scenarios, fn scenario -> + scenario.memory_usage_data.statistics.sample_size > 0 + end) + end + + defp render(scenarios, config) do + scaling_strategy = config.unit_scaling + units = Conversion.units(scenarios, scaling_strategy) + label_width = Helpers.label_width(scenarios) + hide_statistics = all_have_deviation_of_0?(scenarios) + + List.flatten([ + "\nMemory usage statistics:\n", + column_descriptors(label_width, hide_statistics), + scenario_reports(scenarios, units, label_width, hide_statistics), + comparison_report(scenarios, units, label_width, config, hide_statistics), + extended_statistics_report(scenarios, units, label_width, config, hide_statistics) + ]) + end + + defp all_have_deviation_of_0?(scenarios) do + Enum.all?(scenarios, fn scenario -> + scenario.memory_usage_data.statistics.std_dev == 0.0 + end) + end + + defp column_descriptors(label_width, hide_statistics) + + defp column_descriptors(label_width, false) do + "\n~*s~*s~*s~*s~*s\n" + |> :io_lib.format([ + -label_width, + "Name", + @average_width, + "average", + @deviation_width, + "deviation", + @median_width, + "median", + @percentile_width, + "99th %" + ]) + |> to_string + end + + defp column_descriptors(label_width, true) do + "\n~*s~*s\n" + |> :io_lib.format([ + -label_width, + "Name", + @average_width, + "Memory usage" + ]) + |> to_string + end + + @spec scenario_reports([Scenario.t()], unit_per_statistic, integer, boolean) :: [String.t()] + defp scenario_reports(scenarios, units, label_width, hide_statistics) + + defp scenario_reports([scenario | other_scenarios], units, label_width, true) do + [ + reference_report(scenario, units, label_width), + comparisons(other_scenarios, units, label_width), + "\n**All measurements for memory usage were the same**\n" + ] + end + + defp scenario_reports(scenarios, units, label_width, hide_statistics) do + Enum.map(scenarios, fn scenario -> + format_scenario(scenario, units, label_width, hide_statistics) + end) + end + + @na "N/A" + + @spec format_scenario(Scenario.t(), unit_per_statistic, integer, boolean) :: String.t() + defp format_scenario(scenario, units, label_width, hide_statistics) + + defp format_scenario( + scenario = %Scenario{memory_usage_data: %{statistics: %{sample_size: 0}}}, + _, + label_width, + _ + ) do + warning = + "WARNING the scenario \"#{scenario.name}\" has no memory measurements!" <> + " This is probably a bug please report it!\n" <> + "https://github.com/bencheeorg/benchee/issues/new" + + data = + "~*ts~*ts\n" + |> :io_lib.format([ + -label_width, + scenario.name, + @average_width, + @na + ]) + |> to_string + + warning <> "\n" <> data + end + + defp format_scenario(scenario, %{memory: memory_unit}, label_width, false) do + %Scenario{ + name: name, + memory_usage_data: %{ + statistics: %Statistics{ + average: average, + std_dev_ratio: std_dev_ratio, + median: median, + percentiles: %{99 => percentile_99} + } + } + } = scenario + + "~*ts~*ts~*ts~*ts~*ts\n" + |> :io_lib.format([ + -label_width, + name, + @average_width, + memory_output(average, memory_unit), + @deviation_width, + Helpers.deviation_output(std_dev_ratio), + @median_width, + memory_output(median, memory_unit), + @percentile_width, + memory_output(percentile_99, memory_unit) + ]) + |> to_string + end + + defp format_scenario(scenario, %{memory: memory_unit}, label_width, true) do + %Scenario{ + name: name, + memory_usage_data: %{ + statistics: %Statistics{ + average: average + } + } + } = scenario + + "~*ts~*ts\n" + |> :io_lib.format([ + -label_width, + name, + @average_width, + memory_output(average, memory_unit) + ]) + |> to_string + end + + @spec comparison_report([Scenario.t()], unit_per_statistic, integer, map, boolean) :: [ + String.t() + ] + defp comparison_report(scenarios, units, label_width, config, hide_statistics) + + # No need for a comparison when only one benchmark was run + defp comparison_report([_scenario], _, _, _, _), do: [] + defp comparison_report(_, _, _, %{comparison: false}, _), do: [] + defp comparison_report(_, _, _, _, true), do: [] + + defp comparison_report([scenario | other_scenarios], units, label_width, _, _) do + [ + Helpers.descriptor("Comparison"), + reference_report(scenario, units, label_width) + | comparisons(other_scenarios, units, label_width) + ] + end + + defp reference_report(scenario, %{memory: memory_unit}, label_width) do + %Scenario{name: name, memory_usage_data: %{statistics: %Statistics{median: median}}} = + scenario + + "~*s~*s\n" + |> :io_lib.format([ + -label_width, + name, + @median_width, + memory_output(median, memory_unit) + ]) + |> to_string + end + + @spec comparisons([Scenario.t()], unit_per_statistic, integer) :: [String.t()] + defp comparisons(scenarios_to_compare, units, label_width) do + Enum.map( + scenarios_to_compare, + fn scenario -> + statistics = scenario.memory_usage_data.statistics + memory_format = memory_output(statistics.average, units.memory) + + Helpers.format_comparison( + scenario.name, + statistics, + memory_format, + "memory usage", + units.memory, + label_width, + @median_width + ) + end + ) + end + + defp memory_output(nil, _unit), do: "N/A" + + defp memory_output(memory, unit) do + Memory.format({Memory.scale(memory, unit), unit}) + end + + defp extended_statistics_report(scenarios, units, label_width, config, hide_statistics) + defp extended_statistics_report(_, _, _, _, true), do: [] + + defp extended_statistics_report(scenarios, units, label_width, %{extended_statistics: true}, _) do + [ + Helpers.descriptor("Extended statistics"), + extended_column_descriptors(label_width) + | extended_statistics(scenarios, units, label_width) + ] + end + + defp extended_statistics_report(_, _, _, _, _), do: [] + + defp extended_column_descriptors(label_width) do + "\n~*s~*s~*s~*s~*s\n" + |> :io_lib.format([ + -label_width, + "Name", + @minimum_width, + "minimum", + @maximum_width, + "maximum", + @sample_size_width, + "sample size", + @mode_width, + "mode" + ]) + |> to_string + end + + defp extended_statistics(scenarios, units, label_width) do + Enum.map(scenarios, fn scenario -> + format_scenario_extended(scenario, units, label_width) + end) + end + + defp format_scenario_extended(scenario, %{memory: memory_unit}, label_width) do + %Scenario{ + name: name, + memory_usage_data: %{ + statistics: %Statistics{ + minimum: minimum, + maximum: maximum, + sample_size: sample_size, + mode: mode + } + } + } = scenario + + "~*s~*ts~*ts~*ts~*ts\n" + |> :io_lib.format([ + -label_width, + name, + @minimum_width, + Helpers.count_output(minimum, memory_unit), + @maximum_width, + Helpers.count_output(maximum, memory_unit), + @sample_size_width, + Count.format(sample_size), + @mode_width, + Helpers.mode_out(mode, memory_unit) + ]) + |> to_string + end +end diff --git a/deps/benchee/lib/benchee/formatters/console/reductions.ex b/deps/benchee/lib/benchee/formatters/console/reductions.ex new file mode 100644 index 0000000000000000000000000000000000000000..bb941b6ec957fb71f6c6934f8c45b917e8b683e5 --- /dev/null +++ b/deps/benchee/lib/benchee/formatters/console/reductions.ex @@ -0,0 +1,318 @@ +defmodule Benchee.Formatters.Console.Reductions do + @moduledoc false + + alias Benchee.{ + Conversion, + Conversion.Count, + Conversion.Unit, + Formatters.Console.Helpers, + Scenario, + Statistics + } + + @type unit_per_statistic :: %{atom => Unit.t()} + + # Length of column header + @average_width 15 + @deviation_width 11 + @median_width 15 + @percentile_width 15 + @minimum_width 15 + @maximum_width 15 + @sample_size_width 15 + @mode_width 25 + + @doc """ + Formats the reductions statistics to a report suitable for output on the CLI. + """ + @spec format_scenarios([Scenario.t()], map) :: [String.t(), ...] + def format_scenarios(scenarios, config) do + if reductions_measurements_present?(scenarios) do + render(scenarios, config) + else + [] + end + end + + defp reductions_measurements_present?(scenarios) do + Enum.any?(scenarios, fn scenario -> + scenario.reductions_data.statistics.sample_size > 0 + end) + end + + defp render(scenarios, config) do + scaling_strategy = config.unit_scaling + units = Conversion.units(scenarios, scaling_strategy) + label_width = Helpers.label_width(scenarios) + hide_statistics = all_have_deviation_of_0?(scenarios) + + List.flatten([ + "\nReduction count statistics:\n", + column_descriptors(label_width, hide_statistics), + scenario_reports(scenarios, units, label_width, hide_statistics), + comparison_report(scenarios, units, label_width, config, hide_statistics), + extended_statistics_report(scenarios, units, label_width, config, hide_statistics) + ]) + end + + defp all_have_deviation_of_0?(scenarios) do + Enum.all?(scenarios, fn scenario -> + scenario.reductions_data.statistics.std_dev == 0.0 + end) + end + + defp column_descriptors(label_width, hide_statistics) + + defp column_descriptors(label_width, false) do + "\n~*s~*s~*s~*s~*s\n" + |> :io_lib.format([ + -label_width, + "Name", + @average_width, + "average", + @deviation_width, + "deviation", + @median_width, + "median", + @percentile_width, + "99th %" + ]) + |> to_string + end + + defp column_descriptors(label_width, true) do + "\n~*s~*s\n" + |> :io_lib.format([ + -label_width, + "Name", + @average_width, + "Reduction count" + ]) + |> to_string + end + + @spec scenario_reports([Scenario.t()], unit_per_statistic, integer, boolean) :: [String.t()] + defp scenario_reports(scenarios, units, label_width, hide_statistics) + + defp scenario_reports([scenario | other_scenarios], units, label_width, true) do + [ + reference_report(scenario, units, label_width), + comparisons(other_scenarios, units, label_width), + "\n**All measurements for reduction count were the same**\n" + ] + end + + defp scenario_reports(scenarios, units, label_width, hide_statistics) do + Enum.map(scenarios, fn scenario -> + format_scenario(scenario, units, label_width, hide_statistics) + end) + end + + @na "N/A" + + @spec format_scenario(Scenario.t(), unit_per_statistic, integer, boolean) :: String.t() + defp format_scenario(scenario, units, label_width, hide_statistics) + + defp format_scenario( + scenario = %Scenario{reductions_data: %{statistics: %{sample_size: 0}}}, + _, + label_width, + _ + ) do + warning = + "WARNING the scenario \"#{scenario.name}\" has no reduction count measurements!" <> + " This is probably a bug please report it!\n" <> + "https://github.com/bencheeorg/benchee/issues/new" + + data = + "~*ts~*ts\n" + |> :io_lib.format([ + -label_width, + scenario.name, + @average_width, + @na + ]) + |> to_string + + warning <> "\n" <> data + end + + defp format_scenario(scenario, %{reduction_count: reductions_unit}, label_width, false) do + %Scenario{ + name: name, + reductions_data: %{ + statistics: %Statistics{ + average: average, + std_dev_ratio: std_dev_ratio, + median: median, + percentiles: %{99 => percentile_99} + } + } + } = scenario + + "~*ts~*ts~*ts~*ts~*ts\n" + |> :io_lib.format([ + -label_width, + name, + @average_width, + Helpers.count_output(average, reductions_unit), + @deviation_width, + Helpers.deviation_output(std_dev_ratio), + @median_width, + Helpers.count_output(median, reductions_unit), + @percentile_width, + Helpers.count_output(percentile_99, reductions_unit) + ]) + |> to_string + end + + defp format_scenario(scenario, %{reduction_count: reductions_unit}, label_width, true) do + %Scenario{ + name: name, + reductions_data: %{ + statistics: %Statistics{ + average: average + } + } + } = scenario + + "~*ts~*ts\n" + |> :io_lib.format([ + -label_width, + name, + @average_width, + Helpers.count_output(average, reductions_unit) + ]) + |> to_string + end + + @spec comparison_report([Scenario.t()], unit_per_statistic, integer, map, boolean) :: [ + String.t() + ] + defp comparison_report(scenarios, units, label_width, config, hide_statistics) + + # No need for a comparison when only one benchmark was run + defp comparison_report([_scenario], _, _, _, _), do: [] + defp comparison_report(_, _, _, %{comparison: false}, _), do: [] + defp comparison_report(_, _, _, _, true), do: [] + + defp comparison_report([scenario | other_scenarios], units, label_width, _, _) do + [ + Helpers.descriptor("Comparison"), + reference_report(scenario, units, label_width) + | comparisons(other_scenarios, units, label_width) + ] + end + + defp reference_report(scenario, %{reduction_count: reductions_unit}, label_width) do + %Scenario{name: name, reductions_data: %{statistics: %Statistics{median: median}}} = scenario + + count = + if is_nil(median) do + @na + else + Helpers.count_output(median, reductions_unit) + end + + "~*s~*s\n" + |> :io_lib.format([ + -label_width, + name, + @median_width, + count + ]) + |> to_string + end + + @spec comparisons([Scenario.t()], unit_per_statistic, integer) :: [String.t()] + defp comparisons(scenarios_to_compare, units, label_width) do + Enum.map( + scenarios_to_compare, + fn scenario -> + statistics = scenario.reductions_data.statistics + + reductions_format = + if is_nil(statistics.average) do + @na + else + Helpers.count_output(statistics.average, units.reduction_count) + end + + Helpers.format_comparison( + scenario.name, + statistics, + reductions_format, + "reduction count", + units.reduction_count, + label_width, + @median_width + ) + end + ) + end + + defp extended_statistics_report(scenarios, units, label_width, config, hide_statistics) + defp extended_statistics_report(_, _, _, _, true), do: [] + + defp extended_statistics_report(scenarios, units, label_width, %{extended_statistics: true}, _) do + [ + Helpers.descriptor("Extended statistics"), + extended_column_descriptors(label_width) + | extended_statistics(scenarios, units, label_width) + ] + end + + defp extended_statistics_report(_, _, _, _, _), do: [] + + defp extended_column_descriptors(label_width) do + "\n~*s~*s~*s~*s~*s\n" + |> :io_lib.format([ + -label_width, + "Name", + @minimum_width, + "minimum", + @maximum_width, + "maximum", + @sample_size_width, + "sample size", + @mode_width, + "mode" + ]) + |> to_string + end + + defp extended_statistics(scenarios, units, label_width) do + Enum.map(scenarios, fn scenario -> + format_scenario_extended(scenario, units, label_width) + end) + end + + defp format_scenario_extended(scenario, %{reduction_count: reductions_unit}, label_width) do + %Scenario{ + name: name, + reductions_data: %{ + statistics: %Statistics{ + minimum: minimum, + maximum: maximum, + sample_size: sample_size, + mode: mode + } + } + } = scenario + + "~*s~*ts~*ts~*ts~*ts\n" + |> :io_lib.format([ + -label_width, + name, + @minimum_width, + Helpers.count_output(minimum, reductions_unit), + @maximum_width, + Helpers.count_output(maximum, reductions_unit), + @sample_size_width, + Count.format(sample_size), + @mode_width, + Helpers.mode_out(mode, reductions_unit) + ]) + |> to_string + end +end diff --git a/deps/benchee/lib/benchee/formatters/console/run_time.ex b/deps/benchee/lib/benchee/formatters/console/run_time.ex new file mode 100644 index 0000000000000000000000000000000000000000..8147b60abd82d923f9e55efa1421c5354066b9ff --- /dev/null +++ b/deps/benchee/lib/benchee/formatters/console/run_time.ex @@ -0,0 +1,296 @@ +defmodule Benchee.Formatters.Console.RunTime do + @moduledoc false + + # This deals with just the formatting of the run time results. They are similar + # to the way the memory results are formatted, but different enough to where the + # abstractions start to break down pretty significantly, so I wanted to extract + # these two things into separate modules to avoid confusion. + + alias Benchee.{ + Conversion, + Conversion.Count, + Conversion.Duration, + Conversion.Unit, + Formatters.Console.Helpers, + Scenario, + Statistics + } + + @type unit_per_statistic :: %{atom => Unit.t()} + + @ips_width 13 + @average_width 15 + @deviation_width 11 + @median_width 15 + @percentile_width 15 + @minimum_width 15 + @maximum_width 15 + @sample_size_width 15 + @mode_width 25 + + @doc """ + Formats the run time statistics to a report suitable for output on the CLI. + + ## Examples + + ``` + iex> memory_statistics = %Benchee.Statistics{average: 100.0} + ...> + ...> scenarios = [ + ...> %Benchee.Scenario{ + ...> name: "My Job", + ...> run_time_data: %Benchee.CollectionData{ + ...> statistics: %Benchee.Statistics{ + ...> average: 200.0, + ...> ips: 5000.0, + ...> std_dev_ratio: 0.1, + ...> median: 190.0, + ...> percentiles: %{99 => 300.1}, + ...> minimum: 100.1, + ...> maximum: 200.2, + ...> sample_size: 10_101, + ...> mode: 333.2 + ...> } + ...> }, + ...> memory_usage_data: %Benchee.CollectionData{statistics: memory_statistics} + ...> }, + ...> %Benchee.Scenario{ + ...> name: "Job 2", + ...> run_time_data: %Benchee.CollectionData{ + ...> statistics: %Benchee.Statistics{ + ...> average: 400.0, + ...> ips: 2500.0, + ...> std_dev_ratio: 0.2, + ...> median: 390.0, + ...> percentiles: %{99 => 500.1}, + ...> minimum: 200.2, + ...> maximum: 400.4, + ...> sample_size: 20_202, + ...> mode: [612.3, 554.1] + ...> } + ...> }, + ...> memory_usage_data: %Benchee.CollectionData{statistics: memory_statistics} + ...> } + ...> ] + ...> + ...> configuration = %{comparison: false, unit_scaling: :best, extended_statistics: true} + ...> format_scenarios(scenarios, configuration) + [ + "\nName ips average deviation median 99th %\n", + "My Job 5 K 200 ns ±10.00% 190 ns 300.10 ns\n", + "Job 2 2.50 K 400 ns ±20.00% 390 ns 500.10 ns\n", + "\nExtended statistics: \n", + "\nName minimum maximum sample size mode\n", + "My Job 100.10 ns 200.20 ns 10.10 K 333.20 ns\n", + "Job 2 200.20 ns 400.40 ns 20.20 K 612.30 ns, 554.10 ns\n" + ] + + ``` + + """ + @spec format_scenarios([Scenario.t()], map) :: [String.t(), ...] + def format_scenarios(scenarios, config) do + if run_time_measurements_present?(scenarios) do + render(scenarios, config) + else + [] + end + end + + defp run_time_measurements_present?(scenarios) do + Enum.any?(scenarios, fn scenario -> + scenario.run_time_data.statistics.sample_size > 0 + end) + end + + defp render(scenarios, config) do + %{unit_scaling: scaling_strategy} = config + units = Conversion.units(scenarios, scaling_strategy) + label_width = Helpers.label_width(scenarios) + + List.flatten([ + column_descriptors(label_width), + scenario_reports(scenarios, units, label_width), + comparison_report(scenarios, units, label_width, config), + extended_statistics_report(scenarios, units, label_width, config) + ]) + end + + @spec extended_statistics_report([Scenario.t()], unit_per_statistic, integer, map) :: [ + String.t() + ] + defp extended_statistics_report(scenarios, units, label_width, %{extended_statistics: true}) do + [ + Helpers.descriptor("Extended statistics"), + extended_column_descriptors(label_width) + | extended_statistics(scenarios, units, label_width) + ] + end + + defp extended_statistics_report(_, _, _, _) do + [] + end + + @spec extended_statistics([Scenario.t()], unit_per_statistic, integer) :: [String.t()] + defp extended_statistics(scenarios, units, label_width) do + Enum.map(scenarios, fn scenario -> + format_scenario_extended(scenario, units, label_width) + end) + end + + @spec format_scenario_extended(Scenario.t(), unit_per_statistic, integer) :: String.t() + defp format_scenario_extended(scenario, %{run_time: run_time_unit}, label_width) do + %Scenario{ + name: name, + run_time_data: %{ + statistics: %Statistics{ + minimum: minimum, + maximum: maximum, + sample_size: sample_size, + mode: mode + } + } + } = scenario + + "~*s~*ts~*ts~*ts~*ts\n" + |> :io_lib.format([ + -label_width, + name, + @minimum_width, + duration_output(minimum, run_time_unit), + @maximum_width, + duration_output(maximum, run_time_unit), + @sample_size_width, + Count.format(sample_size), + @mode_width, + Helpers.mode_out(mode, run_time_unit) + ]) + |> to_string + end + + @spec extended_column_descriptors(integer) :: String.t() + defp extended_column_descriptors(label_width) do + "\n~*s~*s~*s~*s~*s\n" + |> :io_lib.format([ + -label_width, + "Name", + @minimum_width, + "minimum", + @maximum_width, + "maximum", + @sample_size_width, + "sample size", + @mode_width, + "mode" + ]) + |> to_string + end + + @spec column_descriptors(integer) :: String.t() + defp column_descriptors(label_width) do + "\n~*s~*s~*s~*s~*s~*s\n" + |> :io_lib.format([ + -label_width, + "Name", + @ips_width, + "ips", + @average_width, + "average", + @deviation_width, + "deviation", + @median_width, + "median", + @percentile_width, + "99th %" + ]) + |> to_string + end + + @spec scenario_reports([Scenario.t()], unit_per_statistic, integer) :: [String.t()] + defp scenario_reports(scenarios, units, label_width) do + Enum.map(scenarios, fn scenario -> + format_scenario(scenario, units, label_width) + end) + end + + @spec format_scenario(Scenario.t(), unit_per_statistic, integer) :: String.t() + defp format_scenario(scenario, %{run_time: run_time_unit, ips: ips_unit}, label_width) do + %Scenario{ + name: name, + run_time_data: %{ + statistics: %Statistics{ + average: average, + ips: ips, + std_dev_ratio: std_dev_ratio, + median: median, + percentiles: %{99 => percentile_99} + } + } + } = scenario + + "~*s~*ts~*ts~*ts~*ts~*ts\n" + |> :io_lib.format([ + -label_width, + name, + @ips_width, + Helpers.count_output(ips, ips_unit), + @average_width, + duration_output(average, run_time_unit), + @deviation_width, + Helpers.deviation_output(std_dev_ratio), + @median_width, + duration_output(median, run_time_unit), + @percentile_width, + duration_output(percentile_99, run_time_unit) + ]) + |> to_string + end + + @spec comparison_report([Scenario.t()], unit_per_statistic, integer, map) :: [String.t()] + defp comparison_report(scenarios, units, label_width, config) + + # No need for a comparison when only one benchmark was run + defp comparison_report([_scenario], _, _, _), do: [] + defp comparison_report(_, _, _, %{comparison: false}), do: [] + + defp comparison_report([scenario | other_scenarios], units, label_width, _) do + [ + Helpers.descriptor("Comparison"), + reference_report(scenario, units, label_width) + | comparisons(other_scenarios, units, label_width) + ] + end + + defp reference_report(scenario, %{ips: ips_unit}, label_width) do + %Scenario{name: name, run_time_data: %{statistics: %Statistics{ips: ips}}} = scenario + + "~*s~*s\n" + |> :io_lib.format([-label_width, name, @ips_width, Helpers.count_output(ips, ips_unit)]) + |> to_string + end + + @spec comparisons([Scenario.t()], unit_per_statistic, integer) :: [String.t()] + defp comparisons(scenarios_to_compare, units, label_width) do + Enum.map( + scenarios_to_compare, + fn scenario -> + statistics = scenario.run_time_data.statistics + ips_format = Helpers.count_output(statistics.ips, units.ips) + + Helpers.format_comparison( + scenario.name, + statistics, + ips_format, + "slower", + units.run_time, + label_width, + @ips_width + ) + end + ) + end + + defp duration_output(duration, unit) do + Duration.format({Duration.scale(duration, unit), unit}) + end +end diff --git a/deps/benchee/lib/benchee/formatters/tagged_save.ex b/deps/benchee/lib/benchee/formatters/tagged_save.ex new file mode 100644 index 0000000000000000000000000000000000000000..10cec23f268b4dbcd8b8bd715e86271022d34c9e --- /dev/null +++ b/deps/benchee/lib/benchee/formatters/tagged_save.ex @@ -0,0 +1,90 @@ +defmodule Benchee.Formatters.TaggedSave do + @moduledoc """ + Store the whole suite in the Erlang `ExternalTermFormat` while tagging the + scenarios of the current run with a specified tag - can be used for storing + and later loading the results of previous runs with `Benchee.ScenarioLoader`. + + Automatically configured as the last formatter to run when specifying the + `save` option in the configuration - see `Benchee.Configuration`. + """ + + @behaviour Benchee.Formatter + + alias Benchee.Scenario + alias Benchee.Suite + alias Benchee.Utility.FileCreation + + @doc """ + Tags all scenario with the desired tag and returns it in term_to_binary along with save path. + """ + @impl true + @spec format(Suite.t(), map) :: {binary, String.t()} + def format(suite = %Suite{scenarios: scenarios}, formatter_config) do + tag = determine_tag(scenarios, formatter_config) + tagged_scenarios = tag_scenarios(scenarios, tag) + tagged_suite = %Suite{suite | scenarios: tagged_scenarios} + + {:erlang.term_to_binary(tagged_suite), formatter_config.path} + end + + defp determine_tag(scenarios, %{tag: desired_tag}) do + scenarios + |> Enum.map(fn scenario -> scenario.tag end) + |> Enum.uniq() + |> Enum.filter(fn tag -> + tag != nil && tag =~ ~r/#{Regex.escape(desired_tag)}/ + end) + |> choose_tag(desired_tag) + end + + defp choose_tag([], desired_tag), do: desired_tag + + defp choose_tag(tags, desired_tag) do + max = get_maximum_tag_increaser(tags, desired_tag) + "#{desired_tag}-#{max + 1}" + end + + defp get_maximum_tag_increaser(tags, desired_tag) do + tags + |> Enum.map(fn tag -> String.replace(tag, ~r/#{Regex.escape(desired_tag)}-?/, "") end) + |> Enum.map(&tag_increaser/1) + |> Enum.max() + end + + defp tag_increaser(""), do: 1 + defp tag_increaser(string_number), do: String.to_integer(string_number) + + defp tag_scenarios(scenarios, tag) do + Enum.map(scenarios, fn scenario -> + scenario + |> tagged_scenario(tag) + |> update_name + end) + end + + defp tagged_scenario(scenario = %Scenario{tag: nil}, desired_tag) do + %Scenario{scenario | tag: desired_tag} + end + + defp tagged_scenario(scenario, _desired_tag) do + scenario + end + + defp update_name(scenario = %Scenario{}) do + %Scenario{scenario | name: Scenario.display_name(scenario)} + end + + @doc """ + Writes the binary returned by `format/2` to the indicated location, telling you where that is. + """ + @spec write({binary, String.t()}, map) :: :ok + @impl true + def write({term_binary, filename}, _) do + FileCreation.ensure_directory_exists(filename) + return_value = File.write(filename, term_binary) + + IO.puts("Suite saved in external term format at #{filename}") + + return_value + end +end diff --git a/deps/benchee/lib/benchee/output/benchmark_printer.ex b/deps/benchee/lib/benchee/output/benchmark_printer.ex new file mode 100644 index 0000000000000000000000000000000000000000..2b24cac699b66874bbf89077b126d83565c2037f --- /dev/null +++ b/deps/benchee/lib/benchee/output/benchmark_printer.ex @@ -0,0 +1,140 @@ +defmodule Benchee.Output.BenchmarkPrinter do + @moduledoc false + + alias Benchee.Benchmark + alias Benchee.Conversion.Duration + alias Benchee.System + + @doc """ + Shown when you try benchmark an evaluated function. + + Compiled functions should be preferred as they are less likely to introduce additional overhead to your benchmark timing. + """ + def evaluated_function_warning(job_name) do + IO.puts(""" + Warning: the benchmark #{job_name} is using an evaluated function. + Evaluated functions perform slower than compiled functions. + You can move the Benchee caller to a function in a module and invoke `Mod.fun()` instead. + Alternatively, you can move the benchmark into a benchmark.exs file and run mix run benchmark.exs + """) + end + + @doc """ + Shown when you try to define a benchmark with the same name twice. + + How would you want to discern those anyhow? + """ + def duplicate_benchmark_warning(name) do + IO.puts( + "You already have a job defined with the name \"#{name}\", you can't add two jobs with the same name!" + ) + end + + @doc """ + Prints general information such as system information and estimated + benchmarking time. + """ + def configuration_information(%{configuration: %{print: %{configuration: false}}}) do + nil + end + + def configuration_information(%{scenarios: scenarios, system: sys, configuration: config}) do + system_information(sys) + suite_information(scenarios, config) + end + + defp system_information(%System{ + erlang: erlang_version, + elixir: elixir_version, + jit_enabled?: jit_enabled?, + os: os, + num_cores: num_cores, + cpu_speed: cpu_speed, + available_memory: available_memory + }) do + IO.puts(""" + Operating System: #{os} + CPU Information: #{cpu_speed} + Number of Available Cores: #{num_cores} + Available memory: #{available_memory} + Elixir #{elixir_version} + Erlang #{erlang_version} + JIT enabled: #{jit_enabled?} + """) + end + + defp suite_information(scenarios, %{ + parallel: parallel, + time: time, + warmup: warmup, + inputs: inputs, + memory_time: memory_time, + reduction_time: reduction_time, + exclude_outliers: exclude_outliers + }) do + scenario_count = length(scenarios) + exec_time = warmup + time + memory_time + reduction_time + total_time = scenario_count * exec_time + + IO.puts(""" + Benchmark suite executing with the following configuration: + warmup: #{Duration.format_human(warmup)} + time: #{Duration.format_human(time)} + memory time: #{Duration.format_human(memory_time)} + reduction time: #{Duration.format_human(reduction_time)} + parallel: #{parallel} + inputs: #{inputs_out(inputs)} + Estimated total run time: #{Duration.format_human(total_time)} + Excluding outliers: #{exclude_outliers} + """) + end + + defp inputs_out(nil), do: "none specified" + + defp inputs_out(inputs) do + Enum.map_join(inputs, ", ", fn {name, _} -> name end) + end + + @doc """ + Prints a notice which job is currently being benchmarked. + """ + def benchmarking(_, _, %{print: %{benchmarking: false}}), do: nil + + def benchmarking(name, input_name, config) do + time_configs = [config.time, config.warmup, config.memory_time, config.reduction_time] + + if Enum.all?(time_configs, fn time -> time == 0 end) do + nil + else + IO.puts("Benchmarking #{name}#{input_information(input_name)} ...") + end + end + + @no_input Benchmark.no_input() + defp input_information(@no_input), do: "" + defp input_information(input_name), do: " with input #{input_name}" + + @doc """ + Prints a warning about accuracy of benchmarks when the function is super fast. + """ + def fast_warning do + IO.puts(""" + Warning: The function you are trying to benchmark is super fast, making measurements more unreliable! + This holds especially true for memory measurements or when running with hooks. + + See: https://github.com/bencheeorg/benchee/wiki/Benchee-Warnings#fast-execution-warning + + You may disable this warning by passing print: [fast_warning: false] as configuration options. + """) + end + + @doc """ + Print the measured function call overhead. + """ + @spec function_call_overhead(non_neg_integer()) :: :ok + def function_call_overhead(overhead) do + scaled_overhead = Duration.scale(overhead) + + IO.puts("Measured function call overhead as: #{Duration.format(scaled_overhead)}") + end +end diff --git a/deps/benchee/lib/benchee/output/profile_printer.ex b/deps/benchee/lib/benchee/output/profile_printer.ex new file mode 100644 index 0000000000000000000000000000000000000000..038e3cd4f3db6644fe121763109252bb03eff664 --- /dev/null +++ b/deps/benchee/lib/benchee/output/profile_printer.ex @@ -0,0 +1,10 @@ +defmodule Benchee.Output.ProfilePrinter do + @moduledoc false + + @doc """ + Prints a notification of which job is being profiled. + """ + def profiling(name, profiler) do + IO.puts("\nProfiling #{name} with #{profiler}...") + end +end diff --git a/deps/benchee/lib/benchee/output/progress_printer.ex b/deps/benchee/lib/benchee/output/progress_printer.ex new file mode 100644 index 0000000000000000000000000000000000000000..8876795c41f820af50eb5a63ed96908a4fcce444 --- /dev/null +++ b/deps/benchee/lib/benchee/output/progress_printer.ex @@ -0,0 +1,15 @@ +defmodule Benchee.Output.ProgressPrinter do + @moduledoc false + + def calculating_statistics(%{print: %{benchmarking: false}}), do: nil + + def calculating_statistics(_config) do + IO.puts("Calculating statistics...") + end + + def formatting(%{print: %{benchmarking: false}}), do: nil + + def formatting(_config) do + IO.puts("Formatting results...") + end +end diff --git a/deps/benchee/lib/benchee/profile.ex b/deps/benchee/lib/benchee/profile.ex new file mode 100644 index 0000000000000000000000000000000000000000..a1c94162be3c66e327d8d4dbea92cbca29731125 --- /dev/null +++ b/deps/benchee/lib/benchee/profile.ex @@ -0,0 +1,133 @@ +defmodule Benchee.Profile do + @moduledoc """ + Profiles each scenario after benchmarking them if the `profile_after` option is either set to: + * `true`, + * a valid `profiler`, + * a tuple of a valid `profiler` and a list of options to pass to it, e.g., `{:fprof, [sort: :own]}`. + + The profiler that will be used is either the one set by the `profiler_after` option or, if set to `true`, + the default one (`:eprof`). It accepts however the following profilers: + * `:cprof` will profile with [`Mix.Task.Profile.Cprof`](https://hexdocs.pm/mix/Mix.Tasks.Profile.Cprof.html). + It provides information related to the number of function calls. + * `:eprof` will profile with [`Mix.Task.Profile.Eprof`](https://hexdocs.pm/mix/Mix.Tasks.Profile.Eprof.html). + It provides information related to the time spent on each function in regard to the total execution time. + * `:fprof` will profile with [`Mix.Task.Profile.Fprof`](https://hexdocs.pm/mix/Mix.Tasks.Profile.Cprof.html). + It provides information related to the time spent on each function, both the *total* time spent on it and the time spent on it, + *excluding* the time of called functions. + """ + + alias Benchee.Benchmark.BenchmarkConfig + alias Benchee.Benchmark.Runner + alias Benchee.Benchmark.ScenarioContext + alias Benchee.Output.ProfilePrinter, as: Printer + alias Benchee.Suite + + @default_profiler :eprof + @builtin_profilers [:cprof, :eprof, :fprof] + # https://hexdocs.pm/mix/1.17.0/Mix.Tasks.Profile.Tprof.html + # Tprof was introduced in elixir 1.17.0 and requires OTP 27 + # Elixir errors out fine, but our test kind of put their trust into `builtin_profilers` + # being runnable. + if Version.match?(System.version(), ">= 1.17.0") && + String.to_integer(System.otp_release()) >= 27 do + @builtin_profilers [:tprof | @builtin_profilers] + end + + # we run the function a bunch already, no need for further warmup + @default_profiler_opts [warmup: false] + + @doc """ + Returns the atom corresponding to the default profiler. + """ + @spec default_profiler() :: unquote(@default_profiler) + def default_profiler, do: @default_profiler + + @doc """ + List of supported builtin profilers as atoms. + """ + def builtin_profilers, do: @builtin_profilers + + @doc """ + Runs for each scenario found in the suite the `profile/2` function from the given profiler. + """ + @spec profile(Suite.t(), module) :: Suite.t() + def profile(suite, printer \\ Printer) + def profile(suite = %{configuration: %{profile_after: false}}, _printer), do: suite + + def profile( + suite = %{ + scenarios: scenarios, + configuration: config = %{profile_after: true} + }, + printer + ) do + do_profile(scenarios, {@default_profiler, @default_profiler_opts}, config, printer) + + suite + end + + def profile( + suite = %{ + scenarios: scenarios, + configuration: config = %{profile_after: {profiler, profiler_opts}} + }, + printer + ) do + profiler_opts = Keyword.merge(@default_profiler_opts, profiler_opts) + do_profile(scenarios, {profiler, profiler_opts}, config, printer) + + suite + end + + def profile( + suite = %{ + scenarios: scenarios, + configuration: config = %{profile_after: profiler} + }, + printer + ) do + do_profile(scenarios, {profiler, @default_profiler_opts}, config, printer) + + suite + end + + defp do_profile(scenarios, {profiler, profiler_opts}, config, printer) do + profiler_module = profiler_to_module(profiler) + + Enum.each(scenarios, fn scenario -> + run(scenario, {profiler, profiler_module, profiler_opts}, config, printer) + end) + end + + defp run( + scenario, + {profiler, profiler_module, profiler_opts}, + config, + printer + ) do + printer.profiling(scenario.name, profiler) + + profiler_module.profile( + fn -> + Runner.run_once(scenario, %ScenarioContext{config: BenchmarkConfig.from(config)}) + end, + profiler_opts + ) + end + + # If given a builtin profiler the function will return its proper module. + # In the case of an unknown profiler, it will raise an `UnknownProfilerError` exception. + defp profiler_to_module(profiler) do + if Enum.member?(@builtin_profilers, profiler) do + profiler = + profiler + |> Atom.to_string() + |> String.capitalize() + + Module.concat(Mix.Tasks.Profile, profiler) + else + raise Benchee.UnknownProfilerError, + message: "Got an unknown '#{inspect(profiler)}' built-in profiler." + end + end +end diff --git a/deps/benchee/lib/benchee/relative_statistics.ex b/deps/benchee/lib/benchee/relative_statistics.ex new file mode 100644 index 0000000000000000000000000000000000000000..c487ba43b42c3fe980c3200e54fa9f016381b8d2 --- /dev/null +++ b/deps/benchee/lib/benchee/relative_statistics.ex @@ -0,0 +1,101 @@ +defmodule Benchee.RelativeStatistics do + @moduledoc """ + Statistics that are relative from one scenario to another. + + Such as how much slower/faster something is or what the absolute difference is in the measured + values. + Is its own step because it has to be executed after scenarios have been loaded via + `Benchee.ScenarioLoader` to include them in the calculation, while `Benchee.Statistics` + has to happen before they are loaded to avoid recalculating their statistics. + """ + + alias Benchee.{Scenario, Statistics, Suite} + + @doc """ + Calculate the statistics of scenarios relative to each other and sorts scenarios. + + Such as `relative_more`, `relative_less` and `absolute_difference`, + see `t:Benchee.Statistics.t/0` for more. + + The sorting of scenarios is important so that they always have the same order in + all formatters. Scenarios are sorted first by run time average, then by memory average. + """ + @spec relative_statistics(Suite.t()) :: Suite.t() + def relative_statistics(suite = %Suite{}) do + %Suite{suite | scenarios: calculate_relative_statistics(suite.scenarios)} + end + + defp calculate_relative_statistics([]), do: [] + + defp calculate_relative_statistics(scenarios) do + scenarios + |> scenarios_by_input() + |> Enum.flat_map(fn scenarios_with_same_input -> + sorted_scenarios = sort(scenarios_with_same_input) + {reference, others} = split_reference_scenario(sorted_scenarios) + others_with_relative = statistics_relative_to(others, reference) + [reference | others_with_relative] + end) + end + + @spec sort([Scenario.t()]) :: [Scenario.t()] + defp sort(scenarios) do + Enum.sort_by(scenarios, fn scenario -> + {scenario.run_time_data.statistics.average, scenario.memory_usage_data.statistics.average, + scenario.reductions_data.statistics.average} + end) + end + + # we can't just group_by `input_name` because that'd lose the order of inputs which might + # be important + # Thanks past Tobi, I was just about to do that. - Tobi, 5 years later + defp scenarios_by_input(scenarios) do + original_input_order = scenarios |> Enum.map(& &1.input_name) |> Enum.uniq() + + grouped_scenarios = Enum.group_by(scenarios, & &1.input_name) + + Enum.map(original_input_order, fn input_name -> + Map.fetch!(grouped_scenarios, input_name) + end) + end + + # right now we take the first scenario as we sorted them and it is the fastest, + # whenever we implement #179 though this becomes more involved + defp split_reference_scenario(scenarios) do + [reference | others] = scenarios + {reference, others} + end + + defp statistics_relative_to(scenarios, reference) do + Enum.map(scenarios, fn scenario -> + scenario + |> update_in([Access.key!(:run_time_data), Access.key!(:statistics)], fn statistics -> + add_relative_statistics(statistics, reference.run_time_data.statistics) + end) + |> update_in([Access.key!(:memory_usage_data), Access.key!(:statistics)], fn statistics -> + add_relative_statistics(statistics, reference.memory_usage_data.statistics) + end) + |> update_in([Access.key!(:reductions_data), Access.key!(:statistics)], fn statistics -> + add_relative_statistics(statistics, reference.reductions_data.statistics) + end) + end) + end + + # we might not run time/memory --> we shouldn't crash then ;) + defp add_relative_statistics(statistics = %{average: nil}, _reference), do: statistics + defp add_relative_statistics(statistics, %{average: nil}), do: statistics + + defp add_relative_statistics(statistics = %Statistics{}, reference_statistics) do + %Statistics{ + statistics + | relative_more: zero_safe_division(statistics.average, reference_statistics.average), + relative_less: zero_safe_division(reference_statistics.average, statistics.average), + absolute_difference: statistics.average - reference_statistics.average + } + end + + defp zero_safe_division(+0.0, +0.0), do: 1.0 + defp zero_safe_division(_, 0), do: :infinity + defp zero_safe_division(_, +0.0), do: :infinity + defp zero_safe_division(a, b), do: a / b +end diff --git a/deps/benchee/lib/benchee/scenario.ex b/deps/benchee/lib/benchee/scenario.ex new file mode 100644 index 0000000000000000000000000000000000000000..bdd7337d68023ba21e4b2dda3e44ca1d71e8985b --- /dev/null +++ b/deps/benchee/lib/benchee/scenario.ex @@ -0,0 +1,213 @@ +defmodule Benchee.Scenario do + @moduledoc """ + Core data structure representing one particular case (combination of function and input). + + Represents the combination of a particular function to benchmark (also called "job" defined + by `job_name` and `function`) in combination with a specific input (`input_name` and `input`). + When no input is given, the combined value is representative of "no input". + + A scenario then further gathers all data collected for this particular combination during + `Benchee.Benchmark.collect/3`, which are then used later in the process by `Benchee.Statistics` + to compute the relevant statistics which are then also added to the scenario. + It is the home of the aggregated knowledge regarding this particular case/scenario. + + `name` is the name that should be used by formatters to display scenarios as + it potentially includes the `tag` present when loading scenarios that were + saved before. See `display_name/1`. + """ + + alias Benchee.Benchmark.Hooks + alias Benchee.CollectionData + + defstruct [ + :name, + :job_name, + :function, + :input_name, + :input, + :before_each, + :after_each, + :before_scenario, + :after_scenario, + :tag, + run_time_data: %CollectionData{}, + memory_usage_data: %CollectionData{}, + reductions_data: %CollectionData{} + ] + + @typedoc """ + The main function executed while benchmarking. + + No arguments if no inputs are used, one argument if inputs are used. + """ + @type benchmarking_function :: (-> any) | (any -> any) + + @typedoc """ + What shall be benchmarked, mostly a function but can contain options. + + Options are there for hooks (`after_each`, `before_each` etc.) + """ + @type to_benchmark :: benchmarking_function() | {benchmarking_function(), keyword()} + + @typedoc """ + All the data collected for a scenario (combination of function and input) + + Among all the data required to execute the scenario (function, input, all the hooks aka + after_*/before_*), data needed to display (name, job_name, input_name, tag) and of course + run_time_data and memory_data with all the samples and computed statistics. + """ + @type t :: %__MODULE__{ + name: String.t(), + job_name: String.t(), + function: benchmarking_function, + input_name: String.t() | Benchee.Benchmark.no_input(), + input: any | nil | Benchee.Benchmark.no_input(), + run_time_data: CollectionData.t(), + memory_usage_data: CollectionData.t(), + reductions_data: CollectionData.t(), + before_each: Hooks.hook_function() | nil, + after_each: Hooks.hook_function() | nil, + before_scenario: Hooks.hook_function() | nil, + after_scenario: Hooks.hook_function() | nil, + tag: String.t() | nil + } + + @doc """ + Returns the correct name to display of the given scenario data. + + In the normal case this is `job_name`, however when scenarios are loaded they + are tagged and these tags should be shown for disambiguation. + + ## Examples + + iex> display_name(%Benchee.Scenario{job_name: "flat_map"}) + "flat_map" + + iex> display_name(%Benchee.Scenario{job_name: "flat_map", tag: "main"}) + "flat_map (main)" + + iex> display_name(%{job_name: "flat_map"}) + "flat_map" + """ + @spec display_name(t) :: String.t() + def display_name(%{job_name: job_name, tag: nil}), do: job_name + def display_name(%{job_name: job_name, tag: tag}), do: "#{job_name} (#{tag})" + def display_name(%{job_name: job_name}), do: job_name + + @doc """ + Returns the different measurement types supported. + + + ## Examples + + iex> measurement_types() + [:run_time, :memory, :reductions] + """ + @spec measurement_types :: [:memory | :reductions | :run_time, ...] + def measurement_types, do: [:run_time, :memory, :reductions] + + @doc """ + Given the measurement type name given by `measurement_types/0`, get the associated data. + + Raises if no correct measurement type was specified. + + ## Examples + + iex> scenario = %Benchee.Scenario{ + ...> run_time_data: %Benchee.CollectionData{statistics: %Benchee.Statistics{sample_size: 1}} + ...> } + ...> + ...> measurement_data(scenario, :run_time) + %Benchee.CollectionData{statistics: %Benchee.Statistics{sample_size: 1}} + + iex> scenario = %Benchee.Scenario{ + ...> memory_usage_data: %Benchee.CollectionData{ + ...> statistics: %Benchee.Statistics{sample_size: 2} + ...> } + ...> } + ...> + ...> measurement_data(scenario, :memory) + %Benchee.CollectionData{statistics: %Benchee.Statistics{sample_size: 2}} + + iex> scenario = %Benchee.Scenario{ + ...> reductions_data: %Benchee.CollectionData{ + ...> statistics: %Benchee.Statistics{sample_size: 3} + ...> } + ...> } + ...> + ...> measurement_data(scenario, :reductions) + %Benchee.CollectionData{statistics: %Benchee.Statistics{sample_size: 3}} + + iex> measurement_data(%Benchee.Scenario{}, :memory) + %Benchee.CollectionData{} + """ + @spec measurement_data(t, :memory | :reductions | :run_time) :: CollectionData.t() + # Arguably this access is OO-ish/not great. However, with the incosistency we have in naming + # between the scenario struct fields and the measurement types this should be good/covnenient. + # Technically, we could/should move to a map structure from "measurement_type" to collection + # data but it's probably not worth breaking compatibility for right now. + def measurement_data(scenario, measurement_type) + def measurement_data(scenario, :run_time), do: scenario.run_time_data + def measurement_data(scenario, :memory), do: scenario.memory_usage_data + def measurement_data(scenario, :reductions), do: scenario.reductions_data + + @doc """ + Returns `true` if data of the provided type has been fully procsessed, `false` otherwise. + + Current available types are `run_time` and `memory`. Reasons they might not have been processed + yet are: + * Suite wasn't configured to collect them at all + * `Benchee.statistics/1` hasn't been called yet so that data was collected but statistics + aren't present yet + + ## Examples + + iex> scenario = %Benchee.Scenario{ + ...> run_time_data: %Benchee.CollectionData{ + ...> statistics: %Benchee.Statistics{sample_size: 100} + ...> } + ...> } + ...> + ...> data_processed?(scenario, :run_time) + true + + iex> scenario = %Benchee.Scenario{ + ...> memory_usage_data: %Benchee.CollectionData{ + ...> statistics: %Benchee.Statistics{sample_size: 1} + ...> } + ...> } + ...> + ...> data_processed?(scenario, :memory) + true + + iex> scenario = %Benchee.Scenario{ + ...> reductions_data: %Benchee.CollectionData{ + ...> statistics: %Benchee.Statistics{sample_size: 1} + ...> } + ...> } + ...> + ...> data_processed?(scenario, :reductions) + true + + iex> scenario = %Benchee.Scenario{ + ...> memory_usage_data: %Benchee.CollectionData{ + ...> statistics: %Benchee.Statistics{sample_size: 0} + ...> } + ...> } + ...> + ...> data_processed?(scenario, :memory) + false + """ + @spec data_processed?(t, :run_time | :memory) :: boolean + def data_processed?(scenario, :run_time) do + scenario.run_time_data.statistics.sample_size > 0 + end + + def data_processed?(scenario, :memory) do + scenario.memory_usage_data.statistics.sample_size > 0 + end + + def data_processed?(scenario, :reductions) do + scenario.reductions_data.statistics.sample_size > 0 + end +end diff --git a/deps/benchee/lib/benchee/scenario_loader.ex b/deps/benchee/lib/benchee/scenario_loader.ex new file mode 100644 index 0000000000000000000000000000000000000000..a040cfdf281cc5af99a1f8f69c8d01c5a04c9d94 --- /dev/null +++ b/deps/benchee/lib/benchee/scenario_loader.ex @@ -0,0 +1,40 @@ +defmodule Benchee.ScenarioLoader do + @moduledoc """ + Load scenarios that were saved using the saved option to be included. + + Usually this is done right before the formatters run (that's when it happens + in `Benchee.run/2`) as all measurements and statistics should be there. + However, if you want to recompute statistics or others you can load them at + any time. Just be aware that if you load them before `Benchee.collect/1` then + they'll be rerun and measurements overridden. + """ + + alias Benchee.Suite + + @doc """ + Load the file(s) specified as `load_path` and add the scenarios to the list of the + current scenarios in the suite. + """ + def load(suite = %Suite{configuration: %{load: load_path}, scenarios: scenarios}) do + loaded = load_scenarios(load_path) + %Suite{suite | scenarios: scenarios ++ loaded} + end + + defp load_scenarios(false), do: [] + defp load_scenarios(path) when is_binary(path), do: load_scenarios([path]) + + defp load_scenarios(paths) do + Enum.flat_map(paths, fn path_or_glob -> + Enum.flat_map(Path.wildcard(path_or_glob), &load_scenario/1) + end) + end + + defp load_scenario(path) do + loaded_suite = + path + |> File.read!() + |> :erlang.binary_to_term() + + loaded_suite.scenarios + end +end diff --git a/deps/benchee/lib/benchee/statistics.ex b/deps/benchee/lib/benchee/statistics.ex new file mode 100644 index 0000000000000000000000000000000000000000..7c6e8f700aed12bae542312b3280f40888545d53 --- /dev/null +++ b/deps/benchee/lib/benchee/statistics.ex @@ -0,0 +1,314 @@ +defmodule Benchee.Statistics do + @moduledoc """ + Statistics related functionality that is meant to take the raw benchmark data + and then compute statistics like the average and the standard deviation etc. + + See `statistics/1` for a breakdown of the included statistics. + """ + + alias Benchee.{CollectionData, Conversion.Duration, Scenario, Suite} + alias Benchee.Output.ProgressPrinter + + require Integer + + defstruct [ + :average, + :ips, + :std_dev, + :std_dev_ratio, + :std_dev_ips, + :median, + :percentiles, + :mode, + :minimum, + :maximum, + :relative_more, + :relative_less, + :absolute_difference, + :outliers, + :lower_outlier_bound, + :upper_outlier_bound, + sample_size: 0 + ] + + @typedoc """ + Careful with the mode, might be multiple values, one value or nothing.😱 + """ + @type mode :: [number] | number | nil + + @typedoc """ + All the statistics `statistics/1` computes from the samples. + + This used for run times, memory and reductions. Generally with these, + the lower the better (less run time, memory consumption or reductions). + + These values mostly correspond to their cousins in `Statistex`. + + Overview of all the statistics Benchee currently provides: + + * average - average of all the samples (the lower the better) + * ips - iterations per second, how often can the given function be + executed within one second, used only for run times (the higher the better) + * std_dev - standard deviation, how much results vary among the samples + (the higher the more the results vary) + * std_dev_ratio - standard deviation expressed as how much it is relative to + the average + * std_dev_ips - the absolute standard deviation of iterations per second + * median - when all measured times are sorted, this is the middle + value (or average of the two middle values when the number of times is + even). More stable than the average and somewhat more likely to be a + typical value you see. + * percentiles - a map of percentile ranks. These are the values below + which x% of the samples lie. For example, 99% of samples are less than + is a value for which 99% of the run times are less than it. + * mode - the samples that occur the most. Often one value, but + can be multiple values if they occur the same amount of times. If no value + occurs at least twice, this value will be `nil`. + * minimum - the smallest sample measured for the scenario + * maximum - the biggest sample measured for the scenario + * relative_more - relative to the reference (usually the fastest scenario) how much more + was the average of this scenario. E.g. for reference at 100, this scenario 200 then it + is 2.0. + * relative_less - relative to the reference (usually the fastest scenario) how much less + was the average of this scenario. E.g. for reference at 100, this scenario 200 then it + is 0.5. + * absolute_difference - relative to the reference (usually the fastest scenario) what is + the difference of the averages of the scenarios. e.g. for reference at 100, this + scenario 200 then it is 100. + * sample_size - the number of measurements/samples taken into account for calculating statistics + * outliers - if outlier exclusion was enabled, may include any samples of outliers that were found, empty list otherwise + * lower_outlier_bound - value below which values are considered an outlier + * upper_outlier_bound - value above which values are considered an outlier + """ + @type t :: %__MODULE__{ + average: float, + ips: float | nil, + std_dev: float, + std_dev_ratio: float, + std_dev_ips: float | nil, + median: number, + percentiles: %{number => float}, + mode: mode, + minimum: number, + maximum: number, + relative_more: float | nil | :infinity, + relative_less: float | nil | :infinity, + absolute_difference: float | nil, + outliers: [number], + lower_outlier_bound: number, + upper_outlier_bound: number, + sample_size: integer + } + + @typedoc """ + The samples a `Benchee.Collect` collected to compute statistics from. + """ + @type samples :: [number] + + @doc """ + Takes a suite with scenarios and their data samples, adds the statistics to the + scenarios. For an overview of what the statistics mean see `t:t/0`. + + Note that this will also sort the scenarios fastest to slowest to ensure a consistent order + of scenarios in all used formatters. + + ## Examples + + iex> scenarios = [ + ...> %Benchee.Scenario{ + ...> job_name: "My Job", + ...> run_time_data: %Benchee.CollectionData{ + ...> samples: [200, 400, 400, 400, 500, 500, 500, 700, 900] + ...> }, + ...> memory_usage_data: %Benchee.CollectionData{ + ...> samples: [200, 400, 400, 400, 500, 500, 500, 700, 900] + ...> }, + ...> input_name: "Input", + ...> input: "Input" + ...> } + ...> ] + ...> + ...> suite = %Benchee.Suite{scenarios: scenarios} + ...> statistics(suite, Benchee.Test.FakeProgressPrinter) + %Benchee.Suite{ + scenarios: [ + %Benchee.Scenario{ + job_name: "My Job", + input_name: "Input", + input: "Input", + run_time_data: %Benchee.CollectionData{ + samples: [200, 400, 400, 400, 500, 500, 500, 700, 900], + statistics: %Benchee.Statistics{ + average: 500.0, + ips: 2000_000.0, + std_dev: 200.0, + std_dev_ratio: 0.4, + std_dev_ips: 800_000.0, + median: 500.0, + percentiles: %{25 => 400.0, 50 => 500.0, 75 => 600.0, 99 => 900.0}, + mode: [500, 400], + minimum: 200, + maximum: 900, + sample_size: 9, + outliers: [], + lower_outlier_bound: 100.0, + upper_outlier_bound: 900.0 + } + }, + memory_usage_data: %Benchee.CollectionData{ + samples: [200, 400, 400, 400, 500, 500, 500, 700, 900], + statistics: %Benchee.Statistics{ + average: 500.0, + ips: nil, + std_dev: 200.0, + std_dev_ratio: 0.4, + std_dev_ips: nil, + median: 500.0, + percentiles: %{25 => 400.0, 50 => 500.0, 75 => 600.0, 99 => 900.0}, + mode: [500, 400], + minimum: 200, + maximum: 900, + sample_size: 9, + outliers: [], + lower_outlier_bound: 100.0, + upper_outlier_bound: 900.0 + } + } + } + ], + system: nil + } + + """ + @spec statistics(Suite.t()) :: Suite.t() + def statistics(suite, printer \\ ProgressPrinter) do + printer.calculating_statistics(suite.configuration) + + percentiles = suite.configuration.percentiles + exclude_outliers? = suite.configuration.exclude_outliers + + update_in(suite.scenarios, fn scenarios -> + scenario_statistics = + compute_statistics_in_parallel(scenarios, percentiles, exclude_outliers?) + + update_scenarios_with_statistics(scenarios, scenario_statistics) + end) + end + + defp compute_statistics_in_parallel(scenarios, percentiles, exclude_outliers?) do + scenarios + |> Enum.map(fn scenario -> + # we filter down the data here to avoid sending the input and benchmarking function to + # the other processes + # we send over all of the collection data as in the future (tm) we might want to already + # provide the sample size, which this gives us a way to do that and not touch this code + # again + {scenario.run_time_data, scenario.memory_usage_data, scenario.reductions_data} + end) + # async_stream as we might run a ton of scenarios depending on the benchmark + |> Task.async_stream( + fn scenario_collection_data -> + calculate_scenario_statistics(scenario_collection_data, percentiles, exclude_outliers?) + end, + timeout: :infinity, + ordered: true + ) + |> Enum.map(fn {:ok, stats} -> stats end) + end + + defp update_scenarios_with_statistics(scenarios, scenario_statistics) do + # we can zip them as they retained order + scenarios + |> Enum.zip(scenario_statistics) + |> Enum.map(fn {%Scenario{ + run_time_data: %CollectionData{}, + memory_usage_data: %CollectionData{}, + reductions_data: %CollectionData{} + } = scenario, {run_time_stats, memory_stats, reductions_stats}} -> + %Scenario{ + scenario + | run_time_data: %CollectionData{ + scenario.run_time_data + | statistics: run_time_stats + }, + memory_usage_data: %CollectionData{ + scenario.memory_usage_data + | statistics: memory_stats + }, + reductions_data: %CollectionData{ + scenario.reductions_data + | statistics: reductions_stats + } + } + end) + end + + defp calculate_scenario_statistics( + {run_time_data, memory_data, reductions_data}, + percentiles, + exclude_outliers? + ) do + run_time_stats = + run_time_data.samples + |> calculate_statistics(percentiles, exclude_outliers?) + |> add_ips + + memory_stats = calculate_statistics(memory_data.samples, percentiles, exclude_outliers?) + + reductions_stats = + calculate_statistics(reductions_data.samples, percentiles, exclude_outliers?) + + {run_time_stats, memory_stats, reductions_stats} + end + + defp calculate_statistics([], _, _) do + %__MODULE__{ + sample_size: 0 + } + end + + defp calculate_statistics(samples, percentiles, exclude_outliers?) do + samples + |> Statistex.statistics(percentiles: percentiles, exclude_outliers: exclude_outliers?) + |> convert_from_statistex + end + + # It might seem silly to maintain and map statistex to our own struct, + # but this gives benchee more control and makes it safer to upgrade and change. + # Also, we don't expose changes in statistex versions automatically to plugins. + # + # As an example right now it's being discussed in statistex to add an `m2` statistic that holds + # no value for benchee (as it's ony used to calculate variance). + # + # We also manually add `ips` related stats (see `add_ips/1`) so differences are sufficient. + defp convert_from_statistex(statistex_statistics) do + %__MODULE__{ + average: statistex_statistics.average, + std_dev: statistex_statistics.standard_deviation, + std_dev_ratio: statistex_statistics.standard_deviation_ratio, + median: statistex_statistics.median, + percentiles: statistex_statistics.percentiles, + mode: statistex_statistics.mode, + minimum: statistex_statistics.minimum, + maximum: statistex_statistics.maximum, + sample_size: statistex_statistics.sample_size, + outliers: statistex_statistics.outliers, + lower_outlier_bound: statistex_statistics.lower_outlier_bound, + upper_outlier_bound: statistex_statistics.upper_outlier_bound + } + end + + defp add_ips(statistics = %__MODULE__{sample_size: 0}), do: statistics + defp add_ips(statistics = %__MODULE__{average: +0.0}), do: statistics + + defp add_ips(statistics = %__MODULE__{}) do + ips = Duration.convert_value({1, :second}, :nanosecond) / statistics.average + standard_dev_ips = ips * statistics.std_dev_ratio + + %__MODULE__{ + statistics + | ips: ips, + std_dev_ips: standard_dev_ips + } + end +end diff --git a/deps/benchee/lib/benchee/suite.ex b/deps/benchee/lib/benchee/suite.ex new file mode 100644 index 0000000000000000000000000000000000000000..7e57c310a463872b682277393ac0e4128322af2b --- /dev/null +++ b/deps/benchee/lib/benchee/suite.ex @@ -0,0 +1,158 @@ +defmodule Benchee.Suite do + @moduledoc """ + Main Benchee data structure that aggregates the results from every step. + + Different layers of the benchmarking rely on different data being present + here. For instance for `Benchee.Statistics.statistics/1` to work the + `run_time_data` key of each scenario needs to be filled with the samples + collected by `Benchee.Benchmark.collect/1`. + + Formatters can then use the data to display all of the results and the + configuration. + """ + defstruct [ + :system, + configuration: %Benchee.Configuration{}, + scenarios: [] + ] + + @typedoc """ + Valid key for either input or benchmarking job names. + """ + @type key :: String.t() | atom + + @typedoc """ + The main suite consisting of the configuration data, information about the system and most + importantly a list of `t:Benchee.Scenario.t/0`. + """ + @type t :: %__MODULE__{ + configuration: Benchee.Configuration.t() | nil, + system: Benchee.System.t() | nil, + scenarios: [] | [Benchee.Scenario.t()] + } +end + +defimpl DeepMerge.Resolver, for: Benchee.Suite do + def resolve(original, override = %Benchee.Suite{}, resolver) do + cleaned_override = + override + |> Map.from_struct() + |> Enum.reject(fn {_key, value} -> is_nil(value) end) + |> Map.new() + + Map.merge(original, cleaned_override, resolver) + end + + def resolve(original, override, resolver) when is_map(override) do + Map.merge(original, override, resolver) + end +end + +if Code.ensure_loaded?(Table.Reader) do + defimpl Table.Reader, for: Benchee.Suite do + alias Benchee.Benchmark + alias Benchee.CollectionData + alias Benchee.Scenario + + def init(suite) do + measurements_processed = map_measurements_processed(suite) + columns = get_columns_from_suite(suite, measurements_processed) + {rows, count} = extract_rows_from_suite(suite, measurements_processed) + + {:rows, %{columns: columns, count: count}, rows} + end + + defp map_measurements_processed(suite) do + Enum.filter(Scenario.measurement_types(), fn type -> + Enum.any?(suite.scenarios, fn scenario -> Scenario.data_processed?(scenario, type) end) + end) + end + + @run_time_fields [ + "samples", + "ips", + "average", + "std_dev", + "median", + "minimum", + "maximum", + "mode", + "sample_size" + ] + + @non_run_time_fields List.delete(@run_time_fields, "ips") + + defp get_columns_from_suite(suite, measurements_processed) do + config_percentiles = suite.configuration.percentiles + + percentile_labels = + Enum.map(config_percentiles, fn percentile -> + "p_#{percentile}" + end) + + measurement_headers = + Enum.flat_map(measurements_processed, fn measurement_type -> + fields = fields_for(measurement_type) ++ percentile_labels + + Enum.map(fields, fn field -> "#{measurement_type}_#{field}" end) + end) + + ["job_name", "input_name"] ++ measurement_headers + end + + defp fields_for(:run_time), do: @run_time_fields + defp fields_for(_), do: @non_run_time_fields + + defp extract_rows_from_suite(suite, measurements_processed) do + config_percentiles = suite.configuration.percentiles + + Enum.map_reduce(suite.scenarios, 0, fn %Scenario{} = scenario, count -> + scenario_data = + Enum.flat_map(measurements_processed, fn measurement_type -> + scenario + |> Scenario.measurement_data(measurement_type) + |> get_stats_from_collection_data(measurement_type, config_percentiles) + end) + + no_input = Benchmark.no_input() + + input_name = + case scenario.input_name do + ^no_input -> "" + name -> name + end + + row = [scenario.name, input_name] ++ scenario_data + + {row, count + 1} + end) + end + + defp get_stats_from_collection_data( + %CollectionData{statistics: statistics, samples: samples}, + measurement_type, + percentiles + ) do + percentile_data = + Enum.map(percentiles, fn percentile -> statistics.percentiles[percentile] end) + + Enum.concat([ + [samples], + maybe_ips(statistics, measurement_type), + [ + statistics.average, + statistics.std_dev, + statistics.median, + statistics.minimum, + statistics.maximum, + statistics.mode, + statistics.sample_size + ], + percentile_data + ]) + end + + defp maybe_ips(statistics, :run_time), do: [statistics.ips] + defp maybe_ips(_, _not_run_time), do: [] + end +end diff --git a/deps/benchee/lib/benchee/system.ex b/deps/benchee/lib/benchee/system.ex new file mode 100644 index 0000000000000000000000000000000000000000..90f26619dea3500d88b28a9f1bd5c8e952dfb3a0 --- /dev/null +++ b/deps/benchee/lib/benchee/system.ex @@ -0,0 +1,295 @@ +defmodule Benchee.System do + @moduledoc """ + Provides information about the system the benchmarks are run on. + + Includes information such as elixir/erlang version, OS, CPU and memory. + + So far supports/should work for Linux, MacOS, FreeBSD, Solaris and Windows. + """ + + alias Benchee.Conversion.Memory + alias Benchee.Suite + alias Benchee.Utility.ErlangVersion + + @enforce_keys [ + :elixir, + :erlang, + :jit_enabled?, + :num_cores, + :os, + :available_memory, + :cpu_speed + ] + + defstruct [ + :elixir, + :erlang, + :jit_enabled?, + :num_cores, + :os, + :available_memory, + :cpu_speed + ] + + @type t :: %__MODULE__{ + elixir: String.t(), + erlang: String.t(), + jit_enabled?: boolean(), + num_cores: pos_integer(), + os: :macOS | :Windows | :FreeBSD | :Solaris | :Linux, + cpu_speed: String.t(), + available_memory: String.t() + } + + @doc """ + Adds system information to the suite (currently elixir and erlang versions). + """ + @spec system(Suite.t()) :: Suite.t() + def system(suite = %Suite{}) do + erlang_version = erlang() + + system_info = %__MODULE__{ + elixir: elixir(), + erlang: erlang_version, + jit_enabled?: jit_enabled?(erlang_version), + num_cores: num_cores(), + os: os(), + available_memory: available_memory(), + cpu_speed: cpu_speed() + } + + warn_about_performance_degrading_settings() + + %Suite{suite | system: system_info} + end + + defp erlang do + otp_release = :erlang.system_info(:otp_release) + file = Path.join([:code.root_dir(), "releases", otp_release, "OTP_VERSION"]) + + case File.read(file) do + {:ok, version} -> + String.trim(version) + + # Livebook seemingly doesn't have the file where we expect it to be: + # https://github.com/bencheeorg/benchee/issues/367 + {:error, reason} -> + IO.puts( + "Error trying to determine erlang version #{reason}, falling back to overall OTP version" + ) + + to_string(otp_release) + end + end + + defp elixir, do: System.version() + + @first_jit_version "24.0.0" + defp jit_enabled?(erlang_version) do + if ErlangVersion.includes_fixes_from?(erlang_version, @first_jit_version) do + :erlang.system_info(:emu_flavor) == :jit + else + false + end + end + + defp num_cores do + System.schedulers_online() + end + + defp os do + {_, name} = :os.type() + os(name) + end + + defp os(:darwin), do: :macOS + defp os(:nt), do: :Windows + defp os(:freebsd), do: :FreeBSD + defp os(:sunos), do: :Solaris + defp os(_), do: :Linux + + defp cpu_speed, do: cpu_speed(os()) + + defp cpu_speed(:Windows) do + parse_cpu_for(:Windows, system_cmd("WMIC", ["CPU", "GET", "NAME"])) + end + + defp cpu_speed(:macOS) do + parse_cpu_for(:macOS, system_cmd("sysctl", ["-n", "machdep.cpu.brand_string"])) + end + + defp cpu_speed(:FreeBSD) do + parse_cpu_for(:FreeBSD, system_cmd("sysctl", ["-n", "hw.model"])) + end + + defp cpu_speed(:Solaris) do + parse_cpu_for(:Solaris, system_cmd("kstat", ["-p", "cpu_info:0::brand"])) + end + + defp cpu_speed(:Linux) do + parse_cpu_for(:Linux, system_cmd("cat", ["/proc/cpuinfo"])) + end + + @doc false + def parse_cpu_for(_, "N/A"), do: "N/A" + + def parse_cpu_for(:Windows, raw_output) do + "Name" <> cpu_info = raw_output + String.trim(cpu_info) + end + + def parse_cpu_for(:macOS, raw_output), do: String.trim(raw_output) + + def parse_cpu_for(:FreeBSD, raw_output), do: String.trim(raw_output) + + def parse_cpu_for(:Solaris, raw_output) do + solaris_cpubrand_regex = ~r/^cpu_info:0:cpu_info0:brand\s+(.*)\s*$/i + match_info = Regex.run(solaris_cpubrand_regex, raw_output, capture: :all_but_first) + + case match_info do + [cpu_info] -> cpu_info + _ -> "Unrecognized processor" + end + end + + def parse_cpu_for(:Linux, raw_output) do + linux_cpuinfo_regex = ~r/model name.*:([\w \(\)\-\@\.]*)/i + match_info = Regex.run(linux_cpuinfo_regex, raw_output, capture: :all_but_first) + + case match_info do + [cpu_info] -> String.trim(cpu_info) + _ -> "Unrecognized processor" + end + end + + defp available_memory, do: available_memory(os()) + + defp available_memory(:Windows) do + parse_memory_for( + :Windows, + system_cmd("WMIC", ["COMPUTERSYSTEM", "GET", "TOTALPHYSICALMEMORY"]) + ) + end + + defp available_memory(:macOS) do + parse_memory_for(:macOS, system_cmd("sysctl", ["-n", "hw.memsize"])) + end + + defp available_memory(:FreeBSD) do + parse_memory_for(:FreeBSD, system_cmd("sysctl", ["-n", "hw.physmem"])) + end + + defp available_memory(:Solaris) do + parse_memory_for(:Solaris, system_cmd("prtconf", ["-m"])) + end + + defp available_memory(:Linux) do + parse_memory_for(:Linux, system_cmd("cat", ["/proc/meminfo"])) + end + + defp parse_memory_for(_, "N/A"), do: "N/A" + + defp parse_memory_for(:Windows, raw_output) do + [memory] = Regex.run(~r/\d+/, raw_output) + {memory, _} = Integer.parse(memory) + Memory.format(memory) + end + + defp parse_memory_for(:macOS, raw_output) do + {memory, _} = Integer.parse(raw_output) + Memory.format(memory) + end + + defp parse_memory_for(:FreeBSD, raw_output) do + {memory, _} = Integer.parse(raw_output) + Memory.format(memory) + end + + defp parse_memory_for(:Solaris, raw_output) do + {memory_in_megabytes, _} = Integer.parse(raw_output) + {memory_in_bytes, _} = Memory.convert({memory_in_megabytes, :megabyte}, :byte) + Memory.format(memory_in_bytes) + end + + defp parse_memory_for(:Linux, raw_output) do + ["MemTotal:" <> memory_info] = Regex.run(~r/MemTotal.*kB/, raw_output) + + {memory_in_kilobytes, _} = + memory_info + |> String.trim() + |> String.trim_trailing(" kB") + |> Integer.parse() + + {memory_in_bytes, _} = + Memory.convert( + {memory_in_kilobytes, :kilobyte}, + :byte + ) + + Memory.format(memory_in_bytes) + end + + @doc false + def system_cmd(cmd, args, system_func \\ &System.cmd/2) do + {output, exit_code} = + try do + system_func.(cmd, args) + rescue + e -> + message = Exception.format(:error, e, __STACKTRACE__) + + # this mimics an error return code from the command, + # which is the same behavior we want to have + {message, 1} + end + + if exit_code > 0 do + IO.puts("Something went wrong trying to get system information:") + IO.puts(output) + "N/A" + else + output + end + end + + defp warn_about_performance_degrading_settings do + if !all_protocols_consolidated?() do + IO.puts(""" + Not all of your protocols have been consolidated. In order to achieve the + best possible accuracy for benchmarks, please ensure protocol + consolidation is enabled in your benchmarking environment. + """) + end + end + + # just made public for easy testing purposes + @doc false + def all_protocols_consolidated?(lib_dir_fun \\ &:code.lib_dir/1) do + case lib_dir_fun.(:elixir) do + # do we get a good old erlang charlist? + path when is_list(path) -> + ebin_path = Path.join(path, "ebin") + + [ebin_path] + |> Protocol.extract_protocols() + |> Enum.all?(&Protocol.consolidated?/1) + + _error -> + IO.puts( + "Could not check if protocols are consolidated. Running as escript? Defaulting to they are consolidated." + ) + + true + end + end +end + +defimpl DeepMerge.Resolver, for: Benchee.System do + def resolve(original, override = %Benchee.System{}, resolver) do + Map.merge(original, override, resolver) + end + + def resolve(original, override, resolver) when is_map(override) do + Map.merge(original, override, resolver) + end +end diff --git a/deps/benchee/lib/benchee/utility/deep_convert.ex b/deps/benchee/lib/benchee/utility/deep_convert.ex new file mode 100644 index 0000000000000000000000000000000000000000..7905fca0bd7ef2570f334d0a762630abab747d24 --- /dev/null +++ b/deps/benchee/lib/benchee/utility/deep_convert.ex @@ -0,0 +1,51 @@ +defmodule Benchee.Utility.DeepConvert do + @moduledoc false + + @doc """ + Converts a deep keyword list to the corresponding deep map. + + Exclusions can be provided for key names whose value should not be converted. + + ## Examples + + iex> to_map(a: 1, b: 2) + %{a: 1, b: 2} + + iex> to_map(a: [b: 2], c: [d: 3, e: 4, e: 5]) + %{a: %{b: 2}, c: %{d: 3, e: 5}} + + iex> to_map(a: [b: 2], c: [1, 2, 3], d: []) + %{a: %{b: 2}, c: [1, 2, 3], d: []} + + iex> to_map(%{a: %{b: 2}, c: %{d: 3, e: 5}}) + %{a: %{b: 2}, c: %{d: 3, e: 5}} + + iex> to_map([]) + %{} + + iex> to_map([a: [b: [f: 5]]], [:a]) + %{a: [b: [f: 5]]} + + iex> to_map([a: [b: [f: 5]], c: [d: 3]], [:b]) + %{a: %{b: [f: 5]}, c: %{d: 3}} + """ + def to_map(structure, exclusions \\ []) + def to_map([], _exclusions), do: %{} + def to_map(structure, exclusions), do: do_to_map(structure, exclusions) + + defp do_to_map(kwlist = [{_key, _value} | _tail], exclusions) do + kwlist + |> Enum.map(fn tuple -> to_map_element(tuple, exclusions) end) + |> Map.new() + end + + defp do_to_map(no_list, _exclusions), do: no_list + + defp to_map_element({key, value}, exclusions) do + if Enum.member?(exclusions, key) do + {key, value} + else + {key, do_to_map(value, exclusions)} + end + end +end diff --git a/deps/benchee/lib/benchee/utility/erlang_version.ex b/deps/benchee/lib/benchee/utility/erlang_version.ex new file mode 100644 index 0000000000000000000000000000000000000000..f801537a3d6d257b4fbdd1ea9720a4d6d0115c24 --- /dev/null +++ b/deps/benchee/lib/benchee/utility/erlang_version.ex @@ -0,0 +1,134 @@ +defmodule Benchee.Utility.ErlangVersion do + @moduledoc false + + # Internal module to deal with erlang version parsing oddity + + @doc """ + Was the given version before the reference version? + + Used to check if a bugfix has already landed. + + Applies some manual massaging, as erlang likes to report versions number not compatible with + SemVer. If we can't parse the version, to minimize false positives, we assume it's newer. + + Only the `version_to_check` is treated loosely. `version_to_check` must be SemVer compatible, + as it is assumed to be provided by project maintainers. + + ## Examples + + iex> includes_fixes_from?("22.0.0", "22.0.0") + true + + iex> includes_fixes_from?("22.0.1", "22.0.0") + true + + iex> includes_fixes_from?("22.0.0", "22.0.1") + false + + iex> includes_fixes_from?("22.0.4", "22.0.5") + false + + iex> includes_fixes_from?("22.0.4", "22.0.4") + true + + iex> includes_fixes_from?("22.0.5", "22.0.4") + true + + iex> includes_fixes_from?("21.999.9999", "22.0.0") + false + + iex> includes_fixes_from?("23.0.0", "22.0.0") + true + + # weird longer version numbers work + iex> includes_fixes_from?("22.0.0.0", "22.0.0") + true + + iex> includes_fixes_from?("22.0.0.14", "22.0.0") + true + + iex> includes_fixes_from?("23.3.5.14", "22.0.0") + true + + iex> includes_fixes_from?("21.3.5.14", "22.0.0") + false + + # weird shorter version numbers work + iex> includes_fixes_from?("22.0", "22.0.0") + true + + iex> includes_fixes_from?("22.0", "22.0.1") + false + + iex> includes_fixes_from?("22.1", "22.0.0") + true + + iex> includes_fixes_from?("21.3", "22.0.0") + false + + # rc version numbers work + iex> includes_fixes_from?("22.0-rc3", "22.0.0") + false + iex> includes_fixes_from?("23.0-rc0", "22.0.0") + true + + # since we are falling back to general OTP versions now, test those as well + iex> includes_fixes_from?("21", "22.0.0") + false + iex> includes_fixes_from?("22", "22.0.0") + true + iex> includes_fixes_from?("23.0", "22.0.0") + true + + # completely broken versions are assumed to be good to avoid false positives + # as this is not a main functionality but code to potentially work around an older erlang + # bug. + iex> includes_fixes_from?("super erlang", "22.0.0") + true + iex> includes_fixes_from?("", "22.0.0") + true + """ + def includes_fixes_from?(version_to_check, reference_version) do + erlang_version = parse_erlang_version(version_to_check) + + case erlang_version do + {:ok, version} -> Version.compare(version, reference_version) != :lt + # we do not know which version this is, so don't trust it? + _ -> true + end + end + + # `Version` only supports full SemVer, Erlang loves version numbers like `22.3.4.24` or `22.0` + # which makes `Version` error out so we gotta manually alter them so that it's `22.3.4` + defp parse_erlang_version(erlang_version) do + last_version_segment = ~r/\.\d+$/ + + # dot count is a heuristic but it should work + dot_count = + erlang_version + |> String.graphemes() + |> Enum.count(&(&1 == ".")) + + version = + case dot_count do + 3 -> Regex.replace(last_version_segment, erlang_version, "") + 1 -> deal_with_major_minor(erlang_version) + 0 -> "#{erlang_version}.0.0" + _ -> erlang_version + end + + Version.parse(version) + end + + # Only major/minor seem to get the rc treatment + # but if it is major/minor/patch `Version` handles it correctly. + # For the 4 digit versions we don't really care right now/normally does not happen. + defp deal_with_major_minor(erlang_version) do + # -rc and other weird versions contain - + if String.contains?(erlang_version, "-") do + String.replace(erlang_version, "-", ".0-") + else + "#{erlang_version}.0" + end + end +end diff --git a/deps/benchee/lib/benchee/utility/file_creation.ex b/deps/benchee/lib/benchee/utility/file_creation.ex new file mode 100644 index 0000000000000000000000000000000000000000..144d98daeae6e6978af42c58ba74572b3bdc183e --- /dev/null +++ b/deps/benchee/lib/benchee/utility/file_creation.ex @@ -0,0 +1,155 @@ +defmodule Benchee.Utility.FileCreation do + @moduledoc """ + Methods to easily handle file creation used in plugins. + """ + + alias Benchee.Benchmark + + @doc """ + Open a file for write for all key/value pairs, interleaves the file name with + the key and calls the given function with file, content and filename. + + Uses `interleave/2` to get the base filename and + the given keys together to one nice file name, then creates these files and + calls the function with the file and the content from the given map so that + data can be written to the file. + + If a directory is specified, it creates the directory. + + Expects: + + * names_to_content - a map from input name to contents that should go into + the corresponding file + * filename - the base file name as desired by the user + * function - a function that is then called for every file with the associated + file content from the map, defaults to just writing the file content via + `IO.write/2` and printing where it put the file. + + ## Examples + + # Just writes the contents to a file + Benchee.Utility.FileCreation.each(%{"My Input" => "_awesome html content_"}, + "my.html", + fn(file, content) -> IO.write(file, content) end) + """ + @spec each(%{(String.t() | list(String.t())) => String.t()}, String.t(), fun()) :: :ok + def each(names_to_content, filename, function \\ &default_each/3) do + ensure_directory_exists(filename) + + Enum.each(names_to_content, fn {input_name, content} -> + input_filename = interleave(filename, input_name) + + File.open!(input_filename, [:write, :utf8], fn file -> + function.(file, content, input_filename) + end) + end) + end + + defp default_each(file, content, input_filename) do + :ok = IO.write(file, content) + IO.puts("Generated #{input_filename}") + end + + @doc """ + Make sure the directory for the given file name exists. + """ + def ensure_directory_exists(filename) do + directory = Path.dirname(filename) + File.mkdir_p!(directory) + end + + @doc """ + Gets file name/path, the input name and others together. + + Takes a list of values to interleave or just a single value. + Handles the special no_input key to do no work at all. + + ## Examples + + iex> interleave("abc.csv", "hello") + "abc_hello.csv" + + iex> interleave("abc.csv", "Big Input") + "abc_big_input.csv" + + iex> interleave("abc.csv", "String.length/1") + "abc_string_length_1.csv" + + iex> interleave("bench/abc.csv", "Big Input") + "bench/abc_big_input.csv" + + iex> interleave( + ...> "bench/abc.csv", + ...> ["Big Input"] + ...> ) + "bench/abc_big_input.csv" + + iex> interleave("abc.csv", []) + "abc.csv" + + iex> interleave( + ...> "bench/abc.csv", + ...> ["Big Input", "Comparison"] + ...> ) + "bench/abc_big_input_comparison.csv" + + iex> interleave( + ...> "bench/A B C.csv", + ...> ["Big Input", "Comparison"] + ...> ) + "bench/A B C_big_input_comparison.csv" + + iex> interleave( + ...> "bench/abc.csv", + ...> ["Big Input", "Comparison", "great Stuff"] + ...> ) + "bench/abc_big_input_comparison_great_stuff.csv" + + iex> marker = Benchee.Benchmark.no_input() + ...> interleave("abc.csv", marker) + "abc.csv" + iex> interleave("abc.csv", [marker]) + "abc.csv" + iex> interleave( + ...> "abc.csv", + ...> [marker, "Comparison"] + ...> ) + "abc_comparison.csv" + iex> interleave( + ...> "abc.csv", + ...> ["Something cool", marker, "Comparison"] + ...> ) + "abc_something_cool_comparison.csv" + """ + @spec interleave(String.t(), String.t() | list(String.t())) :: String.t() + def interleave(filename, names) when is_list(names) do + file_names = + names + |> Enum.map(&to_filename/1) + |> prepend(Path.rootname(filename)) + |> Enum.reject(fn string -> String.length(string) < 1 end) + |> Enum.join("_") + + file_names <> Path.extname(filename) + end + + def interleave(filename, name) do + interleave(filename, [name]) + end + + defp prepend(list, item) do + [item | list] + end + + defp to_filename(name_string) do + no_input = Benchmark.no_input() + + case name_string do + ^no_input -> + "" + + _ -> + String.downcase(String.replace(name_string, ~r/[^0-9A-Z]/i, "_")) + end + end +end diff --git a/deps/benchee/lib/benchee/utility/parallel.ex b/deps/benchee/lib/benchee/utility/parallel.ex new file mode 100644 index 0000000000000000000000000000000000000000..1f2c1b8dde4d6c4cd5dcb91f1b7abda97799d4be --- /dev/null +++ b/deps/benchee/lib/benchee/utility/parallel.ex @@ -0,0 +1,16 @@ +defmodule Benchee.Utility.Parallel do + @moduledoc false + + @doc """ + A utility function for mapping over an enumerable collection in parallel. + + Take note that this spawns a process for every element in the collection + which is only advisable if the function does some heavy lifting. + """ + @spec map(Enum.t(), fun) :: list + def map(collection, func) do + collection + |> Enum.map(fn element -> Task.async(fn -> func.(element) end) end) + |> Enum.map(&Task.await(&1, :infinity)) + end +end diff --git a/deps/benchee/lib/benchee/utility/repeat_n.ex b/deps/benchee/lib/benchee/utility/repeat_n.ex new file mode 100644 index 0000000000000000000000000000000000000000..15103ee0aa26ccf4c0ccd946256038e636cb4b3d --- /dev/null +++ b/deps/benchee/lib/benchee/utility/repeat_n.ex @@ -0,0 +1,19 @@ +defmodule Benchee.Utility.RepeatN do + @moduledoc false + + @doc """ + Calls the given function n times. + """ + def repeat_n(_function, 0) do + # noop + end + + def repeat_n(function, 1) do + function.() + end + + def repeat_n(function, count) do + function.() + repeat_n(function, count - 1) + end +end diff --git a/deps/benchee/mix.exs b/deps/benchee/mix.exs new file mode 100644 index 0000000000000000000000000000000000000000..f5d9fdd92ced9fee15b5d6ad17f7b4e0508446a5 --- /dev/null +++ b/deps/benchee/mix.exs @@ -0,0 +1,97 @@ +defmodule Benchee.Mixfile do + use Mix.Project + + @source_url "https://github.com/bencheeorg/benchee" + @version "1.5.0" + + def project do + [ + app: :benchee, + version: @version, + elixir: "~> 1.6", + elixirc_paths: elixirc_paths(Mix.env()), + consolidate_protocols: true, + build_embedded: Mix.env() == :prod, + start_permanent: Mix.env() == :prod, + deps: deps(), + docs: docs(), + package: package(), + test_coverage: [tool: ExCoveralls], + test_ignore_filters: [~r/test\/fixtures/], + dialyzer: [ + flags: [:underspecs], + plt_file: {:no_warn, "tools/plts/benchee.plt"}, + plt_add_apps: [:table] + ], + name: "Benchee", + description: """ + Versatile (micro) benchmarking that is extensible. Get statistics such as: + average, iterations per second, standard deviation and the median. + """ + ] + end + + def cli do + [ + preferred_envs: [ + coveralls: :test, + "coveralls.detail": :test, + "coveralls.post": :test, + "coveralls.html": :test, + "coveralls.travis": :test, + "safe_coveralls.travis": :test + ] + ] + end + + defp elixirc_paths(:test), do: ["lib", "test/support", "mix"] + defp elixirc_paths(_), do: ["lib"] + + defp deps do + deps = [ + {:deep_merge, "~> 1.0"}, + {:statistex, "~> 1.1"}, + {:ex_guard, "~> 1.3", only: :dev}, + {:credo, "~> 1.7.13", only: :dev, runtime: false}, + {:ex_doc, ">= 0.0.0", only: :dev, runtime: false}, + {:excoveralls, "~> 0.13", only: :test}, + {:dialyxir, "~> 1.0", only: :dev, runtime: false}, + {:doctest_formatter, "~> 0.2", only: :dev, runtime: false} + ] + + # table relies on __STACKTRACE__ which was introduced in 1.7, we still support ~>1.6 though + # as it's optional, this does not affect the function of Benchee + if Version.compare(System.version(), "1.7.0") == :gt do + [{:table, "~> 0.1.0", optional: true} | deps] + else + deps + end + end + + defp package do + [ + maintainers: ["Tobias Pfeiffer", "Devon Estes"], + licenses: ["MIT"], + links: %{ + "Changelog" => "https://hexdocs.pm/benchee/changelog.html", + "GitHub" => @source_url, + "Blog posts" => "https://pragtob.wordpress.com/tag/benchee/" + } + ] + end + + defp docs do + [ + extras: [ + "CHANGELOG.md": [], + "LICENSE.md": [title: "License"], + "README.md": [title: "Readme"] + ], + main: "readme", + source_url: @source_url, + source_ref: @version, + api_reference: false, + skip_undefined_reference_warnings_on: ["CHANGELOG.md"] + ] + end +end diff --git a/deps/bumblebee/.formatter.exs b/deps/bumblebee/.formatter.exs new file mode 100644 index 0000000000000000000000000000000000000000..e7f3f46f3a2e64ac2232ed7d98ad3a179743b98a --- /dev/null +++ b/deps/bumblebee/.formatter.exs @@ -0,0 +1,4 @@ +[ + import_deps: [:nx], + inputs: ["{mix,.formatter}.exs", "{config,lib,test,examples}/**/*.{ex,exs}"] +] diff --git a/deps/bumblebee/.hex b/deps/bumblebee/.hex new file mode 100644 index 0000000000000000000000000000000000000000..3cb95415e4fff93793ae7960c787ef9be4175a6c Binary files /dev/null and b/deps/bumblebee/.hex differ diff --git a/deps/bumblebee/CHANGELOG.md b/deps/bumblebee/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..f490a82d6a39fbfc8b25263fe99ff48865028cab --- /dev/null +++ b/deps/bumblebee/CHANGELOG.md @@ -0,0 +1,276 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v0.6.3](https://github.com/elixir-nx/bumblebee/tree/v0.6.3) (2025-07-14) + +### Added + +* Relaxed Nx dependency requirement to allow Nx 0.10 + +## [v0.6.2](https://github.com/elixir-nx/bumblebee/tree/v0.6.2) (2025-06-17) + +### Fixed + +* Fix padded batch items lengthening generation time ([#419](https://github.com/elixir-nx/bumblebee/pull/419)) + +## [v0.6.1](https://github.com/elixir-nx/bumblebee/tree/v0.6.1) (2025-06-12) + +### Added + +* Support for passing string pairs as input to text classification serving +* Support for partial rotary embedding for Phi3 + +### Changed + +* Updated Phoenix examples to use phoenix_playground ([#400](https://github.com/elixir-nx/bumblebee/pull/400)) + +### Fixed + +* Fixed NLLB model crashing on batched input +* Out-of-bound position ids with left padded generation input + +## [v0.6.0](https://github.com/elixir-nx/bumblebee/tree/v0.6.0) (2024-10-08) + +### Added + +* Notebook about Retrieval-Augmented Generation (RAG) ([#353](https://github.com/elixir-nx/bumblebee/pull/353)) +* Phi model ([#356](https://github.com/elixir-nx/bumblebee/pull/356)) +* Gemma model ([#358](https://github.com/elixir-nx/bumblebee/pull/358)) +* Support for input streaming in Whisper serving ([#361](https://github.com/elixir-nx/bumblebee/pull/361)) +* Stable Diffusion ControlNet model ([#359](https://github.com/elixir-nx/bumblebee/pull/359)) +* Support for multiple EOS tokens in text generation ([#368](https://github.com/elixir-nx/bumblebee/pull/368)) +* Phi-3 model ([#374](https://github.com/elixir-nx/bumblebee/pull/374)) +* Support for Llama 3 ([#387](https://github.com/elixir-nx/bumblebee/pull/387)) +* Support for CLS token pooling in text embedding ([#385](https://github.com/elixir-nx/bumblebee/pull/385)) +* Support for HTTP proxies ([#391](https://github.com/elixir-nx/bumblebee/pull/391)) +* M2M100 and NLLB models ([#392](https://github.com/elixir-nx/bumblebee/pull/392)) +* Multilingual translation serving (`Bumblebee.Text.translation/4`) ([#395](https://github.com/elixir-nx/bumblebee/pull/395)) +* Swin model ([#394](https://github.com/elixir-nx/bumblebee/pull/394)) + +### Changed + +* **(Breaking)** Renamed `:use_qkv_bias` spec option to `:use_attention_bias` in ViT, DeiT and DINOv2 +* **(Breaking)** Changed spec options for optional outputs (`:output_hidden_states`, `:output_attentions`) to global layer options ([#360](https://github.com/elixir-nx/bumblebee/pull/360)) +* Whisper serving to stream input using ffmpeg when given a file path ([#361](https://github.com/elixir-nx/bumblebee/pull/361)) +* **(Breaking)** Changed model params to use `%Axon.ModelState{}`, matching Axon v0.7.0 ([#375](https://github.com/elixir-nx/bumblebee/pull/375)) + +### Fixed + +* Token classification crashing when all tokens are special +* Batched text generation finishing too early +* Crash on empty list of entities when aggregating entities in token classification ([#386](https://github.com/elixir-nx/bumblebee/pull/386)) + +## [v0.5.3](https://github.com/elixir-nx/bumblebee/tree/v0.5.3) (2024-02-26) + +### Fixed + +* Loading generation config with nil attributes +* Generating with `:no_repeat_ngram_length` when using lower precision + +## [v0.5.2](https://github.com/elixir-nx/bumblebee/tree/v0.5.2) (2024-02-24) + +### Fixed + +* Fixed loading sharded parameters in the safetensors format + +## [v0.5.1](https://github.com/elixir-nx/bumblebee/tree/v0.5.1) (2024-02-23) + +### Fixed + +* Fixed loading Mistral configuration with attention window disabled + +## [v0.5.0](https://github.com/elixir-nx/bumblebee/tree/v0.5.0) (2024-02-23) + +This release changes the directory structure of the models cache, such that cached files from the same HuggingFace Hub repository are grouped in a separate subdirectory. This change is meant to simplify the process of manually removing specific models from the cache to free up space. As a result, the cache contents from prior versions are invalidated, so you most likely want to remove the current cache contents. To find the cache location run `elixir -e 'Mix.install([{:bumblebee, "0.4.2"}]); IO.puts(Bumblebee.cache_dir())'` (defaults to the standard cache location for the given operating system). + +We also reduced memory usage during parameter loading (both when loading onto the CPU and GPU directly). Previously, larger models sometimes required loading parameters using CPU and only then transfering to the GPU, in order to avoid running out of GPU memory during parameter transformations. With this release this should no longer be the case. Loading parameters now has barely any memory footprint other than the parameters themselves. + +### Added + +* Notebook on LLaMA 2 to the docs ([#259](https://github.com/elixir-nx/bumblebee/pull/259)) +* Mistral model ([#264](https://github.com/elixir-nx/bumblebee/pull/264)) +* Projection head models for ClipText and ClipVision ([#276](https://github.com/elixir-nx/bumblebee/pull/276)) +* Support more rotary embedding options for LLaMA required for Deepseek Coder ([#285](https://github.com/elixir-nx/bumblebee/pull/285)) +* Temperature generation option ([#290](https://github.com/elixir-nx/bumblebee/pull/290)) +* GPTBigCode model (used by Starcoder) ([#294](https://github.com/elixir-nx/bumblebee/pull/294)) +* Automatic detection of diffusers params files (specifying `:params_filename` for Stable Diffusion models is no longer necessary) ([#301](https://github.com/elixir-nx/bumblebee/pull/301)) +* `:seed` option to generation serving inputs ([#303](https://github.com/elixir-nx/bumblebee/pull/303)) +* `:params_variant` option to `Bumblebee.load_model/2` for loading parameters of different precision ([#309](https://github.com/elixir-nx/bumblebee/pull/309)) +* `:type` option to `Bumblebee.load_model/2` for loading model under a specific precision policy ([#311](https://github.com/elixir-nx/bumblebee/pull/311)) +* LCM scheduler ([#320](https://github.com/elixir-nx/bumblebee/pull/320)) +* Token summary to text generation output ([#336](https://github.com/elixir-nx/bumblebee/pull/336)) +* DINOv2 model ([#334](https://github.com/elixir-nx/bumblebee/pull/334)) +* `:spec_overrides` option to `Bumblebee.load_model/2` ([#340](https://github.com/elixir-nx/bumblebee/pull/340)) +* Support for attention sliding window in Mistral ([#341](https://github.com/elixir-nx/bumblebee/pull/341)) + +### Changed + +* **(Breaking)** Text generation to always return only the new text (for some models it used to include the prompt) ([#302](https://github.com/elixir-nx/bumblebee/pull/302)) +* Deprecated all options in `Bumblebee.apply_tokenizer/3`, these should now be set on the tokenizer using `Bumblebee.configure/2` ([#310](https://github.com/elixir-nx/bumblebee/pull/310)) +* Reduced memory used when the `:preallocate_params` serving option is enabled ([#317](https://github.com/elixir-nx/bumblebee/pull/317)) +* **(Breaking)** Changed image size to maps in image featurizers ([#329](https://github.com/elixir-nx/bumblebee/pull/329)) +* **(Breaking)** Renamed ViT and DeiT `:for_masked_image_modeling` output from `:logits` to `:pixel_values` +* **(Breaking)** Renamed CLIP outputs `:text_embeddings` and `:image_embeddings` to singular +* **(Breaking)** Changed ResNet `:pooled_state` output to flatten the extra 1-sized axes +* Cache directory structure to group files by repository ([#332](https://github.com/elixir-nx/bumblebee/pull/332)) +* **(Breaking)** Changed the output of `Bumblebee.Text.Generation.build_generate/4` to a map ([#336](https://github.com/elixir-nx/bumblebee/pull/336)) +* Reduced memory usage during parameter loading ([#344](https://github.com/elixir-nx/bumblebee/pull/344)) + +### Removed + +* Removed the serving `:seed` option in favour of a runtime, per-input seed ([#303](https://github.com/elixir-nx/bumblebee/pull/303)) +* Conversational serving ([#308](https://github.com/elixir-nx/bumblebee/pull/308)) +* Specific tokenizer modules in favour of a single module ([#310](https://github.com/elixir-nx/bumblebee/pull/310)) +* Removed the deprecated `Bumblebee.Audio.speech_to_text/5` (in favour of the more specific `speech_to_text_whisper/5`) + +### Fixed + +* Featurizer batch template when image size is a tuple +* Error in concatenating results when running servings as partitioned ([#282](https://github.com/elixir-nx/bumblebee/pull/282)) +* Decoder cache being casted with low precision policies ([#299](https://github.com/elixir-nx/bumblebee/pull/299)) +* Loading of more recent VAE KL checkpoints ([#305](https://github.com/elixir-nx/bumblebee/pull/305)) +* Tokenizers truncation to account for trailing special tokens ([#307](https://github.com/elixir-nx/bumblebee/pull/307)) +* Loading models with auth token from within a HuggingFace Space ([#314](https://github.com/elixir-nx/bumblebee/pull/314)) +* Zero-shot classification serving to handle uppercased entailment token in model config ([#327](https://github.com/elixir-nx/bumblebee/pull/327)) +* Fixed text generation when using lower precision and encoder-decoder models (such as Whisper) ([#346](https://github.com/elixir-nx/bumblebee/pull/346)) + +## [v0.4.2](https://github.com/elixir-nx/bumblebee/tree/v0.4.2) (2023-09-28) + +### Added + +* More detailed error messages when loading fails ([#256](https://github.com/elixir-nx/bumblebee/pull/256)) + +### Changed + +* Automatic detection there are no model parameters in the `.bin` format, but `.safetensors` is available ([#256](https://github.com/elixir-nx/bumblebee/pull/256)) + +## [v0.4.1](https://github.com/elixir-nx/bumblebee/tree/v0.4.1) (2023-09-25) + +### Changed + +* Aligned batch handling for serving run and batched run ([#252](https://github.com/elixir-nx/bumblebee/pull/252)) + +### Fixed + +* Fixed `:top_k` upper bound in classification servings + +## [v0.4.0](https://github.com/elixir-nx/bumblebee/tree/v0.4.0) (2023-09-14) + +### Added + +* Chunking options to speech-to-text to support long audio transcription ([#236](https://github.com/elixir-nx/bumblebee/pull/236)) +* Support for Whisper timestamps and task/language configuration ([#238](https://github.com/elixir-nx/bumblebee/pull/238)) +* Support for streaming speech-to-text results ([#242](https://github.com/elixir-nx/bumblebee/pull/242)) +* Introduced featurizer batch phase that is compiled as part of the serving computation ([#243](https://github.com/elixir-nx/bumblebee/pull/243)) +* Removed possibly contentious Nx calls from serving postprocessing ([#244](https://github.com/elixir-nx/bumblebee/pull/244), [#245](https://github.com/elixir-nx/bumblebee/pull/245)) + +### Changed + +* Deprecated `Bumblebee.Audio.speech_to_text/5` in favour of the more specific `Bumblebee.Audio.speech_to_text_whisper/5` +* Changed the tensors returned from embedding servings to use `Nx.BinaryBackend` + +## [v0.3.1](https://github.com/elixir-nx/bumblebee/tree/v0.3.1) (2023-08-17) + +### Added + +* LLaMA model ([#199](https://github.com/elixir-nx/bumblebee/pull/199)) +* GPT-NeoX model ([#204](https://github.com/elixir-nx/bumblebee/pull/204)) +* Option to customize scores function in classification tasks ([#211](https://github.com/elixir-nx/bumblebee/pull/211)) +* Text embedding serving ([#214](https://github.com/elixir-nx/bumblebee/pull/214)) +* `Bumblebee.cache_dir/0` for discovering cache location ([#220](https://github.com/elixir-nx/bumblebee/pull/220)) +* Image embedding serving ([#229](https://github.com/elixir-nx/bumblebee/pull/229)) +* Support for compiling text servings for multiple sequence lengths ([#228](https://github.com/elixir-nx/bumblebee/pull/228)) +* Support for streaming chunks during text generation ([#232](https://github.com/elixir-nx/bumblebee/pull/232)) +* Added `:preallocate_params` option to all servings, useful with multiple GPUs ([#233](https://github.com/elixir-nx/bumblebee/pull/233)) +* Support for loading params in the .safetensors format ([#231](https://github.com/elixir-nx/bumblebee/pull/231)) + +## [v0.3.0](https://github.com/elixir-nx/bumblebee/tree/v0.3.0) (2023-04-14) + +In this release we moved all generation options to a new `%Bumblebee.Text.GenerationConfig{}` struct, which needs to be explicitly loaded and configured. A number of generation options is model-specific and they used to be a part of model specification, but encapsulating everything in a single struct improves the transparency of options origin and reconfiguration. The text generation servings (generation, speech-to-text and conversation) need to be adjusted as follows: + +```diff +{:ok, model_info} = Bumblebee.load_model({:hf, "openai-community/gpt2"}) +{:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "openai-community/gpt2"}) ++{:ok, generation_config} = Bumblebee.load_generation_config({:hf, "openai-community/gpt2"}) + ++generation_config = Bumblebee.configure(generation_config, max_new_tokens: 100) ++serving = Bumblebee.Text.generation(model_info, tokenizer, generation_config) +-serving = Bumblebee.Text.generation(model_info, tokenizer, max_new_tokens: 100) +``` + +### Added + +* Word-based aggregations for token classification ([#174](https://github.com/elixir-nx/bumblebee/pull/174)) +* BLIP model ([#181](https://github.com/elixir-nx/bumblebee/pull/181)) +* Text-to-image serving ([#181](https://github.com/elixir-nx/bumblebee/pull/181)) +* Generation option to avoid repeated n-grams ([#182](https://github.com/elixir-nx/bumblebee/pull/182)) +* Blenderbot model ([#177](https://github.com/elixir-nx/bumblebee/pull/177)) +* Option to load models from cache without outgoing traffic ([#183](https://github.com/elixir-nx/bumblebee/pull/183)) +* Whisper Phoenix demo ([#184](https://github.com/elixir-nx/bumblebee/pull/184)) +* Image channels normalization in featurizers ([#189](https://github.com/elixir-nx/bumblebee/pull/189)) +* T5 encoder model ([#190](https://github.com/elixir-nx/bumblebee/pull/190)) +* Contrastive search for sequence generation ([#192](https://github.com/elixir-nx/bumblebee/pull/192)) +* Multinomial sampling for sequence generation ([#161](https://github.com/elixir-nx/bumblebee/pull/161)) +* Support for loading sharded params checkpoints ([#200](https://github.com/elixir-nx/bumblebee/pull/200)) + +### Changed + +* Model loading to not log params diff if everything is loaded correctly ([#186](https://github.com/elixir-nx/bumblebee/pull/186)) +* Moved all generation options to a new `%Bumblebee.Text.GenerationConfig{}` struct ([#193](https://github.com/elixir-nx/bumblebee/pull/193)) + +## [v0.2.0](https://github.com/elixir-nx/bumblebee/tree/v0.2.0) (2023-03-16) + +### Added + +* Support for Stable Diffusion v2 ([#117](https://github.com/elixir-nx/bumblebee/pull/117)) +* CamemBERT model ([#110](https://github.com/elixir-nx/bumblebee/pull/110)) +* XLM-RoBERTa model ([#136](https://github.com/elixir-nx/bumblebee/pull/136)) +* Support for configuring backend used by `load_model` ([#140](https://github.com/elixir-nx/bumblebee/pull/140)) +* Zero-shot classification serving ([#121](https://github.com/elixir-nx/bumblebee/pull/121), [#145](https://github.com/elixir-nx/bumblebee/pull/145)) +* Support parameter files using Zip64 ([#144](https://github.com/elixir-nx/bumblebee/pull/144)) +* Notebook exemplifying fine-tuning with Axon ([#102](https://github.com/elixir-nx/bumblebee/pull/102)) +* Whisper model ([#107](https://github.com/elixir-nx/bumblebee/pull/107)) +* Speech-to-text serving ([#107](https://github.com/elixir-nx/bumblebee/pull/107)) +* Support for loading tokenizers with overridden special tokens ([#141](https://github.com/elixir-nx/bumblebee/pull/141)) +* Question answering serving ([#157](https://github.com/elixir-nx/bumblebee/pull/157)) +* T5 model ([#159](https://github.com/elixir-nx/bumblebee/pull/159)) +* Conversational serving ([#165](https://github.com/elixir-nx/bumblebee/pull/165)) +* DistilBERT model ([#172](https://github.com/elixir-nx/bumblebee/pull/172)) + +### Changed + +* Cancel download request when the caller terminates ([#135](https://github.com/elixir-nx/bumblebee/pull/135)) +* Introduced explicit parameter mapping, which changed parameter names in all models ([#148](https://github.com/elixir-nx/bumblebee/pull/148)) + +### Fixed + +* Initialization of parameters with mismatched shape + +## [v0.1.2](https://github.com/elixir-nx/bumblebee/tree/v0.1.2) (2022-12-15) + +### Fixed + +* Stable Diffusion to accept a string as the input ([#115](https://github.com/elixir-nx/bumblebee/pull/115)) + +## [v0.1.1](https://github.com/elixir-nx/bumblebee/tree/v0.1.1) (2022-12-14) + +### Added + +* Support for a negative prompt in Stable Diffusion input ([#109](https://github.com/elixir-nx/bumblebee/pull/109)) + +### Changed + +* Improved fill-mask output token to not include whitespace or whitespace placeholder ([#106](https://github.com/elixir-nx/bumblebee/pull/106)) + +### Fixed + +* Image rendering in the Stable Diffusion notebook ([#95](https://github.com/elixir-nx/bumblebee/pull/95)) +* Download error when the tmp and cache directories are on different file systems ([#98](https://github.com/elixir-nx/bumblebee/pull/98)) + +## [v0.1.0](https://github.com/elixir-nx/bumblebee/tree/v0.1.0) (2022-12-07) + +Initial release. diff --git a/deps/bumblebee/LICENSE b/deps/bumblebee/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f433b1a53f5b830a205fd2df78e2b34974656c7b --- /dev/null +++ b/deps/bumblebee/LICENSE @@ -0,0 +1,177 @@ + + 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 diff --git a/deps/bumblebee/README.md b/deps/bumblebee/README.md new file mode 100644 index 0000000000000000000000000000000000000000..01640c497d156ab1a9592bcf2d748f7898a4681a --- /dev/null +++ b/deps/bumblebee/README.md @@ -0,0 +1,146 @@ +# Bumblebee + +[![Docs](https://img.shields.io/badge/hex.pm-docs-8e7ce6.svg)](https://hexdocs.pm/bumblebee) +[![Actions Status](https://github.com/livebook-dev/kino_bumblebee/workflows/Test/badge.svg)](https://github.com/elixir-nx/bumblebee/actions) + +Bumblebee provides pre-trained Neural Network models on top of [Axon](https://github.com/elixir-nx/axon). It includes integration with [🤗 Models](https://huggingface.co/models), allowing anyone to download and perform Machine Learning tasks with few lines of code. + +![Numbat and Bumblebees](.github/images/background.jpg) + +## Getting started + +The best way to get started with Bumblebee is with [Livebook](https://livebook.dev). [Our announcement video](https://news.livebook.dev/announcing-bumblebee-gpt2-stable-diffusion-and-more-in-elixir-3Op73O) shows how to use Livebook's Smart Cells to perform different Neural Network tasks with few clicks. You can then tweak the code and deploy it. + +![](.github/images/kino_bumblebee_token_classification.png) + +We also provide single-file examples of running Neural Networks inside your Phoenix (+ LiveView) apps inside the [examples/phoenix](examples/phoenix) folder. + +![](.github/images/phx_image_classification.png) + +You may also check [our official docs](https://hexdocs.pm/bumblebee), which includes notebooks and our API reference. The "Tasks" section in the sidebar covers high-level APIs for using Bumblebee. The remaining modules in the sidebar lists all supported architectures. + +## Installation + +First add Bumblebee and EXLA as dependencies in your `mix.exs`. EXLA is an optional dependency but an important one as it allows you to compile models just-in-time and run them on CPU/GPU: + +```elixir +def deps do + [ + {:bumblebee, "~> 0.6.0"}, + {:exla, ">= 0.0.0"} + ] +end +``` + +Then configure `Nx` to use EXLA backend by default in your `config/config.exs` file: + +```elixir +import Config + +config :nx, default_backend: EXLA.Backend +``` + +To use GPUs, you must [set the `XLA_TARGET` environment variable accordingly](https://github.com/elixir-nx/xla#usage). + +In notebooks and scripts, use the following `Mix.install/2` call to both install and configure dependencies: + +```elixir +Mix.install( + [ + {:bumblebee, "~> 0.6.0"}, + {:exla, ">= 0.0.0"} + ], + config: [nx: [default_backend: EXLA.Backend]] +) +``` + +## Usage + +To get a sense of what Bumblebee does, look at this example: + +```elixir +{:ok, model_info} = Bumblebee.load_model({:hf, "google-bert/bert-base-uncased"}) +{:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "google-bert/bert-base-uncased"}) + +serving = Bumblebee.Text.fill_mask(model_info, tokenizer) +Nx.Serving.run(serving, "The capital of [MASK] is Paris.") +#=> %{ +#=> predictions: [ +#=> %{score: 0.9279842972755432, token: "france"}, +#=> %{score: 0.008412551134824753, token: "brittany"}, +#=> %{score: 0.007433671969920397, token: "algeria"}, +#=> %{score: 0.004957548808306456, token: "department"}, +#=> %{score: 0.004369721747934818, token: "reunion"} +#=> ] +#=> } +``` + +We load the BERT model from Hugging Face Hub, then plug it into an end-to-end pipeline in the form of "serving", finally we use the serving to get our task done. For more details check out [the documentation](https://hexdocs.pm/bumblebee). + + + +## HuggingFace Hub + +HuggingFace Hub is a platform hosting models, datasets and demo apps (Spaces), all using Git repositories (with Git LFS for large files). For further information check out the [Hub documentation](https://huggingface.co/docs/hub/index) and explore the [model repositories](https://huggingface.co/models). + +### Models + +Model repositories are regular Git repositories, therefore they can store arbitrary files. However, most repositories store models saved using the Python [Transformers](https://github.com/huggingface/transformers) library. Bumblebee is an Elixir counterpart of Transformers and allows for importing those models, as long as they are implemented in Bumblebee. + +A repository in the Transformers format does not store an actual model, only the trained parameters and a configuration file. The configuration file specifies the model type (e.g. BERT) and high-level properties, such as the number layers and their size. The model implementation lives in the library code (both Transformers and Bumblebee). When loading a model, the library fetches the configuration and builds a matching model, then it fetches the trained parameters to pair them with the model. The key takeaway is that in order to use any given model, it needs to have an implementation in Bumblebee. + +### Model repository + +Here is a list of files commonly found in a repository following the Transformers format. + + * `config.json` - model configuration, specifies the model type and model-specific options. You can think of this as a blueprint for how the model should be constructed + + * `pytorch_model.bin` - raw model parameters (tensors) serialized from a PyTorch model using [PyTorch format](https://pytorch.org/docs/stable/generated/torch.save.html) (supported by Bumblebee) + + * `model.safetensors` - raw model parameters (tensors) serialized from a PyTorch model using [Safetensors](https://github.com/huggingface/safetensors) (supported by Bumblebee) + + * `flax_model.msgpack`, `tf_model.h5` - raw model parameters (tensors) serialized from Flax and Tensorflow models respectively (not supported by Bumblebee) + + * `tokenizer.json`, `tokenizer_config.json` - tokenizer configuration, describes how to convert text input to model inputs (tensors). See [Tokenizer support](#tokenizer-support) + + * `preprocessor_config.json` - featurizer configuration, describes how to convert real-world input (image, audio) to model inputs (tensors) + + * `generation_config.json` - a set of configuration options specific to text generation, such as token sampling strategy and various constraints + +### Model support + +As pointed out above, in order to load a model, the given model type must be implemented in Bumblebee. To find out whether the model is supported you can call `Bumblebee.load_model({:hf, "model-repo"})` or use [this tool](https://jonatanklosko-bumblebee-tools.hf.space/apps/repository-inspector) to run a number of checks against the repository. + +If you prefer to poke around the code, open the `config.json` file in the model repository and copy the class name under `"architectures"`. Next, [search Bumblebee codebase](https://github.com/search?q=repo%3Aelixir-nx%2Fbumblebee+BertForMaskedLM&type=code) for that keyword. If you find a match, this indicates the model is supported. + +Also note that certain repositories include multiple models in separate repositories, for example [`stabilityai/stable-diffusion-2`](https://huggingface.co/stabilityai/stable-diffusion-2). In such case use `Bumblebee.load_model({:hf, "model-repo", subdir: "..."})`. + +### Tokenizer support + +The Transformers library distinguishes two types of tokenizer implementations: + + * "slow tokenizer" - a tokenizer implemented in Python and stored as `tokenizer_config.json` and a couple extra files + + * "fast tokenizer" - a tokenizer implemented in Rust and stored in a single file - `tokenizer.json` + +Bumblebee relies on the Rust implementations (through bindings to [Tokenizers](https://github.com/huggingface/tokenizers)) and therefore always requires the `tokenizer.json` file. Many repositories only include files for a "slow tokenizer". When you stumble upon such repository, there are two options you can try. + +First, if the repository is clearly a fine-tuned version of another model, you can look for `tokenizer.json` in the original model repository. For example, [`textattack/bert-base-uncased-yelp-polarity`](https://huggingface.co/textattack/bert-base-uncased-yelp-polarity) only includes `tokenizer_config.json`, but it is a fine-tuned version of [`bert-base-uncased`](https://huggingface.co/bert-base-uncased), which does include `tokenizer.json`. Consequently, you can safely load the model from `textattack/bert-base-uncased-yelp-polarity` and tokenizer from `bert-base-uncased`. + +Otherwise, the Transformers library includes conversion rules to load a "slow tokenizer" and convert it to a corresponding "fast tokenizer", which is possible in most cases. You can generate the `tokenizer.json` file using [this tool](https://jonatanklosko-bumblebee-tools.hf.space/apps/tokenizer-generator). Once successful, you can follow the steps to submit a PR adding `tokenizer.json` to the model repository. Note that you do not have to wait for the PR to be merged, instead you can copy commit SHA from the PR and load the tokenizer with `Bumblebee.load_tokenizer({:hf, "model-repo", revision: "..."})`. + + + +## License + + Copyright (c) 2022 Dashbit + + 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](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/deps/bumblebee/hex_metadata.config b/deps/bumblebee/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..d15558c3e65b49433df2120b50cf72c2a94ca324 --- /dev/null +++ b/deps/bumblebee/hex_metadata.config @@ -0,0 +1,145 @@ +{<<"links">>,[{<<"GitHub">>,<<"https://github.com/elixir-nx/bumblebee">>}]}. +{<<"name">>,<<"bumblebee">>}. +{<<"version">>,<<"0.6.3">>}. +{<<"description">>, + <<"Pre-trained and transformer Neural Network models in Axon">>}. +{<<"elixir">>,<<"~> 1.14">>}. +{<<"app">>,<<"bumblebee">>}. +{<<"licenses">>,[<<"Apache-2.0">>]}. +{<<"requirements">>, + [[{<<"name">>,<<"axon">>}, + {<<"app">>,<<"axon">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.7.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"tokenizers">>}, + {<<"app">>,<<"tokenizers">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.4">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"nx">>}, + {<<"app">>,<<"nx">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.9.0 or ~> 0.10.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"nx_image">>}, + {<<"app">>,<<"nx_image">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.1.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"unpickler">>}, + {<<"app">>,<<"unpickler">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.1.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"safetensors">>}, + {<<"app">>,<<"safetensors">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.1.3">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"jason">>}, + {<<"app">>,<<"jason">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 1.4.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"unzip">>}, + {<<"app">>,<<"unzip">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.12.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"progress_bar">>}, + {<<"app">>,<<"progress_bar">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 3.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"nx_signal">>}, + {<<"app">>,<<"nx_signal">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.2.0">>}, + {<<"repository">>,<<"hexpm">>}]]}. +{<<"files">>, + [<<"lib">>,<<"lib/bumblebee.ex">>,<<"lib/bumblebee">>, + <<"lib/bumblebee/configurable.ex">>,<<"lib/bumblebee/layers">>, + <<"lib/bumblebee/layers/decoder.ex">>, + <<"lib/bumblebee/layers/transformer.ex">>,<<"lib/bumblebee/model_spec.ex">>, + <<"lib/bumblebee/featurizer.ex">>,<<"lib/bumblebee/utils">>, + <<"lib/bumblebee/utils/nx.ex">>,<<"lib/bumblebee/utils/axon.ex">>, + <<"lib/bumblebee/utils/image.ex">>,<<"lib/bumblebee/utils/model.ex">>, + <<"lib/bumblebee/utils/http.ex">>,<<"lib/bumblebee/shared">>, + <<"lib/bumblebee/shared/converters.ex">>,<<"lib/bumblebee/vision">>, + <<"lib/bumblebee/vision/convnext_featurizer.ex">>, + <<"lib/bumblebee/vision/swin.ex">>, + <<"lib/bumblebee/vision/image_embedding.ex">>, + <<"lib/bumblebee/vision/deit.ex">>,<<"lib/bumblebee/vision/dino_v2.ex">>, + <<"lib/bumblebee/vision/clip_vision.ex">>, + <<"lib/bumblebee/vision/deit_featurizer.ex">>, + <<"lib/bumblebee/vision/image_to_text.ex">>, + <<"lib/bumblebee/vision/blip_vision.ex">>, + <<"lib/bumblebee/vision/image_classification.ex">>, + <<"lib/bumblebee/vision/bit_featurizer.ex">>, + <<"lib/bumblebee/vision/blip_featurizer.ex">>, + <<"lib/bumblebee/vision/convnext.ex">>,<<"lib/bumblebee/vision/vit.ex">>, + <<"lib/bumblebee/vision/clip_featurizer.ex">>, + <<"lib/bumblebee/vision/resnet.ex">>, + <<"lib/bumblebee/vision/vit_featurizer.ex">>,<<"lib/bumblebee/diffusion">>, + <<"lib/bumblebee/diffusion/pndm_scheduler.ex">>, + <<"lib/bumblebee/diffusion/scheduler_utils.ex">>, + <<"lib/bumblebee/diffusion/layers">>, + <<"lib/bumblebee/diffusion/layers/unet.ex">>, + <<"lib/bumblebee/diffusion/ddim_scheduler.ex">>, + <<"lib/bumblebee/diffusion/vae_kl.ex">>, + <<"lib/bumblebee/diffusion/controlnet.ex">>, + <<"lib/bumblebee/diffusion/layers.ex">>, + <<"lib/bumblebee/diffusion/stable_diffusion">>, + <<"lib/bumblebee/diffusion/stable_diffusion/safety_checker.ex">>, + <<"lib/bumblebee/diffusion/lcm_scheduler.ex">>, + <<"lib/bumblebee/diffusion/stable_diffusion.ex">>, + <<"lib/bumblebee/diffusion/unet_2d_conditional.ex">>, + <<"lib/bumblebee/diffusion/stable_diffusion_controlnet.ex">>, + <<"lib/bumblebee/vision.ex">>,<<"lib/bumblebee/audio.ex">>, + <<"lib/bumblebee/multimodal">>,<<"lib/bumblebee/multimodal/layout_lm.ex">>, + <<"lib/bumblebee/multimodal/clip.ex">>, + <<"lib/bumblebee/multimodal/blip.ex">>,<<"lib/bumblebee/scheduler.ex">>, + <<"lib/bumblebee/audio">>,<<"lib/bumblebee/audio/whisper_featurizer.ex">>, + <<"lib/bumblebee/audio/speech_to_text_whisper.ex">>, + <<"lib/bumblebee/audio/whisper.ex">>,<<"lib/bumblebee/layers.ex">>, + <<"lib/bumblebee/conversion">>, + <<"lib/bumblebee/conversion/pytorch_loader">>, + <<"lib/bumblebee/conversion/pytorch_loader/file_tensor.ex">>, + <<"lib/bumblebee/conversion/pytorch_loader.ex">>, + <<"lib/bumblebee/conversion/pytorch_params.ex">>, + <<"lib/bumblebee/tokenizer.ex">>,<<"lib/bumblebee/huggingface">>, + <<"lib/bumblebee/huggingface/hub.ex">>, + <<"lib/bumblebee/huggingface/transformers">>, + <<"lib/bumblebee/huggingface/transformers/config.ex">>, + <<"lib/bumblebee/huggingface/transformers/model.ex">>, + <<"lib/bumblebee/huggingface/transformers/utils.ex">>, + <<"lib/bumblebee/shared.ex">>,<<"lib/bumblebee/text">>, + <<"lib/bumblebee/text/bart.ex">>,<<"lib/bumblebee/text/distilbert.ex">>, + <<"lib/bumblebee/text/generation_config.ex">>, + <<"lib/bumblebee/text/pre_trained_tokenizer.ex">>, + <<"lib/bumblebee/text/albert.ex">>, + <<"lib/bumblebee/text/question_answering.ex">>, + <<"lib/bumblebee/text/blenderbot.ex">>,<<"lib/bumblebee/text/phi3.ex">>, + <<"lib/bumblebee/text/text_embedding.ex">>, + <<"lib/bumblebee/text/mistral.ex">>,<<"lib/bumblebee/text/generation.ex">>, + <<"lib/bumblebee/text/gpt_big_code.ex">>, + <<"lib/bumblebee/text/blip_text.ex">>,<<"lib/bumblebee/text/roberta.ex">>, + <<"lib/bumblebee/text/gpt2.ex">>,<<"lib/bumblebee/text/t5.ex">>, + <<"lib/bumblebee/text/fill_mask.ex">>,<<"lib/bumblebee/text/gemma.ex">>, + <<"lib/bumblebee/text/whisper_generation_config.ex">>, + <<"lib/bumblebee/text/bert.ex">>, + <<"lib/bumblebee/text/token_classification.ex">>, + <<"lib/bumblebee/text/phi.ex">>,<<"lib/bumblebee/text/llama.ex">>, + <<"lib/bumblebee/text/gpt_neo_x.ex">>, + <<"lib/bumblebee/text/zero_shot_classification.ex">>, + <<"lib/bumblebee/text/mbart.ex">>,<<"lib/bumblebee/text/clip_text.ex">>, + <<"lib/bumblebee/text/text_classification.ex">>, + <<"lib/bumblebee/text/m2m100.ex">>,<<"lib/bumblebee/text/translation.ex">>, + <<"lib/bumblebee/text/generation">>, + <<"lib/bumblebee/text/generation/logits_processing.ex">>, + <<"lib/bumblebee/text/text_generation.ex">>, + <<"lib/bumblebee/application.ex">>,<<"lib/bumblebee/utils.ex">>, + <<"lib/bumblebee/text.ex">>,<<".formatter.exs">>,<<"mix.exs">>, + <<"README.md">>,<<"LICENSE">>,<<"CHANGELOG.md">>]}. +{<<"build_tools">>,[<<"mix">>]}. diff --git a/deps/bumblebee/lib/bumblebee.ex b/deps/bumblebee/lib/bumblebee.ex new file mode 100644 index 0000000000000000000000000000000000000000..51f2330fea49f561b7e7ecbe06a1aae813c7ac94 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee.ex @@ -0,0 +1,1315 @@ +defmodule Bumblebee do + @external_resource "README.md" + + [_, readme_docs, _] = + "README.md" + |> File.read!() + |> String.split("") + + @moduledoc """ + Pre-trained `Axon` models for easy inference and boosted training. + + Bumblebee provides state-of-the-art, configurable `Axon` models. On + top of that, it streamlines the process of loading pre-trained models + by integrating with Hugging Face Hub and [🤗 Transformers](https://github.com/huggingface/transformers). + + ## Usage + + You can load one of the supported models by specifying the model repository: + + {:ok, model_info} = Bumblebee.load_model({:hf, "google-bert/bert-base-uncased"}) + {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "google-bert/bert-base-uncased"}) + + Then you are ready to make predictions: + + inputs = Bumblebee.apply_tokenizer(tokenizer, "Hello Bumblebee!") + outputs = Axon.predict(model_info.model, model_info.params, inputs) + + ### Tasks + + On top of bare models, Bumblebee provides a number of **"servings"** + that act as end-to-end pipelines for specific tasks. + + serving = Bumblebee.Text.fill_mask(model_info, tokenizer) + Nx.Serving.run(serving, "The capital of [MASK] is Paris.") + #=> %{ + #=> predictions: [ + #=> %{score: 0.9279842972755432, token: "france"}, + #=> %{score: 0.008412551134824753, token: "brittany"}, + #=> %{score: 0.007433671969920397, token: "algeria"}, + #=> %{score: 0.004957548808306456, token: "department"}, + #=> %{score: 0.004369721747934818, token: "reunion"} + #=> ] + #=> } + + As you can see the **serving** takes care of pre-processing the + text input, runs the model and also post-processes its output into + more structured data. In the above example we `run` serving on the + fly, however for production usage you can start serving as a process + and it will automatically batch requests from multiple clients. + Processing inputs in batches is usually much more efficient, since + it can take advantage of parallel capabilities of the target device, + which is particularly relevant in case of GPU. For more details read + the `Nx.Serving` docs. + + For more examples see the [Examples](examples.livemd) notebook. + + > #### Note {: .info} + > + > The models are generally large, so make sure to configure an efficient + > `Nx` backend, such as `EXLA` or `Torchx`. + + #{readme_docs} + """ + + alias Bumblebee.HuggingFace + + @config_filename "config.json" + @featurizer_filename "preprocessor_config.json" + @tokenizer_filename "tokenizer.json" + @tokenizer_config_filename "tokenizer_config.json" + @tokenizer_special_tokens_filename "special_tokens_map.json" + @generation_filename "generation_config.json" + @scheduler_filename "scheduler_config.json" + + @params_filenames [ + "pytorch_model.bin", + "diffusion_pytorch_model.bin", + "model.safetensors", + "diffusion_pytorch_model.safetensors" + ] + + @transformers_class_to_model %{ + "AlbertForMaskedLM" => {Bumblebee.Text.Albert, :for_masked_language_modeling}, + "AlbertForMultipleChoice" => {Bumblebee.Text.Albert, :for_multiple_choice}, + "AlbertForPreTraining" => {Bumblebee.Text.Albert, :for_pre_training}, + "AlbertForQuestionAnswering" => {Bumblebee.Text.Albert, :for_question_answering}, + "AlbertForSequenceClassification" => {Bumblebee.Text.Albert, :for_sequence_classification}, + "AlbertForTokenClassification" => {Bumblebee.Text.Albert, :for_token_classification}, + "AlbertModel" => {Bumblebee.Text.Albert, :base}, + "BartForCausalLM" => {Bumblebee.Text.Bart, :for_causal_language_modeling}, + "BartForConditionalGeneration" => {Bumblebee.Text.Bart, :for_conditional_generation}, + "BartForQuestionAnswering" => {Bumblebee.Text.Bart, :for_question_answering}, + "BartForSequenceClassification" => {Bumblebee.Text.Bart, :for_sequence_classification}, + "BartModel" => {Bumblebee.Text.Bart, :base}, + "BertForMaskedLM" => {Bumblebee.Text.Bert, :for_masked_language_modeling}, + "BertForMultipleChoice" => {Bumblebee.Text.Bert, :for_multiple_choice}, + "BertForNextSentencePrediction" => {Bumblebee.Text.Bert, :for_next_sentence_prediction}, + "BertForPreTraining" => {Bumblebee.Text.Bert, :for_pre_training}, + "BertForQuestionAnswering" => {Bumblebee.Text.Bert, :for_question_answering}, + "BertForSequenceClassification" => {Bumblebee.Text.Bert, :for_sequence_classification}, + "BertForTokenClassification" => {Bumblebee.Text.Bert, :for_token_classification}, + "BertLMHeadModel" => {Bumblebee.Text.Bert, :for_causal_language_modeling}, + "BertModel" => {Bumblebee.Text.Bert, :base}, + "BlenderbotForConditionalGeneration" => + {Bumblebee.Text.Blenderbot, :for_conditional_generation}, + "BlenderbotModel" => {Bumblebee.Text.Blenderbot, :base}, + "BlipForConditionalGeneration" => {Bumblebee.Multimodal.Blip, :for_conditional_generation}, + # These models are just RoBERTa models, but the config will list them as CamemBERT + "CamembertModel" => {Bumblebee.Text.Roberta, :base}, + "CamembertForMaskedLM" => {Bumblebee.Text.Roberta, :for_masked_language_modeling}, + "CamembertForSequenceClassification" => + {Bumblebee.Text.Roberta, :for_sequence_classification}, + "CamembertForMultipleChoice" => {Bumblebee.Text.Roberta, :for_multiple_choice}, + "CamembertForTokenClassification" => {Bumblebee.Text.Roberta, :for_token_classification}, + "CamembertForQuestionAnswering" => {Bumblebee.Text.Roberta, :for_question_answering}, + "CLIPModel" => {Bumblebee.Multimodal.Clip, :base}, + "CLIPTextModel" => {Bumblebee.Text.ClipText, :base}, + "CLIPVisionModel" => {Bumblebee.Vision.ClipVision, :base}, + "ControlNetModel" => {Bumblebee.Diffusion.ControlNet, :base}, + "ConvNextForImageClassification" => {Bumblebee.Vision.ConvNext, :for_image_classification}, + "ConvNextModel" => {Bumblebee.Vision.ConvNext, :base}, + "DeiTForImageClassification" => {Bumblebee.Vision.Deit, :for_image_classification}, + "DeiTForImageClassificationWithTeacher" => + {Bumblebee.Vision.Deit, :for_image_classification_with_teacher}, + "DeiTForMaskedImageModeling" => {Bumblebee.Vision.Deit, :for_masked_image_modeling}, + "DeiTModel" => {Bumblebee.Vision.Deit, :base}, + "Dinov2Model" => {Bumblebee.Vision.DinoV2, :base}, + "Dinov2Backbone" => {Bumblebee.Vision.DinoV2, :backbone}, + "Dinov2ForImageClassification" => {Bumblebee.Vision.DinoV2, :for_image_classification}, + "DistilBertModel" => {Bumblebee.Text.Distilbert, :base}, + "DistilBertForMaskedLM" => {Bumblebee.Text.Distilbert, :for_masked_language_modeling}, + "DistilBertForSequenceClassification" => + {Bumblebee.Text.Distilbert, :for_sequence_classification}, + "DistilBertForQuestionAnswering" => {Bumblebee.Text.Distilbert, :for_question_answering}, + "DistilBertForTokenClassification" => {Bumblebee.Text.Distilbert, :for_token_classification}, + "DistilBertForMultipleChoice" => {Bumblebee.Text.Distilbert, :for_multiple_choice}, + "GemmaModel" => {Bumblebee.Text.Gemma, :base}, + "GemmaForCausalLM" => {Bumblebee.Text.Gemma, :for_causal_language_modeling}, + "GemmaForSequenceClassification" => {Bumblebee.Text.Gemma, :for_sequence_classification}, + "GPT2ForSequenceClassification" => {Bumblebee.Text.Gpt2, :for_sequence_classification}, + "GPT2ForTokenClassification" => {Bumblebee.Text.Gpt2, :for_token_classification}, + "GPT2LMHeadModel" => {Bumblebee.Text.Gpt2, :for_causal_language_modeling}, + "GPT2Model" => {Bumblebee.Text.Gpt2, :base}, + "GPTBigCodeModel" => {Bumblebee.Text.GptBigCode, :base}, + "GPTBigCodeForCausalLM" => {Bumblebee.Text.GptBigCode, :for_causal_language_modeling}, + "GPTBigCodeForSequenceClassification" => + {Bumblebee.Text.GptBigCode, :for_sequence_classification}, + "GPTBigCodeForTokenClassification" => {Bumblebee.Text.GptBigCode, :for_token_classification}, + "GPTNeoXModel" => {Bumblebee.Text.GptNeoX, :base}, + "GPTNeoXForCausalLM" => {Bumblebee.Text.GptNeoX, :for_causal_language_modeling}, + "GPTNeoXForSequenceClassification" => {Bumblebee.Text.GptNeoX, :for_sequence_classification}, + "GPTNeoXForTokenClassification" => {Bumblebee.Text.GptNeoX, :for_token_classification}, + "LayoutLMForMaskedLM" => {Bumblebee.Multimodal.LayoutLm, :for_masked_language_modeling}, + "LayoutLMForQuestionAnswering" => {Bumblebee.Multimodal.LayoutLm, :for_question_answering}, + "LayoutLMForSequenceClassification" => + {Bumblebee.Multimodal.LayoutLm, :for_sequence_classification}, + "LayoutLMForTokenClassification" => + {Bumblebee.Multimodal.LayoutLm, :for_token_classification}, + "LayoutLMModel" => {Bumblebee.Multimodal.LayoutLm, :base}, + "LlamaModel" => {Bumblebee.Text.Llama, :base}, + "LlamaForCausalLM" => {Bumblebee.Text.Llama, :for_causal_language_modeling}, + "LlamaForSequenceClassification" => {Bumblebee.Text.Llama, :for_sequence_classification}, + "MBartForCausalLM" => {Bumblebee.Text.Mbart, :for_causal_language_modeling}, + "MBartForConditionalGeneration" => {Bumblebee.Text.Mbart, :for_conditional_generation}, + "MBartForQuestionAnswering" => {Bumblebee.Text.Mbart, :for_question_answering}, + "MBartForSequenceClassification" => {Bumblebee.Text.Mbart, :for_sequence_classification}, + "MBartModel" => {Bumblebee.Text.Mbart, :base}, + "M2M100Model" => {Bumblebee.Text.M2m100, :base}, + "M2M100ForConditionalGeneration" => {Bumblebee.Text.M2m100, :for_conditional_generation}, + "MistralModel" => {Bumblebee.Text.Mistral, :base}, + "MistralForCausalLM" => {Bumblebee.Text.Mistral, :for_causal_language_modeling}, + "MistralForSequenceClassification" => {Bumblebee.Text.Mistral, :for_sequence_classification}, + "PhiModel" => {Bumblebee.Text.Phi, :base}, + "PhiForCausalLM" => {Bumblebee.Text.Phi, :for_causal_language_modeling}, + "PhiForSequenceClassification" => {Bumblebee.Text.Phi, :for_sequence_classification}, + "PhiForTokenClassification" => {Bumblebee.Text.Phi, :for_token_classification}, + "Phi3Model" => {Bumblebee.Text.Phi3, :base}, + "Phi3ForCausalLM" => {Bumblebee.Text.Phi3, :for_causal_language_modeling}, + "Phi3ForSequenceClassification" => {Bumblebee.Text.Phi3, :for_sequence_classification}, + "Phi3ForTokenClassification" => {Bumblebee.Text.Phi3, :for_token_classification}, + "ResNetForImageClassification" => {Bumblebee.Vision.ResNet, :for_image_classification}, + "ResNetModel" => {Bumblebee.Vision.ResNet, :base}, + "RobertaForMaskedLM" => {Bumblebee.Text.Roberta, :for_masked_language_modeling}, + "RobertaForMultipleChoice" => {Bumblebee.Text.Roberta, :for_multiple_choice}, + "RobertaForPreTraining" => {Bumblebee.Text.Roberta, :for_pre_training}, + "RobertaForQuestionAnswering" => {Bumblebee.Text.Roberta, :for_question_answering}, + "RobertaForSequenceClassification" => {Bumblebee.Text.Roberta, :for_sequence_classification}, + "RobertaForTokenClassification" => {Bumblebee.Text.Roberta, :for_token_classification}, + "RobertaForCausalLM" => {Bumblebee.Text.Roberta, :for_causal_language_modeling}, + "RobertaModel" => {Bumblebee.Text.Roberta, :base}, + "SwinModel" => {Bumblebee.Vision.Swin, :base}, + "SwinForImageClassification" => {Bumblebee.Vision.Swin, :for_image_classification}, + "T5Model" => {Bumblebee.Text.T5, :base}, + "T5ForConditionalGeneration" => {Bumblebee.Text.T5, :for_conditional_generation}, + "T5EncoderModel" => {Bumblebee.Text.T5, :encoder}, + "ViTForImageClassification" => {Bumblebee.Vision.Vit, :for_image_classification}, + "ViTForMaskedImageModeling" => {Bumblebee.Vision.Vit, :for_masked_image_modeling}, + "ViTModel" => {Bumblebee.Vision.Vit, :base}, + "WhisperModel" => {Bumblebee.Audio.Whisper, :base}, + "WhisperForConditionalGeneration" => {Bumblebee.Audio.Whisper, :for_conditional_generation}, + # These models are just RoBERTa models, but the config will list them as XLM-RoBERTa + "XLMRobertaForCausalLM" => {Bumblebee.Text.Roberta, :for_causal_language_modeling}, + "XLMRobertaForMaskedLM" => {Bumblebee.Text.Roberta, :for_masked_language_modeling}, + "XLMRobertaForMultipleChoice" => {Bumblebee.Text.Roberta, :for_multiple_choice}, + "XLMRobertaForQuestionAnswering" => {Bumblebee.Text.Roberta, :for_question_answering}, + "XLMRobertaForSequenceClassification" => + {Bumblebee.Text.Roberta, :for_sequence_classification}, + "XLMRobertaForTokenClassification" => {Bumblebee.Text.Roberta, :for_token_classification}, + "XLMRobertaModel" => {Bumblebee.Text.Roberta, :base}, + # Diffusers + "AutoencoderKL" => {Bumblebee.Diffusion.VaeKl, :base}, + "StableDiffusionSafetyChecker" => {Bumblebee.Diffusion.StableDiffusion.SafetyChecker, :base}, + "UNet2DConditionModel" => {Bumblebee.Diffusion.UNet2DConditional, :base} + } + + @transformers_class_to_featurizer %{ + "CLIPFeatureExtractor" => Bumblebee.Vision.ClipFeaturizer, + "ConvNextFeatureExtractor" => Bumblebee.Vision.ConvNextFeaturizer, + "DeiTFeatureExtractor" => Bumblebee.Vision.DeitFeaturizer, + "ViTFeatureExtractor" => Bumblebee.Vision.VitFeaturizer, + "WhisperFeatureExtractor" => Bumblebee.Audio.WhisperFeaturizer + } + + @transformers_image_processor_type_to_featurizer %{ + "BlipImageProcessor" => Bumblebee.Vision.BlipFeaturizer, + "BitImageProcessor" => Bumblebee.Vision.BitFeaturizer + } + + @model_type_to_featurizer %{ + "convnext" => Bumblebee.Vision.ConvNextFeaturizer, + "deit" => Bumblebee.Vision.DeitFeaturizer, + "resnet" => Bumblebee.Vision.ConvNextFeaturizer, + "vit" => Bumblebee.Vision.VitFeaturizer, + "whisper" => Bumblebee.Audio.WhisperFeaturizer + } + + @model_type_to_tokenizer_type %{ + "albert" => :albert, + "bart" => :bart, + "bert" => :bert, + "blenderbot" => :blenderbot, + "blip" => :bert, + "distilbert" => :distilbert, + "camembert" => :camembert, + "clip" => :clip, + "gemma" => :gemma, + "gpt_neox" => :gpt_neo_x, + "gpt2" => :gpt2, + "gpt_bigcode" => :gpt2, + "layoutlm" => :layout_lm, + "llama" => :llama, + "mistral" => :llama, + "mbart" => :mbart, + "phi" => :code_gen, + "phi3" => :llama, + "roberta" => :roberta, + "t5" => :t5, + "whisper" => :whisper, + "xlm-roberta" => :xlm_roberta, + # Both M2M100 and NLLB model checkpoints use the M2M100 model, + # but have distinct tokenizers. Consequently, model type is + # "m2m_100" in both cases. Currently only NLLB has fast tokenizer + # implementation, so if we load the tokenizer correctly, it is + # safe to assume it's NLLB + "m2m_100" => :nllb + } + + @diffusers_class_to_scheduler %{ + "DDIMScheduler" => Bumblebee.Diffusion.DdimScheduler, + "LCMScheduler" => Bumblebee.Diffusion.LcmScheduler, + "PNDMScheduler" => Bumblebee.Diffusion.PndmScheduler + } + + @typedoc """ + A location to fetch model files from. + + Can be either: + + * `{:hf, repository_id}` - the repository on Hugging Face. Options + may be passed as the third element: + + * `:revision` - the specific model version to use, it can be + any valid git identifier, such as branch name, tag name, or + a commit hash + + * `:cache_dir` - the directory to store the downloaded files + in. Defaults to the standard cache location for the given + operating system. You can also configure it globally by + setting the `BUMBLEBEE_CACHE_DIR` environment variable + + * `:offline` - if `true`, only cached files are accessed and + missing files result in an error. You can also configure it + globally by setting the `BUMBLEBEE_OFFLINE` environment + variable to `true` + + * `:auth_token` - the token to use as HTTP bearer authorization + for remote files + + * `:subdir` - the directory within the repository where the + files are located + + * `{:local, directory}` - the directory containing model files + + """ + @type repository :: {:hf, String.t()} | {:hf, String.t(), keyword()} | {:local, Path.t()} + + @typedoc """ + A model together with its state and metadata. + """ + @type model_info :: %{ + model: Axon.t(), + params: %Axon.ModelState{}, + spec: Bumblebee.ModelSpec.t() + } + + @doc """ + Builds or updates a configuration object with the given options. + + Expects a configuration struct or a module supporting configuration. + These are usually configurable: + + * model specification (`Bumblebee.ModelSpec`) + + * featurizer (`Bumblebee.Featurizer`) + + * scheduler (`Bumblebee.Scheduler`) + + ## Examples + + To build a new configuration, pass a module: + + featurizer = Bumblebee.configure(Bumblebee.Vision.ConvNextFeaturizer) + spec = Bumblebee.configure(Bumblebee.Vision.ResNet, architecture: :for_image_classification) + + Similarly, you can update an existing configuration: + + featurizer = Bumblebee.configure(featurizer, resize_method: :bilinear) + spec = Bumblebee.configure(spec, embedding_size: 128) + + """ + @spec configure(module() | Bumblebee.Configurable.t(), keyword()) :: Bumblebee.Configurable.t() + def configure(config, options \\ []) do + %module{} = config = struct!(config) + module.config(config, options) + end + + @doc """ + Builds an `Axon` model according to the given specification. + + ## Options + + * `:type` - either a type or `Axon.MixedPrecision` policy to apply + to the model + + ## Example + + spec = Bumblebee.configure(Bumblebee.Vision.ResNet, architecture: :base, embedding_size: 128) + model = Bumblebee.build_model(spec) + + """ + @doc type: :model + @spec build_model(Bumblebee.ModelSpec.t(), keyword()) :: Axon.t() + def build_model(%module{} = spec, opts \\ []) do + opts = Keyword.validate!(opts, [:type]) + + model = module.model(spec) + + case opts[:type] do + nil -> + model + + %Axon.MixedPrecision.Policy{} = policy -> + Axon.MixedPrecision.apply_policy(model, policy) + + type -> + type = Nx.Type.normalize!(type) + policy = Axon.MixedPrecision.create_policy(params: type, compute: type, output: type) + Axon.MixedPrecision.apply_policy(model, policy) + end + end + + @doc """ + Loads model specification from a model repository. + + ## Options + + * `:module` - the model specification module. By default it is + inferred from the configuration file, if that is not possible, + it must be specified explicitly + + * `:architecture` - the model architecture, must be supported by + `:module`. By default it is inferred from the configuration file + + ## Examples + + {:ok, spec} = Bumblebee.load_spec({:hf, "microsoft/resnet-50"}) + + You can explicitly specify a different architecture: + + {:ok, spec} = Bumblebee.load_spec({:hf, "microsoft/resnet-50"}, architecture: :base) + + """ + @doc type: :model + @spec load_spec(repository(), keyword()) :: + {:ok, Bumblebee.ModelSpec.t()} | {:error, String.t()} + def load_spec(repository, opts \\ []) do + repository = normalize_repository!(repository) + + opts = Keyword.validate!(opts, [:module, :architecture]) + + module = opts[:module] + architecture = opts[:architecture] + + with {:ok, repo_files} <- get_repo_files(repository) do + do_load_spec(repository, repo_files, module, architecture) + end + end + + defp do_load_spec(repository, repo_files, module, architecture) do + case repo_files do + %{@config_filename => etag} -> + with {:ok, path} <- download(repository, @config_filename, etag), + {:ok, spec_data} <- decode_config(path) do + {inferred_module, inferred_architecture, inference_error} = + case infer_model_type(spec_data) do + {:ok, module, architecture} -> {module, architecture, nil} + {:error, error} -> {nil, nil, error} + end + + module = module || inferred_module + architecture = architecture || inferred_architecture + + unless module do + raise ArgumentError, + "#{inference_error}, please specify the :module and :architecture options" + end + + architectures = module.architectures() + + if architecture && architecture not in architectures do + raise ArgumentError, + "expected architecture to be one of: #{Enum.map_join(architectures, ", ", &inspect/1)}, but got: #{inspect(architecture)}" + end + + spec = + if architecture do + configure(module, architecture: architecture) + else + configure(module) + end + + spec = HuggingFace.Transformers.Config.load(spec, spec_data) + + {:ok, spec} + end + + %{} -> + raise ArgumentError, + "no config file found in the given repository. Please refer to Bumblebee" <> + " README to learn about repositories and supported models" + end + end + + defp decode_config(path) do + path + |> File.read!() + |> Jason.decode() + |> case do + {:ok, data} -> {:ok, data} + _ -> {:error, "failed to parse the config file, it is not a valid JSON"} + end + end + + defp infer_model_type(%{"architectures" => [class_name]}) do + case @transformers_class_to_model[class_name] do + nil -> + {:error, + "could not match the class name #{inspect(class_name)} to any of the supported models"} + + {module, architecture} -> + {:ok, module, architecture} + end + end + + defp infer_model_type(%{"_class_name" => class_name}) do + infer_model_type(%{"architectures" => [class_name]}) + end + + defp infer_model_type(_spec_data) do + {:error, "could not infer model type from the configuration"} + end + + @doc """ + Loads a pre-trained model from a model repository. + + The model is downloaded and cached on your disk, use `cache_dir/0` to + find the location. + + ## Parameters precision + + On GPUs computations that use numeric type of lower precision can + be faster and use less memory, while still providing valid results. + You can configure the model to use particular type by passing the + `:type` option, such as `:bf16`. + + Some repositories have multiple variants of the parameter files + with different numeric types. The variant is usually indicated in + the file extension and you can load a particular file by specifying + `:params_variant`, or `:params_filename`. Note however that this + does not determine the numeric type used for inference. The file + type is relevant in context of download bandwidth and disk space. + If you want to use a lower precision for inference, make sure to + also specify `:type`. + + ## Options + + * `:spec` - the model specification to use when building the model. + By default the specification is loaded using `load_spec/2` + + * `:spec_overrides` - additional options to configure the model + specification with. This is a shorthand for using `load_spec/2`, + `configure/2` and passing as `:spec` + + * `:module` - the model specification module. By default it is + inferred from the configuration file, if that is not possible, + it must be specified explicitly + + * `:architecture` - the model architecture, must be supported by + `:module`. By default it is inferred from the configuration file + + * `:params_variant` - when specified, instead of loading parameters + from ".", loads from ".." + + * `:params_filename` - the file with the model parameters to be loaded + + * `:log_params_diff` - whether to log missing, mismatched and unused + parameters. By default diff is logged only if some parameters + cannot be loaded + + * `:backend` - the backend to allocate the tensors on. It is either + an atom or a tuple in the shape `{backend, options}` + + * `:type` - either a type or `Axon.MixedPrecision` policy to apply + to the model. Passing this option automatically casts parameters + to the desired type + + ## Examples + + By default the model type is inferred from configuration, so loading + is as simple as: + + {:ok, resnet} = Bumblebee.load_model({:hf, "microsoft/resnet-50"}) + %{model: model, params: params, spec: spec} = resnet + + You can explicitly specify a different architecture, in which case + matching parameters are still loaded: + + {:ok, resnet} = Bumblebee.load_model({:hf, "microsoft/resnet-50"}, architecture: :base) + + To further customize the model, you can also pass the specification: + + {:ok, spec} = Bumblebee.load_spec({:hf, "microsoft/resnet-50"}) + spec = Bumblebee.configure(spec, num_labels: 10) + {:ok, resnet} = Bumblebee.load_model({:hf, "microsoft/resnet-50"}, spec: spec) + + Or as a shorthand, you can pass just the options to override: + + {:ok, resnet} = + Bumblebee.load_model({:hf, "microsoft/resnet-50"}, spec_overrides: [num_labels: 10]) + + """ + @doc type: :model + @spec load_model(repository(), keyword()) :: {:ok, model_info()} | {:error, String.t()} + def load_model(repository, opts \\ []) do + repository = normalize_repository!(repository) + + opts = + Keyword.validate!(opts, [ + :spec, + :spec_overrides, + :module, + :architecture, + :params_variant, + :params_filename, + :log_params_diff, + :backend, + :type + ]) + + with {:ok, repo_files} <- get_repo_files(repository), + {:ok, spec} <- maybe_load_model_spec(opts, repository, repo_files), + model <- build_model(spec, Keyword.take(opts, [:type])), + {:ok, params} <- load_params(spec, model, repository, repo_files, opts) do + {:ok, %{model: model, params: params, spec: spec}} + end + end + + defp maybe_load_model_spec(opts, repository, repo_files) do + spec_result = + if spec = opts[:spec] do + {:ok, spec} + else + do_load_spec(repository, repo_files, opts[:module], opts[:architecture]) + end + + with {:ok, spec} <- spec_result do + if options = opts[:spec_overrides] do + {:ok, configure(spec, options)} + else + {:ok, spec} + end + end + end + + defp load_params(%module{} = spec, model, repository, repo_files, opts) do + input_template = module.input_template(spec) + + params_mapping = Bumblebee.HuggingFace.Transformers.Model.params_mapping(spec) + + {filename, sharded?} = + infer_params_filename(repo_files, opts[:params_filename], opts[:params_variant]) + + loader_fun = + filename + |> String.replace_suffix(".index.json", "") + |> Path.extname() + |> params_file_loader_fun() + + with {:ok, paths} <- download_params_files(repository, repo_files, filename, sharded?) do + opts = + [ + params_mapping: params_mapping, + loader_fun: loader_fun + ] ++ Keyword.take(opts, [:backend, :log_params_diff]) + + params = Bumblebee.Conversion.PyTorchParams.load_params!(model, input_template, paths, opts) + {:ok, params} + end + end + + defp infer_params_filename(repo_files, nil = _filename, variant) do + validate_variant!(repo_files, variant) + + Enum.find_value(@params_filenames, &lookup_params_filename(repo_files, &1, variant)) || + raise ArgumentError, + "none of the expected parameters files found in the repository." <> + " If the file exists under an unusual name, try specifying :params_filename" + end + + defp infer_params_filename(repo_files, filename, variant) do + if variant do + IO.warn("ignoring :params_variant, because :params_filename was specified") + end + + lookup_params_filename(repo_files, filename, nil) || + raise ArgumentError, "could not find file #{inspect(filename)} in the repository" + end + + defp lookup_params_filename(repo_files, filename, variant) do + full_filename = add_variant(filename, variant) + full_filename_sharded = add_variant(filename <> ".index.json", variant) + + cond do + Map.has_key?(repo_files, full_filename) -> {full_filename, false} + Map.has_key?(repo_files, full_filename_sharded) -> {full_filename_sharded, true} + true -> nil + end + end + + defp add_variant(filename, nil), do: filename + + defp add_variant(filename, variant) do + ext = Path.extname(filename) + base = Path.basename(filename, ext) + base <> "." <> variant <> ext + end + + defp validate_variant!(_repo_files, nil), do: :ok + + defp validate_variant!(repo_files, variant) do + variants = params_variants_in_repo(repo_files) + + cond do + variant in variants -> + :ok + + Enum.empty?(variants) -> + raise ArgumentError, + "parameters variant #{inspect(variant)} not found, the repository has no variants" + + true -> + raise ArgumentError, + "parameters variant #{inspect(variant)} not found, available variants: " <> + Enum.map_join(variants, ", ", &inspect/1) + end + end + + defp params_variants_in_repo(repo_files) do + params_filenames = MapSet.new(@params_filenames) + + Enum.reduce(repo_files, MapSet.new(), fn {name, _etag}, variants -> + parts = String.split(name, ".") + {variant, parts} = List.pop_at(parts, -2) + name = Enum.join(parts, ".") + + if String.replace_suffix(name, ".index.json", "") in params_filenames and + not String.contains?(variant, "-of-") do + MapSet.put(variants, variant) + else + variants + end + end) + end + + defp download_params_files(repository, repo_files, filename, false = _sharded?) do + with {:ok, path} <- download(repository, filename, repo_files[filename]) do + {:ok, [path]} + end + end + + defp download_params_files(repository, repo_files, index_filename, true = _sharded?) do + with {:ok, path} <- download(repository, index_filename, repo_files[index_filename]), + {:ok, sharded_metadata} <- decode_config(path) do + filenames = + for {_layer, filename} <- sharded_metadata["weight_map"], uniq: true, do: filename + + Enum.reduce_while(filenames, {:ok, []}, fn filename, {:ok, paths} -> + case download(repository, filename, repo_files[filename]) do + {:ok, path} -> {:cont, {:ok, [path | paths]}} + error -> {:halt, error} + end + end) + end + end + + defp params_file_loader_fun(".safetensors"), do: &Safetensors.read!(&1, lazy: true) + defp params_file_loader_fun(_), do: &Bumblebee.Conversion.PyTorchLoader.load!/1 + + @doc """ + Featurizes `input` with the given featurizer. + + ## Options + + * `:defn_options` - the options for JIT compilation. Note that + this is only relevant for featurizers implemented with Nx. + Defaults to `[]` + + ## Examples + + featurizer = Bumblebee.configure(Bumblebee.Vision.ConvNextFeaturizer) + {:ok, img} = StbImage.read_file(path) + inputs = Bumblebee.apply_featurizer(featurizer, [img]) + + """ + @doc type: :featurizer + @spec apply_featurizer(Bumblebee.Featurizer.t(), any(), keyword()) :: any() + def apply_featurizer(%module{} = featurizer, input, opts \\ []) do + opts = Keyword.validate!(opts, defn_options: []) + + batch = module.process_input(featurizer, input) + + if Code.ensure_loaded?(module) and function_exported?(module, :process_batch, 2) do + Nx.Defn.jit_apply(&module.process_batch(featurizer, &1), [batch], opts[:defn_options]) + else + batch + end + end + + @doc """ + Loads featurizer from a model repository. + + ## Options + + * `:module` - the featurizer module. By default it is inferred + from the preprocessor configuration file, if that is not possible, + it must be specified explicitly + + ## Examples + + {:ok, featurizer} = Bumblebee.load_featurizer({:hf, "microsoft/resnet-50"}) + + """ + @doc type: :featurizer + @spec load_featurizer(repository(), keyword()) :: + {:ok, Bumblebee.Featurizer.t()} | {:error, String.t()} + def load_featurizer(repository, opts \\ []) do + repository = normalize_repository!(repository) + opts = Keyword.validate!(opts, [:module]) + module = opts[:module] + + case get_repo_files(repository) do + {:ok, %{@featurizer_filename => etag} = repo_files} -> + with {:ok, path} <- download(repository, @featurizer_filename, etag), + {:ok, featurizer_data} <- decode_config(path) do + module = + module || + case infer_featurizer_type(featurizer_data, repository, repo_files) do + {:ok, module} -> + module + + {:error, error} -> + raise ArgumentError, "#{error}, please specify the :module option" + end + + featurizer = configure(module) + featurizer = HuggingFace.Transformers.Config.load(featurizer, featurizer_data) + {:ok, featurizer} + end + + {:ok, %{}} -> + raise ArgumentError, "no featurizer found in the given repository" + + {:error, message} -> + {:error, message} + end + end + + defp infer_featurizer_type(%{"feature_extractor_type" => class_name}, _repository, _repo_files) do + case @transformers_class_to_featurizer[class_name] do + nil -> + {:error, + "could not match the class name #{inspect(class_name)} to any of the supported featurizers"} + + module -> + {:ok, module} + end + end + + defp infer_featurizer_type(%{"image_processor_type" => class_name}, _repository, _repo_files) do + case @transformers_image_processor_type_to_featurizer[class_name] do + nil -> + {:error, + "could not match the class name #{inspect(class_name)} to any of the supported featurizers"} + + module -> + {:ok, module} + end + end + + defp infer_featurizer_type(_featurizer_data, repository, repo_files) do + with {:ok, path} <- download(repository, @config_filename, repo_files[@config_filename]), + {:ok, featurizer_data} <- decode_config(path) do + case featurizer_data do + %{"model_type" => model_type} -> + case @model_type_to_featurizer[model_type] do + nil -> + {:error, + "could not match model type #{inspect(model_type)} to any of the supported featurizers"} + + module -> + {:ok, module} + end + + _ -> + {:error, "could not infer featurizer type from the configuration"} + end + end + end + + @doc """ + Tokenizes and encodes `input` with the given tokenizer. + + ## Examples + + tokenizer = Bumblebee.load_tokenizer({:hf, "google-bert/bert-base-uncased"}) + inputs = Bumblebee.apply_tokenizer(tokenizer, ["The capital of France is [MASK]."]) + + """ + @doc type: :tokenizer + @spec apply_tokenizer( + Bumblebee.Tokenizer.t(), + Bumblebee.Tokenizer.input() | list(Bumblebee.Tokenizer.input()), + keyword() + ) :: any() + def apply_tokenizer(%module{} = tokenizer, input, opts \\ []) do + tokenizer = + if opts == [] do + tokenizer + else + # TODO: remove options on v0.6 + IO.warn( + "passing options to Bumblebee.apply_tokenizer/3 is deprecated," <> + " please use Bumblebee.configure/2 to set tokenizer options" + ) + + Bumblebee.configure(tokenizer, opts) + end + + module.apply(tokenizer, input) + end + + @doc """ + Loads tokenizer from a model repository. + + ## Options + + * `:type` - the tokenizer type. By default it is inferred from + the configuration files, if that is not possible, it must be + specified explicitly + + ## Examples + + {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "google-bert/bert-base-uncased"}) + + """ + @doc type: :tokenizer + @spec load_tokenizer(repository(), keyword()) :: + {:ok, Bumblebee.Tokenizer.t()} | {:error, String.t()} + def load_tokenizer(repository, opts \\ []) do + repository = normalize_repository!(repository) + opts = Keyword.validate!(opts, [:type]) + type = opts[:type] + + case get_repo_files(repository) do + {:ok, %{@tokenizer_filename => etag} = repo_files} -> + with {:ok, path} <- download(repository, @tokenizer_filename, etag) do + type = + type || + case infer_tokenizer_type(repository, repo_files) do + {:ok, type} -> + type + + {:error, error} -> + raise ArgumentError, "#{error}, please specify the :type option" + end + + tokenizer_config_result = + if Map.has_key?(repo_files, @tokenizer_config_filename) do + etag = repo_files[@tokenizer_config_filename] + + with {:ok, path} <- download(repository, @tokenizer_config_filename, etag) do + decode_config(path) + end + else + {:ok, %{}} + end + + special_tokens_map_result = + if Map.has_key?(repo_files, @tokenizer_special_tokens_filename) do + etag = repo_files[@tokenizer_special_tokens_filename] + + with {:ok, path} <- download(repository, @tokenizer_special_tokens_filename, etag) do + decode_config(path) + end + else + {:ok, %{}} + end + + with {:ok, tokenizer_config} <- tokenizer_config_result, + {:ok, special_tokens_map} <- special_tokens_map_result do + tokenizer = struct!(Bumblebee.Text.PreTrainedTokenizer, type: type) + + tokenizer = + HuggingFace.Transformers.Config.load(tokenizer, %{ + "tokenizer_file" => path, + # Note: special_tokens_map.json is a legacy file, now + # tokenizer_config.json includes the same information + # and takes precedence + "special_tokens_map" => Map.merge(tokenizer_config, special_tokens_map) + }) + + {:ok, tokenizer} + end + end + + {:ok, %{@tokenizer_config_filename => _}} -> + raise ArgumentError, + "expected a Rust-compatible tokenizer.json file, however the repository" <> + " includes tokenizer in a different format. Please refer to Bumblebee" <> + " README to see the possible steps you can take" + + {:ok, %{}} -> + raise ArgumentError, "no tokenizer found in the given repository" + + {:error, message} -> + {:error, message} + end + end + + defp infer_tokenizer_type(repository, repo_files) do + with {:ok, path} <- download(repository, @config_filename, repo_files[@config_filename]), + {:ok, tokenizer_data} <- decode_config(path) do + case tokenizer_data do + %{"model_type" => model_type} -> + case @model_type_to_tokenizer_type[model_type] do + nil -> + {:error, + "could not match model type #{inspect(model_type)} to any of the supported tokenizer types"} + + type -> + {:ok, type} + end + + _ -> + {:error, "could not infer tokenizer type from the model configuration"} + end + end + end + + @doc """ + Loads generation config from a model repository. + + Generation config includes a number of model-specific properties, + so it is usually best to load the config and further configure, + rather than building from scratch. + + See `Bumblebee.Text.GenerationConfig` for all the available options. + + ## Options + + * `:spec_module` - the model specification module. By default it + is inferred from the configuration file, if that is not possible, + it must be specified explicitly. Some models have extra options + related to generations and those are loaded into a separate + struct, stored under the `:extra_config` attribute + + ## Examples + + {:ok, generation_config} = Bumblebee.load_generation_config({:hf, "openai-community/gpt2"}) + + generation_config = Bumblebee.configure(generation_config, max_new_tokens: 10) + + """ + @spec load_generation_config(repository()) :: + {:ok, Bumblebee.Text.GenerationConfig.t()} | {:error, String.t()} + def load_generation_config(repository, opts \\ []) do + opts = Keyword.validate!(opts, [:spec_module]) + + repository = normalize_repository!(repository) + + case get_repo_files(repository) do + {:ok, %{@config_filename => etag} = repo_files} -> + with {:ok, path} <- download(repository, @config_filename, etag), + {:ok, spec_data} <- decode_config(path) do + spec_module = opts[:spec_module] + + {inferred_module, inference_error} = + case infer_model_type(spec_data) do + {:ok, module, _architecture} -> {module, nil} + {:error, error} -> {nil, error} + end + + spec_module = spec_module || inferred_module + + unless spec_module do + raise ArgumentError, "#{inference_error}, please specify the :spec_module option" + end + + generation_data_result = + if Map.has_key?(repo_files, @generation_filename) do + etag = repo_files[@generation_filename] + + with {:ok, path} <- download(repository, @generation_filename, etag) do + decode_config(path) + end + else + # Fallback to the spec data, since it used to include + # generation attributes + {:ok, spec_data} + end + + with {:ok, generation_data} <- generation_data_result do + config = struct!(Bumblebee.Text.GenerationConfig) + config = HuggingFace.Transformers.Config.load(config, generation_data) + + extra_config_module = + Bumblebee.Text.Generation.extra_config_module(struct!(spec_module)) + + extra_config = + if extra_config_module do + extra_config = struct!(extra_config_module) + HuggingFace.Transformers.Config.load(extra_config, generation_data) + end + + config = %{config | extra_config: extra_config} + + {:ok, config} + end + end + + {:error, message} -> + {:error, message} + end + end + + @doc """ + Initializes state for a new scheduler loop. + + Returns a pair of `{state, timesteps}`, where `state` is an opaque + container expected by `scheduler_step/4` and `timesteps` is a sequence + of subsequent timesteps for model forward pass. + + Note that the number of `timesteps` may not match `num_steps` exactly. + `num_steps` parameterizes sampling points, however depending on the + method, sampling certain points may require multiple forward passes + of the model and each element in `timesteps` corresponds to a single + forward pass. + """ + @doc type: :scheduler + @spec scheduler_init( + Bumblebee.Scheduler.t(), + non_neg_integer(), + Nx.Tensor.t(), + Nx.Tensor.t() + ) :: {Bumblebee.Scheduler.state(), Nx.Tensor.t()} + def scheduler_init(%module{} = scheduler, num_steps, sample_template, prng_key) do + module.init(scheduler, num_steps, sample_template, prng_key) + end + + @doc """ + Predicts sample at the previous timestep using the given scheduler. + + Takes the current `sample` and `prediction` (usually noise) returned + by the model at the current timestep. Returns `{state, prev_sample}`, + where `state` is the updated scheduler loop state and `prev_sample` + is the predicted sample at the previous timestep. + + Note that some schedulers require several forward passes of the model + (and a couple calls to this function) to make an actual prediction for + the previous sample. + """ + @doc type: :scheduler + @spec scheduler_step( + Bumblebee.Scheduler.t(), + Bumblebee.Scheduler.state(), + Nx.Tensor.t(), + Nx.Tensor.t() + ) :: {Bumblebee.Scheduler.state(), Nx.Tensor.t()} + def scheduler_step(%module{} = scheduler, state, sample, prediction) do + module.step(scheduler, state, sample, prediction) + end + + @doc """ + Loads scheduler from a model repository. + + ## Options + + * `:module` - the scheduler module. By default it is inferred + from the scheduler configuration file, if that is not possible, + it must be specified explicitly + + ## Examples + + {:ok, scheduler} = + Bumblebee.load_scheduler({:hf, "CompVis/stable-diffusion-v1-4", subdir: "scheduler"}) + + """ + @doc type: :scheduler + @spec load_scheduler(repository(), keyword()) :: + {:ok, Bumblebee.Scheduler.t()} | {:error, String.t()} + def load_scheduler(repository, opts \\ []) do + repository = normalize_repository!(repository) + opts = Keyword.validate!(opts, [:module]) + module = opts[:module] + + case get_repo_files(repository) do + {:ok, %{@scheduler_filename => etag}} -> + with {:ok, path} <- download(repository, @scheduler_filename, etag), + {:ok, scheduler_data} <- decode_config(path) do + module = + module || + case infer_scheduler_type(scheduler_data) do + {:ok, module} -> + module + + {:error, error} -> + raise ArgumentError, "#{error}, please specify the :module option" + end + + scheduler = configure(module) + scheduler = HuggingFace.Transformers.Config.load(scheduler, scheduler_data) + {:ok, scheduler} + end + + {:ok, %{}} -> + raise ArgumentError, "no scheduler found in the given repository" + + {:error, message} -> + {:error, message} + end + end + + defp infer_scheduler_type(%{"_class_name" => class_name}) do + case @diffusers_class_to_scheduler[class_name] do + nil -> + {:error, + "could not match the class name #{inspect(class_name)} to any of the supported schedulers"} + + module -> + {:ok, module} + end + end + + defp infer_scheduler_type(_scheduler_data) do + {:error, "could not infer featurizer type from the configuration"} + end + + defp get_repo_files({:local, dir}) do + case File.ls(dir) do + {:ok, filenames} -> + repo_files = + for filename <- filenames, + path = Path.join(dir, filename), + File.regular?(path), + into: %{}, + do: {filename, nil} + + {:ok, repo_files} + + {:error, reason} -> + {:error, "could not read #{dir}, reason: #{:file.format_error(reason)}"} + end + end + + defp get_repo_files({:hf, repository_id, opts}) do + subdir = opts[:subdir] + url = HuggingFace.Hub.file_listing_url(repository_id, subdir, opts[:revision]) + cache_scope = repository_id_to_cache_scope(repository_id) + + result = + HuggingFace.Hub.cached_download( + url, + [cache_scope: cache_scope] ++ Keyword.take(opts, [:cache_dir, :offline, :auth_token]) + ) + + with {:ok, path} <- result, + {:ok, data} <- decode_config(path) do + repo_files = + for entry <- data, entry["type"] == "file", into: %{} do + path = entry["path"] + + name = + if subdir do + String.replace_leading(path, subdir <> "/", "") + else + path + end + + etag_content = entry["lfs"]["oid"] || entry["oid"] + etag = <> + {name, etag} + end + + {:ok, repo_files} + end + end + + defp download({:local, dir}, filename, _etag) do + path = Path.join(dir, filename) + + if File.exists?(path) do + {:ok, path} + else + {:error, "local file #{inspect(path)} does not exist"} + end + end + + defp download({:hf, repository_id, opts}, filename, etag) do + filename = + if subdir = opts[:subdir] do + subdir <> "/" <> filename + else + filename + end + + url = HuggingFace.Hub.file_url(repository_id, filename, opts[:revision]) + cache_scope = repository_id_to_cache_scope(repository_id) + + HuggingFace.Hub.cached_download( + url, + [etag: etag, cache_scope: cache_scope] ++ + Keyword.take(opts, [:cache_dir, :offline, :auth_token]) + ) + end + + defp repository_id_to_cache_scope(repository_id) do + repository_id + |> String.replace("/", "--") + |> String.replace(~r/[^\w-]/, "") + end + + defp normalize_repository!({:hf, repository_id}) when is_binary(repository_id) do + {:hf, repository_id, []} + end + + defp normalize_repository!({:hf, repository_id, opts}) when is_binary(repository_id) do + opts = Keyword.validate!(opts, [:revision, :cache_dir, :offline, :auth_token, :subdir]) + {:hf, repository_id, opts} + end + + defp normalize_repository!({:local, dir}) when is_binary(dir) do + {:local, dir} + end + + defp normalize_repository!(other) do + raise ArgumentError, + "expected repository to be either {:hf, repository_id}, {:hf, repository_id, options}" <> + " or {:local, directory}, got: #{inspect(other)}" + end + + @doc """ + Returns the directory where downloaded files are stored. + + Defaults to the standard cache location for the given operating system. + Can be configured with the `BUMBLEBEE_CACHE_DIR` environment variable. + """ + @spec cache_dir() :: String.t() + def cache_dir() do + if dir = System.get_env("BUMBLEBEE_CACHE_DIR") do + Path.expand(dir) + else + :filename.basedir(:user_cache, "bumblebee") + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/application.ex b/deps/bumblebee/lib/bumblebee/application.ex new file mode 100644 index 0000000000000000000000000000000000000000..ef200583585fe11c7999296752ce4de79206474f --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/application.ex @@ -0,0 +1,19 @@ +defmodule Bumblebee.Application do + @moduledoc false + + use Application + + @impl true + def start(_type, _args) do + Bumblebee.Utils.HTTP.start_inets_profile() + + children = [] + opts = [strategy: :one_for_one, name: Bumblebee.Supervisor] + Supervisor.start_link(children, opts) + end + + @impl true + def stop(_state) do + Bumblebee.Utils.HTTP.stop_inets_profile() + end +end diff --git a/deps/bumblebee/lib/bumblebee/audio.ex b/deps/bumblebee/lib/bumblebee/audio.ex new file mode 100644 index 0000000000000000000000000000000000000000..8b98ddda4064f99bb4f0dd90ecc782c1b6891cec --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/audio.ex @@ -0,0 +1,187 @@ +defmodule Bumblebee.Audio do + @moduledoc """ + High-level tasks related to audio processing. + """ + + @typedoc """ + A term representing audio. + + Can be either of: + + * a 1-dimensional `Nx.Tensor` with audio samples + + * an enumerable of 1-dimensional `Nx.Tensor`s, represending a + continuous stream of input. The tensors are not required to + have the same number of samples, the serving takes care of + accumulating and chunking the input as needed. This input is + only supported when chunking is enabled with the `:chunk_num_seconds` + option + + * `{:file, path}` with path to an audio file (note that this + requires `ffmpeg` installed) + + """ + @type audio :: Nx.t() | Enumerable.t(Nx.t()) | {:file, String.t()} + + @type speech_to_text_whisper_input :: + audio() | %{:audio => audio(), optional(:seed) => integer() | nil} + @type speech_to_text_whisper_output :: %{ + chunks: list(speech_to_text_whisper_chunk()) + } + @type speech_to_text_whisper_chunk :: %{ + text: String.t(), + start_timestamp_seconds: number() | nil, + end_timestamp_seconds: number() | nil + } + + @doc """ + Builds serving for speech-to-text generation with Whisper models. + + The serving accepts `t:speech_to_text_whisper_input/0` and returns + `t:speech_to_text_whisper_output/0`. + + This serving always accepts a single input. A list of tensors is + interpreted as continuous chunks. To transcribe multiple inputs + concurrently use `Nx.Serving.batched_run/2`. + + ## Options + + * `:chunk_num_seconds` - enables long-form transcription by splitting + the input into chunks of the given length. Models generally have + a limit on the input length, so by chunking we can feed smaller + bits into the model, then merge the individual outputs into a + single result at the end. By default chunking is disabled + + * `:context_num_seconds` - specifies the amount of overlap between + chunks on both sides of split points. The context is effectively + discarded when merging the chunks at the end, but it improves + the results at the chunk edges. Note that the context is included + in the total `:chunk_num_seconds`. Defaults to 1/6 of + `:chunk_num_seconds` + + * `:client_batch_size` - the number of input chunks the client + should gather and run at once. When streaming an input that is + already available (such as a file), you can use any value without + introducing a delay. A good default is to use the same value as + `opts[:compile][:batch_size]`. When streaming an input that is + being produced live, you may want to process chunks as soon as + they are available, in which case set this option to `1`. Defaults + to `opts[:compile][:batch_size]` if present, otherwise to `1` + + * `:language` - the language of the speech, when known upfront. + Should be given as ISO alpha-2 code as string. By default no + language is assumed and it is inferred from the input + + * `:task` - either of: + + * `:transcribe` (default) - generate audio transcription in + the same language as the speech + + * `:translate` - generate translation of the given speech in + English + + * `:timestamps` - when set, the model predicts timestamps and each + annotated segment becomes an output chunk. Currently the only + supported value is `:segments`, the length of each segment is up + to the model + + * `:compile` - compiles all computations for predefined input shapes + during serving initialization. Should be a keyword list with the + following keys: + + * `:batch_size` - the maximum batch size of the input. Inputs + are optionally padded to always match this batch size + + It is advised to set this option in production and also configure + a defn compiler using `:defn_options` to maximally reduce inference + time. + + * `:defn_options` - the options for JIT compilation. Defaults to `[]` + + * `:preallocate_params` - when `true`, explicitly allocates params + on the device configured by `:defn_options`. You may want to set + this option when using partitioned serving, to allocate params + on each of the devices. When using this option, you should first + load the parameters into the host. This can be done by passing + `backend: {EXLA.Backend, client: :host}` to `load_model/1` and friends. + Defaults to `false` + + * `:stream` - when `true`, the serving immediately returns a + stream that emits chunks as they are generated. Note that + when using streaming, only a single input can be given to the + serving. To process a batch, call the serving with each input + separately. Defaults to `false` + + ## Examples + + {:ok, whisper} = Bumblebee.load_model({:hf, "openai/whisper-tiny"}) + {:ok, featurizer} = Bumblebee.load_featurizer({:hf, "openai/whisper-tiny"}) + {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "openai/whisper-tiny"}) + {:ok, generation_config} = Bumblebee.load_generation_config({:hf, "openai/whisper-tiny"}) + + serving = + Bumblebee.Audio.speech_to_text_whisper(whisper, featurizer, tokenizer, generation_config, + defn_options: [compiler: EXLA] + ) + + output = Nx.Serving.run(serving, {:file, "/path/to/audio.wav"}) + #=> %{ + #=> chunks: [ + #=> %{ + #=> text: " There is a cat outside the window.", + #=> start_timestamp_seconds: nil, + #=> end_timestamp_seconds: nil + #=> } + #=> ] + #=> } + + text = output.chunks |> Enum.map_join(& &1.text) |> String.trim() + #=> "There is a cat outside the window." + + And with timestamps: + + serving = + Bumblebee.Audio.speech_to_text_whisper(whisper, featurizer, tokenizer, generation_config, + defn_options: [compiler: EXLA], + chunk_num_seconds: 30, + timestamps: :segments + ) + + Nx.Serving.run(serving, {:file, "/path/to/colouredstars_08_mathers_128kb.mp3"}) + #=> %{ + #=> chunks: [ + #=> %{ + #=> text: " Such an eight of colored stars, versions of fifty isiatic love poems by Edward Powis-Mathers.", + #=> start_timestamp_seconds: 0.0, + #=> end_timestamp_seconds: 7.0 + #=> }, + #=> %{ + #=> text: " This the revocs recording is in the public domain. Doubt. From the Japanese of Hori-Kawa,", + #=> start_timestamp_seconds: 7.0, + #=> end_timestamp_seconds: 14.0 + #=> }, + #=> %{ + #=> text: " will he be true to me that I do not know. But since the dawn, I have had as much disorder in my thoughts as in my black hair, and of doubt.", + #=> start_timestamp_seconds: 14.0, + #=> end_timestamp_seconds: 27.0 + #=> } + #=> ] + #=> } + + """ + @spec speech_to_text_whisper( + Bumblebee.model_info(), + Bumblebee.Featurizer.t(), + Bumblebee.Tokenizer.t(), + Bumblebee.Text.GenerationConfig.t(), + keyword() + ) :: Nx.Serving.t() + defdelegate speech_to_text_whisper( + model_info, + featurizer, + tokenizer, + generation_config, + opts \\ [] + ), + to: Bumblebee.Audio.SpeechToTextWhisper +end diff --git a/deps/bumblebee/lib/bumblebee/audio/speech_to_text_whisper.ex b/deps/bumblebee/lib/bumblebee/audio/speech_to_text_whisper.ex new file mode 100644 index 0000000000000000000000000000000000000000..e52e8ce251ed529b48d0b53a153b500dc17bf23c --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/audio/speech_to_text_whisper.ex @@ -0,0 +1,711 @@ +defmodule Bumblebee.Audio.SpeechToTextWhisper do + @moduledoc false + + alias Bumblebee.Shared + alias Bumblebee.Text + + def speech_to_text_whisper( + model_info, + featurizer, + tokenizer, + %Text.GenerationConfig{} = generation_config, + opts \\ [] + ) + when is_struct(model_info.spec, Bumblebee.Audio.Whisper) do + opts = + Keyword.validate!(opts, [ + :chunk_num_seconds, + :context_num_seconds, + :client_batch_size, + :language, + :compile, + :timestamps, + defn_options: [], + preallocate_params: false, + task: :transcribe, + stream: false + ]) + + %{model: model, params: params, spec: spec} = model_info + + Shared.validate_architecture!(spec, [:for_conditional_generation]) + + chunk_num_seconds = opts[:chunk_num_seconds] + + context_num_seconds = + opts[:context_num_seconds] || (chunk_num_seconds && chunk_num_seconds / 6) + + preallocate_params = opts[:preallocate_params] + defn_options = opts[:defn_options] + + compile = + if compile = opts[:compile] do + compile + |> Keyword.validate!([:batch_size]) + |> Shared.require_options!([:batch_size]) + end + + batch_size = compile[:batch_size] + + client_batch_size = opts[:client_batch_size] || batch_size || 1 + + sampling_rate = featurizer.sampling_rate + timestamps? = opts[:timestamps] != nil + + options = %{ + timestamps?: timestamps?, + sampling_rate: sampling_rate, + chunk_num_seconds: chunk_num_seconds, + context_num_seconds: context_num_seconds + } + + {generate_opts, generation_config} = generate_opts(generation_config, opts) + generate_fun = Text.Generation.build_generate(model, spec, generation_config, generate_opts) + + generate_fun = fn params, {inputs, seed} -> + inputs = Bumblebee.Featurizer.process_batch(featurizer, inputs) + inputs = Map.put(inputs, "seed", seed) + %{token_ids: token_ids} = generate_fun.(params, inputs) + token_ids + end + + Nx.Serving.new( + fn defn_options -> + params = Shared.maybe_preallocate(params, preallocate_params, defn_options) + + generate_fun = + Shared.compile_or_jit(generate_fun, :generate, defn_options, compile != nil, fn -> + inputs = Bumblebee.Featurizer.batch_template(featurizer, batch_size) + seed = Nx.template({batch_size}, :s64) + [params, {inputs, seed}] + end) + + fn inputs -> + inputs = Shared.maybe_pad(inputs, batch_size) + generate_fun.(params, inputs) |> Shared.serving_post_computation() + end + end, + defn_options + ) + |> Nx.Serving.batch_size(batch_size) + |> Nx.Serving.client_preprocessing(fn input -> + %{audio: audio, seed: seed} = + case validate_input(input, sampling_rate, chunk_num_seconds) do + {:ok, input} -> input + {:error, message} -> raise ArgumentError, "invalid input, #{message}" + end + + chunks = + if chunk_num_seconds do + chunk_input(audio, sampling_rate, chunk_num_seconds, context_num_seconds) + else + audio + end + + stream = + chunks + |> Stream.chunk_every(client_batch_size) + |> Stream.map(fn chunks -> + seed = + seed + |> Nx.tensor(type: :s64, backend: Nx.BinaryBackend) + |> Nx.broadcast({length(chunks)}) + + inputs = Bumblebee.Featurizer.process_input(featurizer, chunks) + Nx.Batch.concatenate([{inputs, seed}]) + end) + + {stream, {}} + end) + |> add_postprocessing(opts[:stream], spec, featurizer, tokenizer, options) + end + + defp validate_input(%{audio: audio} = input, sampling_rate, chunk_num_seconds) do + with {:ok, audio} <- parse_audio(audio, sampling_rate, chunk_num_seconds) do + {:ok, %{audio: audio, seed: input[:seed] || :erlang.system_time()}} + end + end + + defp validate_input(input, sampling_rate, chunk_num_seconds) do + validate_input(%{audio: input}, sampling_rate, chunk_num_seconds) + end + + defp parse_audio(input, sampling_rate, chunk_num_seconds) do + case input do + %Nx.Tensor{shape: {_}} = input -> + {:ok, [Nx.backend_transfer(input, Nx.BinaryBackend)]} + + {:file, path} when is_binary(path) -> + ffmpeg_read_as_pcm(path, sampling_rate) + + other -> + cond do + Enumerable.impl_for(other) == nil -> + {:error, + "expected audio to be a 1-dimensional tensor, an enumerable, or {:file, path}, got: #{inspect(other)}"} + + chunk_num_seconds == nil -> + {:error, + "enumerable input is only supported when chunking is enabled, make sure to set :chunk_num_seconds"} + + true -> + stream = + Stream.map(other, fn + %Nx.Tensor{shape: {_}} = chunk -> + Nx.backend_transfer(chunk, Nx.BinaryBackend) + + item -> + raise ArgumentError, + "expected each enumerable item to be a 1-dimensional tensor, got: #{inspect(item)}" + end) + + {:ok, stream} + end + end + end + + defp ffmpeg_read_as_pcm(path, sampling_rate) do + channels = 1 + + format = + case System.endianness() do + :little -> "f32le" + :big -> "f32be" + end + + cond do + System.find_executable("ffmpeg") == nil -> + {:error, "ffmpeg not found in PATH"} + + not File.exists?(path) -> + {:error, "no file found at #{path}"} + + true -> + # This chunk can be of arbitrary size, the serving accumulates + # and overlaps chunks internally as needed. We read the file + # as stream to reduce memory usage + chunk_size = 30 + + stream = + Stream.iterate(0, fn offset -> offset + chunk_size end) + |> Stream.transform({}, fn offset, acc -> + System.cmd( + "ffmpeg", + ~w[-ss #{offset} -t #{chunk_size} -i #{path} -ac #{channels} -ar #{sampling_rate} -f #{format} -hide_banner -loglevel quiet pipe:1] + ) + |> case do + {<<>>, 0} -> + {:halt, acc} + + {data, 0} -> + chunk = Nx.from_binary(data, :f32, backend: Nx.BinaryBackend) + {[chunk], acc} + + {_, 1} -> + raise "ffmpeg failed to decode the given file" + end + end) + + {:ok, stream} + end + end + + defp generate_opts(generation_config, opts) do + forced_token_ids = forced_token_ids(opts, generation_config.extra_config) + generation_config = %{generation_config | forced_token_ids: forced_token_ids} + + logits_processors = + if opts[:timestamps] do + [ + &Bumblebee.Text.Generation.LogitsProcessing.whisper_timestamp_processor(&1, &2, + eos_token_id: generation_config.eos_token_id, + forced_token_ids: generation_config.forced_token_ids, + no_timestamps_token_id: generation_config.extra_config.no_timestamps_token_id, + timestamp_begin_id: generation_config.extra_config.no_timestamps_token_id + 1 + ) + ] + else + [] + end + + opts = [logits_processors: logits_processors] + + {opts, generation_config} + end + + defp forced_token_ids(opts, extra_config) do + token_ids = + if language = opts[:language] do + if extra_config.task_to_token_id == %{} do + raise "the generation config does not have any languages defined." <> + " If you are dealing with a monolingual model, set :language to nil." <> + " Otherwise you may need to update generation_config.extra_config.language_to_token_id" + end + + language_token_id = extra_config.language_to_token_id[language] + + unless language_token_id do + values = + extra_config.language_to_token_id + |> Map.keys() + |> Enum.sort() + |> Enum.map_join(", ", &inspect/1) + + raise "invalid language #{inspect(language)}, expected one of: #{values}" + end + + [language_token_id] + else + [nil] + end ++ + if task = opts[:task] do + if extra_config.task_to_token_id == %{} do + raise "the generation config does not have any tasks defined." <> + " If you are dealing with a monolingual model, set :task to nil." <> + " Otherwise you may need to update generation_config.extra_config.task_to_token_id" + end + + task_token_id = extra_config.task_to_token_id[task] + + unless task_token_id do + values = + extra_config.task_to_token_id + |> Map.keys() + |> Enum.sort() + |> Enum.map_join(", ", &inspect/1) + + raise "invalid task #{inspect(task)}, expected one of: #{values}" + end + + [task_token_id] + else + [] + end ++ + if opts[:timestamps] do + [] + else + [extra_config.no_timestamps_token_id] + end + + for {token_id, idx} <- Enum.with_index(token_ids, 1), token_id, do: {idx, token_id} + end + + # Takes a stream of continous tensor chunks and produces a stream + # of overlapping chunks. As a result we get somewhat overlapping + # transcriptions, which we merge at the edges to improve the final + # transcription quality. + defp chunk_input(stream, sampling_rate, chunk_num_seconds, context_num_seconds) do + chunk_length = floor(chunk_num_seconds * sampling_rate) + context_left = floor(context_num_seconds * sampling_rate) + context_right = context_left + + step = chunk_length - context_left - context_right + + if step <= 0 do + raise ArgumentError, + ":chunk_num_seconds must be more than double the length of :context_num_seconds" + end + + Stream.transform( + stream, + fn -> + {[], 0} + end, + fn chunk, {buffer, buffer_size} -> + buffer_size = buffer_size + Nx.size(chunk) + buffer = buffer ++ [chunk] + full_chunks([], {buffer, buffer_size}, chunk_length, step) + end, + fn {buffer, buffer_size} -> + {[Nx.concatenate(buffer)], {buffer, buffer_size}} + end, + fn _ -> :ok end + ) + end + + defp full_chunks(acc, {buffer, buffer_size}, chunk_length, _step) + when chunk_length > buffer_size do + {Enum.reverse(acc), {buffer, buffer_size}} + end + + defp full_chunks(acc, {buffer, buffer_size}, chunk_length, step) do + # We take `chunk_length` samples from the buffer, but drop only + # `step`, since the rest we need for the next chunk + {subchunks1, buffer} = slice_buffer(buffer, step, []) + {subchunks2, _buffer} = slice_buffer(buffer, chunk_length - step, []) + chunk = Nx.concatenate(subchunks1 ++ subchunks2) + buffer_size = buffer_size - step + full_chunks([chunk | acc], {buffer, buffer_size}, chunk_length, step) + end + + defp slice_buffer(buffer, 0, acc), do: {Enum.reverse(acc), buffer} + + defp slice_buffer([chunk | buffer], size, acc) do + chunk_size = Nx.size(chunk) + + if chunk_size <= size do + slice_buffer(buffer, size - chunk_size, [chunk | acc]) + else + {chunk, rest} = Nx.split(chunk, size) + slice_buffer([rest | buffer], 0, [chunk | acc]) + end + end + + defp add_postprocessing(serving, false, spec, featurizer, tokenizer, options) do + Nx.Serving.client_postprocessing(serving, fn {outputs, _metadata}, {} -> + outputs = Nx.to_list(outputs) + state = decode_chunk_outputs_init(spec, featurizer, tokenizer) + {chunks, state} = decode_chunk_outputs_update(state, outputs, tokenizer, options) + {final_chunks, _state} = decode_chunk_outputs_finish(state, tokenizer, options) + chunks = chunks ++ final_chunks + Shared.normalize_output([%{chunks: chunks}], false) + end) + end + + defp add_postprocessing(serving, true, spec, featurizer, tokenizer, options) do + serving + |> Nx.Serving.streaming() + |> Nx.Serving.client_postprocessing(fn stream, {} -> + Stream.transform( + stream, + fn -> + decode_chunk_outputs_init(spec, featurizer, tokenizer) + end, + fn {:batch, outputs, _metadata}, state -> + outputs = Nx.to_list(outputs) + decode_chunk_outputs_update(state, outputs, tokenizer, options) + end, + fn state -> + decode_chunk_outputs_finish(state, tokenizer, options) + end, + fn _ -> :ok end + ) + end) + end + + # We generalize the decoding into multiple steps, where we feed a + # number of outputs at a time. When not streaming we just feed all + # outputs at once. + + defp decode_chunk_outputs_init(spec, featurizer, tokenizer) do + time_precision = featurizer.num_seconds / spec.encoder_max_positions + all_special_tokens = Bumblebee.Tokenizer.all_special_tokens(tokenizer) + timestamp_begin_id = Bumblebee.Tokenizer.token_to_id(tokenizer, "<|notimestamps|>") + 1 + + %{ + time_precision: time_precision, + all_special_tokens: all_special_tokens, + timestamp_begin_id: timestamp_begin_id, + # Accumulation state + time_offset: 0, + right_context_end_time: nil, + previous_sequences: [], + current_sequence: [], + chunks: [], + chunk: empty_chunk() + } + end + + defp decode_chunk_outputs_update(state, outputs, tokenizer, options) do + %{ + timestamps?: timestamps?, + context_num_seconds: context_num_seconds + } = options + + state = + Enum.reduce(outputs, state, fn sequence, state -> + process_output(state, sequence, tokenizer, options) + end) + + state = + cond do + # If timestamps are enabled, chunks are finished on every end + # timestamp, otherwise we need to do it explicitly + timestamps? -> + state + + # If context is enabled, we can emit chunks only once we have + # two consecutive sequences, because we need to merge their + # overlaps + context_num_seconds == nil or context_num_seconds == 0 or + at_least_2?(state.previous_sequences) -> + finish_chunk(state, tokenizer, options) + + true -> + state + end + + pop_chunks(state) + end + + defp decode_chunk_outputs_finish(state, tokenizer, options) do + # Flush any pending sequences + state = finish_chunk(state, tokenizer, options) + pop_chunks(state) + end + + defp at_least_2?([_, _ | _]), do: true + defp at_least_2?(_), do: false + + defp pop_chunks(state) do + get_and_update_in(state.chunks, fn chunks -> + {Enum.reverse(chunks), []} + end) + end + + defp process_output(state, sequence, tokenizer, options) do + %{ + timestamp_begin_id: timestamp_begin_id, + time_precision: time_precision, + all_special_tokens: all_special_tokens + } = state + + %{ + sampling_rate: sampling_rate, + chunk_num_seconds: chunk_num_seconds, + context_num_seconds: context_num_seconds + } = options + + chunk_length_seconds = + chunk_num_seconds && floor(chunk_num_seconds * sampling_rate) / sampling_rate + + context_left_seconds = + if(context_num_seconds, + do: floor(context_num_seconds * sampling_rate) / sampling_rate, + else: 0 + ) + + context_right_seconds = context_left_seconds + + context_left_seconds = if(state.time_offset == 0, do: 0, else: context_left_seconds) + + time_offset = state.time_offset - context_left_seconds + + # We want to ignore timestamps in the right and left contexts, + # because splitting on those would cause issues with merging + # chunk overlaps. Also note that for right context, if there + # are not timestamps in the right context, we ignore the last + # regular timestamp, otherwise we may not have enough tokens + # to merge chunks properly. + # + # Note that we don't know upfront whether the given chunk is the + # last one (because we support input streaming), therefore we + # always assume a non-zero right context (if enabled). However, + # we keep track of the final end time in the right context in the + # state (right_context_end_time), so once the input finishes + # and we emit the last chunk, we can mark the correct end time. + + first_timestamp = timestamp_begin_id + context_left_seconds / time_precision + + {last_timestamp, right_context_last_timestamp} = + if context_right_seconds > 0 do + right_context_start = chunk_length_seconds - context_right_seconds + + sequence + |> Enum.reverse() + |> Enum.reduce_while({nil, nil}, fn token_id, {last_timestamp, right_context_end_time} -> + if token_id >= timestamp_begin_id do + right_context_end_time = right_context_end_time || token_id + + if last_timestamp != nil and + (token_id - timestamp_begin_id) * time_precision < right_context_start do + {:halt, {last_timestamp, right_context_end_time}} + else + {:cont, {token_id, right_context_end_time}} + end + else + {:cont, {last_timestamp, right_context_end_time}} + end + end) + else + {nil, nil} + end + + right_context_end_time = + if right_context_last_timestamp do + time_offset + (right_context_last_timestamp - timestamp_begin_id) * time_precision + end + + state = + Enum.reduce(sequence, state, fn token_id, state -> + if token_id >= timestamp_begin_id do + time = (token_id - timestamp_begin_id) * time_precision + time_offset + time = Float.round(time, 2) + + cond do + last_timestamp && token_id >= last_timestamp -> + state + + # If we are continuing previously open timestamp, ignore + # timestamps within the left context + state.previous_sequences != [] and token_id < first_timestamp -> + state + + state.chunk.start_timestamp_seconds == nil -> + put_in(state.chunk.start_timestamp_seconds, time) + + state.chunk.start_timestamp_seconds == time -> + state + + true -> + state = put_in(state.chunk.end_timestamp_seconds, time) + + state + |> finish_current_sequence() + |> finish_chunk(tokenizer, options) + end + else + token = Bumblebee.Tokenizer.id_to_token(tokenizer, token_id) + + if token in all_special_tokens do + # Skip special tokens + state + else + %{state | current_sequence: [token_id | state.current_sequence]} + end + end + end) + + state = finish_current_sequence(state) + + time_offset = + if chunk_length_seconds do + time_offset + chunk_length_seconds - context_right_seconds + else + time_offset + end + + %{state | time_offset: time_offset, right_context_end_time: right_context_end_time} + end + + defp finish_current_sequence(%{current_sequence: []} = state), do: state + + defp finish_current_sequence(state) do + %{ + state + | current_sequence: [], + previous_sequences: [Enum.reverse(state.current_sequence) | state.previous_sequences] + } + end + + defp finish_chunk(%{previous_sequences: []} = state, _tokenizer, _options) do + %{state | chunk: empty_chunk()} + end + + defp finish_chunk(state, tokenizer, %{timestamps?: timestamps?}) do + sequences = Enum.reverse(state.previous_sequences) + + {token_ids, rest_token_ids} = merge_overlapping_sequences(sequences) + + # With timestamps we always finish chunks outside of context parts, + # so we know the subsequent sequence is not going to overlap with + # the chunk. Without timestamps we always need to keep the last + # sequence for the next merge + {chunk_token_ids, previous_sequences} = + if timestamps? or rest_token_ids == [] do + {token_ids ++ rest_token_ids, []} + else + {token_ids, [rest_token_ids]} + end + + text = Bumblebee.Tokenizer.decode(tokenizer, chunk_token_ids) + + state = + update_in(state.chunk, fn chunk -> + %{ + chunk + | text: text, + # We ignore timestamps in right chunk context, however once + # we get to the last chunk, the right context is no longer + # applicable, so we use the final end timestamp from the + # last right context + end_timestamp_seconds: chunk.end_timestamp_seconds || state.right_context_end_time + } + end) + + %{ + state + | previous_sequences: previous_sequences, + chunks: [state.chunk | state.chunks], + chunk: empty_chunk() + } + end + + defp empty_chunk(), do: %{start_timestamp_seconds: nil, end_timestamp_seconds: nil, text: nil} + + defp merge_overlapping_sequences([sequence]), do: {sequence, []} + + defp merge_overlapping_sequences(sequences) do + # We have a number of consecutive, overlapping sequences and we + # want to merge them into a single sequence. To merge a pair of + # consecutive sequences we slide the sequences and compare the + # overlap: + # + # abcd (left) + # cde (right) + # => compare c = d + # + # abcd (left) + # cde (right) + # => compare cd = cd + # + # We find the best alignment, then cut the overlap in half and + # concatenate the left an right part accordingly. In the example + # above, we would use the second alignment, taking `abc` from the + # left sequence and `de` from the right one. + + # We use binary backend so we are not blocked by the serving computation, + # in this case we do simple operations with small data so it is fine + sequences = Enum.map(sequences, &Nx.tensor(&1, backend: Nx.BinaryBackend)) + + {[left_sequence], right_sequences} = Enum.split(sequences, 1) + + {acc, left_sequence} = + for right_sequence <- right_sequences, reduce: {[], left_sequence} do + {acc, left_sequence} -> + left_length = Nx.size(left_sequence) + right_length = Nx.size(right_sequence) + + {_max_match_score, overlap_indices} = + for i <- 1..(left_length + right_length - 1), + reduce: {0.0, {left_length, left_length, 0, 0}} do + {max_match_score, overlap_indices} -> + left_start = max(0, left_length - i) + left_stop = min(left_length, left_length + right_length - i) + left_overlap = left_sequence[left_start..(left_stop - 1)] + + right_start = max(0, i - left_length) + right_stop = min(right_length, i) + right_overlap = right_sequence[right_start..(right_stop - 1)] + + num_matches = Nx.equal(left_overlap, right_overlap) |> Nx.sum() |> Nx.to_number() + + # Epsilon to favor long perfect matches + eps = i / 10000.0 + match_score = num_matches / i + eps + + if num_matches > 1 and match_score > max_match_score do + overlap_indices = {left_start, left_stop, right_start, right_stop} + {match_score, overlap_indices} + else + {max_match_score, overlap_indices} + end + end + + # Cut in the middle of the overlap + {left_start, left_stop, right_start, right_stop} = overlap_indices + left_mid = div(left_stop + left_start, 2) + right_mid = div(right_stop + right_start, 2) + {[left_sequence[0..(left_mid - 1)] | acc], right_sequence[right_mid..-1//1]} + end + + merged_sequence = + Enum.reduce(acc, [], fn sequence, acc -> + Nx.to_flat_list(sequence) ++ acc + end) + + rest = Nx.to_flat_list(left_sequence) + + {merged_sequence, rest} + end +end diff --git a/deps/bumblebee/lib/bumblebee/audio/whisper.ex b/deps/bumblebee/lib/bumblebee/audio/whisper.ex new file mode 100644 index 0000000000000000000000000000000000000000..9b78c29d7e439eac34d9c14dc4856e296d252d27 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/audio/whisper.ex @@ -0,0 +1,578 @@ +defmodule Bumblebee.Audio.Whisper do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 51865, + doc: """ + the vocabulary size of the model. This corresponds to the number of distinct + tokens that can be represented by the decoder + """ + ], + feature_size: [ + default: 80, + doc: """ + the dimensionality of the input features. This corresponds to the number of Mel + bins in the preprocessed input + """ + ], + encoder_max_positions: [ + default: 1500, + doc: """ + the vocabulary size of the encoder position embedding. This corresponds to the maximum + sequence length of log-mel filter-bank features that the model can process + """ + ], + decoder_max_positions: [ + default: 448, + doc: """ + the vocabulary size of the decoder position embedding. This corresponds to the maximum + sequence length that this model can generate. Typically this is set to a large value just + in case, such as 512, 1024 or 2048 + """ + ], + hidden_size: [ + default: 1024, + doc: "the dimensionality of hidden layers" + ], + encoder_num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the encoder" + ], + decoder_num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the decoder" + ], + encoder_num_attention_heads: [ + default: 16, + doc: "the number of attention heads for each attention layer in the encoder" + ], + decoder_num_attention_heads: [ + default: 16, + doc: "the number of attention heads for each attention layer in the decoder" + ], + encoder_intermediate_size: [ + default: 4096, + docs: + "the dimensionality of the intermediate (often named feed-forward) layer in the encoder" + ], + decoder_intermediate_size: [ + default: 4096, + docs: + "the dimensionality of the intermediate (often named feed-forward) layer in the decoder" + ], + activation: [ + default: :gelu, + doc: "the activation function" + ], + dropout_rate: [ + default: 0.1, + doc: "the dropout rate for encoder and decoder" + ], + attention_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for attention weights" + ], + activation_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for activations inside fully connected layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] + + @moduledoc """ + Whisper model family. + + ## Architectures + + * `:base` - plain Whisper without any head on top + + * `:for_conditional_generation` - Whisper with a language modeling + head. The head returns logits for each token in the original + sequence + + ## Inputs + + * `"input_features"` - `{batch_size, input_length, feature_size}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_head_mask"` - `{num_blocks, num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + * `"input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"input_features"`, which can be specified + for more control over how `"input_features"` are embedded than the + model's internal embedding lookup. If `"input_embeddings"` are present, + then `"input_features"` will be ignored. + + * `"decoder_input_ids"` - `{batch_size, target_sequence_length}` + + Indices of decoder input sequence tokens in the vocabulary. + + * `"decoder_attention_mask"` - `{batch_size, target_sequence_length}` + + Mask indicating which decoder tokens to attend to. This is used + to ignore padding tokens, which are added when processing a batch + of sequences with different length. + + * `"decoder_attention_head_mask"` - `{decoder_num_blocks, decoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the decoder. + + * `"decoder_input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"decoder_input_ids"`, which can be + specified for more control over how `"decoder_input_ids"` are + embedded than the model's internal embedding lookup. If + `"decoder_input_embeddings"` are present, then `"decoder_input_ids"` + will be ignored. + + * `"encoder_hidden_state"` - `{batch_size, sequence_length, hidden_size}` + + Last hidden state output from the encoder. This hidden state is + used in cross-attention blocks in the decoder. If specified, the + model will skip the encoding process and use this value directly + for cross-attentions in the decoder. + + * `"cross_attention_head_mask"` - `{decoder_num_blocks, decoder_num_attention_heads}` + + Mask to nullify selected heads of the cross-attention blocks in + the decoder with shape. + + * `"cache"` + + A container with cached layer results used to speed up sequential + decoding (autoregression). With cache, certain hidden states are + taken from the cache, rather than recomputed on every decoding + pass. The cache should be treated as opaque and initialized with + `Bumblebee.Text.Generation.init_cache/4`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), do: [:base, :for_conditional_generation] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + end + + @impl true + def input_template(spec) do + input_length = 2 * spec.encoder_max_positions + + %{ + "input_features" => Nx.template({1, input_length, spec.feature_size}, :f32), + "decoder_input_ids" => Nx.template({1, 1}, :u32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_conditional_generation} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + Layers.dense_transposed(outputs.hidden_state, spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: "language_modeling_head.output" + ) + + Layers.output(%{ + logits: logits, + decoder_hidden_states: outputs.decoder_hidden_states, + decoder_attentions: outputs.decoder_attentions, + cross_attentions: outputs.cross_attentions, + encoder_hidden_state: outputs.encoder_hidden_state, + encoder_hidden_states: outputs.encoder_hidden_states, + encoder_attentions: outputs.encoder_attentions, + cache: outputs.cache + }) + end + + @impl true + def init_cache(spec, batch_size, max_length, inputs) do + encoder_sequence_length = + if encoder_hidden_state = inputs["encoder_hidden_state"] do + Nx.axis_size(encoder_hidden_state, 1) + end + + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + decoder_num_attention_heads: spec.decoder_num_attention_heads, + encoder_num_attention_heads: spec.encoder_num_attention_heads, + decoder_num_blocks: spec.decoder_num_blocks, + encoder_sequence_length: encoder_sequence_length + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + @impl true + def extra_config_module(_spec), do: Bumblebee.Text.WhisperGenerationConfig + + defp inputs(spec) do + input_length = 2 * spec.encoder_max_positions + + encoder_input_shape = {nil, input_length, spec.feature_size} + decoder_input_shape = {nil, nil} + + encoder_attention_head_mask_shape = + {spec.encoder_num_blocks, spec.encoder_num_attention_heads} + + decoder_attention_head_mask_shape = + {spec.decoder_num_blocks, spec.decoder_num_attention_heads} + + hidden_shape = {nil, nil, spec.hidden_size} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_features", optional: true, shape: encoder_input_shape), + Axon.input("attention_head_mask", optional: true, shape: encoder_attention_head_mask_shape), + Axon.input("input_embeddings", optional: true, shape: hidden_shape), + Axon.input("decoder_input_ids", optional: true, shape: decoder_input_shape), + Axon.input("decoder_attention_mask", optional: true, shape: decoder_input_shape), + Axon.input("decoder_attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("decoder_input_embeddings", optional: true, shape: hidden_shape), + Axon.input("encoder_hidden_state", optional: true, shape: hidden_shape), + Axon.input("cross_attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("cache", optional: true) + ]) + end + + defp core(inputs, spec) do + encoder_outputs = + Layers.if_present inputs["encoder_hidden_state"] do + %{ + hidden_state: inputs["encoder_hidden_state"], + hidden_states: Layers.none(), + attentions: Layers.none() + } + else + embeddings = + encoder_embedder(inputs["input_features"], inputs["input_embeddings"], spec, + name: "encoder_embedder" + ) + + embeddings + |> encoder(inputs["attention_head_mask"], spec, name: "encoder") + |> Map.take([:hidden_state, :hidden_states, :attentions]) + end + + embeddings = + decoder_embedder( + inputs["decoder_input_ids"], + inputs["decoder_input_embeddings"], + inputs["cache"], + spec, + name: "decoder_embedder" + ) + + decoder_outputs = + decoder( + embeddings, + inputs["decoder_attention_mask"], + inputs["decoder_attention_head_mask"], + encoder_outputs.hidden_state, + inputs["cross_attention_head_mask"], + inputs["cache"], + spec, + name: "decoder" + ) + + %{ + hidden_state: decoder_outputs.hidden_state, + decoder_hidden_states: decoder_outputs.hidden_states, + decoder_attentions: decoder_outputs.attentions, + cross_attentions: decoder_outputs.cross_attentions, + cache: decoder_outputs.cache, + encoder_hidden_state: encoder_outputs.hidden_state, + encoder_hidden_states: encoder_outputs.hidden_states, + encoder_attentions: encoder_outputs.attentions + } + end + + defp encoder_embedder(input_features, input_embedding, spec, opts) do + name = opts[:name] + + input_embeddings = + Layers.default input_embedding do + feature_embedding(input_features, spec, name: join(name, "feature_embedding")) + end + + position_embeddings = + Layers.learned_embeddings(spec.encoder_max_positions, spec.hidden_size, + name: join(name, "position_embedding") + ) + + Axon.add([input_embeddings, position_embeddings]) + |> Axon.dropout(rate: spec.dropout_rate) + end + + defp feature_embedding(input_features, spec, opts) do + name = opts[:name] + + input_features + |> Axon.conv(spec.hidden_size, + kernel_size: 3, + padding: [{1, 1}], + name: join(name, "conv_1") + ) + |> Axon.gelu() + |> Axon.conv(spec.hidden_size, + kernel_size: 3, + strides: [2], + padding: [{1, 1}], + name: join(name, "conv_2") + ) + |> Axon.gelu() + end + + defp decoder_embedder(input_ids, input_embeddings, cache, spec, opts) do + name = opts[:name] + + input_embeddings = + Layers.default input_embeddings do + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + name: join(name, "token_embedding") + ) + end + + position_embeddings = + Layers.learned_embeddings(spec.decoder_max_positions, spec.hidden_size, + name: join(name, "position_embedding") + ) + + offset = Layers.Decoder.get_cache_offset(cache) + + # We use learned position embeddings for the maximum sequence + # length, so to add them to the given input embeddings we need + # to slice accordingly + embeddings = + Axon.layer( + fn input_embeddings, position_embeddings, offset, _opts -> + offset = + case offset do + %Axon.None{} -> 0 + offset -> offset + end + + input_sequence_length = Nx.axis_size(input_embeddings, 1) + + position_embeddings = + Nx.slice_along_axis(position_embeddings, offset, input_sequence_length, axis: 1) + + Nx.add(input_embeddings, position_embeddings) + end, + [input_embeddings, position_embeddings, Axon.optional(offset)] + ) + + embeddings + |> Axon.dropout(rate: spec.dropout_rate) + end + + defp encoder(hidden_state, attention_head_mask, spec, opts) do + name = opts[:name] + + outputs = + Layers.Transformer.blocks(hidden_state, + attention_head_mask: attention_head_mask, + num_blocks: spec.encoder_num_blocks, + num_attention_heads: spec.encoder_num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + key_use_bias: false, + layer_norm: [ + epsilon: 1.0e-5 + ], + ffn: [ + intermediate_size: spec.encoder_intermediate_size, + activation: spec.activation + ], + block_type: :norm_first, + name: join(name, "blocks") + ) + + hidden_state = Axon.layer_norm(outputs.hidden_state, name: join(name, "norm")) + + %{ + outputs + | hidden_state: hidden_state, + hidden_states: Layers.append(outputs.hidden_states, hidden_state) + } + end + + defp decoder( + hidden_state, + attention_mask, + attention_head_mask, + encoder_hidden_state, + cross_attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + + outputs = + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + cross_hidden_state: encoder_hidden_state, + cross_attention_head_mask: cross_attention_head_mask, + cache: cache, + causal: true, + num_blocks: spec.decoder_num_blocks, + num_attention_heads: spec.decoder_num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + key_use_bias: false, + layer_norm: [ + epsilon: 1.0e-5 + ], + ffn: [ + intermediate_size: spec.decoder_intermediate_size, + activation: spec.activation + ], + block_type: :norm_first, + name: join(name, "blocks") + ) + + hidden_state = Axon.layer_norm(outputs.hidden_state, name: join(name, "norm")) + + %{ + outputs + | hidden_state: hidden_state, + hidden_states: Layers.append(outputs.hidden_states, hidden_state) + } + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + hidden_size: {"d_model", number()}, + feature_size: {"num_mel_bins", number()}, + encoder_max_positions: {"max_source_positions", number()}, + decoder_max_positions: {"max_target_positions", number()}, + encoder_num_blocks: {"encoder_layers", number()}, + decoder_num_blocks: {"decoder_layers", number()}, + encoder_num_attention_heads: {"encoder_attention_heads", number()}, + decoder_num_attention_heads: {"decoder_attention_heads", number()}, + encoder_intermediate_size: {"encoder_ffn_dim", number()}, + decoder_intermediate_size: {"decoder_ffn_dim", number()}, + activation: {"activation_function", activation()}, + dropout_rate: {"dropout", number()}, + attention_dropout_rate: {"attention_dropout", number()}, + activation_dropout_rate: {"activation_dropout", number()}, + initializer_scale: {"init_std", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "encoder_embedder.feature_embedding.conv_1" => "model.encoder.conv1", + "encoder_embedder.feature_embedding.conv_2" => "model.encoder.conv2", + "encoder_embedder.position_embedding" => %{ + "embeddings" => {[{"model.encoder.embed_positions", "weight"}], fn [value] -> value end} + }, + "encoder.blocks.{n}.self_attention.query" => "model.encoder.layers.{n}.self_attn.q_proj", + "encoder.blocks.{n}.self_attention.key" => "model.encoder.layers.{n}.self_attn.k_proj", + "encoder.blocks.{n}.self_attention.value" => "model.encoder.layers.{n}.self_attn.v_proj", + "encoder.blocks.{n}.self_attention.output" => + "model.encoder.layers.{n}.self_attn.out_proj", + "encoder.blocks.{n}.self_attention_norm" => + "model.encoder.layers.{n}.self_attn_layer_norm", + "encoder.blocks.{n}.ffn.intermediate" => "model.encoder.layers.{n}.fc1", + "encoder.blocks.{n}.ffn.output" => "model.encoder.layers.{n}.fc2", + "encoder.blocks.{n}.output_norm" => "model.encoder.layers.{n}.final_layer_norm", + "encoder.norm" => "model.encoder.layer_norm", + "decoder_embedder.token_embedding" => "model.decoder.embed_tokens", + "decoder_embedder.position_embedding" => %{ + "embeddings" => {[{"model.decoder.embed_positions", "weight"}], fn [value] -> value end} + }, + "decoder.blocks.{n}.self_attention.query" => "model.decoder.layers.{n}.self_attn.q_proj", + "decoder.blocks.{n}.self_attention.key" => "model.decoder.layers.{n}.self_attn.k_proj", + "decoder.blocks.{n}.self_attention.value" => "model.decoder.layers.{n}.self_attn.v_proj", + "decoder.blocks.{n}.self_attention.output" => + "model.decoder.layers.{n}.self_attn.out_proj", + "decoder.blocks.{n}.self_attention_norm" => + "model.decoder.layers.{n}.self_attn_layer_norm", + "decoder.blocks.{n}.cross_attention.query" => + "model.decoder.layers.{n}.encoder_attn.q_proj", + "decoder.blocks.{n}.cross_attention.key" => + "model.decoder.layers.{n}.encoder_attn.k_proj", + "decoder.blocks.{n}.cross_attention.value" => + "model.decoder.layers.{n}.encoder_attn.v_proj", + "decoder.blocks.{n}.cross_attention.output" => + "model.decoder.layers.{n}.encoder_attn.out_proj", + "decoder.blocks.{n}.cross_attention_norm" => + "model.decoder.layers.{n}.encoder_attn_layer_norm", + "decoder.blocks.{n}.ffn.intermediate" => "model.decoder.layers.{n}.fc1", + "decoder.blocks.{n}.ffn.output" => "model.decoder.layers.{n}.fc2", + "decoder.blocks.{n}.output_norm" => "model.decoder.layers.{n}.final_layer_norm", + "decoder.norm" => "model.decoder.layer_norm", + "language_modeling_head.output" => "model.decoder.embed_tokens" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/audio/whisper_featurizer.ex b/deps/bumblebee/lib/bumblebee/audio/whisper_featurizer.ex new file mode 100644 index 0000000000000000000000000000000000000000..e088d91958b251773b7b4e9945ada39e65c5083a --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/audio/whisper_featurizer.ex @@ -0,0 +1,140 @@ +defmodule Bumblebee.Audio.WhisperFeaturizer do + alias Bumblebee.Shared + + import Nx.Defn + + options = [ + feature_size: [ + default: 80, + doc: "the dimension of the extracted features. This corresponds to the number of Mel bins" + ], + sampling_rate: [ + default: 16_000, + doc: "the sampling rate at which the audio files should be digitally expressed in Hertz" + ], + num_seconds: [ + default: 30, + doc: """ + the maximum duration of the audio sequence. This implies that the maximum length of the + input sequence is `:num_seconds` * `:sampling_rate` + """ + ], + hop_length: [ + default: 160, + doc: + "the hop between consecutive overlapping windows for the STFT used to obtain Mel Frequency coefficients" + ], + fft_length: [ + default: 400, + doc: "the size of the fourier transform" + ], + padding_value: [ + default: 0.0, + doc: "the value used to pad the audio. Should correspond to silence" + ] + ] + + @moduledoc """ + Whisper featurizer for audio data. + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct Shared.option_defaults(options) + + @behaviour Bumblebee.Featurizer + @behaviour Bumblebee.Configurable + + @impl true + def config(featurizer, opts) do + Shared.put_config_attrs(featurizer, opts) + end + + @impl true + def process_input(featurizer, raw_samples) do + max_length = featurizer.num_seconds * featurizer.sampling_rate + + samples = + for sample <- List.wrap(raw_samples) do + unless Nx.rank(sample) == 1 do + raise ArgumentError, + "expected sample to be a 1-rank tensor, got: #{Nx.rank(sample)}-rank" + end + + pad_size = max_length - Nx.axis_size(sample, 0) + Nx.pad(sample, featurizer.padding_value, [{0, pad_size, 0}]) + end + + Nx.stack(samples) + end + + @impl true + def batch_template(featurizer, batch_size) do + max_length = featurizer.num_seconds * featurizer.sampling_rate + Nx.template({batch_size, max_length}, :f32) + end + + @impl true + def process_batch(featurizer, samples) do + samples = + samples + |> Nx.vectorize(:batch) + |> extract_fbank_features( + fft_length: featurizer.fft_length, + sampling_rate: featurizer.sampling_rate, + mel_bins: featurizer.feature_size, + hop_length: featurizer.hop_length + ) + |> Nx.devectorize() + + %{"input_features" => samples} + end + + defnp extract_fbank_features(waveform, opts \\ []) do + opts = keyword!(opts, [:fft_length, :sampling_rate, :mel_bins, :hop_length]) + + window = NxSignal.Windows.hann(n: opts[:fft_length], is_periodic: true) + + {stft, _, _} = + NxSignal.stft(waveform, window, + sampling_rate: opts[:sampling_rate], + fft_length: opts[:fft_length], + overlap_length: opts[:fft_length] - opts[:hop_length], + window_padding: :reflect + ) + + stft = stft[0..-2//1] + + # Magic numbers taken from the reference implementation. This yields + # max_mel ~ 3016 + frequency_spacing = 200.0 / 3 + max_mel = frequency_spacing * 45.245640471924965 + + NxSignal.stft_to_mel(stft, opts[:sampling_rate], + fft_length: opts[:fft_length], + mel_bins: opts[:mel_bins], + max_mel: max_mel, + mel_frequency_spacing: frequency_spacing + ) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(featurizer, data) do + import Shared.Converters + + opts = + convert!(data, + feature_size: {"feature_size", number()}, + sampling_rate: {"sampling_rate", number()}, + hop_length: {"hop_length", number()}, + num_seconds: {"chunk_length", number()}, + fft_length: {"n_fft", number()}, + padding_value: {"padding_value", number()} + ) + + @for.config(featurizer, opts) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/configurable.ex b/deps/bumblebee/lib/bumblebee/configurable.ex new file mode 100644 index 0000000000000000000000000000000000000000..cf7804e3fd8ce54332384fbaa97efe965359805c --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/configurable.ex @@ -0,0 +1,15 @@ +defmodule Bumblebee.Configurable do + @moduledoc """ + An interface for configurable entities. + + A module implementing this behaviour is expected to define a struct + with configuration. + """ + + @type t :: struct() + + @doc """ + Configures the struct. + """ + @callback config(t(), keyword()) :: t() +end diff --git a/deps/bumblebee/lib/bumblebee/conversion/pytorch_loader.ex b/deps/bumblebee/lib/bumblebee/conversion/pytorch_loader.ex new file mode 100644 index 0000000000000000000000000000000000000000..97ebb2d9035bba4dcc8be31e04fa90eeddda5c49 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/conversion/pytorch_loader.ex @@ -0,0 +1,294 @@ +defmodule Bumblebee.Conversion.PyTorchLoader do + @moduledoc false + + @doc """ + Loads data saved using [`torch.save`](https://pytorch.org/docs/stable/generated/torch.save.html). + + PyTorch tensors are automatically deserialized as Nx tensors. + + This function supports both the current zip-based file format and + the legacy format. + """ + @spec load!(Path.t()) :: term() + def load!(path) do + # See https://github.com/pytorch/pytorch/blob/v1.11.0/torch/serialization.py#L607 + + if zip?(path) do + load_zip!(path) + else + load_legacy!(path) + end + end + + defp zip?(path) do + # Check for the "local file header signature" + File.open(path, [:read], &IO.binread(&1, 4)) == {:ok, <<80, 75, 3, 4>>} + end + + defp load_zip!(path) do + open_zip!(path, fn unzip -> + file_name_map = + unzip + |> Unzip.list_entries() + |> Map.new(fn %Unzip.Entry{file_name: file_name} -> + # Strip the root dir from the file name + name = file_name |> Path.split() |> Enum.drop(1) |> Enum.join("/") + {name, file_name} + end) + + binary = read_zip_file(unzip, Map.fetch!(file_name_map, "data.pkl")) + + {term, ""} = + Unpickler.load!(binary, + object_resolver: &object_resolver/1, + persistent_id_resolver: fn + {"storage", storage_type, key, _location, _size} -> + file_name = Map.fetch!(file_name_map, "data/#{key}") + {:storage, storage_type, {:zip, path, file_name}} + end + ) + + term + end) + end + + @doc false + def open_zip!(path, fun) do + zip_file = Unzip.LocalFile.open(path) + + try do + {:ok, unzip} = Unzip.new(zip_file) + fun.(unzip) + after + Unzip.LocalFile.close(zip_file) + end + end + + @doc false + def read_zip_file(unzip, file_name) do + unzip + |> Unzip.file_stream!(file_name) + |> Enum.to_list() + |> IO.iodata_to_binary() + end + + defp object_resolver(%{constructor: "collections.OrderedDict", set_items: items}) do + {:ok, Map.new(items)} + end + + # See https://github.com/pytorch/pytorch/blob/v1.11.0/torch/_tensor.py#L271-L280 + defp object_resolver(%{ + constructor: "torch._utils._rebuild_tensor_v2", + args: [storage, offset, shape, strides, _requires_grad, _backward_hooks] + }) do + {:storage, storage_type, storage} = storage + type = storage_type_to_nx(storage_type) + + lazy_tensor = %Bumblebee.Conversion.PyTorchLoader.FileTensor{ + shape: shape, + type: type, + offset: offset, + strides: strides, + storage: storage + } + + {:ok, lazy_tensor} + end + + # See https://github.com/pytorch/pytorch/blob/v1.12.1/torch/_tensor.py#L222-L226 + defp object_resolver(%{ + constructor: "torch._utils._rebuild_device_tensor_from_numpy", + args: [numpy_array, _type, _device, _requires_grad] + }) do + # Tensors on certain devices are serialized as numpy arrays + {:ok, numpy_array} + end + + # See https://github.com/numpy/numpy/blob/v1.23.3/numpy/core/src/multiarray/descriptor.c#L2506-L2508 + defp object_resolver(%{constructor: "numpy.dtype", args: [type, false = _align, true = _copy]}) do + {:ok, numpy_type_to_nx(type)} + end + + # See https://github.com/numpy/numpy/blob/v1.23.3/numpy/core/src/multiarray/methods.c#L2009-L2014 + defp object_resolver(%{ + constructor: "numpy.core.multiarray._reconstruct", + state: {_version, shape, type, fortran_order?, data} + }) do + tensor = + if fortran_order? do + # In Fortran order the axes are reversed in memory + shape = + shape + |> Tuple.to_list() + |> Enum.reverse() + |> List.to_tuple() + + data |> Nx.from_binary(type) |> Nx.reshape(shape) |> Nx.transpose() + else + data |> Nx.from_binary(type) |> Nx.reshape(shape) + end + + {:ok, tensor} + end + + defp object_resolver(_object), do: :error + + defp storage_type_to_nx(%Unpickler.Global{scope: "torch", name: name}) do + # See https://github.com/pytorch/pytorch/blob/v1.11.0/torch/storage.py#L189-L208 + mapping = %{ + "DoubleStorage" => {:f, 64}, + "FloatStorage" => {:f, 32}, + "HalfStorage" => {:f, 16}, + "LongStorage" => {:s, 64}, + "IntStorage" => {:s, 32}, + "ShortStorage" => {:s, 16}, + "CharStorage" => {:s, 8}, + "ByteStorage" => {:u, 8}, + "BoolStorage" => {:u, 8}, + "BFloat16Storage" => {:bf, 16}, + "ComplexDoubleStorage" => {:c, 128}, + "ComplexFloatStorage" => {:c, 64} + } + + if type = mapping[name] do + type + else + raise "unsupported PyTorch storage type: #{inspect(name)}" + end + end + + defp numpy_type_to_nx(name) do + # See https://numpy.org/doc/stable/reference/generated/numpy.dtype.kind.html#numpy-dtype-kind + mapping = %{ + "b1" => {:u, 8}, + "i1" => {:s, 8}, + "i2" => {:s, 16}, + "i4" => {:s, 32}, + "i8" => {:s, 64}, + "u1" => {:u, 8}, + "u2" => {:u, 16}, + "u4" => {:u, 32}, + "u8" => {:u, 64}, + "f2" => {:f, 16}, + "f4" => {:f, 32}, + "f8" => {:f, 64}, + "c8" => {:c, 64}, + "c16" => {:c, 128} + } + + if type = mapping[name] do + type + else + raise "unsupported NumPy data type: #{inspect(name)}" + end + end + + @legacy_magic_number 119_547_037_146_038_801_333_356 + + defp load_legacy!(path) do + data = File.read!(path) + full_size = byte_size(data) + + {@legacy_magic_number, data} = Unpickler.load!(data) + {_protocol_version, data} = Unpickler.load!(data) + {_system_info, data} = Unpickler.load!(data) + + binaries = storage_binaries(data, full_size) + + {term, _} = + Unpickler.load!(data, + object_resolver: &object_resolver/1, + persistent_id_resolver: fn + {"storage", storage_type, root_key, _location, _size, view_metadata} -> + {_, bit_unit} = storage_type_to_nx(storage_type) + byte_unit = div(bit_unit, 8) + + {file_offset, size} = Map.fetch!(binaries, root_key) + + storage = + case view_metadata do + nil -> + {:file, path, file_offset, size} + + {_view_key, offset, view_size} -> + {:file, path, file_offset + offset * byte_unit, view_size * byte_unit} + end + + {:storage, storage_type, storage} + + {"module", module, _source_file, _source} -> + module + end + ) + + term + end + + defp storage_binaries(data, full_size) do + # We first do a dry run on the pickle and extract storage metadata, + # then we use that metadata to read the storage binaries that follow + + {term, data} = + Unpickler.load!(data, + persistent_id_resolver: fn + {"storage", storage_type, root_key, _location, size, _view_metadata} -> + {_, bit_unit} = storage_type_to_nx(storage_type) + byte_unit = div(bit_unit, 8) + {:storage_info, root_key, {size, byte_unit}} + + _other -> + nil + end + ) + + storage_infos = collect_storage_infos(term, %{}) + + {storage_keys, data} = Unpickler.load!(data) + + offset = full_size - byte_size(data) + + {pairs, _offset} = + Enum.map_reduce(storage_keys, offset, fn key, offset -> + {size, byte_unit} = Map.fetch!(storage_infos, key) + bytes = size * byte_unit + + # Each storage binary is prefixed with the number of elements, + # stored as integer-little-signed-size(64), hence the 8 bytes. + # See https://github.com/pytorch/pytorch/blob/v1.11.0/torch/csrc/generic/serialization.cpp#L93-L134 + start_offset = offset + 8 + offset = start_offset + bytes + + {{key, {start_offset, bytes}}, offset} + end) + + Map.new(pairs) + end + + defp collect_storage_infos({:storage_info, key, meta}, storage_infos) do + Map.put(storage_infos, key, meta) + end + + defp collect_storage_infos(list, storages) when is_list(list) do + Enum.reduce(list, storages, &collect_storage_infos/2) + end + + defp collect_storage_infos(%MapSet{} = set, storages) do + Enum.reduce(set, storages, &collect_storage_infos/2) + end + + defp collect_storage_infos(%_{} = struct, storages) do + struct |> Map.values() |> collect_storage_infos(storages) + end + + defp collect_storage_infos(%{} = map, storages) do + Enum.reduce(map, storages, &collect_storage_infos/2) + end + + defp collect_storage_infos(tuple, storages) when is_tuple(tuple) do + tuple |> Tuple.to_list() |> collect_storage_infos(storages) + end + + defp collect_storage_infos(_term, storages) do + storages + end +end diff --git a/deps/bumblebee/lib/bumblebee/conversion/pytorch_loader/file_tensor.ex b/deps/bumblebee/lib/bumblebee/conversion/pytorch_loader/file_tensor.ex new file mode 100644 index 0000000000000000000000000000000000000000..1ae84008798fae5dad639650c2a6acea70f3600e --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/conversion/pytorch_loader/file_tensor.ex @@ -0,0 +1,76 @@ +defmodule Bumblebee.Conversion.PyTorchLoader.FileTensor do + @moduledoc false + + defstruct [:shape, :type, :offset, :strides, :storage] +end + +defimpl Nx.LazyContainer, for: Bumblebee.Conversion.PyTorchLoader.FileTensor do + alias Bumblebee.Conversion.PyTorchLoader + + def traverse(lazy_tensor, acc, fun) do + template = Nx.template(lazy_tensor.shape, lazy_tensor.type) + + load = fn -> + binary = + case lazy_tensor.storage do + {:zip, path, file_name} -> + PyTorchLoader.open_zip!(path, fn unzip -> + PyTorchLoader.read_zip_file(unzip, file_name) + end) + + {:file, path, offset, size} -> + File.open!(path, [:read, :raw], fn file -> + {:ok, binary} = :file.pread(file, offset, size) + binary + end) + end + + %{offset: offset, shape: shape, type: type, strides: strides} = lazy_tensor + + {_, bit_unit} = type + byte_unit = div(bit_unit, 8) + size = Tuple.product(shape) + binary = binary_part(binary, offset * byte_unit, size * byte_unit) + binary |> Nx.from_binary(type) |> to_contiguous(shape, strides) + end + + fun.(template, load, acc) + end + + defp to_contiguous(tensor, shape, strides) do + # PyTorch tensors may not be contiguous in memory, so strides are + # used to indicate jumps necessary when traversing each axis. + # Since Nx doesn't have the notion of strides, we transpose the + # tensor, in a way that makes it contiguous, which is equivalent + # to strides being decreasing + + memory_axes_order = + strides + |> Tuple.to_list() + |> Enum.with_index() + |> Enum.sort_by(&elem(&1, 0), :desc) + |> Enum.map(&elem(&1, 1)) + + if memory_axes_order == Nx.axes(shape) do + Nx.reshape(tensor, shape) + else + memory_shape = + memory_axes_order + |> Enum.map(fn axis -> elem(shape, axis) end) + |> List.to_tuple() + + tensor + |> Nx.reshape(memory_shape) + |> Nx.transpose(axes: inverse_permutation(memory_axes_order)) + end + end + + defp inverse_permutation(list) do + list + |> Enum.with_index() + |> Enum.reduce(List.to_tuple(list), fn {src_idx, dest_idx}, inverse -> + put_elem(inverse, src_idx, dest_idx) + end) + |> Tuple.to_list() + end +end diff --git a/deps/bumblebee/lib/bumblebee/conversion/pytorch_params.ex b/deps/bumblebee/lib/bumblebee/conversion/pytorch_params.ex new file mode 100644 index 0000000000000000000000000000000000000000..88fe3ef24d1f37f2e0b361e8f3d75e0b9a8dfdb1 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/conversion/pytorch_params.ex @@ -0,0 +1,523 @@ +defmodule Bumblebee.Conversion.PyTorchParams do + @moduledoc false + + require Logger + + alias Bumblebee.Utils + + @doc """ + Loads parameters from a PyTorch model state dictionary. + + This function expects files created with `torch.save(model.state_dict(), path)`, + as described in [the documentation](https://pytorch.org/tutorials/beginner/saving_loading_models.html). + + ## Options + + * `:log_params_diff` - whether to log missing, mismatched and unused + parameters. By default diff is logged only if some parameters + cannot be loaded + + * `:backend` - the backend to allocate the tensors on. It is either + an atom or a tuple in the shape `{backend, options}` + + * `:params_mapping` - a map describing layers and params relationship + between the Axon model and the PyTorch state. For more details see + `Bumblebee.HuggingFace.Transformers.Model.params_mapping/1` + + * `:loader_fun` - a 1-arity function that takes a path argument + and loads the params file. Defaults to + `Bumblebee.Conversion.PyTorchLoader.load!/1` + + """ + @spec load_params!(Axon.t(), map(), Path.t() | list(Path.t()), keyword()) :: %Axon.ModelState{} + def load_params!(model, input_template, path, opts \\ []) do + opts = + opts + |> Keyword.validate!([ + :log_params_diff, + :backend, + params_mapping: %{}, + loader_fun: &Bumblebee.Conversion.PyTorchLoader.load!/1 + ]) + + with_default_backend(opts[:backend], fn -> + pytorch_state = + path + |> List.wrap() + |> Enum.map(fn path -> + pytorch_state = opts[:loader_fun].(path) + + unless state_dict?(pytorch_state) do + raise "expected a serialized model state dictionary at #{path}, but got: #{inspect(pytorch_state)}" + end + + pytorch_state + end) + |> Enum.reduce(&Map.merge/2) + + model_state = Axon.trace_init(model, input_template) + + params_expr = model_state.data + {params, diff} = init_params(model, params_expr, pytorch_state, opts[:params_mapping]) + model_state = %{model_state | data: params} + + params_complete? = diff.missing == [] and diff.mismatched == [] + + model_state = + if params_complete? do + model_state + else + {init_fun, _} = Axon.build(model, compiler: Nx.Defn.Evaluator) + init_fun.(input_template, model_state) + end + + if Keyword.get(opts, :log_params_diff, not params_complete?) do + log_params_diff(diff) + end + + model_state + end) + end + + defp with_default_backend(nil, fun), do: fun.() + defp with_default_backend(backend, fun), do: Nx.with_default_backend(backend, fun) + + defp state_dict?(%{} = dict) when not is_struct(dict) do + Enum.all?(dict, fn {key, value} -> + is_binary(key) and Nx.LazyContainer.impl_for(value) != nil + end) + end + + defp state_dict?(_other), do: false + + defp init_params(model, params_expr, pytorch_state, params_mapping) do + layers = + model + |> Utils.Axon.nodes_with_names() + |> Enum.filter(fn {layer, _name} -> layer.parameters != [] end) + + prefixes = infer_prefixes(layers, pytorch_state, params_mapping) + + diff = %{missing: [], mismatched: [], used_keys: []} + + {params, diff} = + layers + |> Enum.filter(fn {_layer, layer_name} -> params_expr[layer_name] end) + |> Enum.map_reduce(diff, fn {layer, layer_name}, diff -> + params_source = params_source(layer_name, prefixes, params_mapping) + + {params, diff} = + Enum.reduce(layer.parameters, {[], diff}, fn param, {params, diff} -> + param_expr = params_expr[layer_name][param.name] + + {sources, builder_fun} = + case params_source do + %{} = param_builders -> + if param_builder = param_builders[param.name] do + param_builder + else + raise "no matching mapping found for parameter #{inspect(param.name)} in #{inspect(param_builders)}" + end + + source_layer_name + when is_binary(source_layer_name) or + is_list(source_layer_name) -> + default_layer_param_builder(layer, param.name, source_layer_name) + end + + {all_sources_found?, source_values, source_keys} = + for source <- sources, reduce: {true, [], []} do + {all_found?, values, keys} -> + # Source can be either {layer_name, param_name}, or + # a list of these, to find any match + source + |> List.wrap() + |> Enum.find_value(fn {source_layer_name, source_param_name} -> + lookup_param(pytorch_state, source_layer_name, source_param_name) + end) + |> case do + {value, key} -> {all_found?, [value | values], [key | keys]} + nil -> {false, values, keys} + end + end + + diff = prepend(diff, :used_keys, source_keys) + + {value, diff} = + if all_sources_found? do + source_values = Enum.map(source_values, &Nx.to_tensor/1) + value = builder_fun.(Enum.reverse(source_values)) + + case verify_param_shape(param_expr, value) do + :ok -> + value = ensure_type(param_expr, value) + {value, diff} + + {:error, expected, actual} -> + {nil, prepend(diff, :mismatched, [{layer_name, param, expected, actual}])} + end + else + {nil, prepend(diff, :missing, [{layer_name, param}])} + end + + if value do + {[{param.name, value} | params], diff} + else + {params, diff} + end + end) + + {{layer_name, Map.new(params)}, diff} + end) + + params = Map.new(params) + + diff = %{ + missing: Enum.reverse(diff.missing), + mismatched: Enum.reverse(diff.mismatched), + unused_keys: Enum.sort(Map.keys(pytorch_state) -- diff.used_keys) + } + + {params, diff} + end + + defp prepend(diff, key, values), do: Map.update!(diff, key, &(values ++ &1)) + + defp infer_prefixes(layers, pytorch_state, params_mapping) do + # Note: target refers to the parameters we are initializing, while + # source refers to the state we are loading from + + target_names = for {_, name} <- layers, do: name + + source_names = + for {key, _} <- pytorch_state, uniq: true do + # Drop parameter name + key |> String.split(".") |> Enum.drop(-1) |> Enum.join(".") + end + + target_templates = Map.keys(params_mapping) + + source_templates = + Enum.flat_map(params_mapping, fn + {_target_template, %{} = param_builders} -> + for {_target_param_name, {sources, _builder_fun}} <- param_builders, + ref_or_refs <- sources, + {source_template, _source_param_name} <- List.wrap(ref_or_refs), + do: source_template + + {_target_template, source_templates} when is_list(source_templates) -> + source_templates + + {_target_template, source_template} when is_binary(source_template) -> + [source_template] + end) + + target_template_prefix = maybe_prefix(target_names, target_templates) + target_name_prefix = maybe_prefix(target_templates, target_names) + source_template_prefix = maybe_prefix(source_names, source_templates) + source_name_prefix = maybe_prefix(source_templates, source_names) + + %{ + target_template: target_template_prefix, + target_name: target_name_prefix, + source_template: source_template_prefix, + source_name: source_name_prefix + } + end + + # If a subset of `names` is present in `prefixed_names` under the + # same prefix, finds that prefix. + defp maybe_prefix(names, prefixed_names) do + (names -- prefixed_names) + |> Enum.map(fn name -> + suffix = "." <> name + + for prefixed_name <- prefixed_names, + String.ends_with?(prefixed_name, suffix), + do: String.replace_suffix(prefixed_name, suffix, ""), + into: MapSet.new() + end) + |> Enum.reject(&Enum.empty?/1) + |> case do + [] -> + nil + + prefix_sets -> + prefix_sets + |> Enum.reduce(&MapSet.intersection/2) + |> Enum.to_list() + |> case do + [prefix] -> prefix + end + end + end + + defp params_source(target_layer_name, prefixes, params_mapping) do + layer_name = change_prefix(target_layer_name, prefixes.target_name, prefixes.target_template) + + params_source = + case params_mapping do + %{^layer_name => params_source} -> + params_source + + mapping -> + params_source = + Enum.find_value(mapping, fn {target_template, params_source} -> + if substitutes = match_template(layer_name, target_template) do + Bumblebee.HuggingFace.Transformers.Utils.map_params_source_layer_names( + params_source, + &fill_template(&1, substitutes) + ) + end + end) + + unless params_source do + raise "no matching mapping found for layer #{inspect(layer_name)} in #{inspect(mapping)}" + end + + params_source + end + + Bumblebee.HuggingFace.Transformers.Utils.map_params_source_layer_names( + params_source, + &change_prefix(&1, prefixes.source_template, prefixes.source_name) + ) + end + + defp change_prefix(layer_name, current_prefix, new_prefix) do + layer_name = + if current_prefix do + String.replace_prefix(layer_name, current_prefix <> ".", "") + else + layer_name + end + + if new_prefix do + new_prefix <> "." <> layer_name + else + layer_name + end + end + + defp match_template(name, template), do: match_template(name, template, %{}) + + defp match_template(<<_, _::binary>> = name, <<"{", template::binary>>, substitutes) do + {value, name} = + case String.split(name, ".", parts: 2) do + [value] -> {value, ""} + [value, name] -> {value, name} + end + + {key, template} = + case String.split(template, "}", parts: 2) do + [key, ""] -> {key, ""} + [key, "." <> template] -> {key, template} + end + + match_template(name, template, put_in(substitutes[key], value)) + end + + defp match_template(<>, <>, substitutes) do + match_template(name, template, substitutes) + end + + defp match_template(<<>>, <<>>, substitutes), do: substitutes + defp match_template(_name, _template, _substitutes), do: nil + + defp fill_template(template, substitutes), do: fill_template(template, substitutes, <<>>) + + defp fill_template(<<>>, _substitutes, name), do: name + + defp fill_template(<<"{", template::binary>>, substitutes, name) do + [key, template] = String.split(template, "}", parts: 2) + value = Map.fetch!(substitutes, key) + fill_template(template, substitutes, <>) + end + + defp fill_template(<>, substitutes, name) do + fill_template(template, substitutes, <>) + end + + defp log_params_diff(%{missing: missing, mismatched: mismatched, unused_keys: unused_keys}) do + if missing != [] do + missing_keys = + Enum.map(missing, fn {layer_name, param} -> layer_name <> "." <> param.name end) + + Logger.debug("the following parameters were missing:\n\n#{format_list(missing_keys)}\n") + end + + if unused_keys != [] do + Logger.debug( + "the following PyTorch parameters were unused:\n\n#{format_list(unused_keys)}\n" + ) + end + + if mismatched != [] do + mismatched_keys = + Enum.map(mismatched, fn {layer_name, param, expected_shape, actual_shape} -> + "#{layer_name}.#{param.name} (expected #{inspect(expected_shape)}, got: #{inspect(actual_shape)})" + end) + + Logger.debug( + "the following parameters were ignored, because of non-matching shape:\n\n#{format_list(mismatched_keys)}\n" + ) + end + end + + defp format_list(items), do: Enum.map_join(items, "\n", &(" * " <> &1)) + + defp default_layer_param_builder(%{op_name: :dense}, "kernel", layer_name) do + {[param_refs(layer_name, "weight")], + fn [kernel] -> + [out_features, in_features] = Nx.axes(kernel) + Nx.transpose(kernel, axes: [in_features, out_features]) + end} + end + + defp default_layer_param_builder(layer, "kernel", layer_name) + when layer.op_name in [:conv, :depthwise_conv] do + {[param_refs(layer_name, "weight")], + fn [kernel] -> + [out_channels, in_channels | kernel_spatials] = Nx.axes(kernel) + + case layer.opts[:channels] do + :first -> kernel + :last -> Nx.transpose(kernel, axes: kernel_spatials ++ [in_channels, out_channels]) + end + end} + end + + defp default_layer_param_builder(%{op_name: :conv_transpose} = layer, "kernel", layer_name) do + {[param_refs(layer_name, "weight")], + fn [kernel] -> + [in_channels, out_channels | kernel_spatials] = Nx.axes(kernel) + + case layer.opts[:channels] do + :first -> Nx.transpose(kernel, axes: [out_channels, in_channels | kernel_spatials]) + :last -> Nx.transpose(kernel, axes: kernel_spatials ++ [in_channels, out_channels]) + end + end} + end + + defp default_layer_param_builder(%{op_name: :lstm}, "bias", layer_name) do + {[param_refs(layer_name, "bias_hh"), param_refs(layer_name, "bias_ih")], + fn [bias_hh, bias_ih] -> + bias = Nx.add(bias_ih, bias_hh) + bias = Nx.reshape(bias, {4, :auto}) + {bias[0], bias[1], bias[2], bias[3]} + end} + end + + defp default_layer_param_builder(%{op_name: :lstm}, "input_kernel", layer_name) do + {[param_refs(layer_name, "weight_ih")], + fn [weight_ih] -> + weight_ih = weight_ih |> unflatten_leading(4) |> Nx.transpose(axes: [0, 2, 1]) + {weight_ih[0], weight_ih[1], weight_ih[2], weight_ih[3]} + end} + end + + defp default_layer_param_builder(%{op_name: :lstm}, "hidden_kernel", layer_name) do + {[param_refs(layer_name, "weight_hh")], + fn [weight_hh] -> + weight_hh = weight_hh |> unflatten_leading(4) |> Nx.transpose(axes: [0, 2, 1]) + {weight_hh[0], weight_hh[1], weight_hh[2], weight_hh[3]} + end} + end + + defp default_layer_param_builder(%{op_name: :gru}, "bias", layer_name) do + {[param_refs(layer_name, "bias_hh"), param_refs(layer_name, "bias_ih")], + fn [bias_hh, bias_ih] -> + bias_hh = unflatten_leading(bias_hh, 3) + bias_ih = unflatten_leading(bias_ih, 3) + {Nx.add(bias_ih[0], bias_hh[0]), Nx.add(bias_ih[1], bias_hh[1]), bias_ih[2], bias_hh[2]} + end} + end + + defp default_layer_param_builder(%{op_name: :gru}, "input_kernel", layer_name) do + {[param_refs(layer_name, "weight_ih")], + fn [weight_ih] -> + weight_ih = weight_ih |> unflatten_leading(4) |> Nx.transpose(axes: [0, 2, 1]) + {weight_ih[0], weight_ih[1], weight_ih[2]} + end} + end + + defp default_layer_param_builder(%{op_name: :gru}, "hidden_kernel", layer_name) do + {[param_refs(layer_name, "weight_hh")], + fn [weight_hh] -> + weight_hh = weight_hh |> unflatten_leading(3) |> Nx.transpose(axes: [0, 2, 1]) + {weight_hh[0], weight_hh[1], weight_hh[2]} + end} + end + + defp default_layer_param_builder(_layer, param_name, layer_name) do + pytorch_names = + case param_name do + # PyTorch uses "weight" instead of "kernel" everywhere + "kernel" -> ["weight"] + # For normalization layers PyTorch uses "weight" and "bias", + # however we check the other ones just in case. + # + # [1]: https://github.com/huggingface/transformers/pull/11394 + # [2]: https://github.com/naver/sqlova/issues/1#issuecomment-463481275 + "gamma" -> ["weight", "gamma"] + "beta" -> ["bias", "beta"] + # Running averages in normalization layers + "mean" -> ["running_mean"] + "var" -> ["running_var"] + name -> [name] + end + + param_source = Enum.flat_map(pytorch_names, ¶m_refs(layer_name, &1)) + + {[param_source], fn [value] -> value end} + end + + defp param_refs(layer_name, param_name) do + for layer_name <- List.wrap(layer_name) do + {layer_name, param_name} + end + end + + defp lookup_param(pytorch_state, layer_name, pytorch_name) do + # Note: the PyTorch model may have some root-level parameters that + # we need to namespace under a layer in Axon, so after trying the + # param within layer_name, we also try the param name directly + pytorch_keys = [layer_name <> "." <> pytorch_name, pytorch_name] + + Enum.find_value(pytorch_keys, fn pytorch_key -> + if value = pytorch_state[pytorch_key] do + {value, pytorch_key} + end + end) + end + + defp verify_param_shape(param_expr, value) do + case {expr_shape(param_expr), expr_shape(value)} do + {shape, shape} -> :ok + {expected, actual} -> {:error, expected, actual} + end + end + + defp expr_shape(expr) do + Utils.Nx.map(expr, &Nx.shape/1) + end + + defp ensure_type(param_expr, value) do + Utils.Nx.zip_with(param_expr, value, fn expr, tensor -> + case {Nx.type(expr), Nx.type(tensor)} do + {type, type} -> tensor + {expected, _actual} -> Nx.as_type(tensor, expected) + end + end) + end + + defp unflatten_leading(tensor, axis_size) do + shape = + tensor + |> Nx.shape() + |> Tuple.insert_at(0, axis_size) + |> put_elem(1, :auto) + + Nx.reshape(tensor, shape) + end +end diff --git a/deps/bumblebee/lib/bumblebee/diffusion/controlnet.ex b/deps/bumblebee/lib/bumblebee/diffusion/controlnet.ex new file mode 100644 index 0000000000000000000000000000000000000000..0e1ff85faedd30c1a9c7dd154c6a7125daf66bd0 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/diffusion/controlnet.ex @@ -0,0 +1,505 @@ +defmodule Bumblebee.Diffusion.ControlNet do + alias Bumblebee.Shared + + options = [ + sample_size: [ + default: 64, + doc: "the size of the input spatial dimensions" + ], + in_channels: [ + default: 4, + doc: "the number of channels in the input" + ], + out_channels: [ + default: 4, + doc: "the number of channels in the output" + ], + embedding_flip_sin_to_cos: [ + default: true, + doc: "whether to flip the sin to cos in the sinusoidal timestep embedding" + ], + embedding_frequency_correction_term: [ + default: 0, + doc: ~S""" + controls the frequency formula in the timestep sinusoidal embedding. The frequency is computed + as $\\omega_i = \\frac{1}{10000^{\\frac{i}{n - s}}}$, for $i \\in \\{0, ..., n-1\\}$, where $n$ + is half of the embedding size and $s$ is the shift. Historically, certain implementations of + sinusoidal embedding used $s=0$, while others used $s=1$ + """ + ], + hidden_sizes: [ + default: [320, 640, 1280, 1280], + doc: "the dimensionality of hidden layers in each upsample/downsample block" + ], + depth: [ + default: 2, + doc: "the number of residual blocks in each upsample/downsample block" + ], + down_block_types: [ + default: [ + :cross_attention_down_block, + :cross_attention_down_block, + :cross_attention_down_block, + :down_block + ], + doc: + "a list of downsample block types. The supported blocks are: `:down_block`, `:cross_attention_down_block`" + ], + up_block_types: [ + default: [ + :up_block, + :cross_attention_up_block, + :cross_attention_up_block, + :cross_attention_up_block + ], + doc: + "a list of upsample block types. The supported blocks are: `:up_block`, `:cross_attention_up_block`" + ], + downsample_padding: [ + default: [{1, 1}, {1, 1}], + doc: "the padding to use in the downsample convolution" + ], + mid_block_scale_factor: [ + default: 1, + doc: "the scale factor to use for the mid block" + ], + num_attention_heads: [ + default: 8, + doc: + "the number of attention heads for each attention layer. Optionally can be a list with one number per block" + ], + cross_attention_size: [ + default: 1024, + doc: "the dimensionality of the cross attention features" + ], + use_linear_projection: [ + default: false, + doc: + "whether the input/output projection of the transformer block should be linear or convolutional" + ], + activation: [ + default: :silu, + doc: "the activation function" + ], + group_norm_num_groups: [ + default: 32, + doc: "the number of groups used by the group normalization layers" + ], + group_norm_epsilon: [ + default: 1.0e-5, + doc: "the epsilon used by the group normalization layers" + ], + conditioning_embedding_hidden_sizes: [ + default: [16, 32, 96, 256], + doc: "the dimensionality of hidden layers in the conditioning input embedding" + ] + ] + + @moduledoc """ + ControlNet model with two spatial dimensions and conditioning state. + + ## Architectures + + * `:base` - the ControlNet model + + ## Inputs + + * `"sample"` - `{batch_size, sample_size, sample_size, in_channels}` + + Sample input with two spatial dimensions. + + * `"timestep"` - `{}` + + The timestep used to parameterize model behaviour in a multi-step + process, such as diffusion. + + * `"encoder_hidden_state"` - `{batch_size, sequence_length, hidden_size}` + + The conditioning state (context) to use with cross-attention. + + * `"conditioning"` - `{batch_size, conditioning_size, conditioning_size, 3}` + + The conditioning spatial input. + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + alias Bumblebee.Diffusion + + @impl true + def architectures(), do: [:base] + + @impl true + def config(spec, opts) do + Shared.put_config_attrs(spec, opts) + end + + @impl true + def input_template(spec) do + sample_shape = {1, spec.sample_size, spec.sample_size, spec.in_channels} + timestep_shape = {} + + conditioning_size = + spec.sample_size * 2 ** (length(spec.conditioning_embedding_hidden_sizes) - 1) + + conditioning_shape = {1, conditioning_size, conditioning_size, 3} + encoder_hidden_state_shape = {1, 1, spec.cross_attention_size} + + %{ + "sample" => Nx.template(sample_shape, :f32), + "timestep" => Nx.template(timestep_shape, :u32), + "conditioning" => Nx.template(conditioning_shape, :f32), + "conditioning_scale" => Nx.template({}, :f32), + "encoder_hidden_state" => Nx.template(encoder_hidden_state_shape, :f32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs(spec) + |> core(spec) + |> Layers.output() + end + + defp inputs(spec) do + sample_shape = {nil, spec.sample_size, spec.sample_size, spec.in_channels} + + conditioning_size = + spec.sample_size * 2 ** (length(spec.conditioning_embedding_hidden_sizes) - 1) + + conditioning_shape = {nil, conditioning_size, conditioning_size, 3} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("sample", shape: sample_shape), + Axon.input("timestep", shape: {}), + Axon.input("conditioning", shape: conditioning_shape), + Axon.input("conditioning_scale", optional: true), + Axon.input("encoder_hidden_state", shape: {nil, nil, spec.cross_attention_size}) + ]) + end + + defp core(inputs, spec) do + sample = inputs["sample"] + timestep = inputs["timestep"] + conditioning = inputs["conditioning"] + + conditioning_scale = + Bumblebee.Layers.default inputs["conditioning_scale"] do + Axon.constant(1) + end + + encoder_hidden_state = inputs["encoder_hidden_state"] + + timestep = + Axon.layer( + fn sample, timestep, _opts -> + Nx.broadcast(timestep, {Nx.axis_size(sample, 0)}) + end, + [sample, timestep], + op_name: :broadcast + ) + + timestep_embedding = + timestep + |> Diffusion.Layers.timestep_sinusoidal_embedding(hd(spec.hidden_sizes), + flip_sin_to_cos: spec.embedding_flip_sin_to_cos, + frequency_correction_term: spec.embedding_frequency_correction_term + ) + |> Diffusion.Layers.UNet.timestep_embedding_mlp(hd(spec.hidden_sizes) * 4, + name: "time_embedding" + ) + + sample = + Axon.conv(sample, hd(spec.hidden_sizes), + kernel_size: 3, + padding: [{1, 1}, {1, 1}], + name: "input_conv" + ) + + controlnet_conditioning_embeddings = + controlnet_embedding(conditioning, spec, name: "controlnet_conditioning_embedding") + + sample = Axon.add(sample, controlnet_conditioning_embeddings) + + {sample, down_block_states} = + down_blocks(sample, timestep_embedding, encoder_hidden_state, spec, name: "down_blocks") + + sample = + mid_block(sample, timestep_embedding, encoder_hidden_state, spec, name: "mid_block") + + down_block_states = controlnet_down_blocks(down_block_states, name: "controlnet_down_blocks") + + down_block_states = + for down_block_state <- Tuple.to_list(down_block_states) do + Axon.multiply(down_block_state, conditioning_scale) + end + |> List.to_tuple() + + mid_block_state = + sample + |> controlnet_mid_block(spec, name: "controlnet_mid_block") + |> Axon.multiply(conditioning_scale) + + %{ + down_block_states: Axon.container(down_block_states), + mid_block_state: mid_block_state + } + end + + defp controlnet_down_blocks(down_block_states, opts) do + name = opts[:name] + + states = + for {{state, out_channels}, i} <- Enum.with_index(Tuple.to_list(down_block_states)) do + Axon.conv(state, out_channels, + kernel_size: 1, + name: name |> join(i) |> join("zero_conv"), + kernel_initializer: :zeros + ) + end + + List.to_tuple(states) + end + + defp controlnet_mid_block(input, spec, opts) do + name = opts[:name] + + Axon.conv(input, List.last(spec.hidden_sizes), + kernel_size: 1, + name: name |> join("zero_conv"), + kernel_initializer: :zeros + ) + end + + defp controlnet_embedding(sample, spec, opts) do + name = opts[:name] + + state = + Axon.conv(sample, hd(spec.conditioning_embedding_hidden_sizes), + kernel_size: 3, + padding: [{1, 1}, {1, 1}], + name: join(name, "input_conv"), + activation: :silu + ) + + size_pairs = Enum.chunk_every(spec.conditioning_embedding_hidden_sizes, 2, 1) + + sample = + for {[in_size, out_size], i} <- Enum.with_index(size_pairs), reduce: state do + input -> + input + |> Axon.conv(in_size, + kernel_size: 3, + padding: [{1, 1}, {1, 1}], + name: name |> join("inner_convs") |> join(2 * i), + activation: :silu + ) + |> Axon.conv(out_size, + kernel_size: 3, + padding: [{1, 1}, {1, 1}], + strides: 2, + name: name |> join("inner_convs") |> join(2 * i + 1), + activation: :silu + ) + end + + Axon.conv(sample, hd(spec.hidden_sizes), + kernel_size: 3, + padding: [{1, 1}, {1, 1}], + name: join(name, "output_conv"), + kernel_initializer: :zeros + ) + end + + defp down_blocks(sample, timestep_embedding, encoder_hidden_state, spec, opts) do + name = opts[:name] + + blocks = + Enum.zip([spec.hidden_sizes, spec.down_block_types, num_attention_heads_per_block(spec)]) + + in_channels = hd(spec.hidden_sizes) + down_block_states = [{sample, in_channels}] + + state = {sample, down_block_states, in_channels} + + {sample, down_block_states, _} = + for {{out_channels, block_type, num_attention_heads}, idx} <- Enum.with_index(blocks), + reduce: state do + {sample, down_block_states, in_channels} -> + last_block? = idx == length(spec.hidden_sizes) - 1 + + {sample, states} = + Diffusion.Layers.UNet.down_block_2d( + block_type, + sample, + timestep_embedding, + encoder_hidden_state, + depth: spec.depth, + in_channels: in_channels, + out_channels: out_channels, + add_downsample: not last_block?, + downsample_padding: spec.downsample_padding, + activation: spec.activation, + norm_epsilon: spec.group_norm_epsilon, + norm_num_groups: spec.group_norm_num_groups, + num_attention_heads: num_attention_heads, + use_linear_projection: spec.use_linear_projection, + name: join(name, idx) + ) + + {sample, down_block_states ++ Tuple.to_list(states), out_channels} + end + + {sample, List.to_tuple(down_block_states)} + end + + defp mid_block(hidden_state, timesteps_embedding, encoder_hidden_state, spec, opts) do + Diffusion.Layers.UNet.mid_cross_attention_block_2d( + hidden_state, + timesteps_embedding, + encoder_hidden_state, + channels: List.last(spec.hidden_sizes), + activation: spec.activation, + norm_epsilon: spec.group_norm_epsilon, + norm_num_groups: spec.group_norm_num_groups, + output_scale_factor: spec.mid_block_scale_factor, + num_attention_heads: spec |> num_attention_heads_per_block() |> List.last(), + use_linear_projection: spec.use_linear_projection, + name: opts[:name] + ) + end + + defp num_attention_heads_per_block(spec) when is_list(spec.num_attention_heads) do + spec.num_attention_heads + end + + defp num_attention_heads_per_block(spec) when is_integer(spec.num_attention_heads) do + num_blocks = length(spec.down_block_types) + List.duplicate(spec.num_attention_heads, num_blocks) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + in_channels: {"in_channels", number()}, + out_channels: {"out_channels", number()}, + sample_size: {"sample_size", number()}, + center_input_sample: {"center_input_sample", boolean()}, + embedding_flip_sin_to_cos: {"flip_sin_to_cos", boolean()}, + embedding_frequency_correction_term: {"freq_shift", number()}, + hidden_sizes: {"block_out_channels", list(number())}, + depth: {"layers_per_block", number()}, + down_block_types: { + "down_block_types", + list( + mapping(%{ + "DownBlock2D" => :down_block, + "CrossAttnDownBlock2D" => :cross_attention_down_block + }) + ) + }, + up_block_types: { + "up_block_types", + list( + mapping(%{ + "UpBlock2D" => :up_block, + "CrossAttnUpBlock2D" => :cross_attention_up_block + }) + ) + }, + downsample_padding: {"downsample_padding", padding(2)}, + mid_block_scale_factor: {"mid_block_scale_factor", number()}, + num_attention_heads: {"attention_head_dim", one_of([number(), list(number())])}, + cross_attention_size: {"cross_attention_dim", number()}, + use_linear_projection: {"use_linear_projection", boolean()}, + activation: {"act_fn", activation()}, + group_norm_num_groups: {"norm_num_groups", number()}, + group_norm_epsilon: {"norm_eps", number()}, + conditioning_embedding_hidden_sizes: + {"conditioning_embedding_out_channels", list(number())} + ) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + alias Bumblebee.HuggingFace.Transformers + + def params_mapping(_spec) do + block_mapping = %{ + "transformers.{m}.norm" => "attentions.{m}.norm", + "transformers.{m}.input_projection" => "attentions.{m}.proj_in", + "transformers.{m}.output_projection" => "attentions.{m}.proj_out", + "transformers.{m}.blocks.{l}.self_attention.query" => + "attentions.{m}.transformer_blocks.{l}.attn1.to_q", + "transformers.{m}.blocks.{l}.self_attention.key" => + "attentions.{m}.transformer_blocks.{l}.attn1.to_k", + "transformers.{m}.blocks.{l}.self_attention.value" => + "attentions.{m}.transformer_blocks.{l}.attn1.to_v", + "transformers.{m}.blocks.{l}.self_attention.output" => + "attentions.{m}.transformer_blocks.{l}.attn1.to_out.0", + "transformers.{m}.blocks.{l}.cross_attention.query" => + "attentions.{m}.transformer_blocks.{l}.attn2.to_q", + "transformers.{m}.blocks.{l}.cross_attention.key" => + "attentions.{m}.transformer_blocks.{l}.attn2.to_k", + "transformers.{m}.blocks.{l}.cross_attention.value" => + "attentions.{m}.transformer_blocks.{l}.attn2.to_v", + "transformers.{m}.blocks.{l}.cross_attention.output" => + "attentions.{m}.transformer_blocks.{l}.attn2.to_out.0", + "transformers.{m}.blocks.{l}.ffn.intermediate" => + "attentions.{m}.transformer_blocks.{l}.ff.net.0.proj", + "transformers.{m}.blocks.{l}.ffn.output" => + "attentions.{m}.transformer_blocks.{l}.ff.net.2", + "transformers.{m}.blocks.{l}.self_attention_norm" => + "attentions.{m}.transformer_blocks.{l}.norm1", + "transformers.{m}.blocks.{l}.cross_attention_norm" => + "attentions.{m}.transformer_blocks.{l}.norm2", + "transformers.{m}.blocks.{l}.output_norm" => + "attentions.{m}.transformer_blocks.{l}.norm3", + "residual_blocks.{m}.timestep_projection" => "resnets.{m}.time_emb_proj", + "residual_blocks.{m}.norm_1" => "resnets.{m}.norm1", + "residual_blocks.{m}.conv_1" => "resnets.{m}.conv1", + "residual_blocks.{m}.norm_2" => "resnets.{m}.norm2", + "residual_blocks.{m}.conv_2" => "resnets.{m}.conv2", + "residual_blocks.{m}.shortcut.projection" => "resnets.{m}.conv_shortcut", + "downsamples.{m}.conv" => "downsamplers.{m}.conv" + } + + blocks_mapping = + ["down_blocks.{n}", "mid_block"] + |> Enum.map(&Transformers.Utils.prefix_params_mapping(block_mapping, &1, &1)) + |> Enum.reduce(&Map.merge/2) + + controlnet = %{ + "controlnet_conditioning_embedding.input_conv" => "controlnet_cond_embedding.conv_in", + "controlnet_conditioning_embedding.inner_convs.{m}" => + "controlnet_cond_embedding.blocks.{m}", + "controlnet_conditioning_embedding.output_conv" => "controlnet_cond_embedding.conv_out", + "controlnet_down_blocks.{m}.zero_conv" => "controlnet_down_blocks.{m}", + "controlnet_mid_block.zero_conv" => "controlnet_mid_block" + } + + %{ + "time_embedding.intermediate" => "time_embedding.linear_1", + "time_embedding.output" => "time_embedding.linear_2", + "input_conv" => "conv_in" + } + |> Map.merge(blocks_mapping) + |> Map.merge(controlnet) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/diffusion/ddim_scheduler.ex b/deps/bumblebee/lib/bumblebee/diffusion/ddim_scheduler.ex new file mode 100644 index 0000000000000000000000000000000000000000..ca1439e9b3c0d41a34de4109f5f852eb3dc5eb23 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/diffusion/ddim_scheduler.ex @@ -0,0 +1,273 @@ +defmodule Bumblebee.Diffusion.DdimScheduler do + options = [ + num_train_steps: [ + default: 1000, + doc: "the number of diffusion steps used to train the model" + ], + beta_schedule: [ + default: :linear, + doc: """ + the beta schedule type, a mapping from a beta range to a sequence of betas for stepping the model. + Either of `:linear`, `:quadratic`, or `:squared_cosine` + """ + ], + beta_start: [ + default: 0.0001, + doc: "the start value for the beta schedule" + ], + beta_end: [ + default: 0.02, + doc: "the end value for the beta schedule" + ], + prediction_type: [ + default: :noise, + doc: """ + prediction type of the denoising model. Either of: + + * `:noise` (default) - the model predicts the noise of the diffusion process + + * `:angular_velocity` - the model predicts velocity in angular parameterization. + See Section 2.4 in [Imagen Video: High Definition Video Generation with Diffusion Models](https://imagen.research.google/video/paper.pdf), + then Section 4 in [Progressive Distillation for Fast Sampling of Diffusion Models](https://arxiv.org/pdf/2202.00512.pdf) + and Appendix D + + """ + ], + alpha_clip_strategy: [ + default: :one, + doc: ~S""" + each step $t$ uses the values of $\bar{\alpha}\_t$ and $\bar{\alpha}\_{t-1}$, + however for $t = 0$ there is no previous alpha. The strategy can be either + `:one` ($\bar{\alpha}\_{t-1} = 1$) or `:alpha_zero` ($\bar{\alpha}\_{t-1} = \bar{\alpha}\_0$) + """ + ], + timesteps_offset: [ + default: 0, + doc: ~S""" + an offset added to the inference steps. You can use a combination of `timesteps_offset: 1` and + `alpha_clip_strategy: :alpha_zero`, so that the last step $t = 1$ uses $\bar{\alpha}\_1$ + and $\bar{\alpha}\_0$, as done in stable diffusion + """ + ], + clip_denoised_sample: [ + default: true, + doc: """ + whether to clip the predicted denoised sample ($x_0$ in Equation (12)) into $[-1, 1]$ + for numerical stability + """ + ], + rederive_noise: [ + default: false, + doc: """ + whether the noise (output of the denoising model) should be re-derived at each step based on the + predicted denoised sample ($x_0$) and the current sample. This technique is used in OpenAI GLIDE + """ + ], + eta: [ + default: 0.0, + doc: """ + a weight for the noise added in a denoising diffusion step. This scales the value of $\\sigma_t$ + in Equation (12) in the original paper, as per Equation (16) + """ + ] + ] + + @moduledoc """ + Denoising diffusion implicit models (DDIMs). + + This sampling method was proposed as a follow up to the original + denoising diffusion probabilistic models (DDPMs) in order to heavily + reduce the number of steps during inference. DDPMs model the diffusion + process as a Markov chain; DDIMs generalize this considering + non-Markovian diffusion processes that lead to the same objective. + This enables a reverse process with many less samples, as compared + to DDPMs, while using the same denoising model. + + DDIMs were shown to be a simple variant of pseudo numerical methods + for diffusion models (PNDMs), see `Bumblebee.Diffusion.PndmScheduler` + and the corresponding paper for more details. + + ## Configuration + + #{Bumblebee.Shared.options_doc(options)} + + ## References + + * [Denoising Diffusion Implicit Models](https://arxiv.org/abs/2010.02502) + + """ + + defstruct Bumblebee.Shared.option_defaults(options) + + @behaviour Bumblebee.Scheduler + @behaviour Bumblebee.Configurable + + import Nx.Defn + + alias Bumblebee.Diffusion.SchedulerUtils + + @impl true + def config(scheduler, opts) do + Bumblebee.Shared.put_config_attrs(scheduler, opts) + end + + @impl true + def init(scheduler, num_steps, _sample_template, prng_key) do + timesteps = + SchedulerUtils.ddim_timesteps( + scheduler.num_train_steps, + num_steps, + scheduler.timesteps_offset + ) + + {alpha_bars} = init_parameters(scheduler: scheduler) + + state = %{ + timesteps: timesteps, + timestep_gap: div(scheduler.num_train_steps, num_steps), + alpha_bars: alpha_bars, + iteration: 0, + prng_key: prng_key + } + + {state, timesteps} + end + + defnp init_parameters(opts \\ []) do + %{ + beta_start: beta_start, + beta_end: beta_end, + beta_schedule: beta_schedule, + num_train_steps: num_train_steps + } = opts[:scheduler] + + betas = + SchedulerUtils.beta_schedule(beta_schedule, num_train_steps, + start: beta_start, + end: beta_end + ) + + alphas = 1 - betas + + {Nx.cumulative_product(alphas)} + end + + @impl true + def step(scheduler, state, sample, prediction) do + do_step(state, sample, prediction, scheduler: scheduler) + end + + defnp do_step(state, sample, prediction, opts) do + scheduler = opts[:scheduler] + + # See Equation (12) + + # Note that in the paper alpha_t represents a cumulative product, + # often denoted as alpha_t with a bar on top. We use an explicit + # alpha_bart_t name for consistency + + timestep = state.timesteps[state.iteration] + prev_timestep = timestep - state.timestep_gap + + alpha_bar_t = state.alpha_bars[timestep] + + alpha_bar_t_prev = + if prev_timestep >= 0 do + state.alpha_bars[prev_timestep] + else + case scheduler.alpha_clip_strategy do + :one -> 1.0 + :alpha_zero -> state.alpha_bars[0] + end + end + + beta_bar_t = 1 - alpha_bar_t + beta_bar_t_prev = 1 - alpha_bar_t_prev + + {pred_denoised_sample, noise} = + case scheduler.prediction_type do + :noise -> + pred_denoised_sample = + (sample - Nx.sqrt(beta_bar_t) * prediction) / Nx.sqrt(alpha_bar_t) + + {pred_denoised_sample, prediction} + + :angular_velocity -> + pred_denoised_sample = + Nx.sqrt(alpha_bar_t) * sample - Nx.sqrt(beta_bar_t) * prediction + + noise = Nx.sqrt(alpha_bar_t) * prediction + Nx.sqrt(beta_bar_t) * sample + {pred_denoised_sample, noise} + end + + pred_denoised_sample = + if scheduler.clip_denoised_sample do + Nx.clip(pred_denoised_sample, -1, 1) + else + pred_denoised_sample + end + + # See Equation (16) + sigma_t = + scheduler.eta * + Nx.sqrt(beta_bar_t_prev / beta_bar_t * (1 - alpha_bar_t / alpha_bar_t_prev)) + + noise = + if scheduler.rederive_noise do + # Re-derive the noise as in GLIDE + (sample - Nx.sqrt(alpha_bar_t) * pred_denoised_sample) / Nx.sqrt(beta_bar_t) + else + noise + end + + pred_sample_direction = Nx.sqrt(beta_bar_t_prev - Nx.pow(sigma_t, 2)) * noise + + prev_sample = Nx.sqrt(alpha_bar_t_prev) * pred_denoised_sample + pred_sample_direction + + {prev_sample, next_key} = + if scheduler.eta > 0 do + {rand, next_key} = Nx.Random.normal(state.prng_key, shape: Nx.shape(prev_sample)) + out = prev_sample + sigma_t * rand + {out, next_key} + else + {prev_sample, state.prng_key} + end + + state = %{state | iteration: state.iteration + 1, prng_key: next_key} + + {state, prev_sample} + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(scheduler, data) do + import Bumblebee.Shared.Converters + + opts = + convert!(data, + num_train_steps: {"num_train_timesteps", number()}, + beta_schedule: { + "beta_schedule", + mapping(%{ + "linear" => :linear, + "scaled_linear" => :quadratic, + "squaredcos_cap_v2" => :squared_cosine + }) + }, + beta_start: {"beta_start", number()}, + beta_end: {"beta_end", number()}, + prediction_type: + {"prediction_type", + mapping(%{"epsilon" => :noise, "v_prediction" => :angular_velocity})}, + alpha_clip_strategy: { + "set_alpha_to_one", + mapping(%{true => :one, false => :alpha_zero}) + }, + timesteps_offset: {"steps_offset", number()}, + clip_denoised_sample: {"clip_sample", boolean()}, + rederive_noise: {"use_clipped_model_output", boolean()} + ) + + @for.config(scheduler, opts) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/diffusion/layers.ex b/deps/bumblebee/lib/bumblebee/diffusion/layers.ex new file mode 100644 index 0000000000000000000000000000000000000000..3967e61857737f91a8ae98b501b391f72e2da826 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/diffusion/layers.ex @@ -0,0 +1,197 @@ +defmodule Bumblebee.Diffusion.Layers do + @moduledoc false + + import Bumblebee.Utils.Model, only: [join: 2] + import Nx.Defn + + @doc """ + Adds a sinusoidal embedding layer to the network. + + Expects a batched timestep tensor (1-dimensional). + + ## Options + + * `:flip_sin_to_cos` - whether to swap the order of sine and cosine + order in the embedding. Defaults to `false` + + * `:frequency_correction_term` - controls the frequency formula used. + The frequency is computed as + $\omega_i = \frac{1}{10000^{\frac{i}{n - s}}}$, for $i \in \{0, ..., n-1\}$, + where $n$ is half of the embedding size and $s$ is the shift. + Historically, certain implementations of sinusoidal embedding + used $s=0$, while other used $s=1$. Defaults to `0` + + * `:base` - the base for the frequency exponentiation. Defaults + to `10_000`. + + * `:scale` - a multiplier for the sin/cos arguments. Defaults to `1` + + """ + def timestep_sinusoidal_embedding(timestep, embedding_size, opts \\ []) do + opts = + Keyword.validate!(opts, + flip_sin_to_cos: false, + frequency_correction_term: 1, + base: 10_000, + scale: 1 + ) + + Axon.layer(×tep_sinusoidal_embedding_impl/2, [timestep], + embedding_size: embedding_size, + op_name: :timestep_sinusoidal_embedding, + flip_sin_to_cos: opts[:flip_sin_to_cos], + frequency_correction_term: opts[:frequency_correction_term], + scale: opts[:scale], + base: opts[:base] + ) + end + + defnp timestep_sinusoidal_embedding_impl(timestep, opts \\ []) do + opts = + keyword!(opts, [ + :embedding_size, + flip_sin_to_cos: false, + frequency_correction_term: 1, + scale: 1, + base: 10_000, + mode: :train + ]) + + embedding_size = opts[:embedding_size] + base = opts[:base] + frequency_correction_term = opts[:frequency_correction_term] + + if rem(embedding_size, 2) != 0 do + raise ArgumentError, + "expected embedding size to be an even number, but got: #{inspect(embedding_size)}" + end + + half_size = div(embedding_size, 2) + + frequency = + Nx.exp(-Nx.log(base) * Nx.iota({half_size}) / (half_size - frequency_correction_term)) + + angle = Nx.new_axis(timestep, -1) * Nx.new_axis(frequency, 0) + angle = opts[:scale] * angle + + if opts[:flip_sin_to_cos] do + Nx.concatenate([Nx.cos(angle), Nx.sin(angle)], axis: -1) + else + Nx.concatenate([Nx.sin(angle), Nx.cos(angle)], axis: -1) + end + end + + @doc """ + Adds a residual block to the network. + """ + def residual_block(hidden_state, in_channels, out_channels, opts \\ []) do + timestep_embedding = opts[:timestep_embedding] + dropout = opts[:dropout] || 0.0 + norm_num_groups = opts[:norm_num_groups] || 32 + norm_num_groups_out = opts[:norm_num_groups_out] || norm_num_groups + norm_epsilon = opts[:norm_epsilon] || 1.0e-6 + activation = opts[:activation] || :swish + output_scale_factor = opts[:output_scale_factor] || 1.0 + project_shortcut? = Keyword.get(opts, :project_shortcut?, in_channels != out_channels) + name = opts[:name] + + shortcut = + if project_shortcut? do + Axon.conv(hidden_state, out_channels, + kernel_size: 1, + strides: 1, + padding: :valid, + name: join(name, "shortcut.projection") + ) + else + hidden_state + end + + hidden_state = + hidden_state + |> Axon.group_norm(norm_num_groups, epsilon: norm_epsilon, name: join(name, "norm_1")) + |> Axon.activation(activation) + |> Axon.conv(out_channels, + kernel_size: 3, + strides: 1, + padding: [{1, 1}, {1, 1}], + name: join(name, "conv_1") + ) + + hidden_state = + if timestep_embedding do + timestep_embedding + |> Axon.activation(activation) + |> Axon.dense(out_channels, name: join(name, "timestep_projection")) + |> Axon.nx(&Nx.new_axis(Nx.new_axis(&1, 1), 1)) + |> Axon.add(hidden_state) + else + hidden_state + end + + hidden_state = + hidden_state + |> Axon.group_norm(norm_num_groups_out, epsilon: norm_epsilon, name: join(name, "norm_2")) + |> Axon.activation(activation) + |> Axon.dropout(rate: dropout) + |> Axon.conv(out_channels, + kernel_size: 3, + strides: 1, + padding: [{1, 1}, {1, 1}], + name: join(name, "conv_2") + ) + + hidden_state + |> Axon.add(shortcut) + |> Axon.nx(&Nx.divide(&1, output_scale_factor)) + end + + @doc """ + Adds a downsample block to the network. + """ + def downsample_2d(hidden_state, channels, opts \\ []) do + padding = opts[:padding] + name = opts[:name] + stride = 2 + + {hidden_state, padding} = + cond do + padding == 0 -> + hidden_state = + Axon.nx(hidden_state, &Nx.pad(&1, 0.0, [{0, 0, 0}, {0, 1, 0}, {0, 1, 0}, {0, 0, 0}])) + + {hidden_state, :valid} + + padding == 1 -> + {hidden_state, [{1, 1}, {1, 1}]} + + true -> + {hidden_state, padding} + end + + Axon.conv(hidden_state, channels, + kernel_size: 3, + strides: stride, + padding: padding, + name: join(name, "conv") + ) + end + + @doc """ + Adds an upsample block to the network. + """ + def upsample_2d(hidden_state, channels, opts \\ []) do + name = opts[:name] + + hidden_state + |> Axon.nx(fn hidden_state -> + {_, h, w, _} = Nx.shape(hidden_state) + Axon.Layers.resize(hidden_state, size: {2 * h, 2 * w}, mode: :nearest) + end) + |> Axon.conv(channels, + kernel_size: 3, + padding: [{1, 1}, {1, 1}], + name: join(name, "conv") + ) + end +end diff --git a/deps/bumblebee/lib/bumblebee/diffusion/layers/unet.ex b/deps/bumblebee/lib/bumblebee/diffusion/layers/unet.ex new file mode 100644 index 0000000000000000000000000000000000000000..50837a23fb7a38b6c134e42d0d9f876189ddf994 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/diffusion/layers/unet.ex @@ -0,0 +1,367 @@ +defmodule Bumblebee.Diffusion.Layers.UNet do + @moduledoc false + + alias Bumblebee.Layers + alias Bumblebee.Diffusion + + import Bumblebee.Utils.Model, only: [join: 2] + + @doc """ + Adds a feed-forward network on top of U-Net timestep embeddings. + + ## Options + + * `:name` - the base layer name + + * `:activation` - the activation used in-between the dense layers. + Defaults to `:silu` + + """ + def timestep_embedding_mlp(sample, embedding_size, opts \\ []) do + opts = Keyword.validate!(opts, [:name, activation: :silu]) + name = opts[:name] + + sample + |> Axon.dense(embedding_size, name: join(name, "intermediate")) + |> Axon.activation(opts[:activation]) + |> Axon.dense(embedding_size, name: join(name, "output")) + end + + @doc """ + Adds a U-Net downsample block of the given type to the network. + """ + def down_block_2d( + :cross_attention_down_block, + sample, + timestep_embedding, + encoder_hidden_state, + opts + ) do + down_block_2d(sample, timestep_embedding, encoder_hidden_state, opts) + end + + def down_block_2d(:down_block, sample, timestep_embedding, _encoder_hidden_state, opts) do + down_block_2d(sample, timestep_embedding, nil, opts) + end + + @doc """ + Adds a U-Net upsample block of the given type to the network. + """ + def up_block_2d( + :cross_attention_up_block, + sample, + timestep_embedding, + down_block_states, + encoder_hidden_state, + opts + ) do + up_block_2d(sample, timestep_embedding, down_block_states, encoder_hidden_state, opts) + end + + def up_block_2d( + :up_block, + sample, + timestep_embedding, + down_block_states, + _encoder_hidden_state, + opts + ) do + up_block_2d(sample, timestep_embedding, down_block_states, nil, opts) + end + + @doc """ + Adds U-Net downsample block to the network. + + When `encoder_hidden_state` is not `nil`, applies cross-attention. + """ + def down_block_2d(hidden_state, timestep_embedding, encoder_hidden_state, opts \\ []) do + in_channels = opts[:in_channels] + out_channels = opts[:out_channels] + dropout = opts[:dropout] || 0.0 + depth = opts[:depth] || 1 + activation = opts[:activation] || :swish + norm_epsilon = opts[:norm_epsilon] || 1.0e-6 + norm_num_groups = opts[:norm_num_groups] || 32 + num_attention_heads = opts[:num_attention_heads] || 1 + use_linear_projection = Keyword.get(opts, :use_linear_projection, false) + output_scale_factor = opts[:output_scale_factor] || 1.0 + downsample_padding = opts[:downsample_padding] || [{1, 1}, {1, 1}] + add_downsample = Keyword.get(opts, :add_downsample, true) + name = opts[:name] + + state = {hidden_state, {}} + + {hidden_state, output_states} = + for idx <- 0..(depth - 1), reduce: state do + {hidden_state, output_states} -> + in_channels = if(idx == 0, do: in_channels, else: out_channels) + + hidden_state = + Diffusion.Layers.residual_block( + hidden_state, + in_channels, + out_channels, + timestep_embedding: timestep_embedding, + norm_epsilon: norm_epsilon, + norm_num_groups: norm_num_groups, + dropout: dropout, + activation: activation, + output_scale_factor: output_scale_factor, + name: name |> join("residual_blocks") |> join(idx) + ) + + hidden_state = + if encoder_hidden_state do + transformer_2d(hidden_state, encoder_hidden_state, + hidden_size: out_channels, + num_heads: num_attention_heads, + use_linear_projection: use_linear_projection, + depth: 1, + name: name |> join("transformers") |> join(idx) + ) + else + hidden_state + end + + {hidden_state, + Tuple.insert_at(output_states, tuple_size(output_states), {hidden_state, out_channels})} + end + + if add_downsample do + hidden_state = + Diffusion.Layers.downsample_2d(hidden_state, out_channels, + padding: downsample_padding, + name: join(name, "downsamples.0") + ) + + {hidden_state, + Tuple.insert_at(output_states, tuple_size(output_states), {hidden_state, out_channels})} + else + {hidden_state, output_states} + end + end + + @doc """ + Adds U-Net upsample block to the network. + + When `encoder_hidden_state` is not `nil`, applies cross-attention. + """ + def up_block_2d( + hidden_state, + timestep_embedding, + down_block_states, + encoder_hidden_state, + opts + ) do + in_channels = opts[:in_channels] + out_channels = opts[:out_channels] + dropout = opts[:dropout] || 0.0 + depth = opts[:depth] || 1 + activation = opts[:activation] || :swish + norm_epsilon = opts[:norm_epsilon] || 1.0e-6 + norm_num_groups = opts[:norm_num_groups] || 32 + num_attention_heads = opts[:num_attention_heads] || 1 + use_linear_projection = Keyword.get(opts, :use_linear_projection, false) + output_scale_factor = opts[:output_scale_factor] || 1.0 + add_upsample = Keyword.get(opts, :add_upsample, true) + name = opts[:name] + + ^depth = length(down_block_states) + + hidden_state = + for {{down_block_state, down_block_channels}, idx} <- Enum.with_index(down_block_states), + reduce: hidden_state do + hidden_state -> + in_channels = if(idx == 0, do: in_channels, else: out_channels) + + hidden_state = + Axon.concatenate([hidden_state, down_block_state], axis: -1) + |> Diffusion.Layers.residual_block( + in_channels + down_block_channels, + out_channels, + timestep_embedding: timestep_embedding, + norm_epsilon: norm_epsilon, + norm_num_groups: norm_num_groups, + dropout: dropout, + activation: activation, + output_scale_factor: output_scale_factor, + name: name |> join("residual_blocks") |> join(idx) + ) + + if encoder_hidden_state do + transformer_2d(hidden_state, encoder_hidden_state, + hidden_size: out_channels, + num_heads: num_attention_heads, + use_linear_projection: use_linear_projection, + depth: 1, + name: name |> join("transformers") |> join(idx) + ) + else + hidden_state + end + end + + if add_upsample do + Diffusion.Layers.upsample_2d(hidden_state, out_channels, name: join(name, "upsamples.0")) + else + hidden_state + end + end + + @doc """ + Adds a U-Net middle block with cross attention to the network. + """ + def mid_cross_attention_block_2d( + hidden_state, + timestep_embedding, + encoder_hidden_state, + opts \\ [] + ) do + channels = opts[:channels] + dropout = opts[:dropout] || 0.0 + depth = opts[:depth] || 1 + norm_epsilon = opts[:norm_epsilon] || 1.0e-6 + activation = opts[:activation] || :swish + norm_num_groups = opts[:norm_num_groups] || 32 + num_attention_heads = opts[:num_attention_heads] || 1 + use_linear_projection = Keyword.get(opts, :use_linear_projection, false) + output_scale_factor = opts[:output_scale_factor] || 1.0 + name = opts[:name] + + residual_block_opts = [ + epsilon: norm_epsilon, + num_groups: norm_num_groups, + dropout: dropout, + activation: activation, + output_scale_factor: output_scale_factor + ] + + hidden_state = + Diffusion.Layers.residual_block( + hidden_state, + channels, + channels, + residual_block_opts ++ + [timestep_embedding: timestep_embedding, name: join(name, "residual_blocks.0")] + ) + + for idx <- 0..(depth - 1), reduce: hidden_state do + hidden_state -> + hidden_state + |> transformer_2d( + encoder_hidden_state, + hidden_size: channels, + num_heads: num_attention_heads, + use_linear_projection: use_linear_projection, + depth: 1, + name: name |> join("transformers") |> join(idx) + ) + |> Diffusion.Layers.residual_block( + channels, + channels, + residual_block_opts ++ + [ + timestep_embedding: timestep_embedding, + name: name |> join("residual_blocks") |> join(idx + 1) + ] + ) + end + end + + defp transformer_2d(hidden_state, cross_hidden_state, opts) do + hidden_size = opts[:hidden_size] + num_heads = opts[:num_heads] + use_linear_projection = opts[:use_linear_projection] + depth = opts[:depth] || 1 + dropout = opts[:dropout] || 0.0 + name = opts[:name] + + shortcut = hidden_state + + flatten_spatial = + &Axon.layer( + fn hidden_state, shortcut, _opts -> + {b, h, w, c} = Nx.shape(shortcut) + Nx.reshape(hidden_state, {b, h * w, c}) + end, + [&1, shortcut] + ) + + unflatten_spatial = + &Axon.layer( + fn hidden_state, shortcut, _opts -> + Nx.reshape(hidden_state, Nx.shape(shortcut)) + end, + [&1, shortcut] + ) + + hidden_state + |> Axon.group_norm(32, epsilon: 1.0e-6, name: join(name, "norm")) + |> then(fn hidden_state -> + if use_linear_projection do + hidden_state + |> flatten_spatial.() + |> Axon.dense(hidden_size, name: join(name, "input_projection")) + else + hidden_state + |> Axon.conv(hidden_size, + kernel_size: 1, + strides: 1, + padding: :valid, + name: join(name, "input_projection") + ) + |> flatten_spatial.() + end + end) + |> Layers.Transformer.blocks( + cross_hidden_state: cross_hidden_state, + num_blocks: depth, + num_attention_heads: num_heads, + hidden_size: hidden_size, + query_use_bias: false, + key_use_bias: false, + value_use_bias: false, + layer_norm: [ + epsilon: 1.0e-5 + ], + dropout_rate: dropout, + ffn: &ffn_geglu(&1, 4 * hidden_size, hidden_size, dropout: dropout, name: &2), + block_type: :norm_first, + name: join(name, "blocks") + ) + |> then(fn %{hidden_state: hidden_state} -> + if use_linear_projection do + hidden_state + |> Axon.dense(hidden_size, name: join(name, "output_projection")) + |> unflatten_spatial.() + else + hidden_state + |> unflatten_spatial.() + |> Axon.conv(hidden_size, + kernel_size: 1, + strides: 1, + padding: :valid, + name: join(name, "output_projection") + ) + end + end) + |> Axon.add(shortcut) + end + + # A feed-forward network with GEGLU nonlinearity as in https://arxiv.org/abs/2002.05202 + defp ffn_geglu(x, intermediate_size, output_size, opts) do + name = opts[:name] + dropout = opts[:dropout] || 0.0 + + {x, gate} = + x + |> Axon.dense(intermediate_size * 2, name: join(name, "intermediate")) + |> Axon.split(2, axis: -1) + + x = Axon.multiply(x, Axon.gelu(gate)) + + x + |> Axon.dropout(rate: dropout, name: join(name, "dropout")) + |> Axon.dense(output_size, name: join(name, "output")) + end +end diff --git a/deps/bumblebee/lib/bumblebee/diffusion/lcm_scheduler.ex b/deps/bumblebee/lib/bumblebee/diffusion/lcm_scheduler.ex new file mode 100644 index 0000000000000000000000000000000000000000..1baf226b3d408c8b47a850f5cff68adb44eaf887 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/diffusion/lcm_scheduler.ex @@ -0,0 +1,323 @@ +defmodule Bumblebee.Diffusion.LcmScheduler do + options = [ + num_train_steps: [ + default: 1000, + doc: "the number of diffusion steps used to train the model" + ], + beta_schedule: [ + default: :quadratic, + doc: """ + the beta schedule type, a mapping from a beta range to a sequence of betas for stepping the model. + Either of `:linear`, `:quadratic`, or `:squared_cosine` + """ + ], + beta_start: [ + default: 0.00085, + doc: "the start value for the beta schedule" + ], + beta_end: [ + default: 0.012, + doc: "the end value for the beta schedule" + ], + prediction_type: [ + default: :noise, + doc: """ + prediction type of the denoising model. Either of: + + * `:noise` (default) - the model predicts the noise of the diffusion process + + * `:angular_velocity` - the model predicts velocity in angular parameterization. + See Section 2.4 in [Imagen Video: High Definition Video Generation with Diffusion Models](https://imagen.research.google/video/paper.pdf), + then Section 4 in [Progressive Distillation for Fast Sampling of Diffusion Models](https://arxiv.org/pdf/2202.00512.pdf) + and Appendix D + + """ + ], + alpha_clip_strategy: [ + default: :one, + doc: ~S""" + each step $t$ uses the values of $\bar{\alpha}\_t$ and $\bar{\alpha}\_{t-1}$, + however for $t = 0$ there is no previous alpha. The strategy can be either + `:one` ($\bar{\alpha}\_{t-1} = 1$) or `:alpha_zero` ($\bar{\alpha}\_{t-1} = \bar{\alpha}\_0$) + """ + ], + clip_denoised_sample: [ + default: false, + doc: """ + whether to clip the predicted denoised sample ($x_0$ in Equation (12)) into $[-1, 1]$ + for numerical stability + """ + ], + num_original_steps: [ + default: 50, + doc: ~S""" + the number of denoising steps used during Latent Consistency Distillation (LCD). + The LCD procedure distills a base diffusion model, but instead of sampling all + `:num_train_steps` it skips steps and uses another scheduler accordingly. See + Section 4.3 + """ + ], + boundary_condition_timestep_scale: [ + default: 10.0, + doc: ~S""" + the scaling factor used in the consistency function coefficients. In the original + LCM implementation the authors use the formulation + $$ + c_{skip}(t) = \frac{\sigma_{data}^2}{(st)^2 + \sigma_{data}^2}, \quad + c_{out}(t) = \frac{st}{\sqrt{(st)^2 + \sigma_{data}^2}} + $$ + where $\sigma_{data} = 0.5$ and $s$ is the scaling factor. Increasing the scaling + factor will decrease approximation error, although the approximation error at the + default of `10.0` is already pretty small + """ + ] + ] + + @moduledoc """ + Latent Consistency Model (LCM) sampling. + + This sampling method should be used in combination with LCM. LCM is + a model distilled from a regular diffusion model to predict the + final denoised sample in a single step. The sample quality can be + improved by alternating a couple denoising and noise injection + steps (multi-step sampling), as per Appendix B. + + ## Configuration + + #{Bumblebee.Shared.options_doc(options)} + + ## References + + * [Latent Consistency Models: Synthesizing High-Resolution Images with Few-Step Inference](https://arxiv.org/abs/2310.04378) + * [Consistency Models](https://arxiv.org/pdf/2303.01469.pdf) + + """ + + defstruct Bumblebee.Shared.option_defaults(options) + + @behaviour Bumblebee.Scheduler + @behaviour Bumblebee.Configurable + + import Nx.Defn + + alias Bumblebee.Diffusion.SchedulerUtils + + @impl true + def config(scheduler, opts) do + Bumblebee.Shared.put_config_attrs(scheduler, opts) + end + + @impl true + def init(scheduler, num_steps, _sample_template, prng_key, opts \\ []) do + opts = Keyword.validate!(opts, [:strength]) + + strength = Keyword.get(opts, :strength, 1.0) + + timesteps = + timesteps(num_steps, scheduler.num_original_steps, scheduler.num_train_steps, strength) + + {alpha_bars} = init_parameters(scheduler: scheduler) + + state = %{ + timesteps: timesteps, + alpha_bars: alpha_bars, + iteration: 0, + prng_key: prng_key + } + + {state, timesteps} + end + + deftransformp timesteps(num_steps, num_original_steps, num_train_steps, strength) do + skipping_step_k = div(num_train_steps, num_original_steps) + + # Original steps used during Latent Consistency Distillation + original_timesteps = + {floor(num_original_steps * strength)} + |> Nx.iota() + |> Nx.add(1) + |> Nx.multiply(skipping_step_k) + |> Nx.subtract(1) + + if num_steps > num_train_steps do + raise ArgumentError, + "expected the number of steps to be less or equal to the number of" <> + " training steps (#{num_train_steps}), got: #{num_steps}" + end + + if num_steps > num_original_steps do + raise ArgumentError, + "expected the number of steps to be less or equal to the number of" <> + " original steps (#{num_original_steps}), got: #{num_steps}" + end + + if num_steps > Nx.size(original_timesteps) do + raise ArgumentError, + "expected the number of steps to be less or equal to num_original_steps * strength" <> + " (#{num_original_steps} * #{strength}). Either reduce the number of steps or" <> + "increase the strength" + end + + # We select evenly spaced indices from the original timesteps. + # See the discussion in https://github.com/huggingface/diffusers/pull/5836 + indices = + Nx.linspace(0, Nx.size(original_timesteps), n: num_steps, endpoint: false) + |> Nx.floor() + |> Nx.as_type(:s64) + + original_timesteps + |> Nx.reverse() + |> Nx.take(indices) + end + + defnp init_parameters(opts \\ []) do + %{ + beta_start: beta_start, + beta_end: beta_end, + beta_schedule: beta_schedule, + num_train_steps: num_train_steps + } = opts[:scheduler] + + betas = + SchedulerUtils.beta_schedule(beta_schedule, num_train_steps, + start: beta_start, + end: beta_end + ) + + alphas = 1 - betas + + {Nx.cumulative_product(alphas)} + end + + @impl true + def step(scheduler, state, sample, prediction) do + do_step(state, sample, prediction, scheduler: scheduler) + end + + defnp do_step(state, sample, prediction, opts) do + scheduler = opts[:scheduler] + + step_index = state.iteration + prev_step_index = state.iteration + 1 + + timestep = state.timesteps[step_index] + + prev_timestep = + if prev_step_index < Nx.size(state.timesteps) do + state.timesteps[prev_step_index] + else + timestep + end + + # Note that in the paper alpha_bar_t is denoted as a(t) and + # beta_bar_t is denoted as sigma(t)^2 + + alpha_bar_t = state.alpha_bars[timestep] + + alpha_bar_t_prev = + if prev_timestep >= 0 do + state.alpha_bars[prev_timestep] + else + case scheduler.alpha_clip_strategy do + :one -> 1.0 + :alpha_zero -> state.alpha_bars[0] + end + end + + beta_bar_t = 1 - alpha_bar_t + beta_bar_t_prev = 1 - alpha_bar_t_prev + + # See Appendix D + pred_denoised_sample = + case scheduler.prediction_type do + :noise -> + (sample - Nx.sqrt(beta_bar_t) * prediction) / Nx.sqrt(alpha_bar_t) + + :angular_velocity -> + Nx.sqrt(alpha_bar_t) * sample - Nx.sqrt(beta_bar_t) * prediction + end + + pred_denoised_sample = + if scheduler.clip_denoised_sample do + Nx.clip(pred_denoised_sample, -1, 1) + else + pred_denoised_sample + end + + {c_skip, c_out} = + consistency_model_coefficients(timestep, + boundary_condition_timestep_scale: scheduler.boundary_condition_timestep_scale + ) + + # See Equation (9) + denoised_sample = c_skip * sample + c_out * pred_denoised_sample + + # See Appendix B + # + # We insert additional noise after each but last step. This also + # means no noise is used for one-step sampling + {prev_sample, next_key} = + if state.iteration < Nx.size(state.timesteps) - 1 do + {rand, next_key} = Nx.Random.normal(state.prng_key, shape: Nx.shape(denoised_sample)) + out = Nx.sqrt(alpha_bar_t_prev) * denoised_sample + Nx.sqrt(beta_bar_t_prev) * rand + {out, next_key} + else + {denoised_sample, state.prng_key} + end + + state = %{state | iteration: state.iteration + 1, prng_key: next_key} + + {state, prev_sample} + end + + defnp consistency_model_coefficients(timestep, opts) do + # See Appendix C in https://arxiv.org/pdf/2303.01469.pdf + # + # Note that LCM authors use different coefficients for the + # consistency function than the original CM paper. In their + # formulation the timestep is scaled by a constant factor. + + boundary_condition_timestep_scale = opts[:boundary_condition_timestep_scale] + sigma_data = 0.5 + + scaled_timestep = timestep * boundary_condition_timestep_scale + + c_skip = sigma_data ** 2 / (scaled_timestep ** 2 + sigma_data ** 2) + c_out = scaled_timestep / Nx.sqrt(scaled_timestep ** 2 + sigma_data ** 2) + + {c_skip, c_out} + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(scheduler, data) do + import Bumblebee.Shared.Converters + + opts = + convert!(data, + num_train_steps: {"num_train_timesteps", number()}, + beta_schedule: { + "beta_schedule", + mapping(%{ + "linear" => :linear, + "scaled_linear" => :quadratic, + "squaredcos_cap_v2" => :squared_cosine + }) + }, + beta_start: {"beta_start", number()}, + beta_end: {"beta_end", number()}, + prediction_type: + {"prediction_type", + mapping(%{"epsilon" => :noise, "v_prediction" => :angular_velocity})}, + alpha_clip_strategy: { + "set_alpha_to_one", + mapping(%{true => :one, false => :alpha_zero}) + }, + clip_denoised_sample: {"clip_sample", boolean()}, + num_original_steps: {"original_inference_steps", number()}, + boundary_condition_timestep_scale: {"timestep_scaling", number()} + ) + + @for.config(scheduler, opts) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/diffusion/pndm_scheduler.ex b/deps/bumblebee/lib/bumblebee/diffusion/pndm_scheduler.ex new file mode 100644 index 0000000000000000000000000000000000000000..29177dae2db3262186d6a4798afebbaa8134836d --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/diffusion/pndm_scheduler.ex @@ -0,0 +1,447 @@ +defmodule Bumblebee.Diffusion.PndmScheduler do + options = [ + num_train_steps: [ + default: 1000, + doc: "the number of diffusion steps used to train the model" + ], + beta_schedule: [ + default: :linear, + doc: """ + the beta schedule type, a mapping from a beta range to a sequence of betas for stepping the model. + Either of `:linear`, `:quadratic`, or `:squared_cosine` + """ + ], + beta_start: [ + default: 0.0001, + doc: "the start value for the beta schedule" + ], + beta_end: [ + default: 0.02, + doc: "the end value for the beta schedule" + ], + prediction_type: [ + default: :noise, + doc: """ + prediction type of the denoising model. Either of: + + * `:noise` (default) - the model predicts the noise of the diffusion process + + * `:angular_velocity` - the model predicts velocity in angular parameterization. + See Section 2.4 in [Imagen Video: High Definition Video Generation with Diffusion Models](https://imagen.research.google/video/paper.pdf), + then Section 4 in [Progressive Distillation for Fast Sampling of Diffusion Models](https://arxiv.org/pdf/2202.00512.pdf) + and Appendix D + + """ + ], + alpha_clip_strategy: [ + default: :alpha_zero, + doc: ~S""" + each step $t$ uses the values of $\bar{\alpha}\_t$ and $\bar{\alpha}\_{t-1}$, + however for $t = 0$ there is no previous alpha. The strategy can be either + `:one` ($\bar{\alpha}\_{t-1} = 1$) or `:alpha_zero` ($\bar{\alpha}\_{t-1} = \bar{\alpha}\_0$) + """ + ], + timesteps_offset: [ + default: 0, + doc: ~S""" + an offset added to the inference steps. You can use a combination of `timesteps_offset: 1` and + `alpha_clip_strategy: :alpha_zero`, so that the last step $t = 1$ uses $\bar{\alpha}\_1$ + and $\bar{\alpha}\_0$, as done in stable diffusion + """ + ], + reduce_warmup: [ + default: false, + doc: """ + when `true`, the first few samples are computed using lower-order linear multi-step, + rather than the Runge-Kutta method. This results in less forward passes of the model + """ + ] + ] + + @moduledoc """ + Pseudo numerical methods for diffusion models (PNDMs). + + The sampling is based on two numerical methods for solving ODE: the + Runge-Kutta method (RK) and the linear multi-step method (LMS). The + gradient at each step is computed according to either of these methods, + however the transfer part (approximating the next sample based on + current sample and gradient) is non-linear. Because of this property, + the authors of the paper refer to them as pseudo numerical methods, + denoted as PRK and PLMS respectively. + + ## Configuration + + #{Bumblebee.Shared.options_doc(options)} + + ## References + + * [Pseudo Numerical Methods for Diffusion Models on Manifolds](https://arxiv.org/abs/2202.09778) + + """ + + defstruct Bumblebee.Shared.option_defaults(options) + + @behaviour Bumblebee.Scheduler + @behaviour Bumblebee.Configurable + + import Nx.Defn + + alias Bumblebee.Diffusion.SchedulerUtils + + @impl true + def config(scheduler, opts) do + Bumblebee.Shared.put_config_attrs(scheduler, opts) + end + + @impl true + def init(scheduler, num_steps, sample_template, _prng_key) do + timesteps = + timesteps( + scheduler.num_train_steps, + num_steps, + scheduler.timesteps_offset, + scheduler.reduce_warmup + ) + + alpha_bars = init_parameters(scheduler: scheduler) + + empty = Nx.fill(sample_template, 0) + + state = %{ + timesteps: timesteps, + timestep_gap: div(scheduler.num_train_steps, num_steps), + alpha_bars: alpha_bars, + iteration: 0, + recent_prediction: empty |> List.duplicate(4) |> List.to_tuple(), + current_sample: empty, + prediction_prime: empty + } + + {state, timesteps} + end + + defnp init_parameters(opts \\ []) do + %{ + beta_start: beta_start, + beta_end: beta_end, + beta_schedule: beta_schedule, + num_train_steps: num_train_steps + } = opts[:scheduler] + + betas = + SchedulerUtils.beta_schedule(beta_schedule, num_train_steps, + start: beta_start, + end: beta_end + ) + + alphas = 1 - betas + + Nx.cumulative_product(alphas) + end + + deftransformp timesteps(num_train_steps, num_steps, offset, reduce_warmup) do + # Note that there are more timesteps than `num_steps`. + # That's because each timestep corresponds to a single forward pass + # of the denoising model and the first few steps require multiple such + # passes. In other words, the timesteps list is used for subsequent + # model calls, while the actual sampling happens at the same timesteps + # as with DDIM. + + timestep_gap = div(num_train_steps, num_steps) + + ddim_timesteps = SchedulerUtils.ddim_timesteps(num_train_steps, num_steps, offset) + + if reduce_warmup do + if num_steps < 2 do + raise ArgumentError, + "expected at least 2 steps when using :reduce_warmup, got: #{inspect(num_steps)}" + end + + just_plms_timesteps(ddim_timesteps, timestep_gap) + else + if num_steps < 4 do + raise ArgumentError, "expected at least 4 steps, got: #{inspect(num_steps)}" + end + + prk_plms_timesteps(ddim_timesteps, timestep_gap) + end + end + + defnp prk_plms_timesteps(ddim_timesteps, timestep_gap) do + if Nx.size(ddim_timesteps) < 4 do + prk_timesteps(ddim_timesteps, timestep_gap) + else + prk_timesteps = prk_timesteps(ddim_timesteps[0..2//1], timestep_gap) + plms_timesteps = ddim_timesteps[3..-1//1] + Nx.concatenate([prk_timesteps, plms_timesteps]) + end + end + + defnp prk_timesteps(timesteps, timestep_gap) do + deltas = Nx.stack([0, div(timestep_gap, 2), div(timestep_gap, 2), timestep_gap]) + + timesteps + |> Nx.reshape({:auto, 1}) + |> Nx.subtract(Nx.reshape(deltas, {1, :auto})) + |> Nx.flatten() + end + + defnp just_plms_timesteps(ddim_timesteps, timestep_gap) do + leading_timesteps = Nx.stack([ddim_timesteps[0], ddim_timesteps[0] - timestep_gap]) + + if Nx.size(ddim_timesteps) < 2 do + leading_timesteps + else + Nx.concatenate([leading_timesteps, ddim_timesteps[1..-1//1]]) + end + end + + @impl true + def step(scheduler, state, sample, prediction) do + do_step(state, sample, prediction, scheduler: scheduler) + end + + defnp do_step(state, sample, prediction, opts) do + scheduler = opts[:scheduler] + + {state, prev} = + if scheduler.reduce_warmup do + step_just_plms(scheduler, state, sample, prediction) + else + step_prk_plms(scheduler, state, sample, prediction) + end + + state = %{state | iteration: state.iteration + 1} + + {state, prev} + end + + defnp step_prk_plms(scheduler, state, sample, prediction) do + # This is the version from the original paper [1], specifically F-PNDM. + # It uses the Runge-Kutta method to compute the first 3 results (each + # requiring 4 iterations). + # + # [1]: https://arxiv.org/abs/2202.09778 + + if state.iteration < 12 do + step_prk(scheduler, state, sample, prediction) + else + step_plms(scheduler, state, sample, prediction) + end + end + + defnp step_just_plms(scheduler, state, sample, prediction) do + # This alternative version is based on the paper, however instead of the + # Runge-Kutta method, it uses lower-order linear multi-step for computing + # the first 3 results (2, 1, 1 iterations respectively). For the original + # implementation see [1]. + # + # [1]: https://github.com/CompVis/latent-diffusion/pull/51 + + if state.iteration < 4 do + step_warmup_plms(scheduler, state, sample, prediction) + else + step_plms(scheduler, state, sample, prediction) + end + end + + # # Note on notation + # + # The paper denotes sample as x_t, prediction as e_t, model as eps, + # prev_sample function as phi. The superscript in case of x_t and e_t + # translates to consecutive iterations, since we have one iteration + # per model forward pass (the eps function). We keep track of x_t as + # current_sample, and prediction_prime corresponds to e_t prime. + + defnp step_prk(scheduler, state, sample, prediction) do + # See Equation (13) + + %{prediction_prime: prediction_prime, current_sample: current_sample} = state + + rk_step_number = rem(state.iteration, 4) + + state = + if rk_step_number == 0 do + store_prediction(state, prediction) + else + state + end + + {prediction_prime, current_sample, prediction} = + cond do + rk_step_number == 0 -> + prediction_prime = prediction_prime + prediction / 6 + {prediction_prime, sample, prediction} + + rk_step_number == 1 -> + prediction_prime = prediction_prime + prediction / 3 + {prediction_prime, current_sample, prediction} + + rk_step_number == 2 -> + prediction_prime = prediction_prime + prediction / 3 + {prediction_prime, current_sample, prediction} + + true -> + prediction_prime = prediction_prime + prediction / 6 + {Nx.broadcast(0.0, prediction_prime), current_sample, prediction_prime} + end + + state = %{state | current_sample: current_sample, prediction_prime: prediction_prime} + + timestep = state.timesteps[state.iteration - rk_step_number] + diff = if(rk_step_number < 2, do: div(state.timestep_gap, 2), else: state.timestep_gap) + prev_timestep = timestep - diff + + prev_sample = + prev_sample(scheduler, state, current_sample, prediction, timestep, prev_timestep) + + {state, prev_sample} + end + + defnp step_warmup_plms(scheduler, state, sample, prediction) do + # The first two iterations use Equation (22), third iteration uses + # Equation (23), and fourth iteration uses third-order LMS in the + # same spirit. + + %{current_sample: current_sample} = state + + state = + if state.iteration != 1 do + store_prediction(state, prediction) + else + state + end + + {current_sample, prediction} = + cond do + state.iteration == 0 -> + {sample, prediction} + + state.iteration == 1 -> + prediction_prime = (prediction + elem(state.recent_prediction, 0)) / 2 + {current_sample, prediction_prime} + + state.iteration == 2 -> + prediction_prime = + (3 * elem(state.recent_prediction, 0) - elem(state.recent_prediction, 1)) / 2 + + {sample, prediction_prime} + + true -> + prediction_prime = + (23 * elem(state.recent_prediction, 0) - 16 * elem(state.recent_prediction, 1) + + 5 * elem(state.recent_prediction, 2)) / 12 + + {sample, prediction_prime} + end + + state = %{state | current_sample: current_sample} + + timestep = + if state.iteration == 1 do + state.timesteps[state.iteration - 1] + else + state.timesteps[state.iteration] + end + + prev_timestep = timestep - state.timestep_gap + + prev_sample = + prev_sample(scheduler, state, current_sample, prediction, timestep, prev_timestep) + + {state, prev_sample} + end + + defnp step_plms(scheduler, state, sample, prediction) do + # See Equation (12) + + state = store_prediction(state, prediction) + + prediction = + (55 * elem(state.recent_prediction, 0) - 59 * elem(state.recent_prediction, 1) + + 37 * elem(state.recent_prediction, 2) - 9 * elem(state.recent_prediction, 3)) / 24 + + timestep = state.timesteps[state.iteration] + prev_timestep = timestep - state.timestep_gap + + prev_sample = prev_sample(scheduler, state, sample, prediction, timestep, prev_timestep) + + {state, prev_sample} + end + + defnp prev_sample(scheduler, state, sample, prediction, timestep, prev_timestep) do + # See Equation (11) + + alpha_bar_t = state.alpha_bars[timestep] + + alpha_bar_t_prev = + if prev_timestep >= 0 do + state.alpha_bars[prev_timestep] + else + case scheduler.alpha_clip_strategy do + :one -> 1.0 + :alpha_zero -> state.alpha_bars[0] + end + end + + sample_coeff = (alpha_bar_t_prev / alpha_bar_t) ** 0.5 + + noise_coeff = alpha_bar_t_prev - alpha_bar_t + + noise_denom_coeff = + alpha_bar_t * (1 - alpha_bar_t_prev) ** 0.5 + + (alpha_bar_t * (1 - alpha_bar_t) * alpha_bar_t_prev) ** 0.5 + + noise = + case scheduler.prediction_type do + :noise -> + prediction + + :angular_velocity -> + Nx.sqrt(alpha_bar_t) * prediction + Nx.sqrt(1 - alpha_bar_t) * sample + end + + sample_coeff * sample - noise_coeff * noise / noise_denom_coeff + end + + deftransformp store_prediction(state, prediction) do + recent_prediction = + state.recent_prediction + |> Tuple.delete_at(tuple_size(state.recent_prediction) - 1) + |> Tuple.insert_at(0, prediction) + + %{state | recent_prediction: recent_prediction} + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(scheduler, data) do + import Bumblebee.Shared.Converters + + opts = + convert!(data, + num_train_steps: {"num_train_timesteps", number()}, + beta_schedule: { + "beta_schedule", + mapping(%{ + "linear" => :linear, + "scaled_linear" => :quadratic, + "squaredcos_cap_v2" => :squared_cosine + }) + }, + beta_start: {"beta_start", number()}, + beta_end: {"beta_end", number()}, + prediction_type: + {"prediction_type", + mapping(%{"epsilon" => :noise, "v_prediction" => :angular_velocity})}, + alpha_clip_strategy: { + "set_alpha_to_one", + mapping(%{true => :one, false => :alpha_zero}) + }, + timesteps_offset: {"steps_offset", number()}, + reduce_warmup: {"skip_prk_steps", boolean()} + ) + + @for.config(scheduler, opts) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/diffusion/scheduler_utils.ex b/deps/bumblebee/lib/bumblebee/diffusion/scheduler_utils.ex new file mode 100644 index 0000000000000000000000000000000000000000..60069987eeef3e18e09482e1f9f2a7a410f8ed60 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/diffusion/scheduler_utils.ex @@ -0,0 +1,74 @@ +defmodule Bumblebee.Diffusion.SchedulerUtils do + @moduledoc false + + import Nx.Defn + + @pi :math.pi() + + @doc """ + Returns a beta schedule of the given type. + + The supported types are: + + * `:linear` - a linear schedule from Ho et al. (https://arxiv.org/pdf/2006.11239.pdf) + + * `:quadratic` - a quadratic schedule specific to the latent diffusion models + + * `:squared_cosine` - a cosine schedule from Nichol et al. (https://arxiv.org/pdf/2102.09672.pdf), + used in OpenAI GLIDE + + ## Options + + * `:start` - start for the linear and quadratic schedules. Defaults to `0.0001` + + * `:end` - end for the linear and quadratic schedules. Defaults to `0.02` + + """ + deftransform beta_schedule(type, num_timesteps, opts \\ []) do + opts = Keyword.validate!(opts, start: 0.0001, end: 0.02) + beta_start = opts[:start] + beta_end = opts[:end] + + case type do + :linear -> + Nx.linspace(beta_start, beta_end, n: num_timesteps) + + :quadratic -> + Nx.linspace(Nx.sqrt(beta_start), Nx.sqrt(beta_end), n: num_timesteps) |> Nx.pow(2) + + :squared_cosine -> + betas_for_alpha_bar(&squared_cosine_alpha_bar/1, num_timesteps: num_timesteps) + end + end + + defnp squared_cosine_alpha_bar(t) do + s = 0.008 + Nx.cos((t + s) / (1 + s) * @pi / 2) ** 2 + end + + # Creates a beta schedule that discretizes the given alpha_t_bar function, + # which defines the cumulative product of (1 - beta) over time t in [0, 1]. + defnp betas_for_alpha_bar(alpha_t_bar_fun, opts \\ []) do + opts = keyword!(opts, [:num_timesteps, max_beta: 0.999]) + num_timesteps = opts[:num_timesteps] + max_beta = opts[:max_beta] + + i = Nx.iota({num_timesteps}) + t1 = i / num_timesteps + t2 = (i + 1) / num_timesteps + beta = 1 - alpha_t_bar_fun.(t2) / alpha_t_bar_fun.(t1) + min(beta, max_beta) + end + + @doc """ + Returns evenly spaced timesteps as used in the DDIM schedule. + """ + deftransform ddim_timesteps(num_train_steps, num_steps, offset) do + timestep_gap = div(num_train_steps, num_steps) + + Nx.iota({num_steps}) + |> Nx.multiply(timestep_gap) + |> Nx.add(offset) + |> Nx.reverse() + end +end diff --git a/deps/bumblebee/lib/bumblebee/diffusion/stable_diffusion.ex b/deps/bumblebee/lib/bumblebee/diffusion/stable_diffusion.ex new file mode 100644 index 0000000000000000000000000000000000000000..71fd5d343208986b3aeb5d37d1dec2f38deffb5b --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/diffusion/stable_diffusion.ex @@ -0,0 +1,458 @@ +defmodule Bumblebee.Diffusion.StableDiffusion do + @moduledoc """ + High-level tasks based on Stable Diffusion. + """ + + import Nx.Defn + + alias Bumblebee.Utils + alias Bumblebee.Shared + + @type text_to_image_input :: + String.t() + | %{ + :prompt => String.t(), + optional(:negative_prompt) => String.t() | nil, + optional(:seed) => integer() | nil + } + @type text_to_image_output :: %{results: list(text_to_image_result())} + @type text_to_image_result :: %{:image => Nx.Tensor.t(), optional(:is_safe) => boolean()} + + @doc ~S""" + Build serving for prompt-driven image generation. + + The serving accepts `t:text_to_image_input/0` and returns `t:text_to_image_output/0`. + A list of inputs is also supported. + + You can specify `:safety_checker` model to automatically detect + when a generated image is offensive or harmful and filter it out. + + ## Options + + * `:safety_checker` - the safety checker model info map. When a + safety checker is used, each output entry has an additional + `:is_safe` property and unsafe images are automatically zeroed. + Make sure to also set `:safety_checker_featurizer` + + * `:safety_checker_featurizer` - the featurizer to use to preprocess + the safety checker input images + + * `:num_steps` - the number of denoising steps. More denoising + steps usually lead to higher image quality at the expense of + slower inference. Defaults to `50` + + * `:num_images_per_prompt` - the number of images to generate for + each prompt. Defaults to `1` + + * `:guidance_scale` - the scale used for classifier-free diffusion + guidance. Higher guidance scale makes the generated images more + closely reflect the text prompt. This parameter corresponds to + $\omega$ in Equation (2) of the [Imagen paper](https://arxiv.org/pdf/2205.11487.pdf). + Defaults to `7.5` + + * `:compile` - compiles all computations for predefined input shapes + during serving initialization. Should be a keyword list with the + following keys: + + * `:batch_size` - the maximum batch size of the input. Inputs + are optionally padded to always match this batch size + + * `:sequence_length` - the maximum input sequence length. Input + sequences are always padded/truncated to match that length + + It is advised to set this option in production and also configure + a defn compiler using `:defn_options` to maximally reduce inference + time. + + * `:defn_options` - the options for JIT compilation. Defaults to `[]` + + * `:preallocate_params` - when `true`, explicitly allocates params + on the device configured by `:defn_options`. You may want to set + this option when using partitioned serving, to allocate params + on each of the devices. When using this option, you should first + load the parameters into the host. This can be done by passing + `backend: {EXLA.Backend, client: :host}` to `load_model/1` and friends. + Defaults to `false` + + ## Examples + + repository_id = "CompVis/stable-diffusion-v1-4" + + {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "openai/clip-vit-large-patch14"}) + {:ok, clip} = Bumblebee.load_model({:hf, repository_id, subdir: "text_encoder"}) + {:ok, unet} = Bumblebee.load_model({:hf, repository_id, subdir: "unet"}) + {:ok, vae} = Bumblebee.load_model({:hf, repository_id, subdir: "vae"}, architecture: :decoder) + {:ok, scheduler} = Bumblebee.load_scheduler({:hf, repository_id, subdir: "scheduler"}) + {:ok, featurizer} = Bumblebee.load_featurizer({:hf, repository_id, subdir: "feature_extractor"}) + {:ok, safety_checker} = Bumblebee.load_model({:hf, repository_id, subdir: "safety_checker"}) + + serving = + Bumblebee.Diffusion.StableDiffusion.text_to_image(clip, unet, vae, tokenizer, scheduler, + num_steps: 20, + num_images_per_prompt: 2, + safety_checker: safety_checker, + safety_checker_featurizer: featurizer, + compile: [batch_size: 1, sequence_length: 60], + defn_options: [compiler: EXLA] + ) + + prompt = "numbat in forest, detailed, digital art" + Nx.Serving.run(serving, prompt) + #=> %{ + #=> results: [ + #=> %{ + #=> image: #Nx.Tensor< + #=> u8[512][512][3] + #=> ... + #=> >, + #=> is_safe: true + #=> }, + #=> %{ + #=> image: #Nx.Tensor< + #=> u8[512][512][3] + #=> ... + #=> >, + #=> is_safe: true + #=> } + #=> ] + #=> } + + """ + @spec text_to_image( + Bumblebee.model_info(), + Bumblebee.model_info(), + Bumblebee.model_info(), + Bumblebee.Tokenizer.t(), + Bumblebee.Scheduler.t(), + keyword() + ) :: Nx.Serving.t() + def text_to_image(encoder, unet, vae, tokenizer, scheduler, opts \\ []) do + opts = + Keyword.validate!(opts, [ + :safety_checker, + :safety_checker_featurizer, + :compile, + num_steps: 50, + num_images_per_prompt: 1, + guidance_scale: 7.5, + defn_options: [], + preallocate_params: false + ]) + + safety_checker = opts[:safety_checker] + safety_checker_featurizer = opts[:safety_checker_featurizer] + num_steps = opts[:num_steps] + num_images_per_prompt = opts[:num_images_per_prompt] + preallocate_params = opts[:preallocate_params] + defn_options = opts[:defn_options] + + if safety_checker != nil and safety_checker_featurizer == nil do + raise ArgumentError, "got :safety_checker but no :safety_checker_featurizer was specified" + end + + safety_checker? = safety_checker != nil + + compile = + if compile = opts[:compile] do + compile + |> Keyword.validate!([:batch_size, :sequence_length]) + |> Shared.require_options!([:batch_size, :sequence_length]) + end + + batch_size = compile[:batch_size] + sequence_length = compile[:sequence_length] + + tokenizer = + Bumblebee.configure(tokenizer, + length: sequence_length, + return_token_type_ids: false, + return_attention_mask: false + ) + + {_, encoder_predict} = Axon.build(encoder.model) + {_, vae_predict} = Axon.build(vae.model) + {_, unet_predict} = Axon.build(unet.model) + + scheduler_init = &Bumblebee.scheduler_init(scheduler, num_steps, &1, &2) + scheduler_step = &Bumblebee.scheduler_step(scheduler, &1, &2, &3) + + image_fun = + &text_to_image_impl( + encoder_predict, + &1, + unet_predict, + &2, + vae_predict, + &3, + scheduler_init, + scheduler_step, + &4, + num_images_per_prompt: opts[:num_images_per_prompt], + latents_sample_size: unet.spec.sample_size, + latents_channels: unet.spec.in_channels, + guidance_scale: opts[:guidance_scale] + ) + + safety_checker_fun = + if safety_checker do + {_, predict_fun} = Axon.build(safety_checker.model) + + fn params, input -> + input = Bumblebee.Featurizer.process_batch(safety_checker_featurizer, input) + predict_fun.(params, input) + end + end + + # Note that all of these are copied when using serving as a process + init_args = [ + {image_fun, safety_checker_fun}, + encoder.params, + unet.params, + vae.params, + {safety_checker?, safety_checker[:params]}, + safety_checker_featurizer, + {compile != nil, batch_size, sequence_length}, + num_images_per_prompt, + preallocate_params + ] + + Nx.Serving.new( + fn defn_options -> apply(&init/10, init_args ++ [defn_options]) end, + defn_options + ) + |> Nx.Serving.batch_size(batch_size) + |> Nx.Serving.client_preprocessing(&client_preprocessing(&1, tokenizer)) + |> Nx.Serving.client_postprocessing(&client_postprocessing(&1, &2, safety_checker)) + end + + defp init( + {image_fun, safety_checker_fun}, + encoder_params, + unet_params, + vae_params, + {safety_checker?, safety_checker_params}, + safety_checker_featurizer, + {compile?, batch_size, sequence_length}, + num_images_per_prompt, + preallocate_params, + defn_options + ) do + encoder_params = Shared.maybe_preallocate(encoder_params, preallocate_params, defn_options) + unet_params = Shared.maybe_preallocate(unet_params, preallocate_params, defn_options) + vae_params = Shared.maybe_preallocate(vae_params, preallocate_params, defn_options) + + image_fun = + Shared.compile_or_jit(image_fun, :image, defn_options, compile?, fn -> + inputs = %{ + "conditional_and_unconditional" => %{ + "input_ids" => Nx.template({batch_size, 2, sequence_length}, :u32) + }, + "seed" => Nx.template({batch_size}, :s64) + } + + [encoder_params, unet_params, vae_params, inputs] + end) + + safety_checker_fun = + safety_checker_fun && + Shared.compile_or_jit(safety_checker_fun, :safety_checker, defn_options, compile?, fn -> + inputs = + Bumblebee.Featurizer.batch_template( + safety_checker_featurizer, + batch_size * num_images_per_prompt + ) + + [safety_checker_params, inputs] + end) + + safety_checker_params = + safety_checker_params && + Shared.maybe_preallocate(safety_checker_params, preallocate_params, defn_options) + + fn inputs -> + inputs = Shared.maybe_pad(inputs, batch_size) + + image = image_fun.(encoder_params, unet_params, vae_params, inputs) + + output = + if safety_checker? do + inputs = Bumblebee.Featurizer.process_input(safety_checker_featurizer, image) + outputs = safety_checker_fun.(safety_checker_params, inputs) + %{image: image, is_unsafe: outputs.is_unsafe} + else + %{image: image} + end + + output + |> Utils.Nx.composite_unflatten_batch(Utils.Nx.batch_size(inputs)) + |> Shared.serving_post_computation() + end + end + + defp client_preprocessing(input, tokenizer) do + {inputs, multi?} = Shared.validate_serving_input!(input, &validate_input/1) + + seed = Enum.map(inputs, & &1.seed) |> Nx.tensor(type: :s64, backend: Nx.BinaryBackend) + + # Note: we need to tokenize all sequences together, so that + # they are padded to the same length (if not specified) + prompts = Enum.flat_map(inputs, &[&1.prompt, &1.negative_prompt]) + + prompt_pairs = + Nx.with_default_backend(Nx.BinaryBackend, fn -> + inputs = Bumblebee.apply_tokenizer(tokenizer, prompts) + Utils.Nx.composite_unflatten_batch(inputs, Nx.axis_size(seed, 0)) + end) + + inputs = %{"conditional_and_unconditional" => prompt_pairs, "seed" => seed} + + {Nx.Batch.concatenate([inputs]), multi?} + end + + defp client_postprocessing({outputs, _metadata}, multi?, safety_checker?) do + for outputs <- Utils.Nx.batch_to_list(outputs) do + results = + for outputs = %{image: image} <- Utils.Nx.batch_to_list(outputs) do + if safety_checker? do + if Nx.to_number(outputs.is_unsafe) == 1 do + %{image: zeroed(image), is_safe: false} + else + %{image: image, is_safe: true} + end + else + %{image: image} + end + end + + %{results: results} + end + |> Shared.normalize_output(multi?) + end + + defp zeroed(tensor) do + 0 + |> Nx.tensor(type: Nx.type(tensor), backend: Nx.BinaryBackend) + |> Nx.broadcast(Nx.shape(tensor)) + end + + defnp text_to_image_impl( + encoder_predict, + encoder_params, + unet_predict, + unet_params, + vae_predict, + vae_params, + scheduler_init, + scheduler_step, + inputs, + opts \\ [] + ) do + num_images_per_prompt = opts[:num_images_per_prompt] + latents_sample_size = opts[:latents_sample_size] + latents_in_channels = opts[:latents_channels] + guidance_scale = opts[:guidance_scale] + + seed = inputs["seed"] + + inputs = + inputs["conditional_and_unconditional"] + # Transpose conditional and unconditional to separate blocks + |> composite_transpose_leading() + |> Utils.Nx.composite_flatten_batch() + + %{hidden_state: text_embeddings} = encoder_predict.(encoder_params, inputs) + + {_twice_batch_size, sequence_length, hidden_size} = Nx.shape(text_embeddings) + + text_embeddings = + text_embeddings + |> Nx.new_axis(1) + |> Nx.tile([1, num_images_per_prompt, 1, 1]) + |> Nx.reshape({:auto, sequence_length, hidden_size}) + + prng_key = + seed + |> Nx.vectorize(:batch) + |> Nx.Random.key() + |> Nx.Random.split(parts: num_images_per_prompt) + |> Nx.devectorize() + |> Nx.flatten(axes: [0, 1]) + |> Nx.vectorize(:batch) + + {latents, prng_key} = + Nx.Random.normal(prng_key, + shape: {latents_sample_size, latents_sample_size, latents_in_channels} + ) + + {scheduler_state, timesteps} = scheduler_init.(Nx.to_template(latents), prng_key) + + latents = Nx.devectorize(latents) + + {latents, _} = + while {latents, {scheduler_state, text_embeddings, unet_params}}, timestep <- timesteps do + unet_inputs = %{ + "sample" => Nx.concatenate([latents, latents]), + "timestep" => timestep, + "encoder_hidden_state" => text_embeddings + } + + %{sample: noise_pred} = unet_predict.(unet_params, unet_inputs) + + {noise_pred_conditional, noise_pred_unconditional} = + split_conditional_and_unconditional(noise_pred) + + noise_pred = + noise_pred_unconditional + + guidance_scale * (noise_pred_conditional - noise_pred_unconditional) + + {scheduler_state, latents} = + scheduler_step.( + scheduler_state, + Nx.vectorize(latents, :batch), + Nx.vectorize(noise_pred, :batch) + ) + + latents = Nx.devectorize(latents) + + {latents, {scheduler_state, text_embeddings, unet_params}} + end + + latents = latents * (1 / 0.18215) + + %{sample: image} = vae_predict.(vae_params, latents) + + NxImage.from_continuous(image, -1, 1) + end + + deftransformp composite_transpose_leading(container) do + Utils.Nx.map(container, fn tensor -> + [first, second | rest] = Nx.axes(tensor) + Nx.transpose(tensor, axes: [second, first | rest]) + end) + end + + defnp split_conditional_and_unconditional(tensor) do + batch_size = Nx.axis_size(tensor, 0) + half_size = div(batch_size, 2) + {tensor[0..(half_size - 1)//1], tensor[half_size..-1//1]} + end + + defp validate_input(prompt) when is_binary(prompt), do: validate_input(%{prompt: prompt}) + + defp validate_input(%{prompt: prompt} = input) do + {:ok, + %{ + prompt: prompt, + negative_prompt: input[:negative_prompt] || "", + seed: input[:seed] || :erlang.system_time() + }} + end + + defp validate_input(%{} = input) do + {:error, "expected the input map to have :prompt key, got: #{inspect(input)}"} + end + + defp validate_input(input) do + {:error, "expected either a string or a map, got: #{inspect(input)}"} + end +end diff --git a/deps/bumblebee/lib/bumblebee/diffusion/stable_diffusion/safety_checker.ex b/deps/bumblebee/lib/bumblebee/diffusion/stable_diffusion/safety_checker.ex new file mode 100644 index 0000000000000000000000000000000000000000..e587509fdd0c8a8ff3f982772c933e34550dfeba --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/diffusion/stable_diffusion/safety_checker.ex @@ -0,0 +1,205 @@ +defmodule Bumblebee.Diffusion.StableDiffusion.SafetyChecker do + alias Bumblebee.Shared + + options = [ + clip_spec: [ + default: nil, + doc: "the specification of the CLIP model. See `Bumblebee.Multimodal.Clip` for details" + ] + ] + + @moduledoc """ + A CLIP-based model for detecting unsafe image content. + + This model is designed primarily to check images generated using + Stable Diffusion. + + ## Architectures + + * `:base` - the base safety detection model + + ## Inputs + + * `"pixel_values"` - `{batch_size, image_size, image_size, num_channels}` + + Featurized image pixel values. + + ## Configuration + + #{Shared.options_doc(options)} + + ## References + + * [CompVis/stable-diffusion-v1-4](https://huggingface.co/CompVis/stable-diffusion-v1-4#safety-module) + + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + import Nx.Defn + + alias Bumblebee.Layers + + @impl true + def architectures(), do: [:base] + + @impl true + def config(spec, opts) do + Shared.put_config_attrs(spec, opts) + end + + @impl true + def input_template(%{clip_spec: %{vision_spec: vision_spec}}) do + vision_shape = {1, vision_spec.image_size, vision_spec.image_size, vision_spec.num_channels} + + %{"pixel_values" => Nx.template(vision_shape, :f32)} + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + %{clip_spec: %{vision_spec: vision_spec}} = spec + + vision_shape = {nil, vision_spec.image_size, vision_spec.image_size, vision_spec.num_channels} + + inputs = + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("pixel_values", shape: vision_shape) + ]) + + vision_model = + vision_spec + |> Bumblebee.build_model() + |> Bumblebee.Utils.Axon.prefix_names("vision_model.") + |> Bumblebee.Utils.Axon.plug_inputs(%{ + "pixel_values" => inputs["pixel_values"] + }) + + image_embeddings = + vision_model + |> Axon.nx(& &1.pooled_state) + |> Axon.dense(spec.clip_spec.projection_size, use_bias: false, name: "visual_projection") + + is_unsafe = unsafe_detection(image_embeddings, spec, name: "unsafe_detection") + + Layers.output(%{ + is_unsafe: is_unsafe + }) + end + + defp unsafe_detection(image_embeddings, spec, opts) do + name = opts[:name] + + # The embeddings are precomputed using the CLIP text model and + # represent sensitive/unsafe concepts in the latent space. We then + # check whether an image is far enough from those concepts in the + # latent space (using a hand-engineered threshold for each concept). + + num_sensitive_concepts = 3 + num_unsafe_concepts = 17 + + sensitive_concept_embeddings = + Axon.param("sensitive_concept_embeddings", fn _ -> + {num_sensitive_concepts, spec.clip_spec.projection_size} + end) + + unsafe_concept_embeddings = + Axon.param("unsafe_concept_embeddings", fn _ -> + {num_unsafe_concepts, spec.clip_spec.projection_size} + end) + + sensitive_concept_thresholds = + Axon.param("sensitive_concept_thresholds", fn _ -> {num_sensitive_concepts} end) + + unsafe_concept_thresholds = + Axon.param("unsafe_concept_thresholds", fn _ -> {num_unsafe_concepts} end) + + Axon.layer( + &unsafe_detection_impl/6, + [ + image_embeddings, + sensitive_concept_embeddings, + unsafe_concept_embeddings, + sensitive_concept_thresholds, + unsafe_concept_thresholds + ], + name: name + ) + end + + defnp unsafe_detection_impl( + image_embeddings, + sensitive_concept_embeddings, + unsafe_concept_embeddings, + sensitive_concept_thresholds, + unsafe_concept_thresholds, + _opts \\ [] + ) do + sensitive_concept_distances = + Bumblebee.Utils.Nx.cosine_similarity(image_embeddings, sensitive_concept_embeddings) + + unsafe_concept_distances = + Bumblebee.Utils.Nx.cosine_similarity(image_embeddings, unsafe_concept_embeddings) + + sensitive_concept_thresholds = Nx.new_axis(sensitive_concept_thresholds, 0) + unsafe_concept_thresholds = Nx.new_axis(unsafe_concept_thresholds, 0) + + sensitive_concept_scores = sensitive_concept_distances - sensitive_concept_thresholds + sensitive? = Nx.any(sensitive_concept_scores > 0, axes: [1], keep_axes: true) + + # Use a lower threshold if an image has any sensitive concept + unsafe_threshold_adjustment = Nx.select(sensitive?, 0.01, 0.0) + + unsafe_concept_scores = + unsafe_concept_distances - unsafe_concept_thresholds + unsafe_threshold_adjustment + + Nx.any(unsafe_concept_scores > 0, axes: [1]) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + clip_spec = + Bumblebee.Multimodal.Clip + |> Bumblebee.configure() + |> Bumblebee.HuggingFace.Transformers.Config.load(data) + + @for.config(spec, clip_spec: clip_spec) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + alias Bumblebee.HuggingFace.Transformers + + def params_mapping(spec) do + vision_mapping = + spec.clip_spec.vision_spec + |> Transformers.Model.params_mapping() + |> Transformers.Utils.prefix_params_mapping("vision_model", "vision_model") + + %{ + "visual_projection" => "visual_projection", + "unsafe_detection" => %{ + "sensitive_concept_embeddings" => { + [{"unsafe_detection", "special_care_embeds"}], + fn [value] -> value end + }, + "unsafe_concept_embeddings" => { + [{"unsafe_detection", "concept_embeds"}], + fn [value] -> value end + }, + "sensitive_concept_thresholds" => { + [{"unsafe_detection", "special_care_embeds_weights"}], + fn [value] -> value end + }, + "unsafe_concept_thresholds" => { + [{"unsafe_detection", "concept_embeds_weights"}], + fn [value] -> value end + } + } + } + |> Map.merge(vision_mapping) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/diffusion/stable_diffusion_controlnet.ex b/deps/bumblebee/lib/bumblebee/diffusion/stable_diffusion_controlnet.ex new file mode 100644 index 0000000000000000000000000000000000000000..eaf578138bd5cf38e79c2fafeaefb3d05db6f4f1 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/diffusion/stable_diffusion_controlnet.ex @@ -0,0 +1,542 @@ +defmodule Bumblebee.Diffusion.StableDiffusionControlNet do + @moduledoc """ + High-level tasks based on Stable Diffusion with ControlNet. + """ + + import Nx.Defn + + alias Bumblebee.Utils + alias Bumblebee.Shared + + @type text_to_image_input :: + String.t() + | %{ + :prompt => String.t(), + :conditioning => Nx.Tensor.t(), + optional(:conditioning_scale) => integer(), + optional(:negative_prompt) => String.t(), + optional(:seed) => integer() + } + @type text_to_image_output :: %{results: list(text_to_image_result())} + @type text_to_image_result :: %{:image => Nx.Tensor.t(), optional(:is_safe) => boolean()} + + @doc ~S""" + Build serving for prompt-driven image generation. + + The serving accepts `t:text_to_image_input/0` and returns `t:text_to_image_output/0`. + A list of inputs is also supported. + + You can specify `:safety_checker` model to automatically detect + when a generated image is offensive or harmful and filter it out. + + ## Options + + * `:safety_checker` - the safety checker model info map. When a + safety checker is used, each output entry has an additional + `:is_safe` property and unsafe images are automatically zeroed. + Make sure to also set `:safety_checker_featurizer` + + * `:safety_checker_featurizer` - the featurizer to use to preprocess + the safety checker input images + + * `:num_steps` - the number of denoising steps. More denoising + steps usually lead to higher image quality at the expense of + slower inference. Defaults to `50` + + * `:num_images_per_prompt` - the number of images to generate for + each prompt. Defaults to `1` + + * `:guidance_scale` - the scale used for classifier-free diffusion + guidance. Higher guidance scale makes the generated images more + closely reflect the text prompt. This parameter corresponds to + $\omega$ in Equation (2) of the [Imagen paper](https://arxiv.org/pdf/2205.11487.pdf). + Defaults to `7.5` + + * `:compile` - compiles all computations for predefined input shapes + during serving initialization. Should be a keyword list with the + following keys: + + * `:batch_size` - the maximum batch size of the input. Inputs + are optionally padded to always match this batch size + + * `:sequence_length` - the maximum input sequence length. Input + sequences are always padded/truncated to match that length + + It is advised to set this option in production and also configure + a defn compiler using `:defn_options` to maximally reduce inference + time. + + * `:defn_options` - the options for JIT compilation. Defaults to `[]` + + * `:preallocate_params` - when `true`, explicitly allocates params + on the device configured by `:defn_options`. You may want to set + this option when using partitioned serving, to allocate params + on each of the devices. When using this option, you should first + load the parameters into the host. This can be done by passing + `backend: {EXLA.Backend, client: :host}` to `load_model/1` and friends. + Defaults to `false` + + ## Examples + + repository_id = "CompVis/stable-diffusion-v1-4" + + {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "openai/clip-vit-large-patch14"}) + {:ok, clip} = Bumblebee.load_model({:hf, repository_id, subdir: "text_encoder"}) + {:ok, unet} = Bumblebee.load_model({:hf, repository_id, subdir: "unet"}) + {:ok, controlnet} = Bumblebee.load_model({:hf, "lllyasviel/sd-controlnet-scribble"}) + {:ok, vae} = Bumblebee.load_model({:hf, repository_id, subdir: "vae"}, architecture: :decoder) + {:ok, scheduler} = Bumblebee.load_scheduler({:hf, repository_id, subdir: "scheduler"}) + {:ok, featurizer} = Bumblebee.load_featurizer({:hf, repository_id, subdir: "feature_extractor"}) + {:ok, safety_checker} = Bumblebee.load_model({:hf, repository_id, subdir: "safety_checker"}) + + serving = + Bumblebee.Diffusion.StableDiffusionControlNet.text_to_image( + clip, + unet, + vae, + controlnet, + tokenizer, + scheduler, + num_steps: 20, + num_images_per_prompt: 2, + safety_checker: safety_checker, + safety_checker_featurizer: featurizer, + compile: [batch_size: 1, sequence_length: 60], + defn_options: [compiler: EXLA] + ) + + prompt = "numbat in forest, detailed, digital art" + + # The conditioning image matching the given ControlNet condition, + # such as edges, pose or depth. Here we use a simple handcrafted + # tensor + conditioning = + Nx.tensor( + [List.duplicate(255, 8) ++ List.duplicate(0, 24)], + type: :u8 + ) + |> Nx.tile([256, 8, 3]) + |> Nx.pad(0, [{192, 64, 0}, {192, 64, 0}, {0, 0, 0}]) + |> Nx.transpose(axes: [1, 0, 2]) + + Nx.Serving.run(serving, %{prompt: prompt, conditioning: conditioning}) + #=> %{ + #=> results: [ + #=> %{ + #=> image: #Nx.Tensor< + #=> u8[512][512][3] + #=> ... + #=> >, + #=> is_safe: true + #=> }, + #=> %{ + #=> image: #Nx.Tensor< + #=> u8[512][512][3] + #=> ... + #=> >, + #=> is_safe: true + #=> } + #=> ] + #=> } + + """ + @spec text_to_image( + Bumblebee.model_info(), + Bumblebee.model_info(), + Bumblebee.model_info(), + Bumblebee.model_info(), + Bumblebee.Tokenizer.t(), + Bumblebee.Scheduler.t(), + keyword() + ) :: Nx.Serving.t() + def text_to_image(encoder, unet, vae, controlnet, tokenizer, scheduler, opts \\ []) do + opts = + Keyword.validate!(opts, [ + :safety_checker, + :safety_checker_featurizer, + :compile, + num_steps: 50, + num_images_per_prompt: 1, + guidance_scale: 7.5, + defn_options: [], + preallocate_params: false + ]) + + safety_checker = opts[:safety_checker] + safety_checker_featurizer = opts[:safety_checker_featurizer] + num_steps = opts[:num_steps] + num_images_per_prompt = opts[:num_images_per_prompt] + preallocate_params = opts[:preallocate_params] + defn_options = opts[:defn_options] + + if safety_checker != nil and safety_checker_featurizer == nil do + raise ArgumentError, "got :safety_checker but no :safety_checker_featurizer was specified" + end + + safety_checker? = safety_checker != nil + + compile = + if compile = opts[:compile] do + compile + |> Keyword.validate!([:batch_size, :sequence_length]) + |> Shared.require_options!([:batch_size, :sequence_length]) + end + + batch_size = compile[:batch_size] + sequence_length = compile[:sequence_length] + + conditioning_size = + controlnet.spec.sample_size * + 2 ** (length(controlnet.spec.conditioning_embedding_hidden_sizes) - 1) + + tokenizer = + Bumblebee.configure(tokenizer, + length: sequence_length, + return_token_type_ids: false, + return_attention_mask: false + ) + + {_, encoder_predict} = Axon.build(encoder.model) + {_, vae_predict} = Axon.build(vae.model) + {_, unet_predict} = Axon.build(unet.model) + {_, controlnet_predict} = Axon.build(controlnet.model) + + scheduler_init = &Bumblebee.scheduler_init(scheduler, num_steps, &1, &2) + scheduler_step = &Bumblebee.scheduler_step(scheduler, &1, &2, &3) + + image_fun = + &text_to_image_impl( + encoder_predict, + &1, + unet_predict, + &2, + vae_predict, + &3, + controlnet_predict, + &4, + scheduler_init, + scheduler_step, + &5, + num_images_per_prompt: opts[:num_images_per_prompt], + latents_sample_size: unet.spec.sample_size, + latents_channels: unet.spec.in_channels, + guidance_scale: opts[:guidance_scale] + ) + + safety_checker_fun = + if safety_checker do + {_, predict_fun} = Axon.build(safety_checker.model) + predict_fun + end + + # Note that all of these are copied when using serving as a process + init_args = [ + {image_fun, safety_checker_fun}, + encoder.params, + unet.params, + vae.params, + controlnet.params, + {safety_checker?, safety_checker[:spec], safety_checker[:params]}, + safety_checker_featurizer, + {compile != nil, batch_size, sequence_length, conditioning_size}, + num_images_per_prompt, + preallocate_params + ] + + Nx.Serving.new( + fn defn_options -> apply(&init/11, init_args ++ [defn_options]) end, + defn_options + ) + |> Nx.Serving.batch_size(batch_size) + |> Nx.Serving.client_preprocessing(&client_preprocessing(&1, tokenizer)) + |> Nx.Serving.client_postprocessing(&client_postprocessing(&1, &2, safety_checker)) + end + + defp init( + {image_fun, safety_checker_fun}, + encoder_params, + unet_params, + vae_params, + controlnet_params, + {safety_checker?, safety_checker_spec, safety_checker_params}, + safety_checker_featurizer, + {compile?, batch_size, sequence_length, conditioning_size}, + num_images_per_prompt, + preallocate_params, + defn_options + ) do + encoder_params = Shared.maybe_preallocate(encoder_params, preallocate_params, defn_options) + unet_params = Shared.maybe_preallocate(unet_params, preallocate_params, defn_options) + vae_params = Shared.maybe_preallocate(vae_params, preallocate_params, defn_options) + + controlnet_params = + Shared.maybe_preallocate(controlnet_params, preallocate_params, defn_options) + + image_fun = + Shared.compile_or_jit(image_fun, :image, defn_options, compile?, fn -> + inputs = %{ + "conditional_and_unconditional" => %{ + "input_ids" => Nx.template({batch_size, 2, sequence_length}, :u32) + }, + "seed" => Nx.template({batch_size}, :s64), + "conditioning" => + Nx.template( + {batch_size, conditioning_size, conditioning_size, 3}, + :f32 + ), + "conditioning_scale" => Nx.template({batch_size}, :f32) + } + + [encoder_params, unet_params, vae_params, controlnet_params, inputs] + end) + + safety_checker_fun = + safety_checker_fun && + Shared.compile_or_jit(safety_checker_fun, :safety_checker, defn_options, compile?, fn -> + inputs = %{ + "pixel_values" => + Shared.input_template(safety_checker_spec, "pixel_values", [ + batch_size * num_images_per_prompt + ]) + } + + [safety_checker_params, inputs] + end) + + safety_checker_params = + safety_checker_params && + Shared.maybe_preallocate(safety_checker_params, preallocate_params, defn_options) + + fn inputs -> + inputs = Shared.maybe_pad(inputs, batch_size) + + image = image_fun.(encoder_params, unet_params, vae_params, controlnet_params, inputs) + + output = + if safety_checker? do + inputs = Bumblebee.apply_featurizer(safety_checker_featurizer, image) + outputs = safety_checker_fun.(safety_checker_params, inputs) + %{image: image, is_unsafe: outputs.is_unsafe} + else + %{image: image} + end + + output + |> Utils.Nx.composite_unflatten_batch(Utils.Nx.batch_size(inputs)) + |> Shared.serving_post_computation() + end + end + + defp preprocess_image(image) do + NxImage.to_continuous(image, 0, 1) + end + + defp client_preprocessing(input, tokenizer) do + {inputs, multi?} = Shared.validate_serving_input!(input, &validate_input/1) + + seed = Enum.map(inputs, & &1.seed) |> Nx.tensor(type: :s64, backend: Nx.BinaryBackend) + + # Note: we need to tokenize all sequences together, so that + # they are padded to the same length (if not specified) + prompts = Enum.flat_map(inputs, &[&1.prompt, &1.negative_prompt]) + + prompt_pairs = + Nx.with_default_backend(Nx.BinaryBackend, fn -> + inputs = Bumblebee.apply_tokenizer(tokenizer, prompts) + Utils.Nx.composite_unflatten_batch(inputs, Nx.axis_size(seed, 0)) + end) + + conditioning = + Enum.map(inputs, & &1.conditioning) + |> Nx.stack() + |> preprocess_image() + + conditioning_scale = + Enum.map(inputs, & &1.conditioning_scale) + |> Nx.tensor(type: :f32, backend: Nx.BinaryBackend) + + inputs = %{ + "conditional_and_unconditional" => prompt_pairs, + "seed" => seed, + "conditioning" => conditioning, + "conditioning_scale" => conditioning_scale + } + + {Nx.Batch.concatenate([inputs]), multi?} + end + + defp client_postprocessing({outputs, _metadata}, multi?, safety_checker?) do + for outputs <- Utils.Nx.batch_to_list(outputs) do + results = + for outputs = %{image: image} <- Utils.Nx.batch_to_list(outputs) do + if safety_checker? do + if Nx.to_number(outputs.is_unsafe) == 1 do + %{image: zeroed(image), is_safe: false} + else + %{image: image, is_safe: true} + end + else + %{image: image} + end + end + + %{results: results} + end + |> Shared.normalize_output(multi?) + end + + defp zeroed(tensor) do + 0 + |> Nx.tensor(type: Nx.type(tensor), backend: Nx.BinaryBackend) + |> Nx.broadcast(Nx.shape(tensor)) + end + + defnp text_to_image_impl( + encoder_predict, + encoder_params, + unet_predict, + unet_params, + vae_predict, + vae_params, + controlnet_predict, + controlnet_params, + scheduler_init, + scheduler_step, + inputs, + opts \\ [] + ) do + num_images_per_prompt = opts[:num_images_per_prompt] + latents_sample_size = opts[:latents_sample_size] + latents_in_channels = opts[:latents_channels] + guidance_scale = opts[:guidance_scale] + + seed = inputs["seed"] + conditioning = inputs["conditioning"] + conditioning_scale = inputs["conditioning_scale"] + + inputs = + inputs["conditional_and_unconditional"] + # Transpose conditional and unconditional to separate blocks + |> composite_transpose_leading() + |> Utils.Nx.composite_flatten_batch() + + %{hidden_state: text_embeddings} = encoder_predict.(encoder_params, inputs) + + {_twice_batch_size, sequence_length, hidden_size} = Nx.shape(text_embeddings) + + text_embeddings = + text_embeddings + |> Nx.new_axis(1) + |> Nx.tile([1, num_images_per_prompt, 1, 1]) + |> Nx.reshape({:auto, sequence_length, hidden_size}) + + prng_key = + seed + |> Nx.vectorize(:batch) + |> Nx.Random.key() + |> Nx.Random.split(parts: num_images_per_prompt) + |> Nx.devectorize() + |> Nx.flatten(axes: [0, 1]) + |> Nx.vectorize(:batch) + + {latents, prng_key} = + Nx.Random.normal(prng_key, + shape: {latents_sample_size, latents_sample_size, latents_in_channels} + ) + + {scheduler_state, timesteps} = scheduler_init.(Nx.to_template(latents), prng_key) + + latents = Nx.devectorize(latents) + + {latents, _} = + while {latents, + {scheduler_state, text_embeddings, unet_params, conditioning, conditioning_scale, + controlnet_params}}, + timestep <- timesteps do + sample = Nx.concatenate([latents, latents]) + + controlnet_inputs = %{ + "conditioning" => conditioning, + "conditioning_scale" => conditioning_scale, + "sample" => sample, + "timestep" => timestep, + "encoder_hidden_state" => text_embeddings + } + + %{down_block_states: down_block_states, mid_block_state: mid_block_state} = + controlnet_predict.(controlnet_params, controlnet_inputs) + + unet_inputs = + %{ + "sample" => sample, + "timestep" => timestep, + "encoder_hidden_state" => text_embeddings, + "additional_down_block_states" => down_block_states, + "additional_mid_block_state" => mid_block_state + } + + %{sample: noise_pred} = unet_predict.(unet_params, unet_inputs) + + {noise_pred_conditional, noise_pred_unconditional} = + split_conditional_and_unconditional(noise_pred) + + noise_pred = + noise_pred_unconditional + + guidance_scale * (noise_pred_conditional - noise_pred_unconditional) + + {scheduler_state, latents} = + scheduler_step.( + scheduler_state, + Nx.vectorize(latents, :batch), + Nx.vectorize(noise_pred, :batch) + ) + + latents = Nx.devectorize(latents) + + {latents, + {scheduler_state, text_embeddings, unet_params, conditioning, conditioning_scale, + controlnet_params}} + end + + latents = latents * (1 / 0.18215) + + %{sample: image} = vae_predict.(vae_params, latents) + + NxImage.from_continuous(image, -1, 1) + end + + deftransformp composite_transpose_leading(container) do + Utils.Nx.map(container, fn tensor -> + [first, second | rest] = Nx.axes(tensor) + Nx.transpose(tensor, axes: [second, first | rest]) + end) + end + + defnp split_conditional_and_unconditional(tensor) do + batch_size = Nx.axis_size(tensor, 0) + half_size = div(batch_size, 2) + {tensor[0..(half_size - 1)//1], tensor[half_size..-1//1]} + end + + defp validate_input(prompt) when is_binary(prompt), do: validate_input(%{prompt: prompt}) + + defp validate_input(%{prompt: prompt, conditioning: conditioning} = input) do + {:ok, + %{ + prompt: prompt, + conditioning: conditioning, + conditioning_scale: input[:conditioning_scale] || 1.0, + negative_prompt: input[:negative_prompt] || "", + seed: input[:seed] || :erlang.system_time() + }} + end + + defp validate_input(%{} = input) do + {:error, + "expected the input map to have :prompt and :conditioning key, got: #{inspect(input)}"} + end + + defp validate_input(input) do + {:error, "expected either a string or a map, got: #{inspect(input)}"} + end +end diff --git a/deps/bumblebee/lib/bumblebee/diffusion/unet_2d_conditional.ex b/deps/bumblebee/lib/bumblebee/diffusion/unet_2d_conditional.ex new file mode 100644 index 0000000000000000000000000000000000000000..8045eca9e4e52dd5de6ec3192715d21d801b753c --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/diffusion/unet_2d_conditional.ex @@ -0,0 +1,512 @@ +defmodule Bumblebee.Diffusion.UNet2DConditional do + alias Bumblebee.Shared + + options = [ + sample_size: [ + default: 32, + doc: "the size of the input spatial dimensions" + ], + in_channels: [ + default: 4, + doc: "the number of channels in the input" + ], + out_channels: [ + default: 4, + doc: "the number of channels in the output" + ], + center_input_sample: [ + default: false, + doc: "whether to center the input sample" + ], + embedding_flip_sin_to_cos: [ + default: true, + doc: "whether to flip the sin to cos in the sinusoidal timestep embedding" + ], + embedding_frequency_correction_term: [ + default: 0, + doc: ~S""" + controls the frequency formula in the timestep sinusoidal embedding. The frequency is computed + as $\\omega_i = \\frac{1}{10000^{\\frac{i}{n - s}}}$, for $i \\in \\{0, ..., n-1\\}$, where $n$ + is half of the embedding size and $s$ is the shift. Historically, certain implementations of + sinusoidal embedding used $s=0$, while others used $s=1$ + """ + ], + hidden_sizes: [ + default: [320, 640, 1280, 1280], + doc: "the dimensionality of hidden layers in each upsample/downsample block" + ], + depth: [ + default: 2, + doc: "the number of residual blocks in each upsample/downsample block" + ], + down_block_types: [ + default: [ + :cross_attention_down_block, + :cross_attention_down_block, + :cross_attention_down_block, + :down_block + ], + doc: + "a list of downsample block types. The supported blocks are: `:down_block`, `:cross_attention_down_block`" + ], + up_block_types: [ + default: [ + :up_block, + :cross_attention_up_block, + :cross_attention_up_block, + :cross_attention_up_block + ], + doc: + "a list of upsample block types. The supported blocks are: `:up_block`, `:cross_attention_up_block`" + ], + downsample_padding: [ + default: [{1, 1}, {1, 1}], + doc: "the padding to use in the downsample convolution" + ], + mid_block_scale_factor: [ + default: 1, + doc: "the scale factor to use for the mid block" + ], + num_attention_heads: [ + default: 8, + doc: + "the number of attention heads for each attention layer. Optionally can be a list with one number per block" + ], + cross_attention_size: [ + default: 1280, + doc: "the dimensionality of the cross attention features" + ], + use_linear_projection: [ + default: false, + doc: + "whether the input/output projection of the transformer block should be linear or convolutional" + ], + activation: [ + default: :silu, + doc: "the activation function" + ], + group_norm_num_groups: [ + default: 32, + doc: "the number of groups used by the group normalization layers" + ], + group_norm_epsilon: [ + default: 1.0e-5, + doc: "the epsilon used by the group normalization layers" + ] + ] + + @moduledoc """ + U-Net model with two spatial dimensions and conditioning state. + + ## Architectures + + * `:base` - the U-Net model + + ## Inputs + + * `"sample"` - `{batch_size, sample_size, sample_size, in_channels}` + + Sample input with two spatial dimensions. + + * `"timestep"` - `{}` + + The timestep used to parameterize model behaviour in a multi-step + process, such as diffusion. + + * `"encoder_hidden_state"` - `{batch_size, sequence_length, hidden_size}` + + The conditioning state (context) to use with cross-attention. + + * `"additional_down_block_states"` + + Optional outputs matching the structure of down blocks, added as + part of the encoder-decoder skip connections. + + * `"additional_mid_block_state"` + + Optional output added to the mid block result. + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + alias Bumblebee.Diffusion + + @impl true + def architectures(), do: [:base] + + @impl true + def config(spec, opts) do + Shared.put_config_attrs(spec, opts) + end + + @impl true + def input_template(spec) do + sample_shape = {1, spec.sample_size, spec.sample_size, spec.in_channels} + timestep_shape = {} + encoder_hidden_state_shape = {1, 1, spec.cross_attention_size} + + %{ + "sample" => Nx.template(sample_shape, :f32), + "timestep" => Nx.template(timestep_shape, :u32), + "encoder_hidden_state" => Nx.template(encoder_hidden_state_shape, :f32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + sample = core(inputs, spec) + Layers.output(%{sample: sample}) + end + + defp inputs(spec) do + sample_shape = {nil, spec.sample_size, spec.sample_size, spec.in_channels} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("sample", shape: sample_shape), + Axon.input("timestep", shape: {}), + Axon.input("encoder_hidden_state", shape: {nil, nil, spec.cross_attention_size}), + Axon.input("additional_down_block_states", optional: true), + Axon.input("additional_mid_block_state", optional: true) + ]) + end + + defp core(inputs, spec) do + sample = inputs["sample"] + timestep = inputs["timestep"] + encoder_hidden_state = inputs["encoder_hidden_state"] + + sample = + if spec.center_input_sample do + Axon.nx(sample, fn sample -> 2 * sample - 1.0 end, op_name: :center) + else + sample + end + + timestep = + Axon.layer( + fn sample, timestep, _opts -> + Nx.broadcast(timestep, {Nx.axis_size(sample, 0)}) + end, + [sample, timestep], + op_name: :broadcast + ) + + timestep_embedding = + timestep + |> Diffusion.Layers.timestep_sinusoidal_embedding(hd(spec.hidden_sizes), + flip_sin_to_cos: spec.embedding_flip_sin_to_cos, + frequency_correction_term: spec.embedding_frequency_correction_term + ) + |> Diffusion.Layers.UNet.timestep_embedding_mlp(hd(spec.hidden_sizes) * 4, + name: "time_embedding" + ) + + sample = + Axon.conv(sample, hd(spec.hidden_sizes), + kernel_size: 3, + padding: [{1, 1}, {1, 1}], + name: "input_conv" + ) + + {sample, down_block_states} = + down_blocks(sample, timestep_embedding, encoder_hidden_state, spec, name: "down_blocks") + + down_block_states = + maybe_add_down_block_states(down_block_states, inputs["additional_down_block_states"]) + + sample = + sample + |> mid_block(timestep_embedding, encoder_hidden_state, spec, name: "mid_block") + |> maybe_add_mid_block_state(inputs["additional_mid_block_state"]) + + sample + |> up_blocks(timestep_embedding, down_block_states, encoder_hidden_state, spec, + name: "up_blocks" + ) + |> Axon.group_norm(spec.group_norm_num_groups, + epsilon: spec.group_norm_epsilon, + name: "output_norm" + ) + |> Axon.activation(:silu) + |> Axon.conv(spec.out_channels, + kernel_size: 3, + padding: [{1, 1}, {1, 1}], + name: "output_conv" + ) + end + + defp down_blocks(sample, timestep_embedding, encoder_hidden_state, spec, opts) do + name = opts[:name] + + blocks = + Enum.zip([spec.hidden_sizes, spec.down_block_types, num_attention_heads_per_block(spec)]) + + in_channels = hd(spec.hidden_sizes) + down_block_states = [{sample, in_channels}] + + state = {sample, down_block_states, in_channels} + + {sample, down_block_states, _} = + for {{out_channels, block_type, num_attention_heads}, idx} <- Enum.with_index(blocks), + reduce: state do + {sample, down_block_states, in_channels} -> + last_block? = idx == length(spec.hidden_sizes) - 1 + + {sample, states} = + Diffusion.Layers.UNet.down_block_2d( + block_type, + sample, + timestep_embedding, + encoder_hidden_state, + depth: spec.depth, + in_channels: in_channels, + out_channels: out_channels, + add_downsample: not last_block?, + downsample_padding: spec.downsample_padding, + activation: spec.activation, + norm_epsilon: spec.group_norm_epsilon, + norm_num_groups: spec.group_norm_num_groups, + num_attention_heads: num_attention_heads, + use_linear_projection: spec.use_linear_projection, + name: join(name, idx) + ) + + {sample, down_block_states ++ Tuple.to_list(states), out_channels} + end + + {sample, List.to_tuple(down_block_states)} + end + + defp mid_block(hidden_state, timesteps_embedding, encoder_hidden_state, spec, opts) do + Diffusion.Layers.UNet.mid_cross_attention_block_2d( + hidden_state, + timesteps_embedding, + encoder_hidden_state, + channels: List.last(spec.hidden_sizes), + activation: spec.activation, + norm_epsilon: spec.group_norm_epsilon, + norm_num_groups: spec.group_norm_num_groups, + output_scale_factor: spec.mid_block_scale_factor, + num_attention_heads: spec |> num_attention_heads_per_block() |> List.last(), + use_linear_projection: spec.use_linear_projection, + name: opts[:name] + ) + end + + defp up_blocks( + sample, + timestep_embedding, + down_block_states, + encoder_hidden_state, + spec, + opts + ) do + name = opts[:name] + + down_block_states = + down_block_states + |> Tuple.to_list() + |> Enum.reverse() + |> Enum.chunk_every(spec.depth + 1) + + reversed_hidden_sizes = Enum.reverse(spec.hidden_sizes) + in_channels = hd(reversed_hidden_sizes) + + num_attention_heads_per_block = + spec + |> num_attention_heads_per_block() + |> Enum.reverse() + + blocks_and_chunks = + [ + reversed_hidden_sizes, + spec.up_block_types, + num_attention_heads_per_block, + down_block_states + ] + |> Enum.zip() + |> Enum.with_index() + + {sample, _} = + for {{out_channels, block_type, num_attention_heads, states}, idx} <- blocks_and_chunks, + reduce: {sample, in_channels} do + {sample, in_channels} -> + last_block? = idx == length(spec.hidden_sizes) - 1 + + sample = + Diffusion.Layers.UNet.up_block_2d( + block_type, + sample, + timestep_embedding, + states, + encoder_hidden_state, + depth: spec.depth + 1, + in_channels: in_channels, + out_channels: out_channels, + add_upsample: not last_block?, + norm_epsilon: spec.group_norm_epsilon, + norm_num_groups: spec.group_norm_num_groups, + activation: spec.activation, + num_attention_heads: num_attention_heads, + use_linear_projection: spec.use_linear_projection, + name: join(name, idx) + ) + + {sample, out_channels} + end + + sample + end + + defp maybe_add_mid_block_state(mid_block_state, additional_mid_block_state) do + maybe_add(mid_block_state, additional_mid_block_state) + end + + defp maybe_add_down_block_states(down_block_states, additional_down_block_states) do + down_block_states = Tuple.to_list(down_block_states) + + for {{down_block_state, out_channels}, i} <- Enum.with_index(down_block_states) do + additional_down_block_state = Axon.nx(additional_down_block_states, &elem(&1, i)) + {maybe_add(down_block_state, additional_down_block_state), out_channels} + end + |> List.to_tuple() + end + + defp maybe_add(left, maybe_right) do + Axon.layer( + fn left, maybe_right, _opts -> + case maybe_right do + %Axon.None{} -> left + right -> Nx.add(left, right) + end + end, + [left, Axon.optional(maybe_right)] + ) + end + + defp num_attention_heads_per_block(spec) when is_list(spec.num_attention_heads) do + spec.num_attention_heads + end + + defp num_attention_heads_per_block(spec) when is_integer(spec.num_attention_heads) do + num_blocks = length(spec.down_block_types) + List.duplicate(spec.num_attention_heads, num_blocks) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + in_channels: {"in_channels", number()}, + out_channels: {"out_channels", number()}, + sample_size: {"sample_size", number()}, + center_input_sample: {"center_input_sample", boolean()}, + embedding_flip_sin_to_cos: {"flip_sin_to_cos", boolean()}, + embedding_frequency_correction_term: {"freq_shift", number()}, + hidden_sizes: {"block_out_channels", list(number())}, + depth: {"layers_per_block", number()}, + down_block_types: { + "down_block_types", + list( + mapping(%{ + "DownBlock2D" => :down_block, + "CrossAttnDownBlock2D" => :cross_attention_down_block + }) + ) + }, + up_block_types: { + "up_block_types", + list( + mapping(%{ + "UpBlock2D" => :up_block, + "CrossAttnUpBlock2D" => :cross_attention_up_block + }) + ) + }, + downsample_padding: {"downsample_padding", padding(2)}, + mid_block_scale_factor: {"mid_block_scale_factor", number()}, + num_attention_heads: {"attention_head_dim", one_of([number(), list(number())])}, + cross_attention_size: {"cross_attention_dim", number()}, + use_linear_projection: {"use_linear_projection", boolean()}, + activation: {"act_fn", activation()}, + group_norm_num_groups: {"norm_num_groups", number()}, + group_norm_epsilon: {"norm_eps", number()} + ) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + alias Bumblebee.HuggingFace.Transformers + + def params_mapping(_spec) do + block_mapping = %{ + "transformers.{m}.norm" => "attentions.{m}.norm", + "transformers.{m}.input_projection" => "attentions.{m}.proj_in", + "transformers.{m}.output_projection" => "attentions.{m}.proj_out", + "transformers.{m}.blocks.{l}.self_attention.query" => + "attentions.{m}.transformer_blocks.{l}.attn1.to_q", + "transformers.{m}.blocks.{l}.self_attention.key" => + "attentions.{m}.transformer_blocks.{l}.attn1.to_k", + "transformers.{m}.blocks.{l}.self_attention.value" => + "attentions.{m}.transformer_blocks.{l}.attn1.to_v", + "transformers.{m}.blocks.{l}.self_attention.output" => + "attentions.{m}.transformer_blocks.{l}.attn1.to_out.0", + "transformers.{m}.blocks.{l}.cross_attention.query" => + "attentions.{m}.transformer_blocks.{l}.attn2.to_q", + "transformers.{m}.blocks.{l}.cross_attention.key" => + "attentions.{m}.transformer_blocks.{l}.attn2.to_k", + "transformers.{m}.blocks.{l}.cross_attention.value" => + "attentions.{m}.transformer_blocks.{l}.attn2.to_v", + "transformers.{m}.blocks.{l}.cross_attention.output" => + "attentions.{m}.transformer_blocks.{l}.attn2.to_out.0", + "transformers.{m}.blocks.{l}.ffn.intermediate" => + "attentions.{m}.transformer_blocks.{l}.ff.net.0.proj", + "transformers.{m}.blocks.{l}.ffn.output" => + "attentions.{m}.transformer_blocks.{l}.ff.net.2", + "transformers.{m}.blocks.{l}.self_attention_norm" => + "attentions.{m}.transformer_blocks.{l}.norm1", + "transformers.{m}.blocks.{l}.cross_attention_norm" => + "attentions.{m}.transformer_blocks.{l}.norm2", + "transformers.{m}.blocks.{l}.output_norm" => + "attentions.{m}.transformer_blocks.{l}.norm3", + "residual_blocks.{m}.timestep_projection" => "resnets.{m}.time_emb_proj", + "residual_blocks.{m}.norm_1" => "resnets.{m}.norm1", + "residual_blocks.{m}.conv_1" => "resnets.{m}.conv1", + "residual_blocks.{m}.norm_2" => "resnets.{m}.norm2", + "residual_blocks.{m}.conv_2" => "resnets.{m}.conv2", + "residual_blocks.{m}.shortcut.projection" => "resnets.{m}.conv_shortcut", + "downsamples.{m}.conv" => "downsamplers.{m}.conv", + "upsamples.{m}.conv" => "upsamplers.{m}.conv" + } + + blocks_mapping = + ["down_blocks.{n}", "mid_block", "up_blocks.{n}"] + |> Enum.map(&Transformers.Utils.prefix_params_mapping(block_mapping, &1, &1)) + |> Enum.reduce(&Map.merge/2) + + %{ + "time_embedding.intermediate" => "time_embedding.linear_1", + "time_embedding.output" => "time_embedding.linear_2", + "input_conv" => "conv_in", + "output_norm" => "conv_norm_out", + "output_conv" => "conv_out" + } + |> Map.merge(blocks_mapping) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/diffusion/vae_kl.ex b/deps/bumblebee/lib/bumblebee/diffusion/vae_kl.ex new file mode 100644 index 0000000000000000000000000000000000000000..4d1a7221e05335334746ae9773dedb86f6a2adfb --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/diffusion/vae_kl.ex @@ -0,0 +1,490 @@ +defmodule Bumblebee.Diffusion.VaeKl do + alias Bumblebee.Shared + + options = [ + sample_size: [ + default: 32, + doc: "the size of the input spatial dimensions" + ], + in_channels: [ + default: 3, + doc: "the number of channels in the input" + ], + out_channels: [ + default: 3, + doc: "the number of channels in the output" + ], + latent_channels: [ + default: 4, + doc: "the number of channels in the latent space" + ], + hidden_sizes: [ + default: [64], + doc: "the dimensionality of hidden layers in each upsample/downsample block" + ], + depth: [ + default: 1, + doc: "the number of residual blocks in each upsample/downsample block" + ], + down_block_types: [ + default: [:down_block], + doc: "a list of downsample block types. Currently the only supported type is `:down_block`" + ], + up_block_types: [ + default: [:up_block], + doc: "a list of upsample block types. Currently the only supported type is `:up_block`" + ], + activation: [ + default: :silu, + doc: "the activation function" + ] + ] + + @moduledoc """ + Variational autoencoder (VAE) with Kullback–Leibler divergence (KL) loss. + + ## Architectures + + * `:base` - the entire VAE model + + * `:encoder` - just the encoder part of the base model + + * `:decoder` - just the decoder part of the base model + + ## Inputs + + * `"sample"` - `{batch_size, sample_size, sample_size, in_channels}` + + Sample input with two spatial dimensions. Note that in case of + the `:decoder` model, the input usually has lower dimensionality. + + * `"sample_posterior"` - `{}` + + When `true`, the decoder input is sampled from the encoder output + distribution. Otherwise the distribution mode value is used instead. + This input is only relevant for the `:base` model. Defaults to `false`. + + ## Configuration + + #{Shared.options_doc(options)} + + ## References + + * [Auto-Encoding Variational Bayes](https://arxiv.org/abs/1312.6114) + + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + alias Bumblebee.Diffusion + + @impl true + def architectures(), do: [:base, :encoder, :decoder] + + @impl true + def config(spec, opts) do + Shared.put_config_attrs(spec, opts) + end + + @impl true + def input_template(spec) do + sample_shape = spec |> sample_shape() |> put_elem(0, 1) + %{"sample" => Nx.template(sample_shape, :f32)} + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + sample = core(inputs, spec) + Layers.output(%{sample: sample}) + end + + def model(%__MODULE__{architecture: :encoder} = spec) do + inputs = inputs(spec) + posterior = encoder(inputs["sample"], spec, name: "encoder") + Layers.output(%{latent_dist: Axon.container(posterior)}) + end + + def model(%__MODULE__{architecture: :decoder} = spec) do + inputs = inputs(spec) + sample = decoder(inputs["sample"], spec, name: "decoder") + Layers.output(%{sample: sample}) + end + + defp inputs(%__MODULE__{architecture: :base} = spec) do + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("sample", shape: sample_shape(spec)), + Axon.input("sample_posterior", shape: {}, optional: true) + ]) + end + + defp inputs(spec) do + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("sample", shape: sample_shape(spec)) + ]) + end + + defp sample_shape(%__MODULE__{architecture: :decoder} = spec) do + downsample_rate = (length(spec.hidden_sizes) - 1) * 2 + size = div(spec.sample_size, downsample_rate) + {nil, size, size, spec.latent_channels} + end + + defp sample_shape(spec) do + {nil, spec.sample_size, spec.sample_size, spec.in_channels} + end + + defp core(inputs, spec) do + x = inputs["sample"] + + sample_posterior = + Layers.default inputs["sample_posterior"] do + Axon.constant(Nx.tensor(0, type: {:u, 8})) + end + + posterior = encoder(x, spec, name: "encoder") + + z = + Axon.cond( + sample_posterior, + &Nx.equal(&1, Nx.tensor(1)), + sample(posterior, name: "sample"), + mode(posterior) + ) + + decoder(z, spec, name: "decoder") + end + + defp encoder(x, spec, opts) do + name = opts[:name] + + x + |> Axon.conv(hd(spec.hidden_sizes), + kernel_size: 3, + strides: 1, + padding: [{1, 1}, {1, 1}], + name: join(name, "input_conv") + ) + |> down_blocks(spec, name: join(name, "down_blocks")) + |> mid_block(spec, name: join(name, "mid_block")) + |> Axon.group_norm(32, epsilon: 1.0e-6, name: join(name, "output_norm")) + |> Axon.activation(:silu) + |> Axon.conv(2 * spec.latent_channels, + kernel_size: 3, + padding: [{1, 1}, {1, 1}], + name: join(name, "output_conv") + ) + # Note: plain VAE doesn't employ vector quantization (VQ), however + # the reference implementation uses the pre and post quantization + # convolutions as in VQ-VAE, so we reflect this naming here too + |> Axon.conv(2 * spec.latent_channels, + kernel_size: 1, + name: join(name, "pre_quantization_conv") + ) + |> diagonal_gaussian_distribution() + end + + defp decoder(z, spec, opts) do + name = opts[:name] + + z + |> Axon.conv(spec.latent_channels, + kernel_size: 1, + name: join(name, "post_quantization_conv") + ) + |> Axon.conv(List.last(spec.hidden_sizes), + kernel_size: 3, + strides: 1, + padding: [{1, 1}, {1, 1}], + name: join(name, "input_conv") + ) + |> mid_block(spec, name: join(name, "mid_block")) + |> up_blocks(spec, name: join(name, "up_blocks")) + |> Axon.group_norm(32, epsilon: 1.0e-6, name: join(name, "output_norm")) + |> Axon.activation(:silu) + |> Axon.conv(spec.out_channels, + kernel_size: 3, + padding: [{1, 1}, {1, 1}], + name: join(name, "output_conv") + ) + end + + defp down_blocks(sample, spec, opts) do + name = opts[:name] + blocks = Enum.zip(spec.hidden_sizes, spec.down_block_types) + + acc = {sample, hd(spec.hidden_sizes)} + + {sample, _} = + for {{output_channel, down_block_type}, idx} <- Enum.with_index(blocks), reduce: acc do + {sample, in_channels} -> + last_block? = idx == length(spec.hidden_sizes) - 1 + + block_opts = [ + depth: spec.depth, + in_channels: in_channels, + out_channels: output_channel, + add_downsample: not last_block?, + activation: spec.activation, + name: join(name, idx) + ] + + {do_down_block(down_block_type, sample, block_opts), output_channel} + end + + sample + end + + defp do_down_block(:down_block, sample, opts), + do: down_block(sample, opts) + + defp down_block(hidden_state, opts) do + in_channels = opts[:in_channels] + out_channels = opts[:out_channels] + depth = opts[:depth] + activation = opts[:activation] + add_downsample = opts[:add_downsample] + name = opts[:name] + + hidden_state = + for idx <- 0..(depth - 1), reduce: hidden_state do + hidden_state -> + in_channels = if(idx == 0, do: in_channels, else: out_channels) + + Diffusion.Layers.residual_block(hidden_state, in_channels, out_channels, + activation: activation, + name: name |> join("residual_blocks") |> join(idx) + ) + end + + if add_downsample do + Diffusion.Layers.downsample_2d(hidden_state, out_channels, + padding: 0, + name: join(name, "downsamples.0") + ) + else + hidden_state + end + end + + defp up_blocks(sample, spec, opts) do + name = opts[:name] + reversed_hidden_sizes = Enum.reverse(spec.hidden_sizes) + blocks = Enum.zip(reversed_hidden_sizes, spec.up_block_types) + + acc = {sample, hd(reversed_hidden_sizes)} + + {sample, _} = + for {{output_channel, up_block_type}, idx} <- Enum.with_index(blocks), reduce: acc do + {sample, in_channels} -> + last_block? = idx == length(spec.hidden_sizes) - 1 + + block_opts = [ + depth: spec.depth + 1, + in_channels: in_channels, + out_channels: output_channel, + add_upsample: not last_block?, + activation: spec.activation, + name: join(name, idx) + ] + + {do_up_block(up_block_type, sample, block_opts), output_channel} + end + + sample + end + + defp do_up_block(:up_block, sample, opts), + do: up_block(sample, opts) + + defp up_block(hidden_state, opts) do + in_channels = opts[:in_channels] + out_channels = opts[:out_channels] + depth = opts[:depth] + activation = opts[:activation] + add_upsample = opts[:add_upsample] + name = opts[:name] + + hidden_state = + for idx <- 0..(depth - 1), reduce: hidden_state do + hidden_state -> + in_channels = if(idx == 0, do: in_channels, else: out_channels) + + Diffusion.Layers.residual_block(hidden_state, in_channels, out_channels, + activation: activation, + name: name |> join("residual_blocks") |> join(idx) + ) + end + + if add_upsample do + Diffusion.Layers.upsample_2d(hidden_state, out_channels, name: join(name, "upsamples.0")) + else + hidden_state + end + end + + defp mid_block(hidden_state, spec, opts) do + name = opts[:name] + + in_channels = List.last(spec.hidden_sizes) + + hidden_state + |> Diffusion.Layers.residual_block(in_channels, in_channels, + activation: spec.activation, + name: join(name, "residual_blocks.0") + ) + |> attention_block(in_channels, num_heads: 1, name: join(name, "attentions.0")) + |> Diffusion.Layers.residual_block(in_channels, in_channels, + activation: spec.activation, + name: join(name, "residual_blocks.1") + ) + end + + defp attention_block(hidden_state, channels, opts) do + num_heads = opts[:num_heads] + name = opts[:name] + + shortcut = hidden_state + + hidden_state = + hidden_state + |> Axon.group_norm(32, epsilon: 1.0e-6, name: join(name, "norm")) + |> Axon.reshape({:batch, :auto, channels}) + + {hidden_state, _attention, _self_attention_cache, _position_bias} = + Layers.Transformer.multi_head_attention(hidden_state, hidden_state, hidden_state, + num_heads: num_heads, + hidden_size: channels, + name: name + ) + + hidden_state = + Axon.layer( + fn hidden_state, shortcut, _opts -> + Nx.reshape(hidden_state, Nx.shape(shortcut)) + end, + [hidden_state, shortcut] + ) + + Axon.add(hidden_state, shortcut) + end + + defp diagonal_gaussian_distribution(x) do + {mean, logvar} = Axon.split(x, 2, axis: -1) + logvar = Axon.nx(logvar, &Nx.clip(&1, -30.0, 20.0)) + std = Axon.nx(logvar, &Nx.exp(Nx.multiply(0.5, &1))) + var = Axon.nx(logvar, &Nx.exp/1) + %{mean: mean, logvar: logvar, std: std, var: var} + end + + defp sample(posterior, opts) do + name = opts[:name] + + key_state = + Axon.param("key", fn _ -> {2} end, + type: {:u, 32}, + initializer: fn _, _ -> Nx.Random.key(:erlang.system_time()) end + ) + + z = + Axon.layer( + fn mean, prng_key, opts -> + mode = opts[:mode] + + case mode do + :train -> + {rand, next_key} = Nx.Random.normal(prng_key, shape: Nx.shape(mean)) + %Axon.StatefulOutput{output: rand, state: %{"key" => next_key}} + + :inference -> + {rand, _next_key} = Nx.Random.normal(prng_key, shape: Nx.shape(mean)) + rand + end + end, + [posterior.mean, key_state], + name: name + ) + + z + |> Axon.multiply(posterior.std) + |> Axon.add(posterior.mean) + end + + defp mode(%{mean: mean}) do + mean + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + sample_size: {"sample_size", number()}, + in_channels: {"in_channels", number()}, + out_channels: {"out_channels", number()}, + latent_channels: {"latent_channels", number()}, + hidden_sizes: {"block_out_channels", list(number())}, + depth: {"layers_per_block", number()}, + down_block_types: + {"down_block_types", list(mapping(%{"DownEncoderBlock2D" => :down_block}))}, + up_block_types: {"up_block_types", list(mapping(%{"UpDecoderBlock2D" => :up_block}))}, + activation: {"act_fn", activation()} + ) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + alias Bumblebee.HuggingFace.Transformers + + def params_mapping(_spec) do + block_mapping = %{ + "attentions.{m}.norm" => "attentions.{m}.group_norm", + # The layer name has been renamed upstream, so we try both + "attentions.{m}.query" => ["attentions.{m}.to_q", "attentions.{m}.query"], + "attentions.{m}.key" => ["attentions.{m}.to_k", "attentions.{m}.key"], + "attentions.{m}.value" => ["attentions.{m}.to_v", "attentions.{m}.value"], + "attentions.{m}.output" => ["attentions.{m}.to_out.0", "attentions.{m}.proj_attn"], + "residual_blocks.{m}.norm_1" => "resnets.{m}.norm1", + "residual_blocks.{m}.conv_1" => "resnets.{m}.conv1", + "residual_blocks.{m}.norm_2" => "resnets.{m}.norm2", + "residual_blocks.{m}.conv_2" => "resnets.{m}.conv2", + "residual_blocks.{m}.shortcut.projection" => "resnets.{m}.conv_shortcut", + "downsamples.{m}.conv" => "downsamplers.{m}.conv", + "upsamples.{m}.conv" => "upsamplers.{m}.conv" + } + + blocks_mapping = + [ + "encoder.down_blocks.{n}", + "encoder.mid_block", + "decoder.mid_block", + "decoder.up_blocks.{n}" + ] + |> Enum.map(&Transformers.Utils.prefix_params_mapping(block_mapping, &1, &1)) + |> Enum.reduce(&Map.merge/2) + + %{ + "encoder.input_conv" => "encoder.conv_in", + "encoder.output_norm" => "encoder.conv_norm_out", + "encoder.output_conv" => "encoder.conv_out", + "encoder.pre_quantization_conv" => "quant_conv", + "decoder.post_quantization_conv" => "post_quant_conv", + "decoder.input_conv" => "decoder.conv_in", + "decoder.output_norm" => "decoder.conv_norm_out", + "decoder.output_conv" => "decoder.conv_out", + # TODO: this is never loaded, add support for :ignored source name + "sample" => "sample" + } + |> Map.merge(blocks_mapping) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/featurizer.ex b/deps/bumblebee/lib/bumblebee/featurizer.ex new file mode 100644 index 0000000000000000000000000000000000000000..64fd5a2af9e76c6308f245a843fb63bb972e411e --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/featurizer.ex @@ -0,0 +1,79 @@ +defmodule Bumblebee.Featurizer do + @moduledoc """ + An interface for configuring and applying featurizers. + + A featurizer is used to convert raw data into model input. + + Every module implementing this behaviour is expected to also define + a configuration struct. + """ + + @type t :: Bumblebee.Configurable.t() + + @doc """ + Converts the given input to a batched tensor (or a tensor container). + + Numerical batch processing should be moved to `c:process_batch/2` + whenever possible. + """ + @callback process_input(t(), input :: any()) :: Nx.t() | Nx.Container.t() + + @doc """ + Returns an input template for `c:process_batch/2`. + + The shape is effectively the same as the result of `c:process_input/2`, + except for the batch size. + """ + @callback batch_template(t(), batch_size :: pos_integer()) :: Nx.t() | Nx.Container.t() + + @doc """ + Optional batch processing stage. + + This is a numerical function. It receives the result of `c:process_input/2`, + except the batch size may differ. + + When using featurizer as part of `Nx.Serving`, the batch stage can + be merged with the model computation and compiled together. + """ + @callback process_batch(t(), input :: Nx.t() | Nx.Container.t()) :: Nx.t() | Nx.Container.t() + + @optional_callbacks batch_template: 2, process_batch: 2 + + @doc """ + Converts the given input to a batched tensor (or a tensor container). + """ + @spec process_input(t(), any()) :: Nx.t() | Nx.Container.t() + def process_input(%module{} = featurizer, input) do + module.process_input(featurizer, input) + end + + @doc """ + Returns an input template for `process_batch/2`. + + If the featurizer does not define batch processing, `nil` is returned. + """ + @spec batch_template(t(), pos_integer()) :: Nx.t() | Nx.Container.t() | nil + def batch_template(%module{} = featurizer, batch_size) do + if Code.ensure_loaded?(module) and function_exported?(module, :batch_template, 2) do + module.batch_template(featurizer, batch_size) + end + end + + @doc """ + Optional batch processing stage. + + This is a numerical function. It receives the result of `c:process_input/2`, + except the batch size may differ. + + If the featurizer does not define batch processing, the input is + returned as is. + """ + @spec process_batch(t(), Nx.t() | Nx.Container.t()) :: Nx.t() | Nx.Container.t() + def process_batch(%module{} = featurizer, batch) do + if Code.ensure_loaded?(module) and function_exported?(module, :process_batch, 2) do + module.process_batch(featurizer, batch) + else + batch + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/huggingface/hub.ex b/deps/bumblebee/lib/bumblebee/huggingface/hub.ex new file mode 100644 index 0000000000000000000000000000000000000000..6a730301f808f9cf65c9733b80d4915dea4fb1aa --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/huggingface/hub.ex @@ -0,0 +1,240 @@ +defmodule Bumblebee.HuggingFace.Hub do + @moduledoc false + + alias Bumblebee.Utils.HTTP + + @huggingface_endpoint "https://huggingface.co" + + @doc """ + Returns a URL pointing to the given file in a Hugging Face repository. + """ + @spec file_url(String.t(), String.t(), String.t() | nil) :: String.t() + def file_url(repository_id, filename, revision) do + revision = revision || "main" + @huggingface_endpoint <> "/#{repository_id}/resolve/#{revision}/#{filename}" + end + + @doc """ + Returns a URL to list the contents of a Hugging Face repository. + """ + @spec file_listing_url(String.t(), String.t() | nil, String.t() | nil) :: String.t() + def file_listing_url(repository_id, subdir, revision) do + revision = revision || "main" + path = if(subdir, do: "/" <> subdir) + @huggingface_endpoint <> "/api/models/#{repository_id}/tree/#{revision}#{path}" + end + + @doc """ + Downloads file from the given URL and returns a path to the file. + + The file is cached based on the received ETag. Subsequent requests + for the same URL validate the ETag and return a file from the cache + if there is a match. + + ## Options + + * `:cache_dir` - the directory to store the downloaded files in. + Defaults to the standard cache location for the given operating + system + + * `:offline` - if `true`, cached path is returned if exists and + and error otherwise + + * `:auth_token` - the token to use as HTTP bearer authorization + for remote files + + * `:etag` - by default a HEAD request is made to fetch the latest + ETag value, however if the value is already known, it can be + passed as an option instead (to skip the extra request) + + * `:cache_scope` - a namespace to put the cached files under in + the cache directory + + """ + @spec cached_download(String.t(), keyword()) :: {:ok, String.t()} | {:error, String.t()} + def cached_download(url, opts \\ []) do + cache_dir = opts[:cache_dir] || Bumblebee.cache_dir() + offline = Keyword.get(opts, :offline, bumblebee_offline?()) + auth_token = opts[:auth_token] + + dir = Path.join(cache_dir, "huggingface") + + dir = + if cache_scope = opts[:cache_scope] do + Path.join(dir, cache_scope) + else + dir + end + + File.mkdir_p!(dir) + + headers = + if auth_token do + [{"Authorization", "Bearer " <> auth_token}] + else + [] + end + + metadata_path = Path.join(dir, metadata_filename(url)) + + cond do + offline -> + case load_json(metadata_path) do + {:ok, %{"etag" => etag}} -> + entry_path = Path.join(dir, entry_filename(url, etag)) + {:ok, entry_path} + + _ -> + {:error, + "could not find file in local cache and outgoing traffic is disabled, url: #{url}"} + end + + entry_path = opts[:etag] && cached_path_for_etag(dir, url, opts[:etag]) -> + {:ok, entry_path} + + true -> + with {:ok, etag, download_url, redirect?} <- head_download(url, headers) do + if entry_path = cached_path_for_etag(dir, url, etag) do + {:ok, entry_path} + else + entry_path = Path.join(dir, entry_filename(url, etag)) + + headers = + if redirect? do + List.keydelete(headers, "Authorization", 0) + else + headers + end + + download_url + |> HTTP.download(entry_path, headers: headers) + |> finish_request(download_url) + |> case do + :ok -> + :ok = store_json(metadata_path, %{"etag" => etag, "url" => url}) + {:ok, entry_path} + + error -> + File.rm_rf!(metadata_path) + File.rm_rf!(entry_path) + error + end + end + end + end + end + + defp cached_path_for_etag(dir, url, etag) do + metadata_path = Path.join(dir, metadata_filename(url)) + + case load_json(metadata_path) do + {:ok, %{"etag" => ^etag}} -> + path = Path.join(dir, entry_filename(url, etag)) + + # Make sure the file exists, in case someone manually removed it + if File.exists?(path) do + path + end + + _ -> + nil + end + end + + defp head_download(url, headers) do + with {:ok, response} <- + HTTP.request(:head, url, follow_redirects: false, headers: headers) + |> finish_request(url) do + if response.status in 300..399 do + location = HTTP.get_header(response, "location") + + # Follow relative redirects + if URI.parse(location).host == nil do + url = + url + |> URI.parse() + |> Map.replace!(:path, location) + |> URI.to_string() + + head_download(url, headers) + else + with {:ok, etag} <- fetch_etag(response), do: {:ok, etag, location, true} + end + else + with {:ok, etag} <- fetch_etag(response), do: {:ok, etag, url, false} + end + end + end + + defp finish_request(:ok, _url), do: :ok + + defp finish_request({:ok, response}, _url) when response.status in 100..399, do: {:ok, response} + + defp finish_request({:ok, response}, url) do + case HTTP.get_header(response, "x-error-code") do + code when code == "RepoNotFound" or response.status == 401 -> + {:error, + "repository not found, url: #{url}. Please make sure you specified" <> + " the correct repository id. If you are trying to access a private" <> + " or gated repository, use an authentication token"} + + "EntryNotFound" -> + {:error, "file not found, url: #{url}"} + + "RevisionNotFound" -> + {:error, "revision not found, url: #{url}"} + + "GatedRepo" -> + {:error, + "cannot access gated repository, url: #{url}. Make sure to request access" <> + " for the repository and use an authentication token"} + + _ -> + {:error, "HTTP request failed with status #{response.status}, url: #{url}"} + end + end + + defp finish_request({:error, reason}, _url) do + {:error, "failed to make an HTTP request, reason: #{inspect(reason)}"} + end + + defp fetch_etag(response) do + if etag = HTTP.get_header(response, "x-linked-etag") || HTTP.get_header(response, "etag") do + {:ok, etag} + else + {:error, "no ETag found on the resource"} + end + end + + defp metadata_filename(url) do + encode_url(url) <> ".json" + end + + defp entry_filename(url, etag) do + encode_url(url) <> "." <> encode_etag(etag) + end + + defp encode_url(url) do + url |> :erlang.md5() |> Base.encode32(case: :lower, padding: false) + end + + defp encode_etag(etag) do + Base.encode32(etag, case: :lower, padding: false) + end + + defp load_json(path) do + case File.read(path) do + {:ok, content} -> {:ok, Jason.decode!(content)} + _error -> :error + end + end + + defp store_json(path, data) do + json = Jason.encode!(data) + File.write(path, json) + end + + defp bumblebee_offline?() do + System.get_env("BUMBLEBEE_OFFLINE") in ~w(1 true) + end +end diff --git a/deps/bumblebee/lib/bumblebee/huggingface/transformers/config.ex b/deps/bumblebee/lib/bumblebee/huggingface/transformers/config.ex new file mode 100644 index 0000000000000000000000000000000000000000..f9aa611c5b25d146bad86dcc273a7955e4e1d26c --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/huggingface/transformers/config.ex @@ -0,0 +1,12 @@ +defprotocol Bumblebee.HuggingFace.Transformers.Config do + @moduledoc false + + # This protocol defines a bridge between Bumblebee and huggingface/transformers + # configuration. + + @doc """ + Updates configuration based on a parsed JSON data. + """ + @spec load(t(), map()) :: Bumblebee.ModelSpec.t() + def load(config, data) +end diff --git a/deps/bumblebee/lib/bumblebee/huggingface/transformers/model.ex b/deps/bumblebee/lib/bumblebee/huggingface/transformers/model.ex new file mode 100644 index 0000000000000000000000000000000000000000..ac844d5b81d9eff4c79f275e0dd723771daef4b2 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/huggingface/transformers/model.ex @@ -0,0 +1,80 @@ +defprotocol Bumblebee.HuggingFace.Transformers.Model do + @moduledoc false + + # This protocol defines details related to loading Bumblebee model + # from huggingface/transformers model. + + @type params_mapping :: %{layer_name() => params_source()} + + @type params_source :: layer_name() | list(layer_name()) | param_builders() + + @type param_builders :: %{param_name() => param_builder()} + + @type param_builder :: + {list(param_source()), (list(Nx.tensor()) -> Nx.Tensor.t() | Nx.Container.t())} + + @type param_source :: param_ref() | list(param_ref()) + @type param_ref :: {layer_name(), param_name()} + + @type layer_name :: String.t() + @type param_name :: String.t() + + @doc """ + Returns a map describing layers/parameters relationship between an + Axon model and a corresponding huggingface/transformers model. + + ## Mapping format + + The basic mapping format is a map with Axon layer names (target) as + keys and PyTorch layer names (source) as values. For example: + + %{ + "embedder.token_embedding" => "bert.embeddings.word_embeddings", + ... + } + + The mapping should always use the longest names, that is, depending on + the architecture, the PyTorch layer name could be either + `"bert.embeddings.word_embeddings"` or `"embeddings.word_embeddings"`. + The longer version should generally be used. Prefixes are removed/added + as necessary, so loading partial models is supported automatically. + + The layer names may include simple substitutions, useful for lists + of layers: + + %{ + "encoder.blocks.{n}.self_attention.query" => "bert.encoder.layer.{n}.attention.self.query", + ... + } + + Both param names and values for corresponding layers may not match + exactly, so they require further transformations. For example, the + convolution `"kernel"` in Axon corresponds to a transposed `"weight"` + from PyTorch. For most common layers such conversions are handled + automatically. + + In some cases, particularly with model-specific layers/parameters, + we may need more control over the parameter mapping. In such cases, + instead of source layer name, a map with parameter-level transformations + may be specified: + + %{ + "embedder.class_embedding" => %{ + "embedding" => { + [{"vit.embeddings", "cls_token"}], + fn [value] -> Nx.squeeze(value, axes: [0, 1]) end + } + }, + ... + } + + For each parameter, we specify a list of source parameters in the + form of `{source_layer_name, source_param_name}`, then a function + to build our parameter value. Instead of a single tuple, we can + specify a list of those to try one by one. With the explicit + transformation we can handle arbitrary parameter name and value + transformations. + """ + @spec params_mapping(t()) :: params_mapping() + def params_mapping(spec) +end diff --git a/deps/bumblebee/lib/bumblebee/huggingface/transformers/utils.ex b/deps/bumblebee/lib/bumblebee/huggingface/transformers/utils.ex new file mode 100644 index 0000000000000000000000000000000000000000..911a3c18f887d2923dc3264f68d2f94267a5568a --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/huggingface/transformers/utils.ex @@ -0,0 +1,56 @@ +defmodule Bumblebee.HuggingFace.Transformers.Utils do + @moduledoc false + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.HuggingFace.Transformers + + @doc """ + Prefixes target and source layer names in the given params mapping. + """ + @spec prefix_params_mapping( + Transformers.Model.params_mapping(), + String.t() | nil, + String.t() | nil + ) :: Transformers.Model.params_mapping() + def prefix_params_mapping(params_mapping, target_prefix, source_prefix) do + Map.new(params_mapping, fn {target_layer_name, params_source} -> + { + join(target_prefix, target_layer_name), + map_params_source_layer_names(params_source, &join(source_prefix, &1)) + } + end) + end + + @doc """ + Maps layer names in a params mapping value. + """ + @spec map_params_source_layer_names( + Transformers.Model.params_source(), + (String.t() -> String.t()) + ) :: Transformers.Model.params_source() + def map_params_source_layer_names(%{} = param_builders, fun) do + Map.new(param_builders, fn {param_name, {sources, builder_fun}} -> + sources = + for ref_or_refs <- sources do + case ref_or_refs do + {layer_name, param_name} -> + {fun.(layer_name), param_name} + + refs -> + for {layer_name, param_name} <- refs, do: {fun.(layer_name), param_name} + end + end + + {param_name, {sources, builder_fun}} + end) + end + + def map_params_source_layer_names(layer_names, fun) when is_list(layer_names) do + Enum.map(layer_names, fun) + end + + def map_params_source_layer_names(layer_name, fun) when is_binary(layer_name) do + fun.(layer_name) + end +end diff --git a/deps/bumblebee/lib/bumblebee/layers.ex b/deps/bumblebee/lib/bumblebee/layers.ex new file mode 100644 index 0000000000000000000000000000000000000000..3c9c92cac74f9cd22637a6a4b6ebf8f2d73f7998 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/layers.ex @@ -0,0 +1,1430 @@ +defmodule Bumblebee.Layers do + @moduledoc false + + import Nx.Defn + + @unsupported_activations [:gelu_approx_tanh, :gelu_approx_sigmoid] + + @pi :math.pi() + + @doc """ + Adds an activation layer. + + Handles all activations built into Axon, as well as several custom + activations. + + ## Options + + * `:name` - layer name + + """ + def activation(%Axon{} = input, activation, opts \\ []) do + opts = Keyword.validate!(opts, [:name]) + name = opts[:name] + + if activation in @unsupported_activations do + Axon.activation(input, &apply(__MODULE__, activation, [&1, &2]), name: name) + else + Axon.activation(input, activation, name: name) + end + end + + @doc """ + Implements the GeLU activation approximated with tanh. + + ## References + + * [Gaussian Error Linear Units (GeLUs)](https://arxiv.org/pdf/1606.08415.pdf) + + """ + defn gelu_approx_tanh(input, _opts \\ []) do + 0.5 * input * + (1.0 + Nx.tanh(Nx.sqrt(2.0 / @pi) * (input + 0.044715 * Nx.pow(input, 3.0)))) + end + + @doc """ + Implements the GeLU activation approximated with sigmoid. + + Note that this approximation is less accurate than `gelu_approx_tanh/2`. + + ## References + + * [Gaussian Error Linear Units (GeLUs)](https://arxiv.org/pdf/1606.08415.pdf) + + """ + defn gelu_approx_sigmoid(input, _opts \\ []) do + input * Nx.sigmoid(1.702 * input) + end + + @doc """ + Computes relative attention bias. + """ + def relative_attention_bias(query, key, attention_cache, offset, opts \\ []) do + opts = + Keyword.validate!(opts, [ + :name, + bidirectional: true, + num_heads: 8, + num_buckets: 32, + max_distance: 128 + ]) + + name = opts[:name] + + relative_position_buckets = + Axon.layer( + &compute_relative_position_buckets/4, + [query, key, Axon.optional(attention_cache)], + bidirectional: opts[:bidirectional], + num_buckets: opts[:num_buckets], + max_distance: opts[:max_distance] + ) + + bias = + relative_position_buckets + |> Axon.embedding(opts[:num_buckets], opts[:num_heads], name: name) + |> Axon.transpose([2, 0, 1]) + |> Axon.nx(&Nx.new_axis(&1, 0)) + + Axon.layer( + fn bias, query, offset, _opts -> + case offset do + %Axon.None{} -> + bias + + offset -> + mask_shift = offset + query_length = Nx.axis_size(query, 1) + Nx.slice_along_axis(bias, mask_shift, query_length, axis: 2) + end + end, + [bias, query, Axon.optional(offset)] + ) + end + + defnp compute_relative_position_buckets(query, key, attention_cache, opts \\ []) do + opts = + keyword!(opts, mode: :inference, bidirectional: true, num_buckets: 32, max_distance: 128) + + {key_length, query_length} = key_query_lengths(query, key, attention_cache) + + context_position = Nx.iota({query_length, 1}) + memory_position = Nx.iota({1, key_length}) + relative_position = memory_position - context_position + + {num_buckets, relative_buckets, relative_position} = + bidirectional_buckets(relative_position, opts[:num_buckets], opts[:bidirectional]) + + max_exact = Nx.quotient(num_buckets, 2) + is_small = Nx.less(relative_position, max_exact) + + relative_position_if_large = + max_exact + + Nx.log(relative_position / max_exact) / Nx.log(opts[:max_distance] / max_exact) * + (num_buckets - max_exact) + + relative_position_if_large = + Nx.min( + relative_position_if_large, + Nx.broadcast(num_buckets - 1, Nx.shape(relative_position_if_large)) + ) + |> Nx.as_type(:s64) + + relative_buckets + Nx.select(is_small, relative_position, relative_position_if_large) + end + + deftransformp key_query_lengths(query, key, attention_cache) do + case attention_cache do + %Axon.None{} -> + {Nx.axis_size(key, 1), Nx.axis_size(query, 1)} + + attention_cache -> + key_length = Nx.axis_size(attention_cache.key, 1) + {key_length, key_length} + end + end + + deftransformp bidirectional_buckets(relative_position, num_buckets, bidirectional) do + relative_buckets = 0 + + if bidirectional do + num_buckets = div(num_buckets, 2) + + relative_buckets = + Nx.add(relative_buckets, Nx.multiply(Nx.greater(relative_position, 0), num_buckets)) + + relative_position = Nx.abs(relative_position) + {num_buckets, relative_buckets, relative_position} + else + relative_position = + relative_position + |> Nx.min(Nx.broadcast(0, Nx.shape(relative_position))) + |> Nx.negate() + + {num_buckets, relative_buckets, relative_position} + end + end + + @doc ~S""" + Computes scaled dot-product attention for multiple attention heads. + + This is the core calculation behind multi-head attention, the projection + layers should be applied on top of this layer. + + Given input sequences $Q, K, V \in R^{N \times d}$, where $N$ is the + sequence length and $d$ is the head dimension, the scaled dot-product + attention is defined as: + + $$ + Attention(Q, K, V) = softmax(\frac{QK^T}{\sqrt{d}})V + $$ + + This operations is further batched across multiple heads and multiple + input sequences. + + Intuitively scaled dot-product attention can be thought of as information + retrieval, where for each sequence element in $Q$ the objective is + to extract relevant context from sequence elements in $V$. In this + analogy, $K$ is the summarization of information, while $V$ is the + actual information. Then, assuming $Q$ and $K$ are embedded into a + common space (which is the job of prior projection layers), the + $QK^T$ dot product is a cosine similarity and gives us relevance + weights for sequence elements in $V$. + + In case of self-attention, where $Q, K, V$ originate from the same + sequence, the $QK^T$ weights indicate how much "each word attends + to other words". + + ## Parameter Shapes + + * `query` - `{batch_size, sequence_length, num_heads, head_size}` + * `key` - `{batch_size, kv_sequence_length, num_heads, head_size}` + * `value` - `{batch_size, kv_sequence_length, num_heads, head_size}` + * `key_mask` (optional) - `{batch_size, kv_sequence_length} | {batch_size, num_heads, sequence_length, kv_sequence_length}` + * `head_mask` (optional) - `{num_heads}` + * `bias` (optional) - `{batch_size | 1, num_heads | 1, sequence_length, kv_sequence_length}` + * `offset` (optional) - `{}` + + ## Output Shape + + `{batch_size, sequence_length, num_heads, head_size}` + + ## Options + + * `:causal` - whether to apply causal mask to attention weights. + This is typically used for next token prediction and it + effectively makes each input token use information exclusively + from prior tokens. Defaults to `false` + + * `:window_size` - when set, enables sliding window attention. + Should be a `{left, right}` tuple with window size on each side + + * `:scale` - whether to scale attention weights by $\frac{1}{\sqrt{d}}$. + Defaults to `true` + + * `:dropout_rate` - the dropout rate for attention weights dropout. + Defaults to `0.0` + + ## References + + * [Attention Is All You Need](https://arxiv.org/abs/1706.03762), Figure 2 (left) + + """ + def attention(query, key, value, key_mask, head_mask, bias, offset, opts \\ []) do + opts = Keyword.validate!(opts, [:window_size, causal: false, scale: true, dropout_rate: 0.0]) + + weights = + Axon.layer( + &attention_weights_impl/7, + [ + query, + key, + Axon.optional(key_mask), + Axon.optional(head_mask), + Axon.optional(bias), + Axon.optional(offset) + ], + causal: opts[:causal], + window_size: opts[:window_size], + scale: opts[:scale] + ) + |> Axon.dropout(rate: opts[:dropout_rate]) + + output = Axon.layer(&attention_output_impl/3, [weights, value], opts) + + {output, weights} + end + + defnp attention_weights_impl(query, key, key_mask, head_mask, bias, offset, opts \\ []) do + opts = keyword!(opts, [:window_size, mode: :inference, scale: true, causal: false]) + + query = Nx.transpose(query, axes: [0, 2, 1, 3]) + key = Nx.transpose(key, axes: [0, 2, 1, 3]) + + weights = Nx.dot(query, [3], [0, 1], key, [3], [0, 1]) + + weights = + if opts[:scale] do + depth = Nx.axis_size(query, -1) + weights / Nx.as_type(Nx.sqrt(depth), Nx.type(query)) + else + weights + end + + key_mask = + case key_mask do + %Axon.None{} -> + Nx.broadcast(1, {1, 1, 1, 1}) + + key_mask -> + case Nx.rank(key_mask) do + 2 -> key_mask |> Nx.new_axis(1) |> Nx.new_axis(1) + 4 -> key_mask + end + end + + query_sequence_length = Nx.axis_size(query, 2) + key_sequence_length = Nx.axis_size(key, 2) + offset = ensure_offset(offset) + + causal_and_window_mask = + case {opts[:causal], opts[:window_size]} do + {false, nil} -> + Nx.broadcast(1, {1, 1}) + + {false, {left_size, right_size}} -> + window_mask(query_sequence_length, key_sequence_length, offset, left_size, right_size) + + {true, nil} -> + causal_mask(query_sequence_length, key_sequence_length, offset) + + {true, {left_size, _right_size}} -> + window_mask(query_sequence_length, key_sequence_length, offset, left_size, 0) + end + |> Nx.new_axis(0) + |> Nx.new_axis(0) + + mask = key_mask and causal_and_window_mask + + bias = + case bias do + %Axon.None{} -> + Nx.select( + mask, + Nx.tensor(0.0, type: Nx.type(query)), + Nx.Constants.min_finite(Nx.type(query)) + ) + + bias -> + Nx.select( + Nx.broadcast(mask, max_shape(mask, bias)), + bias, + Nx.Constants.min_finite(Nx.type(query)) + ) + end + + weights = weights + bias + + weights = Axon.Activations.softmax(weights, axis: -1) + + case head_mask do + %Axon.None{} -> + weights + + head_mask -> + head_mask = Nx.reshape(head_mask, {1, :auto, 1, 1}) + Nx.multiply(weights, head_mask) + end + end + + defnp causal_mask(query_sequence_length, key_sequence_length, offset) do + Nx.greater_equal( + Nx.iota({query_sequence_length, 1}) + offset, + Nx.iota({1, key_sequence_length}) + ) + end + + defnp window_mask(query_sequence_length, key_sequence_length, offset, left_size, right_size) do + position_diff = + Nx.subtract( + Nx.iota({query_sequence_length, 1}) + offset, + Nx.iota({1, key_sequence_length}) + ) + + left_size >= position_diff and position_diff >= -right_size + end + + defnp attention_output_impl(weights, value, _opts \\ []) do + value = Nx.transpose(value, axes: [0, 2, 1, 3]) + out = Nx.dot(weights, [3], [0, 1], value, [2], [0, 1]) + Nx.transpose(out, axes: [0, 2, 1, 3]) + end + + defnp ensure_offset(offset) do + case offset do + %Axon.None{} -> 0 + offset -> offset + end + end + + deftransformp max_shape(left, right) do + Enum.zip_with( + Tuple.to_list(Nx.shape(left)), + Tuple.to_list(Nx.shape(right)), + &max/2 + ) + |> List.to_tuple() + end + + @doc """ + Adds a dense layer to the network. + + The kernel parameter is transposed with respect to `Axon.dense/3`. + + ## Options + + * `:name` - layer name + + * `:kernel_initializer` - initializer for `kernel` weights. + Defaults to `:glorot_uniform` + + * `:bias_initializer` - initializer for `bias` weights. Defaults + to `:zeros`. + + * `:use_bias` - whether the layer should add bias to the output. + Defaults to `false` + + """ + def dense_transposed(%Axon{} = x, units, opts \\ []) do + opts = + Keyword.validate!(opts, [ + :name, + kernel_initializer: :glorot_uniform, + bias_initializer: :zeros, + use_bias: false + ]) + + kernel_shape = fn input_shape -> + kernel_shape = Axon.Shape.dense_kernel(input_shape, units) + + # We expect a transposed kernel + kernel_shape + |> Tuple.to_list() + |> Enum.reverse() + |> List.to_tuple() + end + + bias_shape = &Axon.Shape.dense_bias(&1, units) + + kernel = Axon.param("kernel", kernel_shape, initializer: opts[:kernel_initializer]) + + {inputs, op} = + if opts[:use_bias] do + bias = Axon.param("bias", bias_shape, initializer: opts[:bias_initializer]) + {[x, kernel, bias], &dense_transposed_impl/4} + else + {[x, kernel], &dense_transposed_impl/3} + end + + Axon.layer(op, inputs, name: opts[:name], op_name: :dense_transposed) + end + + deftransformp dense_transposed_impl(x, kernel, bias \\ 0, _opts) do + Nx.dot(x, [-1], kernel, [1]) + |> Nx.add(bias) + end + + @doc """ + Adds a 1-dimensional convolution layer to the network. + + ## Options + + * `:name` - layer name. + + * `:kernel_initializer` - initializer for `kernel` weights. + Defaults to `:glorot_uniform`. + + * `:bias_initializer` - initializer for `bias` weights. Defaults + to `:zeros` + + * `:use_bias` - whether the layer should add bias to the output. + Defaults to `true` + + """ + def conv1d(%Axon{} = x, units, opts) do + opts = + Keyword.validate!(opts, [ + :name, + kernel_initializer: :glorot_uniform, + bias_initializer: :zeros, + use_bias: true + ]) + + kernel_shape = fn input_shape -> + {elem(input_shape, tuple_size(input_shape) - 1), units} + end + + bias_shape = fn _ -> {units} end + + kernel = Axon.param("kernel", kernel_shape, initializer: opts[:kernel_initializer]) + + {inputs, op} = + if opts[:use_bias] do + bias = Axon.param("bias", bias_shape, initializer: opts[:bias_initializer]) + {[x, kernel, bias], &conv1d_impl/4} + else + {[x, kernel], &conv1d_impl(&1, &2, 0, &3)} + end + + Axon.layer(op, inputs, name: opts[:name], op_name: :conv1d) + end + + defnp conv1d_impl(input, kernel, bias, _opts \\ []) do + input + |> Nx.dot([Nx.rank(input) - 1], [], kernel, [0], []) + |> Nx.add(bias) + end + + @doc """ + Adds a scaling layer to the network. + + The scaling layer scales inputs by a learned scale parameter. + + ## Options + + * `:name` - layer name + + * `:scale_initializer` - initializer for the scale parameter + + * `:channel_index` - index of the axis to scale. Defaults to the + last axis + + """ + def scale(%Axon{} = x, opts \\ []) do + opts = + Keyword.validate!(opts, [ + :name, + scale_initializer: Axon.Initializers.full(1.0e-6), + channel_index: -1 + ]) + + name = opts[:name] + scale_initializer = opts[:scale_initializer] + channel_index = opts[:channel_index] + + scale_shape = fn input_shape -> + rank = tuple_size(input_shape) + channel_index = rem(rank + channel_index, rank) + out_channels = elem(input_shape, channel_index) + {out_channels} + end + + scale_param = Axon.param("scale", scale_shape, initializer: scale_initializer) + + Axon.layer( + fn input, scale, _opts -> + channel_index = Nx.axis_index(input, channel_index) + shape = Tuple.duplicate(1, Nx.rank(input)) |> put_elem(channel_index, :auto) + scale = Nx.reshape(scale, shape) + Nx.multiply(input, scale) + end, + [x, scale_param], + name: name, + op_name: :scale + ) + end + + @doc """ + Adds a drop-path layer to the network for stochastic depth. + + ## Options + + * `:name` - layer name + + * `:rate` - drop path rate + + ## References + + * [Deep Networks with Stochastic Depth](https://arxiv.org/pdf/1603.09382.pdf) + + """ + def drop_path(%Axon{} = input, opts \\ []) do + opts = Keyword.validate!(opts, [:name, :seed, rate: 0.0]) + seed = Keyword.get_lazy(opts, :seed, fn -> :erlang.system_time() end) + + key_state = + Axon.param("key", fn _ -> {2} end, + type: {:u, 32}, + initializer: fn _, _ -> Nx.Random.key(seed) end + ) + + if opts[:rate] > 0.0 do + Axon.layer(&drop_path_impl/3, [input, key_state], + name: opts[:name], + op_name: :drop_path, + rate: opts[:rate] + ) + else + input + end + end + + deftransformp drop_path_impl(x, prng_key, opts \\ []) do + opts = Keyword.validate!(opts, rate: 0.0, mode: :train) + rate = opts[:rate] + + case opts[:mode] do + :train -> + keep_prob = 1 - rate + shape = Tuple.duplicate(1, Nx.rank(x)) |> put_elem(0, Nx.axis_size(x, 0)) + + {rand, next_key} = Nx.Random.uniform(prng_key, shape: shape) + + bernoulli_noise = + keep_prob + |> Nx.add(rand) + |> Nx.floor() + + out = + x + |> Nx.divide(keep_prob) + |> Nx.multiply(bernoulli_noise) + + %Axon.StatefulOutput{output: out, state: %{"key" => next_key}} + + _mode -> + x + end + end + + @doc """ + Takes the first element along the given axis. + + This is a common operation in many architectures. It reduces + dimensionality by dropping the given axis. + + ## Options + + * `:name` - layer name + + * `:axis` - axis to slice token from + + * `:index` - index to slice head. Defaults to 0 + + """ + def take_token(%Axon{} = input, opts \\ []) do + opts = Keyword.validate!(opts, [:name, :axis, index: 0]) + + Axon.nx( + input, + fn x -> + x + |> Nx.slice_along_axis(opts[:index], 1, axis: opts[:axis]) + |> Nx.squeeze(axes: [opts[:axis]]) + end, + name: opts[:name] + ) + end + + @doc """ + Implements position masking for embedded patches of visual inputs. + + This layer expects computed patch embeddings and an optional mask. + If the mask is not specified, it will skip masking altogether. + + ## Options + + * `:name` - layer name + + """ + def apply_vision_patch_mask(%Axon{} = embeddings, patch_mask, opts \\ []) do + opts = Keyword.validate!(opts, [:name]) + name = opts[:name] + + mask_token_shape = fn embeddings_shape, _ -> + hidden_size = elem(embeddings_shape, 2) + {1, 1, hidden_size} + end + + mask_token = Axon.param("mask_token", mask_token_shape, initializer: :zeros) + + if_present patch_mask do + Axon.layer( + fn embeddings, patch_mask, mask_tokens, _opts -> + hidden_size = Nx.axis_size(embeddings, 2) + batch_size = Nx.axis_size(embeddings, 0) + sequence_length = Nx.axis_size(embeddings, 1) + mask_tokens = Nx.broadcast(mask_tokens, {batch_size, sequence_length, hidden_size}) + + mask = + patch_mask + |> Nx.new_axis(-1) + |> Nx.broadcast({batch_size, sequence_length, hidden_size}) + + Nx.select(mask, mask_tokens, embeddings) + end, + [embeddings, patch_mask, mask_token], + name: name, + op_name: :apply_patch_mask + ) + else + embeddings + end + end + + @doc """ + Splits the hidden dimension into the given number of attention heads. + + In other words, the input with shape `{batch_size, sequence_length, hidden_size}` + is reshaped to `{batch_size, sequence_length, num_heads, *}`. + """ + def split_heads(states, num_heads) do + Axon.nx(states, fn states -> + batch_size = Nx.axis_size(states, 0) + sequence_length = Nx.axis_size(states, 1) + new_shape = {batch_size, sequence_length, num_heads, :auto} + Nx.reshape(states, new_shape) + end) + end + + @doc """ + Splits the input node with shape `{batch_size, sequence_length, 2}` into + two nodes with shape `{batch_size, sequence_length}`. + """ + def split_pair(%Axon{} = x) do + left = Axon.nx(x, & &1[[.., .., 0]]) + right = Axon.nx(x, & &1[[.., .., 1]]) + {left, right} + end + + @doc """ + Adds a layer to the network which flattens the leading axes of the + input. + """ + def flatten_leading(%Axon{} = x) do + Axon.nx(x, fn x -> + shape = + x + |> Nx.shape() + |> Tuple.delete_at(0) + |> put_elem(0, :auto) + + Nx.reshape(x, shape) + end) + end + + @doc """ + Adds a layer to the network which flattens the trailing axes of the + input. + """ + def flatten_trailing(%Axon{} = x) do + Axon.nx(x, fn x -> + shape = Nx.shape(x) + rank = tuple_size(shape) + + shape = + shape + |> Tuple.delete_at(rank - 1) + |> put_elem(rank - 2, :auto) + + Nx.reshape(x, shape) + end) + end + + @doc """ + Adds a pixel rearrangement layer to the network. + + Rearranges elements in a tensor of shape `{*, H, W, C × r^2}` to a + tensor of shape `{*, H × r, W × r, C}`, where r is an upscale factor. + + This is useful for implementing efficient sub-pixel convolution + with a stride of `1 / r`. + + ## Options + + * `:name` - layer name + + """ + def pixel_shuffle(input, upscale_factor, opts \\ []) do + opts = Keyword.validate!(opts, [:name]) + + Axon.layer(&pixel_shuffle_impl/2, [input], + name: opts[:name], + op_name: :pixel_shuffle, + upscale_factor: upscale_factor + ) + end + + deftransformp pixel_shuffle_impl(input, opts \\ []) do + opts = Keyword.validate!(opts, [:upscale_factor, mode: :inference]) + upscale_factor = opts[:upscale_factor] + + {batch, [height, width, channels]} = + input + |> Nx.shape() + |> Tuple.to_list() + |> Enum.split(-3) + + out_height = height * upscale_factor + out_width = width * upscale_factor + out_channels = div(channels, upscale_factor * upscale_factor) + + x = + Nx.reshape( + input, + List.to_tuple(batch ++ [height, width, out_channels, upscale_factor, upscale_factor]) + ) + + {batch_axes, [height_axis, width_axis, out_channels_axis, upscale_axis1, upscale_axis2]} = + x + |> Nx.axes() + |> Enum.split(-5) + + x + |> Nx.transpose( + axes: + batch_axes ++ [height_axis, upscale_axis1, width_axis, upscale_axis2, out_channels_axis] + ) + |> Nx.reshape(List.to_tuple(batch ++ [out_height, out_width, out_channels])) + end + + @doc """ + Adds a layer that computes cosine similarity between the inputs. + """ + def cosine_similarity(x, y) do + Axon.layer(&cosine_similarity_impl/3, [x, y], op_names: :cosine_similarity) + end + + defnp cosine_similarity_impl(x, y, _opts \\ []) do + Bumblebee.Utils.Nx.cosine_similarity(x, y) + end + + @doc """ + Unwraps a tuple result from `Axon` node into separate nodes. + """ + def unwrap_tuple(%Axon{} = input, size) do + for i <- 0..(size - 1) do + Axon.nx(input, &elem(&1, i)) + end + |> List.to_tuple() + end + + @doc """ + Adds a default layer to handle optional nodes. + + This layer evaluates to the result of `x` if present, otherwise + falls back to the result of the default node. + + ## Examples + + input_ids = Axon.input("input_ids") + attention_mask = Axon.input("attention_mask", optional: true) + + attention_mask = + Bumblebee.Layers.default attention_mask do + Axon.nx(input_ids, &Nx.broadcast(1, &1)) + end + + """ + def default(%Axon{} = x, do: default) do + Axon.layer( + fn x, default, _ -> + case x do + %Axon.None{} -> default + _ -> x + end + end, + [Axon.optional(x), Axon.optional(default)], + op_name: :default + ) + end + + @doc """ + Adds a conditional layer. + + This layer evaluates to either branch, depending on whether the + optional `condition` value is present or missing. + + The branches can be either `Axon` nodes or `Nx.Container`s with + `Axon` nodes and the same structure. If containers are given, this + function also returns a matching container. + + ## Examples + + {hidden_state, cross_attention} = + Bumblebee.Layers.if_present encoder_hidden_state do + ... + {hidden_state, cross_attention} + else + {hidden_state, Bumblebee.Layers.none()} + end + + """ + def if_present(%Axon{} = condition, blocks) do + on_true = Keyword.fetch!(blocks, :do) + on_false = blocks[:else] + + case {on_true, on_false} do + {%Axon{}, %Axon{}} -> + if_present_layer(condition, on_true, on_false) + + {%Axon{}, nil} -> + if_present_layer(condition, on_true, none()) + + _ -> + on_false = on_false || Bumblebee.Utils.Axon.container_map(on_true, fn _ -> none() end) + + Bumblebee.Utils.Axon.container_zip_with(on_true, on_false, fn left, right -> + if_present_layer(condition, left, right) + end) + end + end + + defp if_present_layer(condition, on_true, on_false) do + Axon.layer( + fn condition, on_true, on_false, _ -> + case condition do + %Axon.None{} -> on_false + _ -> on_true + end + end, + [Axon.optional(condition), Axon.optional(on_true), Axon.optional(on_false)], + op_name: :if_present + ) + end + + @doc """ + Returns an Axon layer that resolves to `%Axon.None{}`. + """ + def none() do + Axon.layer(fn _opts -> %Axon.None{} end, [], op_name: :none) + end + + @doc """ + Adds a layer that passes the input through only if the given global + layer option is set. + """ + def global_opt_in(%Axon{} = input, global_option_name) do + Axon.layer( + fn input, opts -> + if opts[global_option_name] do + input + else + %Axon.None{} + end + end, + [input], + op_name: :global_opt_in, + global_options: [global_option_name] + ) + end + + @doc """ + Appends tuple element to the node result. + """ + def append(%Axon{} = tuple, %Axon{} = x) do + Axon.layer( + fn tuple, x, _ -> + Tuple.insert_at(tuple, tuple_size(tuple), x) + end, + [tuple, x], + op_name: :append + ) + end + + @doc """ + Replaces tuple element in the node result. + """ + def replace(%Axon{} = tuple, idx, %Axon{} = x) do + Axon.layer(fn tuple, x, _ -> tuple_replace(tuple, idx, x) end, [tuple, x], op_name: :replace) + end + + defp tuple_replace(tuple, index, value) when index < 0 do + tuple_replace(tuple, tuple_size(tuple) + index, value) + end + + defp tuple_replace(tuple, index, value) do + put_elem(tuple, index, value) + end + + @doc """ + Builds an `Axon` container with the given outputs. + + All values are wrapped with `Axon.optional/2`, so if any of them is + missing, it gets returned as `%Axon.None{}`. + + Also, guards known optional outputs behind a global layer option + using `global_opt_in/2`. + """ + @spec output(map()) :: Axon.t() + def output(outputs) do + outputs + |> Map.new(fn {key, %Axon{} = val} -> + {key, val |> maybe_opt_in_output(key) |> Axon.optional()} + end) + |> Axon.container() + end + + @opt_in_outputs %{ + :hidden_states => :output_hidden_states, + :attentions => :output_attentions + } + + defp maybe_opt_in_output(%Axon{} = input, key) do + if option_name = @opt_in_outputs[key] do + global_opt_in(input, option_name) + else + input + end + end + + @doc """ + Computes a 1-full mask matching the first two dimensions of `input` + (batch size and sequence length). + """ + def default_attention_mask(%Axon{} = input) do + Axon.nx(input, fn input -> + batch_size = Nx.axis_size(input, 0) + sequence_length = Nx.axis_size(input, 1) + Nx.broadcast(1, {batch_size, sequence_length}) + end) + end + + @doc """ + Computes increasing position ids matching the first two dimensions + of `input` (batch size and sequence length). + + ## Options + + * `:offset` - the index of the first position. Defaults to `0` + + """ + def default_position_ids(%Axon{} = input, opts \\ []) do + opts = Keyword.validate!(opts, offset: 0) + offset = opts[:offset] + + Axon.nx(input, fn input -> + batch_size = Nx.axis_size(input, 0) + sequence_length = Nx.axis_size(input, 1) + Nx.iota({batch_size, sequence_length}, axis: -1) |> Nx.add(offset) + end) + end + + @doc """ + Computes 0-full mask matching the first two dimensions of `input` + (batch size and sequence length). + """ + def default_token_type_ids(%Axon{} = input) do + Axon.nx(input, fn input -> + batch_size = Nx.axis_size(input, 0) + sequence_length = Nx.axis_size(input, 1) + Nx.broadcast(0, {batch_size, sequence_length}) + end) + end + + @doc """ + Computes 0-full bounding box for document-understanding models. + """ + def default_bounding_box(%Axon{} = input) do + Axon.nx(input, fn input -> + batch_size = Nx.axis_size(input, 0) + sequence_length = Nx.axis_size(input, 1) + Nx.broadcast(0, {batch_size, sequence_length, 4}) + end) + end + + @doc """ + Shifts the given input ids by removing the last token and prepending + the given start token. + + Some models use this technique to generate default decoder input ids. + """ + def shift_tokens_right(%Axon{} = input_ids, decoder_start_token_id) do + Axon.nx(input_ids, fn input_ids -> + batch_size = Nx.axis_size(input_ids, 0) + sequence_length = Nx.axis_size(input_ids, 1) + start_ids = Nx.broadcast(decoder_start_token_id, {batch_size, 1}) + + if sequence_length == 1 do + start_ids + else + Nx.concatenate([start_ids, input_ids[[.., 0..-2//1]]], axis: 1) + end + end) + end + + @doc """ + Returns a node with parameterized embeddings. + + ## Options + + * `:name` - layer name + + * `:initializer` - initializer for the embeddings. Defaults to + `:zeros` + + """ + def learned_embeddings(num_embeddings, embedding_size, opts \\ []) do + opts = Keyword.validate!(opts, [:name, initializer: :zeros]) + + name = opts[:name] + + embeddings = + Axon.param("embeddings", fn -> {num_embeddings, embedding_size} end, + initializer: opts[:initializer] + ) + + Axon.layer( + fn embeddings, _opts -> Nx.new_axis(embeddings, 0) end, + [embeddings], + name: name, + op_name: :learned_embeddings + ) + end + + @doc """ + Concatenates sequence embeddings, automatically broadcasting batch + dimension when necessary. + + ## Options + + * `:name` - layer name + + """ + def concatenate_embeddings(inputs, opts \\ []) do + opts = Keyword.validate!(opts, [:name]) + + name = opts[:name] + + Axon.layer( + fn inputs, _opts -> + inputs = Tuple.to_list(inputs) + + batch_size = + inputs + |> Enum.map(&Nx.axis_size(&1, 0)) + |> Enum.max() + + inputs = + Enum.map(inputs, fn input -> + new_shape = input |> Nx.shape() |> put_elem(0, batch_size) + Nx.broadcast(input, new_shape) + end) + + Nx.concatenate(inputs, axis: 1) + end, + [Axon.container(List.to_tuple(inputs))], + name: name, + op_name: :concatenate_embeddings + ) + end + + @doc """ + Adds an RMS Normalization layer to the network. + + ## Options + + * `:name` - layer name + + * `:initializer` - initializer for the standard deviation parameter. + Defaults to `:ones` + + * `:channel_index` - input feature index used for calculating + variance. Defaults to `-1` + + * `:epsilon` - numerical stability term + + * `:shift` - numeric shift in the scaling expression. Defaults to + `0.0` + + * `:upcast` - adds explicit type casting to make sure the norm + is computed in high numerical precision. Either of: + + * `:normalization` (default) - upcasts only the input normalization + part + + * `:all` - upcasts both input normalization and the scaling + expression + + """ + # TODO: Add to Axon + def rms_norm(input, opts \\ []) do + opts = + Keyword.validate!(opts, [ + :name, + shift: 0.0, + channel_index: -1, + epsilon: 1.0e-6, + upcast: :normalization, + initializer: :ones + ]) + + impl = + case opts[:upcast] do + :normalization -> + &rms_norm_impl_upcast_normalization/3 + + :all -> + &rms_norm_impl_upcast_all/3 + + other -> + raise ArgumentError, + "expected :upcast to be either :all or :normalization, got: #{other}" + end + + weight = + Axon.param("weight", &Axon.Shape.norm_param(&1, opts[:channel_index]), + initializer: opts[:initializer] + ) + + Axon.layer(impl, [input, weight], + name: opts[:name], + shift: opts[:shift], + epsilon: opts[:epsilon], + op_name: :rms_norm + ) + end + + defnp rms_norm_impl_upcast_normalization(input, weight, opts \\ []) do + opts = keyword!(opts, shift: 0.0, epsilon: 1.0e-6, channel_index: -1, mode: :train) + + normalized_input = + input + |> Nx.as_type(:f32) + |> rms_normalize(opts) + |> Nx.as_type(Nx.type(input)) + + normalized_input * (opts[:shift] + weight) + end + + defnp rms_norm_impl_upcast_all(input, weight, opts \\ []) do + opts = keyword!(opts, shift: 0.0, epsilon: 1.0e-6, channel_index: -1, mode: :train) + + input = Nx.as_type(input, :f32) + weight = Nx.as_type(weight, :f32) + + normalized_input = rms_normalize(input, opts) + + normalized_input * (opts[:shift] + weight) + end + + defnp rms_normalize(input, opts) do + variance = + input + |> Nx.pow(2) + |> Nx.mean(axes: [opts[:channel_index]], keep_axes: true) + + input * Nx.rsqrt(variance + opts[:epsilon]) + end + + @doc """ + Adds a rotary embedding layer to the network. + """ + def rotary_embedding(query, key, position_ids, attention_mask, size, opts \\ []) do + opts = Keyword.validate!(opts, [:name, :scaling_strategy, max_positions: 2048, base: 10_000]) + + output = + Axon.layer( + &apply_rotary_embedding/5, + [query, key, position_ids, Axon.optional(attention_mask)], + [size: size] ++ opts + ) + + unwrap_tuple(output, 2) + end + + deftransformp create_sinusoidal_positions( + sequence_length, + max_positions, + size, + base, + scaling_strategy + ) do + position = Nx.iota({sequence_length}) + + range = Nx.iota({div(size, 2)}) |> Nx.multiply(2) |> Nx.divide(size) + + case scaling_strategy do + %{type: :linear, factor: factor} -> + inv_frequency = inv_frequency(base, range) + position = Nx.divide(position, factor) + positions_cos_sin(position, inv_frequency) + + %{type: :dynamic, factor: factor} when sequence_length > max_positions -> + base = + base + |> Nx.multiply(factor * sequence_length / max_positions - (factor - 1)) + |> Nx.pow(size / (size - 2)) + + inv_frequency = inv_frequency(base, range) + positions_cos_sin(position, inv_frequency) + + %{ + type: :longrope, + short_factor: short_factor, + long_factor: long_factor, + original_max_positions: original_max_positions + } -> + factor = + if sequence_length > original_max_positions do + Nx.tensor(long_factor, type: :f32) + else + Nx.tensor(short_factor, type: :f32) + end + + scale = max_positions / original_max_positions + + cos_sin_factor = + if scale <= 1.0 do + 1.0 + else + Nx.divide(Nx.log(scale), Nx.log(original_max_positions)) + |> Nx.add(1) + |> Nx.sqrt() + end + + inv_frequency = inv_frequency(base, range) |> Nx.divide(factor) + {cos, sin} = positions_cos_sin(position, inv_frequency) + {Nx.multiply(cos, cos_sin_factor), Nx.multiply(sin, cos_sin_factor)} + + %{ + type: :llama3, + factor: factor, + low_frequency_factor: low_frequency_factor, + high_frequency_factor: high_frequency_factor, + original_max_positions: original_max_positions + } -> + inv_frequency = inv_frequency(base, range) + + inv_frequency = + llama3_inv_frequency( + inv_frequency, + factor, + low_frequency_factor, + high_frequency_factor, + original_max_positions + ) + + positions_cos_sin(position, inv_frequency) + + _other -> + inv_frequency = inv_frequency(base, range) + positions_cos_sin(position, inv_frequency) + end + end + + defnp llama3_inv_frequency( + inv_frequency, + factor, + low_frequency_factor, + high_frequency_factor, + original_max_positions + ) do + low_frequency_wavelength = original_max_positions / low_frequency_factor + high_frequency_wavelength = original_max_positions / high_frequency_factor + + # Vectorize to enable cleaner conditional + inv_frequency = Nx.vectorize(inv_frequency, :range) + + wavelength = 2 * Nx.Constants.pi() / inv_frequency + + inv_frequency = + cond do + wavelength < high_frequency_wavelength -> + inv_frequency + + wavelength > low_frequency_wavelength -> + inv_frequency / factor + + true -> + # Interpolation between the two cases above + + smooth_factor = + (original_max_positions / wavelength - low_frequency_factor) / + (high_frequency_factor - low_frequency_factor) + + (1 - smooth_factor) * inv_frequency / factor + smooth_factor * inv_frequency + end + + Nx.devectorize(inv_frequency) + end + + defnp inv_frequency(base, range) do + frequency = Nx.pow(base, range) + 1.0 / frequency + end + + defnp positions_cos_sin(position, inv_frequency) do + angle = Nx.outer(position, inv_frequency) + angle = Nx.concatenate([angle, angle], axis: -1) + {Nx.cos(angle), Nx.sin(angle)} + end + + defnp apply_rotary_embedding(query, key, position_ids, attention_mask, opts \\ []) do + opts = + keyword!(opts, [ + :size, + :scaling_strategy, + mode: :inference, + max_positions: 2048, + base: 10_000 + ]) + + # When decoding with cache position_ids may be a partial sequence, + # but in that case we always have full-length attention mask + sequence_length = + case attention_mask do + %Axon.None{} -> Nx.axis_size(position_ids, 1) + _other -> Nx.axis_size(attention_mask, 1) + end + + {cos, sin} = + create_sinusoidal_positions( + sequence_length, + opts[:max_positions], + opts[:size], + opts[:base], + opts[:scaling_strategy] + ) + + position_ids = Nx.as_type(position_ids, :s64) + + cos = cos |> Nx.take(position_ids) |> Nx.new_axis(2) |> Nx.as_type(Nx.type(query)) + sin = sin |> Nx.take(position_ids) |> Nx.new_axis(2) |> Nx.as_type(Nx.type(query)) + + rotated_query = query * cos + rotate_half(query) * sin + rotated_key = key * cos + rotate_half(key) * sin + + {rotated_query, rotated_key} + end + + defnp rotate_half(x) do + size = div(Nx.axis_size(x, -1), 2) + x1 = x[[.., .., .., 0..(size - 1)//1]] + x2 = x[[.., .., .., size..-1//1]] + Nx.concatenate([-x2, x1], axis: -1) + end + + @doc """ + Adds a repeat layer to the network. + + ## Options + + * `:name` - layer name + + * `:axis` - the axis to repeat along. Defaults to `-1` + + """ + def repeat_interleave(x, times, opts \\ []) do + opts = Keyword.validate!(opts, [:name, axis: -1]) + + Axon.layer( + fn x, opts -> + axis = Nx.axis_index(x, opts[:axis]) + Bumblebee.Utils.Nx.repeat_interleave(x, times, axis: axis) + end, + [x], + opts + ) + end +end diff --git a/deps/bumblebee/lib/bumblebee/layers/decoder.ex b/deps/bumblebee/lib/bumblebee/layers/decoder.ex new file mode 100644 index 0000000000000000000000000000000000000000..e08c7c0c5037a1d13dc4da77115d8b8607959eb0 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/layers/decoder.ex @@ -0,0 +1,246 @@ +defmodule Bumblebee.Layers.Decoder do + @moduledoc false + + import Nx.Defn + + alias Bumblebee.Layers + + @doc """ + Builds a fresh cache for iterative decoding. + + ## Caching + + Sequence generation involves iterative inference using the decoder + prat of the model. The inference is autoregressive, which means that + the decoder output token is appended to the input sequence for the + next iteration. Passing all tokens on every iteration is wasteful, + because certain hidden states are always the same for the same token, + so they would be unnecessarily recomputed on every subsequent iteration. + To reduce the complexity, we can feed a single input token at a time, + put those hidden states in a cache and use on subsequent iterations. + + For self-attention blocks, we cache the key and value state for the + input token and append them to the cache. + + For cross-attention blocks, we compute the whole key and value state + on the first iteration and reuse on subsequent ones. + + We also accumulate an attention mask corresponding to each token. + + In order to reuse compiled computation, we want the cache to keep + the same shape, so we initialize it for a fixed max length of the + decoder sequence. + + ## Options + + * `:hidden_size` - the dimensionality of the hidden layers + + * `:attention_head_size` - the size of the key, value, and query + projection per attention head + + * `:decoder_num_blocks` - the number of Transformer blocks in the decoder + + * `:decoder_num_attention_heads` - the number of decoder attention heads + + * `:encoder_num_attention_heads` - the number of encoder attention heads + (for cross attention) + + * `:encoder_sequence_length` - the encoder input sequence length + (for cross attention) + + """ + def init_cache(batch_size, max_length, opts \\ []) do + hidden_size = Keyword.fetch!(opts, :hidden_size) + decoder_num_attention_heads = Keyword.fetch!(opts, :decoder_num_attention_heads) + decoder_num_blocks = Keyword.fetch!(opts, :decoder_num_blocks) + encoder_num_attention_heads = opts[:encoder_num_attention_heads] + encoder_sequence_length = opts[:encoder_sequence_length] + + decoder_head_size = + opts[:attention_head_size] || div(hidden_size, decoder_num_attention_heads) + + self_attention = + attention_cache(batch_size, max_length, decoder_num_attention_heads, decoder_head_size) + + cross_attention = + if encoder_sequence_length do + encoder_head_size = + opts[:attention_head_size] || div(hidden_size, encoder_num_attention_heads) + + attention_cache( + batch_size, + encoder_sequence_length, + encoder_num_attention_heads, + encoder_head_size + ) + else + %Axon.None{} + end + + blocks = + %{self_attention: self_attention, cross_attention: cross_attention} + |> List.duplicate(decoder_num_blocks) + |> List.to_tuple() + + offset = Nx.tensor(0) + + attention_mask = Nx.broadcast(0, {batch_size, max_length}) + + %{blocks: blocks, offset: offset, attention_mask: attention_mask} + end + + defp attention_cache(batch_size, sequence_length, num_heads, head_size) do + shape = {batch_size, sequence_length, num_heads, head_size} + zeros = Nx.broadcast(0.0, shape) + %{key: zeros, value: zeros} + end + + @doc """ + Calls `fun` for every batched tensor in cache initialized with + `init_cache/3`. + """ + def traverse_cache(cache, fun) do + %{blocks: blocks, offset: offset, attention_mask: attention_mask} = cache + + %{ + blocks: Bumblebee.Utils.Nx.map(blocks, fun), + offset: offset, + attention_mask: fun.(attention_mask) + } + end + + @doc """ + Combines new attention mask with the one in cache. + + The function returns the full attention mask and the updated cache. + """ + def cached_attention_mask(attention_mask, cache) do + Layers.if_present cache do + Axon.layer( + fn attention_mask, cache, _ -> + indices = [0, Nx.as_type(cache.offset, {:s, 64})] + attention_mask = Nx.put_slice(cache.attention_mask, indices, attention_mask) + {attention_mask, %{cache | attention_mask: attention_mask}} + end, + [attention_mask, cache] + ) + |> Layers.unwrap_tuple(2) + else + {attention_mask, cache} + end + end + + @doc """ + Combines new key and value state with those in cache. + + The function returns the full key and value state and the updated + cache. + """ + def cached_attention_key_values(key, value, attention_cache, offset) do + Layers.if_present attention_cache do + Axon.layer(&update_attention_cache/5, [key, value, attention_cache, offset]) + |> Layers.unwrap_tuple(3) + else + {key, value, attention_cache} + end + end + + deftransformp update_attention_cache(key, value, attention_cache, offset, _opts \\ []) do + if Nx.shape(key) == Nx.shape(attention_cache.key) and + Nx.shape(value) == Nx.shape(attention_cache.value) do + # If the shapes are the same, it means the keys and values would + # be the same on every iteration, so we take cache all of them at + # at once (as in cross-attention) + replace_attention_cache(key, value, attention_cache, offset) + else + # Otherwise we compute keys and values incrementally, so we append + # to the cache (as in self-attention) + append_attention_cache(key, value, attention_cache, offset) + end + end + + defnp replace_attention_cache(key, value, attention_cache, offset, _opts \\ []) do + if offset == 0 do + attention_cache = %{attention_cache | key: key, value: value} + {key, value, attention_cache} + else + {attention_cache.key, attention_cache.value, attention_cache} + end + end + + defnp append_attention_cache(key, value, attention_cache, offset, _opts \\ []) do + %{key: cached_key, value: cached_value} = attention_cache + indices = [0, offset, 0, 0] + key = Nx.put_slice(cached_key, indices, key) + value = Nx.put_slice(cached_value, indices, value) + updated_cache = %{key: key, value: value} + {key, value, updated_cache} + end + + @doc """ + Retrieves cache for a specific decoder block. + """ + def get_block_cache(cache, block_idx) do + Axon.nx(cache, &elem(&1.blocks, block_idx)) + end + + @doc """ + Puts an updated cache entry for the given decoder block. + """ + def put_block_cache(cache, block_idx, block_cache) do + Axon.layer( + fn cache, block_cache, _opts -> + put_in(cache, [:blocks, Access.elem(block_idx)], block_cache) + end, + [cache, block_cache] + ) + end + + @doc """ + Retrieves self-attention and cross-attention caches from a block + cache. + """ + def get_attention_caches(block_cache) do + {Axon.nx(block_cache, & &1.self_attention), Axon.nx(block_cache, & &1.cross_attention)} + end + + @doc """ + Puts updated self-attention and cross-attention cache entries for + in the decoder block cache. + """ + def put_attention_caches(block_cache, self_attention_cache, cross_attention_cache) do + Axon.layer( + fn block_cache, self_attention_cache, cross_attention_cache, _opts -> + %{ + block_cache + | self_attention: self_attention_cache, + cross_attention: cross_attention_cache + } + end, + [block_cache, Axon.optional(self_attention_cache), Axon.optional(cross_attention_cache)] + ) + end + + @doc """ + Retrieves the cache offset. + + Cache offset keeps track of how many input tokens were processed + and are in the cache. + """ + def get_cache_offset(cache) do + Axon.nx(cache, & &1.offset) + end + + @doc """ + Bumps the cache offset by the number of tokens in `input_embeddings`. + """ + def update_cache_offset(cache, input_embeddings) do + Axon.layer( + fn cache, input_embeddings, _ -> + sequence_length = Nx.axis_size(input_embeddings, 1) + update_in(cache.offset, &Nx.add(&1, sequence_length)) + end, + [cache, input_embeddings] + ) + end +end diff --git a/deps/bumblebee/lib/bumblebee/layers/transformer.ex b/deps/bumblebee/lib/bumblebee/layers/transformer.ex new file mode 100644 index 0000000000000000000000000000000000000000..6cf93cd6e404cbf8a949c94c31f7c052dfccd924 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/layers/transformer.ex @@ -0,0 +1,893 @@ +defmodule Bumblebee.Layers.Transformer do + @moduledoc false + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @doc """ + Adds a list of transformer block to the network. + + Adds transformer blocks (see `block/2`), while also accumulating + caches and outputs. This is a convenience function, since this + chunk is oftentimes the same across transformer models. + + ## Options + + * `:num_blocks` (required) - the number of consecutive transformer + blocks to add + + * `:share_attention_relative_bias` - when attention relative bias + is configured, this option controls whether the bias from the + first block is used for all other blocks. Defaults to `false` + + * `:name` - the prefix for layer names + + For all other options (including required options) see `block/2`. + Note that `:attention_head_mask`, `:cross_attention_head_mask` should + have an additional leading axis corresponding to the number of blocks, + since each block gets its own mask. Similarly `:cache` is a tuple of + block caches. + """ + def blocks(hidden_state, opts) do + validate_required_keys!(opts, [:num_blocks, :num_attention_heads, :hidden_size, :ffn]) + + block_opts_keys = [ + :num_attention_heads, + :num_key_value_heads, + :causal, + :hidden_size, + :ffn, + :kernel_initializer, + :attention_head_size, + :dropout_rate, + :attention_dropout_rate, + :query_use_bias, + :key_use_bias, + :value_use_bias, + :output_use_bias, + :layer_norm, + :block_type, + :attention_window_size, + :scale_attention_weights, + :rotary_embedding + ] + + opts = + Keyword.validate!( + opts, + block_opts_keys ++ + [ + :name, + :num_blocks, + attention_mask: Layers.none(), + attention_head_mask: Layers.none(), + attention_relative_bias: nil, + share_attention_relative_bias: false, + cross_hidden_state: nil, + cross_attention_mask: Layers.none(), + cross_attention_head_mask: Layers.none(), + cache: Layers.none() + ] + ) + + name = opts[:name] + num_blocks = opts[:num_blocks] + + attention_mask = opts[:attention_mask] + attention_head_mask = opts[:attention_head_mask] + cross_hidden_state = opts[:cross_hidden_state] + cross_attention_mask = opts[:cross_attention_mask] + cross_attention_head_mask = opts[:cross_attention_head_mask] + cache = opts[:cache] + + block_opts = Keyword.take(opts, block_opts_keys) + + {attention_mask, cache} = Layers.Decoder.cached_attention_mask(attention_mask, cache) + offset = Layers.Decoder.get_cache_offset(cache) + + state = %{ + hidden_state: hidden_state, + hidden_states: Axon.container({hidden_state}), + attentions: Axon.container({}), + cross_attentions: Axon.container({}), + cache: cache, + attention_relative_bias: Layers.none() + } + + outputs = + for idx <- 0..(num_blocks - 1), reduce: state do + state -> + block_attention_head_mask = Axon.nx(attention_head_mask, & &1[idx]) + block_cross_attention_head_mask = Axon.nx(cross_attention_head_mask, & &1[idx]) + block_cache = Layers.Decoder.get_block_cache(state.cache, idx) + + attention_relative_bias = + if opts[:share_attention_relative_bias] and idx > 0 do + state.attention_relative_bias + else + opts[:attention_relative_bias] || Layers.none() + end + + {hidden_state, attention, cross_attention, block_cache, attention_relative_bias} = + block( + state.hidden_state, + [ + attention_mask: attention_mask, + attention_head_mask: block_attention_head_mask, + attention_relative_bias: attention_relative_bias, + cross_hidden_state: cross_hidden_state, + cross_attention_mask: cross_attention_mask, + cross_attention_head_mask: block_cross_attention_head_mask, + block_cache: block_cache, + offset: offset, + name: join(name, idx) + ] ++ block_opts + ) + + cache = Layers.Decoder.put_block_cache(state.cache, idx, block_cache) + + %{ + hidden_state: hidden_state, + hidden_states: Layers.append(state.hidden_states, hidden_state), + attentions: Layers.append(state.attentions, attention), + cross_attentions: Layers.append(state.cross_attentions, cross_attention), + attention_relative_bias: attention_relative_bias, + cache: cache + } + end + + update_in(outputs.cache, &Layers.Decoder.update_cache_offset(&1, hidden_state)) + end + + @doc """ + Adds a transformer block to the network + + Depending on the configuration, this can implement both the encoder + and the decoder block. + + A transformer block consists of self-attention, shortcut connection, + normalization and dropout layers. It may also include a cross-attention + block. + + ## Options + + * `:num_attention_heads` (required) - the number of attention heads + + * `:hidden_size` (required) - the dimensionality of the attention + block and the last layer in the output feed-forward network + + * `:ffn` (required) - configuration of the feed-forward network at + the end of the transformer block. By default the network has two + dense layers with an activation in-between and is configured with + the following options: + + * `:intermediate_size` (required) - the dimensionality of the + first dense layer + + * `:activation` - the activation used in-between the layers. + Defaults to `:gelu` + + Alternatively a custom 2-arity function may be given. The function + should add FFN nodes to the given Axon node. The function also + receives layer name prefix as the second argument. + + * `:attention_mask` - a mask indicating which positions to attend to + + * `:attention_head_mask` - a mask to nullify selected attention heads + + * `:attention_relative_bias` - configuration of relative bias. If set, + will apply relative attention bias with the given options. Valid + options are: + + * `:num_buckets` (required) - number of relative attention buckets + + * `:max_distance` (required) - maximum distance of the relative attention + bias + + * `:bidirectional` (required) - whether to apply the relative attention + bias bidirectionally + + Alternatively an `Axon` node may be given with the computed bias. + + * `:cross_hidden_state` - the second input for the the cross-attention + block. The cross-attention block is added only when this is specified. + Defaults to `nil` + + * `:cross_attention_mask` - a mask indicating which positions to + attend to in the cross-attention block + + * `:cross_attention_head_mask` - a mask to nullify selected attention + heads in the cross-attention block + + * `:block_cache` - cache for all attention blocks in this block, + used in iterative decoding + + * `:offset` - offset in the input sequence during iterative decoding + + * `:causal` - whether the self-attention block should be causal. + Defaults to `false` + + * `:kernel_initializer` - initializer for kernel weights. Defaults + to `:glorot_uniform` + + * `:attention_head_size` - the projection size for key, value, + and query states per-head. Defaults to `div(hidden_size, num_attention_heads)` + + * `:dropout_rate` - the dropout rate for dropout layers. Defaults + to `0.0` + + * `:attention_dropout_rate` - the dropout rate for attention weights + dropout. Defaults to `0.0` + + * `:query_use_bias` - whether to use bias in the query projection. + Defaults to `true` + + * `:key_use_bias` - whether to use bias in the key projection. + Defaults to `true` + + * `:value_use_bias` - whether to use bias in the value projection. + Defaults to `true` + + * `:output_use_bias` - whether to use bias in the output projection. + Defaults to `true` + + * `:layer_norm` - configuration of the layer norm operation + at the end of the transformer block. By default the network uses regular + layer normalization configured with the following options: + + * `:epsilon` - the epsilon used by the layer normalization + layers. Defaults to `1.0e-5` + + Alternatively a custom 2-arity function may be given. The function + should add a normalization node to the given Axon node. The function + also receives the layer name prefix as the second argument. + + * `:block_type` - controls which configuration of the block to use, + one of: + + * `:standard` (default) - the original transformer block + + * `:norm_first` - same as `:standard`, but with normalization layers + placed before each group of layers, rather than after + + * `:parallel` - block with attention and FFN independently (in parallel). + This type doesn't support cross-attention + + Alternatively a custom 3-arity function may be given. The function + receives the input hidden state, a map with block steps and a + name to prefix any additional layers. + + * `:attention_window_size` - when set, enables sliding window attention. + Should be a `{left, right}` tuple with window size on each side + + * `:scale_attention_weights` - whether to scale query in the traditional style of + multi-headed attention. Defaults to `true` + + * `:rotary_embedding` - configuration of rotary embedding. If set, + will apply rotary position embedding with the given options. Valid + options are: + + * `:position_ids` (required) - input position ids used for the + embedding + + * `:max_positions` - the maximum number of distinct positions + + * `:base` - base for computing rotary embedding frequency. Defaults + to `10_000`. + + * `:percentage` - percentage of hidden dimensions to allocate to rotary embeddings. + Defaults to `1.0`. + + * `:name` - the prefix for layer names + + ## References + + * [Attention Is All You Need](https://arxiv.org/abs/1706.03762), Figure 1 + + """ + def block(hidden_state, opts) do + validate_required_keys!(opts, [:num_attention_heads, :hidden_size, :ffn]) + + opts = + Keyword.validate!(opts, [ + :name, + :num_attention_heads, + :hidden_size, + :ffn, + :num_key_value_heads, + attention_mask: Layers.none(), + attention_head_mask: Layers.none(), + attention_relative_bias: Layers.none(), + cross_hidden_state: nil, + cross_attention_mask: Layers.none(), + cross_attention_head_mask: Layers.none(), + block_cache: Layers.none(), + offset: Layers.none(), + causal: false, + kernel_initializer: :glorot_uniform, + attention_head_size: nil, + dropout_rate: 0.0, + attention_dropout_rate: 0.0, + query_use_bias: true, + key_use_bias: true, + value_use_bias: true, + output_use_bias: true, + block_type: :standard, + layer_norm: [], + attention_window_size: nil, + scale_attention_weights: true, + rotary_embedding: nil + ]) + + name = opts[:name] + num_attention_heads = opts[:num_attention_heads] + num_key_value_heads = opts[:num_key_value_heads] || num_attention_heads + hidden_size = opts[:hidden_size] + ffn = opts[:ffn] + causal = opts[:causal] + kernel_initializer = opts[:kernel_initializer] + attention_head_size = opts[:attention_head_size] + dropout_rate = opts[:dropout_rate] + attention_dropout_rate = opts[:attention_dropout_rate] + query_use_bias = opts[:query_use_bias] + key_use_bias = opts[:key_use_bias] + value_use_bias = opts[:value_use_bias] + output_use_bias = opts[:output_use_bias] + attention_mask = opts[:attention_mask] + attention_head_mask = opts[:attention_head_mask] + attention_relative_bias = opts[:attention_relative_bias] + cross_hidden_state = opts[:cross_hidden_state] + cross_attention_mask = opts[:cross_attention_mask] + cross_attention_head_mask = opts[:cross_attention_head_mask] + block_cache = opts[:block_cache] + offset = opts[:offset] + layer_norm = opts[:layer_norm] + block_type = opts[:block_type] + attention_window_size = opts[:attention_window_size] + scale_attention_weights = opts[:scale_attention_weights] + rotary_embedding = opts[:rotary_embedding] + + ffn_fun = + case ffn do + opts when is_list(opts) -> + validate_required_keys!(opts, [:intermediate_size]) + opts = Keyword.validate!(opts, [:intermediate_size, activation: :gelu]) + + &basic_ffn(&1, opts[:intermediate_size], hidden_size, + activation: opts[:activation], + kernel_initializer: kernel_initializer, + dropout_rate: dropout_rate, + name: &2 + ) + + fun when is_function(fun) -> + fun + end + + layer_norm_fun = + case layer_norm do + opts when is_list(opts) -> + opts = Keyword.validate!(opts, epsilon: 1.0e-5) + + &Axon.layer_norm(&1, epsilon: opts[:epsilon], name: &2) + + fun when is_function(fun) -> + fun + end + + {self_attention_cache, cross_attention_cache} = + Layers.Decoder.get_attention_caches(block_cache) + + # Self-attention, shortcut connection, normalization and dropout + + self_attention_norm = &layer_norm_fun.(&1, join(name, "self_attention_norm")) + + self_attention = fn hidden_state -> + {hidden_state, attention, self_attention_cache, attention_relative_bias} = + multi_head_attention(hidden_state, hidden_state, hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + attention_relative_bias: attention_relative_bias, + attention_cache: self_attention_cache, + offset: offset, + causal: causal, + num_heads: num_attention_heads, + num_key_value_heads: num_key_value_heads, + hidden_size: hidden_size, + kernel_initializer: kernel_initializer, + attention_head_size: attention_head_size, + dropout_rate: attention_dropout_rate, + query_use_bias: query_use_bias, + key_use_bias: key_use_bias, + value_use_bias: value_use_bias, + output_use_bias: output_use_bias, + attention_window_size: attention_window_size, + scale_attention_weights: scale_attention_weights, + rotary_embedding: rotary_embedding, + name: join(name, "self_attention") + ) + + hidden_state = + Axon.dropout(hidden_state, rate: dropout_rate, name: join(name, "self_attention_dropout")) + + {hidden_state, {attention, self_attention_cache, attention_relative_bias}} + end + + # Cross-attention, shortcut connection, normalization and dropout + + cross_attention_maybe = fn hidden_state, fun -> + if cross_hidden_state do + Layers.if_present cross_hidden_state do + fun.(hidden_state) + else + {hidden_state, {Layers.none(), cross_attention_cache}} + end + else + {hidden_state, {Layers.none(), cross_attention_cache}} + end + end + + cross_attention_norm = &layer_norm_fun.(&1, join(name, "cross_attention_norm")) + + cross_attention = fn hidden_state -> + {hidden_state, cross_attention, cross_attention_cache, _cross_attention_relative_bias} = + multi_head_attention(hidden_state, cross_hidden_state, cross_hidden_state, + attention_mask: cross_attention_mask, + attention_head_mask: cross_attention_head_mask, + attention_cache: cross_attention_cache, + offset: offset, + num_heads: num_attention_heads, + num_key_value_heads: num_key_value_heads, + hidden_size: hidden_size, + kernel_initializer: kernel_initializer, + attention_head_size: attention_head_size, + dropout_rate: attention_dropout_rate, + query_use_bias: query_use_bias, + key_use_bias: key_use_bias, + value_use_bias: value_use_bias, + output_use_bias: output_use_bias, + attention_window_size: attention_window_size, + scale_attention_weights: scale_attention_weights, + rotary_embedding: rotary_embedding, + name: join(name, "cross_attention") + ) + + hidden_state = + Axon.dropout( + hidden_state, + rate: dropout_rate, + name: join(name, "cross_attention_dropout") + ) + + {hidden_state, {cross_attention, cross_attention_cache}} + end + + # Output feed-forward network, shortcut connection, normalization and dropout + + output_norm = &layer_norm_fun.(&1, join(name, "output_norm")) + + ffn = &ffn_fun.(&1, join(name, "ffn")) + + block_impl = + case block_type do + type when is_atom(type) -> &block_impl(type, &1, &2, &3) + fun when is_function(fun) -> fun + end + + {hidden_state, attention_info, cross_attention_info} = + block_impl.( + hidden_state, + %{ + self_attention_norm: self_attention_norm, + self_attention: self_attention, + cross_attention_maybe: cross_attention_maybe, + cross_attention_norm: cross_attention_norm, + cross_attention: cross_attention, + output_norm: output_norm, + ffn: ffn + }, + name + ) + + {attention, self_attention_cache, attention_relative_bias} = attention_info + {cross_attention, cross_attention_cache} = cross_attention_info + + block_cache = + Layers.Decoder.put_attention_caches( + block_cache, + self_attention_cache, + cross_attention_cache + ) + + {hidden_state, attention, cross_attention, block_cache, attention_relative_bias} + end + + defp block_impl(:standard, hidden_state, steps, _name) do + shortcut = hidden_state + + {hidden_state, attention_info} = steps.self_attention.(hidden_state) + + hidden_state = + hidden_state + |> Axon.add(shortcut) + |> steps.self_attention_norm.() + + {hidden_state, cross_attention_info} = + steps.cross_attention_maybe.(hidden_state, fn hidden_state -> + shortcut = hidden_state + + {hidden_state, cross_attention_info} = steps.cross_attention.(hidden_state) + + hidden_state = + hidden_state + |> Axon.add(shortcut) + |> steps.cross_attention_norm.() + + {hidden_state, cross_attention_info} + end) + + shortcut = hidden_state + + hidden_state = + hidden_state + |> steps.ffn.() + |> Axon.add(shortcut) + |> steps.output_norm.() + + {hidden_state, attention_info, cross_attention_info} + end + + defp block_impl(:norm_first, hidden_state, steps, _name) do + shortcut = hidden_state + + {hidden_state, attention_info} = + hidden_state + |> steps.self_attention_norm.() + |> steps.self_attention.() + + hidden_state = Axon.add(hidden_state, shortcut) + + {hidden_state, cross_attention_info} = + steps.cross_attention_maybe.(hidden_state, fn hidden_state -> + shortcut = hidden_state + + {hidden_state, cross_attention_info} = + hidden_state + |> steps.cross_attention_norm.() + |> steps.cross_attention.() + + hidden_state = Axon.add(hidden_state, shortcut) + + {hidden_state, cross_attention_info} + end) + + shortcut = hidden_state + + hidden_state = + hidden_state + |> steps.output_norm.() + |> steps.ffn.() + |> Axon.add(shortcut) + + {hidden_state, attention_info, cross_attention_info} + end + + defp block_impl(:parallel, hidden_state, steps, _name) do + shortcut = hidden_state + + {attention_hidden_state, attention_info} = + hidden_state + |> steps.self_attention_norm.() + |> steps.self_attention.() + + {_hidden_state, cross_attention_info} = + steps.cross_attention_maybe.(hidden_state, fn _hidden_state -> + raise "cross attention not supported" + end) + + ffn_hidden_state = + hidden_state + |> steps.output_norm.() + |> steps.ffn.() + + hidden_state = Axon.add([shortcut, attention_hidden_state, ffn_hidden_state]) + + {hidden_state, attention_info, cross_attention_info} + end + + defp basic_ffn(x, intermediate_size, output_size, opts) do + name = opts[:name] + + x + |> Axon.dense(intermediate_size, + kernel_initializer: opts[:kernel_initializer], + name: join(name, "intermediate") + ) + |> Layers.activation(opts[:activation]) + |> Axon.dense(output_size, + kernel_initializer: opts[:kernel_initializer], + name: join(name, "output") + ) + |> Axon.dropout(rate: opts[:dropout_rate]) + end + + @doc """ + Adds a multi-head attention block to the network. + + When `query`, `key` and `value` are the same, this is self-attention. + When `query` comes from the decoder, while `key` and `value` come from + the encoder, this is cross-attention. + + Returns the tuple `{attention_output, attention_weights, attention_cache}`. + + ## Options + + * `:num_heads` (required) - the number of attention heads + + * `:hidden_size` (required) - the dimensionality of query/key/value + projections + + * `:attention_mask` - a mask indicating which positions to attend to + + * `:attention_head_mask` - a mask to nullify selected attention heads + + * `:attention_relative_bias` - configuration of relative bias. If set, + will apply relative attention bias with the given options. Valid + options are: + + * `:num_buckets` (required) - number of relative attention buckets + + * `:max_distance` (required) - maximum distance of the relative attention + bias + + * `:bidirectional` (required) - whether to apply the relative attention + bias bidirectionally + + Alternatively an `Axon` node may be given with the computed bias. + + * `:attention_cache` - cache with accumulated key/values useful for + iterative decoding + + * `:offset` - offset in the input sequence during iterative decoding + + * `:causal` - whether to apply causal attention mask, so that tokens + are attended to only in a single direction. Defaults to `false` + + * `:kernel_initializer` - initializer for kernel weights. Defaults + to `:glorot_uniform` + + * `:dropout_rate` - the dropout rate for attention weights dropout. + Defaults to `0.0` + + * `:attention_head_size` - the projection size for key, value, + and query states per-head. Defaults to `div(hidden_size, num_attention_heads)` + + * `:query_use_bias` - whether to use bias in the query projection. + Defaults to `true` + + * `:key_use_bias` - whether to use bias in the key projection. + Defaults to `true` + + * `:value_use_bias` - whether to use bias in the value projection. + Defaults to `true` + + * `:output_use_bias` - whether to use bias in the output projection. + Defaults to `true` + + * `:attention_window_size` - when set, enables sliding window attention. + Should be a `{left, right}` tuple with window size on each side + + * `:scale_attention_weights` - whether to scale query in the traditional style of + multi-headed attention. Defaults to `true` + + * `:rotary_embedding` - configuration of rotary embedding. If set, + will apply rotary position embedding with the given options. Valid + options are: + + * `:position_ids` (required) - input position ids used for the + embedding + + * `:max_positions` - the maximum number of distinct positions + + * `:name` - the prefix for layer names + + ## References + + * [Attention Is All You Need](https://arxiv.org/abs/1706.03762), Figure 2 (right) + + """ + def multi_head_attention(query, key, value, opts) do + validate_required_keys!(opts, [:num_heads, :hidden_size]) + + opts = + Keyword.validate!(opts, [ + :name, + :num_heads, + :hidden_size, + :num_key_value_heads, + attention_mask: Layers.none(), + attention_head_mask: Layers.none(), + attention_relative_bias: Layers.none(), + attention_cache: Layers.none(), + offset: Layers.none(), + causal: false, + attention_window_size: nil, + scale_attention_weights: true, + kernel_initializer: :glorot_uniform, + dropout_rate: 0.0, + attention_head_size: nil, + query_use_bias: true, + key_use_bias: true, + value_use_bias: true, + output_use_bias: true, + rotary_embedding: nil + ]) + + attention_mask = opts[:attention_mask] + attention_head_mask = opts[:attention_head_mask] + attention_cache = opts[:attention_cache] + offset = opts[:offset] + + name = opts[:name] + num_heads = opts[:num_heads] + num_key_value_heads = opts[:num_key_value_heads] || num_heads + hidden_size = opts[:hidden_size] + kernel_initializer = opts[:kernel_initializer] + causal = opts[:causal] + attention_window_size = opts[:attention_window_size] + scale_attention_weights = opts[:scale_attention_weights] + dropout_rate = opts[:dropout_rate] + rotary_embedding = opts[:rotary_embedding] + + query_use_bias = opts[:query_use_bias] + key_use_bias = opts[:key_use_bias] + value_use_bias = opts[:value_use_bias] + output_use_bias = opts[:output_use_bias] + + attention_relative_bias = opts[:attention_relative_bias] + + attention_head_size = opts[:attention_head_size] || div(hidden_size, num_heads) + inner_size = num_heads * attention_head_size + inner_kv_size = num_key_value_heads * attention_head_size + + query = + query + |> Axon.dense(inner_size, + kernel_initializer: kernel_initializer, + name: join(name, "query"), + use_bias: query_use_bias + ) + |> Layers.split_heads(num_heads) + + key = + key + |> Axon.dense(inner_kv_size, + kernel_initializer: kernel_initializer, + name: join(name, "key"), + use_bias: key_use_bias + ) + |> Layers.split_heads(num_key_value_heads) + + value = + value + |> Axon.dense(inner_kv_size, + kernel_initializer: kernel_initializer, + name: join(name, "value"), + use_bias: value_use_bias + ) + |> Layers.split_heads(num_key_value_heads) + + {query, key} = + case rotary_embedding do + opts when is_list(opts) -> + validate_required_keys!(opts, [:position_ids]) + + opts = + Keyword.validate!(opts, [ + :position_ids, + :max_positions, + :scaling_strategy, + base: 10_000, + percentage: 1.0 + ]) + + {position_ids, opts} = Keyword.pop(opts, :position_ids) + {percentage, opts} = Keyword.pop(opts, :percentage) + + size = trunc(attention_head_size * percentage) + + rotary_opts = [name: join(name, "rotary_embedding")] ++ opts + + if size == attention_head_size do + Layers.rotary_embedding(query, key, position_ids, attention_mask, size, rotary_opts) + else + query_rotary = Axon.nx(query, & &1[[.., .., .., 0..(size - 1)//1]]) + query_pass = Axon.nx(query, & &1[[.., .., .., size..-1//1]]) + + key_rotary = Axon.nx(key, & &1[[.., .., .., 0..(size - 1)//1]]) + key_pass = Axon.nx(key, & &1[[.., .., .., size..-1//1]]) + + {query_rotary, key_rotary} = + Layers.rotary_embedding( + query_rotary, + key_rotary, + position_ids, + attention_mask, + size, + rotary_opts + ) + + {Axon.concatenate([query_rotary, query_pass], axis: -1), + Axon.concatenate([key_rotary, key_pass], axis: -1)} + end + + nil -> + {query, key} + end + + num_key_value_groups = div(num_heads, num_key_value_heads) + key = repeat_states(key, num_key_value_groups) + value = repeat_states(value, num_key_value_groups) + + {key, value, attention_cache} = + Layers.Decoder.cached_attention_key_values(key, value, attention_cache, offset) + + attention_relative_bias = + case attention_relative_bias do + %Axon{} -> + attention_relative_bias + + bias_opts when is_list(bias_opts) -> + validate_required_keys!(bias_opts, [:num_buckets, :max_distance, :bidirectional]) + bias_opts = Keyword.validate!(bias_opts, [:num_buckets, :max_distance, :bidirectional]) + + Layers.relative_attention_bias(query, key, attention_cache, offset, + num_buckets: bias_opts[:num_buckets], + max_distance: bias_opts[:max_distance], + bidirectional: bias_opts[:bidirectional], + num_heads: num_heads, + name: join(name, "relative_attention_bias") + ) + end + + {attention_output, attention_weights} = + Layers.attention( + query, + key, + value, + attention_mask, + attention_head_mask, + attention_relative_bias, + offset, + scale: scale_attention_weights, + causal: causal, + window_size: attention_window_size, + dropout_rate: dropout_rate + ) + + attention_output = + attention_output + |> Layers.flatten_trailing() + |> Axon.dense(hidden_size, + kernel_initializer: kernel_initializer, + name: join(name, "output"), + use_bias: output_use_bias + ) + + {attention_output, attention_weights, attention_cache, attention_relative_bias} + end + + defp repeat_states(state, 1), do: state + + defp repeat_states(state, times) do + Layers.repeat_interleave(state, times, axis: 2) + end + + defp validate_required_keys!(opts, keys) do + case keys -- Keyword.keys(opts) do + [] -> :ok + missing -> raise ArgumentError, "missing required options: #{inspect(missing)}" + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/model_spec.ex b/deps/bumblebee/lib/bumblebee/model_spec.ex new file mode 100644 index 0000000000000000000000000000000000000000..681dcf7b46732fdc12857d72a791a82863499d38 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/model_spec.ex @@ -0,0 +1,28 @@ +defmodule Bumblebee.ModelSpec do + @moduledoc """ + An interface for configuring and building models based on the same + architecture. + + Every module implementing this behaviour is expected to also define + a configuration struct. + """ + + @type t :: Bumblebee.Configurable.t() + + @doc """ + Returns the list of supported model architectures. + """ + @callback architectures :: list(atom()) + + @doc """ + Builds a template input for the model. + + The template is used to compile the model when initializing parameters. + """ + @callback input_template(t()) :: map() + + @doc """ + Builds an `Axon` model according to the given configuration. + """ + @callback model(t()) :: Axon.t() +end diff --git a/deps/bumblebee/lib/bumblebee/multimodal/blip.ex b/deps/bumblebee/lib/bumblebee/multimodal/blip.ex new file mode 100644 index 0000000000000000000000000000000000000000..26a523c45225813c1e6c9fa9cee43837bad6d6b1 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/multimodal/blip.ex @@ -0,0 +1,256 @@ +defmodule Bumblebee.Multimodal.Blip do + alias Bumblebee.Shared + + options = + [ + text_spec: [ + default: nil, + doc: "the specification of the text model. See `Bumblebee.Text.BlipText` for details" + ], + vision_spec: [ + default: nil, + doc: + "the specification of the vision model. See `Bumblebee.Vision.BlipVision` for details" + ], + projection_size: [ + default: 512, + doc: "the dimensionality of text and vision projection layers" + ], + logit_scale_initial_value: [ + default: 2.6592, + doc: "the initial value for the scaling layer used to scale similarity logits" + ] + ] + + @moduledoc """ + The BLIP model for text-image similarity. + + ## Architectures + + * `:for_conditional_generation` - BLIP model with a language + modeling head + + ## Inputs + + * `"pixel_values"` - `{batch_size, image_size, image_size, num_channels}` + + Featurized image pixel values. + + * `"decoder_input_ids"` - `{batch_size, target_sequence_length}` + + Indices of decoder input sequence tokens in the vocabulary. If not + present and `"input_ids"` is, it will be generated by shifting + each token in `"input_ids"` to the right once. + + * `"decoder_attention_mask"` - `{batch_size, target_sequence_length}` + + Mask indicating which decoder tokens to attend to. This is used + to ignore padding tokens, which are added when processing a batch + of sequences with different length. + + * `"decoder_position_ids"` - `{batch_size, target_sequence_length}` + + Indices of positions of each decoder input sequence tokens in + the position embeddings. + + * `"encoder_hidden_state"` - `{batch_size, sequence_length, hidden_size}` + + Last hidden state output from the encoder. This hidden state is + used in cross-attention blocks in the decoder. If specified, the + model will skip the image encoding process and use this value + directly for cross-attentions in the text decoder. + + * `"cache"` + + A container with cached layer results used to speed up sequential + decoding (autoregression). With cache, certain hidden states are + taken from the cache, rather than recomputed on every decoding + pass. The cache should be treated as opaque and initialized with + `Bumblebee.Text.Generation.init_cache/4`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + + ## References + + * [BLIP: Bootstrapping Language-Image Pre-training for Unified Vision-Language Understanding and Generation](https://arxiv.org/abs/2201.12086) + + """ + + defstruct [architecture: :for_conditional_generation] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + alias Bumblebee.Layers + + @impl true + def architectures(), do: [:for_conditional_generation] + + @impl true + def config(spec, opts) do + Shared.put_config_attrs(spec, opts) + end + + @impl true + def input_template(%{vision_spec: vision_spec}) do + vision_shape = {1, vision_spec.image_size, vision_spec.image_size, vision_spec.num_channels} + + %{ + "pixel_values" => Nx.template(vision_shape, :f32), + "decoder_input_ids" => Nx.template({1, 1}, :u32) + } + end + + @impl true + def model(%__MODULE__{architecture: :for_conditional_generation} = spec) do + %{vision_spec: vision_spec, text_spec: text_spec} = spec + + vision_shape = {nil, vision_spec.image_size, vision_spec.image_size, vision_spec.num_channels} + text_shape = {nil, nil} + vision_hidden_shape = {nil, nil, vision_spec.hidden_size} + + inputs = + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("pixel_values", shape: vision_shape), + Axon.input("decoder_input_ids", optional: true, shape: text_shape), + Axon.input("decoder_attention_mask", optional: true, shape: text_shape), + Axon.input("decoder_position_ids", optional: true, shape: text_shape), + Axon.input("encoder_hidden_state", optional: true, shape: vision_hidden_shape), + Axon.input("cache", optional: true) + ]) + + vision_model = + vision_spec + |> Bumblebee.build_model() + |> Bumblebee.Utils.Axon.prefix_names("vision_model.") + |> Bumblebee.Utils.Axon.plug_inputs(%{ + "pixel_values" => inputs["pixel_values"] + }) + + vision_model_outputs = + Layers.if_present inputs["encoder_hidden_state"] do + %{ + hidden_state: inputs["encoder_hidden_state"], + hidden_states: Layers.none(), + attentions: Layers.none() + } + else + %{ + hidden_state: Axon.nx(vision_model, & &1.hidden_state), + hidden_states: Axon.nx(vision_model, & &1.hidden_states), + attentions: Axon.nx(vision_model, & &1.attentions) + } + end + + text_decoder = + text_spec + |> Bumblebee.build_model() + |> Bumblebee.Utils.Axon.prefix_names("text_decoder.") + |> Bumblebee.Utils.Axon.plug_inputs(%{ + "input_ids" => inputs["decoder_input_ids"], + "attention_mask" => inputs["decoder_attention_mask"], + "position_ids" => inputs["decoder_position_ids"], + "encoder_hidden_state" => vision_model_outputs.hidden_state, + "cache" => inputs["cache"] + }) + + Layers.output(%{ + logits: Axon.nx(text_decoder, & &1.logits), + decoder_hidden_states: Axon.nx(text_decoder, & &1.hidden_states), + decoder_attentions: Axon.nx(text_decoder, & &1.attentions), + cross_attentions: Axon.nx(text_decoder, & &1.cross_attentions), + encoder_hidden_state: vision_model_outputs.hidden_state, + encoder_hidden_states: vision_model_outputs.hidden_states, + encoder_attentions: vision_model_outputs.attentions, + cache: Axon.nx(text_decoder, & &1.cache) + }) + end + + @impl true + def init_cache( + %{vision_spec: vision_spec, text_spec: text_spec}, + batch_size, + max_length, + inputs + ) do + num_patches = div(vision_spec.image_size, vision_spec.patch_size) ** 2 + encoder_sequence_length = num_patches + 1 + encoder_shape = {batch_size, encoder_sequence_length, text_spec.hidden_size} + + inputs = + %{ + "input_ids" => inputs["decoder_input_ids"], + "attention_mask" => inputs["decoder_attention_mask"], + "position_ids" => inputs["decoder_position_ids"], + "encoder_hidden_state" => Nx.template(encoder_shape, :f32) + } + |> Map.reject(&match?({_, nil}, &1)) + + text_spec.__struct__.init_cache(text_spec, batch_size, max_length, inputs) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + {text_data, data} = Map.pop(data, "text_config", %{}) + {vision_data, data} = Map.pop(data, "vision_config", %{}) + + text_spec = + Bumblebee.Text.BlipText + |> Bumblebee.configure(architecture: :for_causal_language_modeling) + |> Bumblebee.HuggingFace.Transformers.Config.load(text_data) + + vision_spec = + Bumblebee.Vision.BlipVision + |> Bumblebee.configure() + |> Bumblebee.HuggingFace.Transformers.Config.load(vision_data) + + opts = + convert!(data, + projection_size: {"projection_dim", number()}, + logit_scale_initial_value: {"logit_scale_init_value", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts ++ [text_spec: text_spec, vision_spec: vision_spec]) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + alias Bumblebee.HuggingFace.Transformers + + def params_mapping(spec) do + text_mapping = + spec.text_spec + |> Transformers.Model.params_mapping() + |> Transformers.Utils.prefix_params_mapping("text_decoder", nil) + + vision_mapping = + spec.vision_spec + |> Transformers.Model.params_mapping() + |> Transformers.Utils.prefix_params_mapping("vision_model", nil) + + %{ + "text_projection" => "text_projection", + "visual_projection" => "visual_projection", + "scale" => %{ + "scale" => {[{"scale", "logit_scale"}], fn [scale] -> scale end} + } + } + |> Map.merge(text_mapping) + |> Map.merge(vision_mapping) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/multimodal/clip.ex b/deps/bumblebee/lib/bumblebee/multimodal/clip.ex new file mode 100644 index 0000000000000000000000000000000000000000..29b18939f7806ac81329ccc09f51aef460e9cfa6 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/multimodal/clip.ex @@ -0,0 +1,225 @@ +defmodule Bumblebee.Multimodal.Clip do + alias Bumblebee.Shared + + options = + [ + text_spec: [ + default: nil, + doc: "the specification of the text model. See `Bumblebee.Text.ClipText` for details" + ], + vision_spec: [ + default: nil, + doc: + "the specification of the vision model. See `Bumblebee.Vision.ClipVision` for details" + ], + projection_size: [ + default: 512, + doc: "the dimensionality of text and vision projection layers" + ], + logit_scale_initial_value: [ + default: 2.6592, + doc: "the initial value for the scaling layer used to scale similarity logits" + ] + ] + + @moduledoc """ + The CLIP model for text-image similarity. + + ## Architectures + + * `:base` - the base CLIP model + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"pixel_values"` - `{batch_size, image_size, image_size, num_channels}` + + Featurized image pixel values. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + + ## References + + * [CLIP: Connecting Text and Images](https://openai.com/blog/clip) + + * [Learning Transferable Visual Models From Natural Language Supervision](https://arxiv.org/abs/2103.00020) + + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + alias Bumblebee.Layers + + @impl true + def architectures(), do: [:base] + + @impl true + def config(spec, opts) do + Shared.put_config_attrs(spec, opts) + end + + @impl true + def input_template(%{vision_spec: vision_spec}) do + vision_shape = {1, vision_spec.image_size, vision_spec.image_size, vision_spec.num_channels} + + %{ + "input_ids" => Nx.template({1, 1}, :u32), + "pixel_values" => Nx.template(vision_shape, :f32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + %{text_spec: text_spec, vision_spec: vision_spec} = spec + + text_shape = {nil, nil} + vision_shape = {nil, vision_spec.image_size, vision_spec.image_size, vision_spec.num_channels} + + inputs = + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", shape: text_shape), + Axon.input("attention_mask", optional: true, shape: text_shape), + Axon.input("position_ids", optional: true, shape: text_shape), + Axon.input("pixel_values", shape: vision_shape) + ]) + + text_model = + text_spec + |> Bumblebee.build_model() + |> Bumblebee.Utils.Axon.prefix_names("text_model.") + |> Bumblebee.Utils.Axon.plug_inputs(%{ + "input_ids" => inputs["input_ids"], + "attention_mask" => inputs["attention_mask"], + "position_ids" => inputs["position_ids"] + }) + + vision_model = + vision_spec + |> Bumblebee.build_model() + |> Bumblebee.Utils.Axon.prefix_names("vision_model.") + |> Bumblebee.Utils.Axon.plug_inputs(%{ + "pixel_values" => inputs["pixel_values"] + }) + + text_embedding = + text_model + |> Axon.nx(& &1.pooled_state) + |> Axon.dense(spec.projection_size, use_bias: false, name: "text_projection") + + image_embedding = + vision_model + |> Axon.nx(& &1.pooled_state) + |> Axon.dense(spec.projection_size, use_bias: false, name: "visual_projection") + + logits_per_text = + text_embedding + |> Layers.cosine_similarity(image_embedding) + |> exp_scale( + name: "scale", + scale_initializer: Axon.Initializers.full(spec.logit_scale_initial_value) + ) + + logits_per_image = Axon.transpose(logits_per_text) + + Layers.output(%{ + logits_per_text: logits_per_text, + logits_per_image: logits_per_image, + text_embedding: text_embedding, + image_embedding: image_embedding + }) + end + + defp exp_scale(input, opts) do + opts = Keyword.validate!(opts, [:name, scale_initializer: Axon.Initializers.full(1.0e-6)]) + + name = opts[:name] + scale_initializer = opts[:scale_initializer] + + scale_param = Axon.param("scale", fn _ -> {} end, initializer: scale_initializer) + + Axon.layer( + fn input, scale, _opts -> + Nx.multiply(input, Nx.exp(scale)) + end, + [input, scale_param], + name: name, + op_name: :exp_scale + ) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + {text_data, data} = Map.pop(data, "text_config", %{}) + {vision_data, data} = Map.pop(data, "vision_config", %{}) + + text_spec = + Bumblebee.Text.ClipText + |> Bumblebee.configure() + |> Bumblebee.HuggingFace.Transformers.Config.load(text_data) + + vision_spec = + Bumblebee.Vision.ClipVision + |> Bumblebee.configure() + |> Bumblebee.HuggingFace.Transformers.Config.load(vision_data) + + opts = + convert!(data, + projection_size: {"projection_dim", number()}, + logit_scale_initial_value: {"logit_scale_init_value", number()} + ) + + @for.config(spec, opts ++ [text_spec: text_spec, vision_spec: vision_spec]) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + alias Bumblebee.HuggingFace.Transformers + + def params_mapping(spec) do + text_mapping = + spec.text_spec + |> Transformers.Model.params_mapping() + |> Transformers.Utils.prefix_params_mapping("text_model", nil) + + vision_mapping = + spec.vision_spec + |> Transformers.Model.params_mapping() + |> Transformers.Utils.prefix_params_mapping("vision_model", nil) + + %{ + "text_projection" => "text_projection", + "visual_projection" => "visual_projection", + "scale" => %{ + "scale" => {[{"scale", "logit_scale"}], fn [scale] -> scale end} + } + } + |> Map.merge(text_mapping) + |> Map.merge(vision_mapping) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/multimodal/layout_lm.ex b/deps/bumblebee/lib/bumblebee/multimodal/layout_lm.ex new file mode 100644 index 0000000000000000000000000000000000000000..9c44854bb1ba9b004d61afaa5901dd6c80bf0a00 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/multimodal/layout_lm.ex @@ -0,0 +1,543 @@ +defmodule Bumblebee.Multimodal.LayoutLm do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 30522, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 1024, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + max_spatial_positions: [ + default: 1024, + doc: """ + the maximum value of the spatial position embedding. Typically this is set to a large value + just in case, such as 512, 1024, or 2048 + """ + ], + max_token_types: [ + default: 2, + doc: """ + the vocabulary size of the token type embedding (also referred to as segment embedding). + This corresponds to how many different token groups can be distinguished in the input + """ + ], + hidden_size: [ + default: 768, + doc: "the dimensionality of hidden layers" + ], + num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the encoder" + ], + num_attention_heads: [ + default: 12, + doc: "the number of attention heads for each attention layer in the decoder" + ], + intermediate_size: [ + default: 3072, + doc: """ + the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the decoder. + If not specified, defaults to 4 times `:hidden_size` + """ + ], + activation: [ + default: :gelu, + doc: "the activation function" + ], + dropout_rate: [ + default: 0.1, + doc: "the dropout rate for embedding and encoder" + ], + attention_dropout_rate: [ + default: 0.1, + doc: "the dropout rate for attention weights" + ], + classifier_dropout_rate: [ + default: nil, + doc: + "the dropout rate for the classification head. If not specified, the value of `:dropout_rate` is used instead" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ], + layer_norm_epsilon: [ + default: 1.0e-12, + doc: "the epsilon used by the layer normalization layers" + ] + ] ++ Shared.common_options([:num_labels, :id_to_label]) + + @moduledoc """ + LayoutLM Model family. + + ## Architectures + + * `:base` - plain LayoutLM without any head on top + + * `:for_masked_language_modeling` - LayoutLM with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_sequence_classification` - LayoutLM with a sequence + classification head. The head returns logits corresponding to + possible classes + + * `:for_token_classification` - LayoutLM with a token classification + head. The head returns logits for each token in the original + sequence + + * `:for_question_answering` - LayoutLM with a span classification head. + The head returns logits for the span start and end positions + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"token_type_ids"` - `{batch_size, sequence_length}` + + Mask distinguishing groups in the input sequence. This is used + in when the input sequence is a semantically a pair of sequences. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{num_blocks, num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + * `"bounding_box"` - `{batch_size, sequence_length, 4}` + + Bounding boxes of each input sequence token. Each bounding box is + `{x0, y0, x1, y1}` where `{x0, y0}` is the upper left corner and + `{x1, y1}` is the lower right corner. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + + ## References + + * [LayoutLM: LayoutLM: Pre-training of Text and Layout for Document Image Understanding](https://arxiv.org/abs/1912.13318) + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_masked_language_modeling, + :for_sequence_classification, + :for_token_classification, + :for_question_answering + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(%{architecture: :for_multiple_choice}) do + %{"input_ids" => Nx.template({1, 1, 1}, :u32)} + end + + def input_template(_spec) do + %{"input_ids" => Nx.template({1, 1}, :u32)} + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_masked_language_modeling} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_sequence_classification} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + outputs.pooled_state + |> Axon.dropout( + rate: classifier_dropout_rate(spec), + name: "sequence_classification_head.dropout" + ) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "sequence_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_token_classification} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + outputs.hidden_state + |> Axon.dropout( + rate: classifier_dropout_rate(spec), + name: "token_classification_head.dropout" + ) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "token_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_question_answering} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + Axon.dense(outputs.hidden_state, 2, + kernel_initializer: kernel_initializer(spec), + name: "question_answering_head.output" + ) + + {start_logits, end_logits} = Layers.split_pair(logits) + + Layers.output(%{ + start_logits: start_logits, + end_logits: end_logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + defp inputs(spec, opts \\ []) do + shape = Keyword.get(opts, :shape, {nil, nil}) + + attention_head_mask_shape = {spec.num_blocks, spec.num_attention_heads} + bounding_box_shape = Tuple.insert_at(shape, tuple_size(shape), 4) + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", shape: shape), + Axon.input("bounding_box", optional: true, shape: bounding_box_shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("token_type_ids", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: attention_head_mask_shape) + ]) + end + + defp core(inputs, spec) do + embeddings = + embedder( + inputs["input_ids"], + inputs["bounding_box"], + inputs["position_ids"], + inputs["token_type_ids"], + spec, + name: "embedder" + ) + + encoder_outputs = + encoder(embeddings, inputs["attention_mask"], inputs["attention_head_mask"], spec, + name: "encoder" + ) + + pooled_state = pooler(encoder_outputs.hidden_state, spec, name: "pooler") + + %{ + hidden_state: encoder_outputs.hidden_state, + pooled_state: pooled_state, + hidden_states: encoder_outputs.hidden_states, + attentions: encoder_outputs.attentions + } + end + + defp embedder(input_ids, bounding_box, position_ids, token_type_ids, spec, opts) do + name = opts[:name] + + bounding_box = + Layers.default bounding_box do + Layers.default_bounding_box(input_ids) + end + + position_ids = + Layers.default position_ids do + Layers.default_position_ids(input_ids) + end + + token_type_ids = + Layers.default token_type_ids do + Layers.default_token_type_ids(input_ids) + end + + inputs_embeddings = + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + name: join(name, "token_embedding") + ) + + position_embeddings = + Axon.embedding(position_ids, spec.max_positions, spec.hidden_size, + name: join(name, "position_embedding") + ) + + token_type_embeddings = + Axon.embedding(token_type_ids, spec.max_token_types, spec.hidden_size, + name: join(name, "token_type_embedding") + ) + + # TODO: Explicitly tie these weights + + left_position_embeddings = + bounding_box + |> Axon.nx(& &1[[.., .., 0]]) + |> Axon.embedding(spec.max_spatial_positions, spec.hidden_size, + name: join(name, "x_position_embedding") + ) + + right_position_embeddings = + bounding_box + |> Axon.nx(& &1[[.., .., 2]]) + |> Axon.embedding(spec.max_spatial_positions, spec.hidden_size, + name: join(name, "x_position_embedding") + ) + + upper_position_embeddings = + bounding_box + |> Axon.nx(& &1[[.., .., 1]]) + |> Axon.embedding(spec.max_spatial_positions, spec.hidden_size, + name: join(name, "y_position_embedding") + ) + + lower_position_embeddings = + bounding_box + |> Axon.nx(& &1[[.., .., 3]]) + |> Axon.embedding(spec.max_spatial_positions, spec.hidden_size, + name: join(name, "y_position_embedding") + ) + + h_position_embeddings = + bounding_box + |> Axon.nx(fn x -> Nx.subtract(x[[.., .., 3]], x[[.., .., 1]]) end) + |> Axon.embedding(spec.max_spatial_positions, spec.hidden_size, + name: join(name, "h_position_embedding") + ) + + w_position_embeddings = + bounding_box + |> Axon.nx(fn x -> Nx.subtract(x[[.., .., 2]], x[[.., .., 0]]) end) + |> Axon.embedding(spec.max_spatial_positions, spec.hidden_size, + name: join(name, "w_position_embedding") + ) + + embeddings = + Axon.add([ + inputs_embeddings, + position_embeddings, + token_type_embeddings, + left_position_embeddings, + right_position_embeddings, + upper_position_embeddings, + lower_position_embeddings, + h_position_embeddings, + w_position_embeddings + ]) + + embeddings + |> Axon.layer_norm(epsilon: spec.layer_norm_epsilon, name: join(name, "norm")) + |> Axon.dropout(rate: spec.dropout_rate) + end + + defp encoder(hidden_state, attention_mask, attention_head_mask, spec, opts) do + name = opts[:name] + + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: spec.layer_norm_epsilon + ], + ffn: [ + intermediate_size: spec.intermediate_size, + activation: spec.activation + ], + name: join(name, "blocks") + ) + end + + defp pooler(hidden_state, spec, opts) do + name = opts[:name] + + hidden_state + |> Layers.take_token(index: 0, axis: 1, name: join(name, "head")) + |> Axon.dense(spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + |> Axon.tanh() + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: use a shared parameter with embeddings.word_embeddings.kernel + # if spec.tie_word_embeddings is true (relevant for training) + + hidden_state + |> Axon.dense(spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "dense") + ) + |> Layers.activation(spec.activation, name: join(name, "activation")) + |> Axon.layer_norm(epsilon: spec.layer_norm_epsilon, name: join(name, "norm")) + # We reuse the kernel of input embeddings and add bias for each token + |> Layers.dense_transposed(spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + |> Axon.bias(name: join(name, "bias")) + end + + defp classifier_dropout_rate(spec) do + spec.classifier_dropout_rate || spec.dropout_rate + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"max_position_embeddings", number()}, + max_token_types: {"type_vocab_size", number()}, + hidden_size: {"hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_attention_heads: {"num_attention_heads", number()}, + intermediate_size: {"intermediate_size", number()}, + activation: {"hidden_act", activation()}, + dropout_rate: {"hidden_dropout_prob", number()}, + attention_dropout_rate: {"attention_probs_dropout_prob", number()}, + classifier_dropout_rate: {"classifier_dropout", optional(number())}, + layer_norm_epsilon: {"layer_norm_eps", number()}, + initializer_scale: {"initializer_range", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.token_embedding" => "layoutlm.embeddings.word_embeddings", + "embedder.position_embedding" => "layoutlm.embeddings.position_embeddings", + "embedder.token_type_embedding" => "layoutlm.embeddings.token_type_embeddings", + "embedder.x_position_embedding" => "layoutlm.embeddings.x_position_embeddings", + "embedder.y_position_embedding" => "layoutlm.embeddings.y_position_embeddings", + "embedder.h_position_embedding" => "layoutlm.embeddings.h_position_embeddings", + "embedder.w_position_embedding" => "layoutlm.embeddings.w_position_embeddings", + "embedder.norm" => "layoutlm.embeddings.LayerNorm", + "encoder.blocks.{n}.self_attention.query" => + "layoutlm.encoder.layer.{n}.attention.self.query", + "encoder.blocks.{n}.self_attention.key" => + "layoutlm.encoder.layer.{n}.attention.self.key", + "encoder.blocks.{n}.self_attention.value" => + "layoutlm.encoder.layer.{n}.attention.self.value", + "encoder.blocks.{n}.self_attention.output" => + "layoutlm.encoder.layer.{n}.attention.output.dense", + "encoder.blocks.{n}.self_attention_norm" => + "layoutlm.encoder.layer.{n}.attention.output.LayerNorm", + "encoder.blocks.{n}.cross_attention.query" => + "layoutlm.encoder.layer.{n}.crossattention.self.query", + "encoder.blocks.{n}.cross_attention.key" => + "layoutlm.encoder.layer.{n}.crossattention.self.key", + "encoder.blocks.{n}.cross_attention.value" => + "layoutlm.encoder.layer.{n}.crossattention.self.value", + "encoder.blocks.{n}.cross_attention.output" => + "layoutlm.encoder.layer.{n}.crossattention.output.dense", + "encoder.blocks.{n}.cross_attention_norm" => + "layoutlm.encoder.layer.{n}.crossattention.output.LayerNorm", + "encoder.blocks.{n}.ffn.intermediate" => "layoutlm.encoder.layer.{n}.intermediate.dense", + "encoder.blocks.{n}.ffn.output" => "layoutlm.encoder.layer.{n}.output.dense", + "encoder.blocks.{n}.output_norm" => "layoutlm.encoder.layer.{n}.output.LayerNorm", + "pooler.output" => "layoutlm.pooler.dense", + "language_modeling_head.dense" => "cls.predictions.transform.dense", + "language_modeling_head.norm" => "cls.predictions.transform.LayerNorm", + "language_modeling_head.output" => "cls.predictions.decoder", + "language_modeling_head.bias" => "cls.predictions", + "sequence_classification_head.output" => "classifier", + "token_classification_head.output" => "classifier", + "multiple_choice_head.output" => "classifier", + "question_answering_head.output" => "qa_outputs" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/scheduler.ex b/deps/bumblebee/lib/bumblebee/scheduler.ex new file mode 100644 index 0000000000000000000000000000000000000000..1bca9b64cc7700921f43cd87564c2fa13cffbfbf --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/scheduler.ex @@ -0,0 +1,71 @@ +defmodule Bumblebee.Scheduler do + @moduledoc """ + An interface for configuring and using schedulers. + + A scheduler defines a sampling method, usually used for multi-step + denoising process, as in stable diffusion. + + Every module implementing this behaviour is expected to also define + a configuration struct. + + ## Context + + Imagine a denoising model trained in 1000 steps. During training, + we take some original data and add random noise 1000 times, this + way we obtain 1000 steps with increasing level of noise. Then, the + model learns to predict noise at each timestep, given data at that + step (sample) and the timestep. + + Once such model is trained, we can obtain brand new data (such as + image) by generating random data and denoising it with our model in + 1000 steps. + + Doing 1000 forward passes of the model for a single generation can + be expensive, hence multiple methods have been developed to reduce + the number of steps during denoising, with no changes to the model. + + Each method specifies a subset of the original timesteps, at each + timestep we need to do a forward pass of the model (or possibly a + few), then the method extrapolates the sample to the next selected + timestep, possibly skipping a lot of timesteps in between. + + ## Note on wording + + Throughout the docs and APIs the word "steps" refers to diffusion + steps, whereas "timesteps" is more specific and refers to the exact + values $t$ (points in time). + """ + + @type t :: Bumblebee.Configurable.t() + + @type state :: Nx.Container.t() + + @doc """ + Initializes state for a new scheduler loop. + + Returns a pair of `{state, timesteps}`, where `state` is an opaque + `Nx.Container` and `timesteps` is a tensor with the subsequent + timesteps for model forward pass. + """ + @callback init( + t(), + num_steps :: pos_integer(), + sample_template :: Nx.Tensor.t(), + prng_key :: Nx.Tensor.t() + ) :: {state :: map(), timesteps :: Nx.Tensor.t()} + + @doc """ + Predicts sample at the previous timestep. + + Takes the current `sample` and `prediction` (usually noise) returned + by the model at the current timestep. Returns `{state, prev_sample}`, + where `state` is the updated state and `prev_sample` is the predicted + sample at the previous timestep. + """ + @callback step( + t(), + state(), + sample :: Nx.Tensor.t(), + prediction :: Nx.Tensor.t() + ) :: {state :: map(), prev_sample :: Nx.Tensor.t()} +end diff --git a/deps/bumblebee/lib/bumblebee/shared.ex b/deps/bumblebee/lib/bumblebee/shared.ex new file mode 100644 index 0000000000000000000000000000000000000000..36dc135f5ca18ce93806dfefe77a2bc1d58e2b35 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/shared.ex @@ -0,0 +1,549 @@ +defmodule Bumblebee.Shared do + @moduledoc false + + @doc """ + Returns specification for the given common options. + """ + @spec common_options(list(atom())) :: keyword() + def common_options(keys) do + common_options = [ + output_hidden_states: [ + default: false, + doc: "whether the model should return all hidden states" + ], + output_attentions: [ + default: false, + doc: "whether the model should return all attentions" + ], + num_labels: [ + default: 2, + doc: "the number of labels to use in the last layer for the classification task" + ], + id_to_label: [ + default: %{}, + doc: "a map from class index to label" + ], + use_cross_attention: [ + default: false, + doc: + "whether cross-attention layers should be added to the model. " <> + "This is only relevant for decoder models" + ] + ] + + Keyword.take(common_options, keys) + end + + @doc """ + Returns specification for the token options with the corresponding + defaults. + """ + @spec token_options(keyword()) :: keyword() + def token_options(defaults) do + for {key, default} <- defaults do + {key, [default: default, doc: nil]} + end + end + + @doc """ + Generates documentation string for the given options specification. + """ + @spec options_doc(keyword()) :: String.t() + def options_doc(options) do + items = + for {key, info} <- options, doc = info[:doc] do + doc = String.replace(doc, "\n", "\n ") + item = " * `#{inspect(key)}` - #{doc}" + + case info[:default] do + nil -> item + default -> "#{item}. Defaults to `#{inspect(default)}`" + end + end + + Enum.join(items, "\n\n") + end + + @doc """ + Generates documentation string for the given global layer options. + """ + @spec global_layer_options_doc(list(atom())) :: String.t() + def global_layer_options_doc(names) do + docs = [ + output_hidden_states: "when `true`, the model output includes all hidden states", + output_attentions: "when `true`, the model output includes all attention weights" + ] + + Enum.map_join(names, "\n\n", fn name -> + doc = Keyword.fetch!(docs, name) + " * `#{inspect(name)}` - #{doc}" + end) + end + + @doc """ + Returns option defaults form the options specification. + + This function is useful in combination with `defstruct`. + """ + @spec option_defaults(keyword()) :: keyword() + def option_defaults(options) do + for {key, info} <- options, do: {key, info[:default]} + end + + @doc """ + Converts common options from huggingface/transformers configuration. + """ + @spec common_options_from_transformers(map(), Bumblebee.ModelSpec.t()) :: keyword() + def common_options_from_transformers(data, spec) do + import Bumblebee.Shared.Converters + + converters = [ + output_hidden_states: {"output_hidden_states", boolean()}, + output_attentions: {"output_attentions", boolean()}, + num_labels: {"num_labels", number()}, + id_to_label: {"id2label", map(integer_as_string(), string())}, + use_cross_attention: {"use_cross_attention", false}, + # Tokens + pad_token_id: {"pad_token_id", number()}, + bos_token_id: {"bos_token_id", number()}, + eos_token_id: {"eos_token_id", number()}, + decoder_start_token_id: {"decoder_start_token_id", number()} + ] + + converters = + Keyword.filter(converters, fn {key, _} -> + Map.has_key?(spec, key) + end) + + opts = convert!(data, converters) + + if Map.has_key?(spec, :num_labels) and + not Keyword.has_key?(opts, :num_labels) and opts[:id_to_label] do + Keyword.put(opts, :num_labels, map_size(opts[:id_to_label])) + else + opts + end + end + + @doc """ + Merges the given list of attributes into a configuration struct. + + Raises `ArgumentError` if an invalid attribute name is found. + """ + @spec put_config_attrs(struct(), keyword()) :: struct() + def put_config_attrs(config, opts) do + Enum.reduce(opts, config, fn {key, value}, config -> + case config do + %{^key => _} -> + %{config | key => value} + + _ -> + raise ArgumentError, + "unexpected attribute #{inspect(key)} for %#{inspect(config.__struct__)}{}" + end + end) + end + + @doc """ + Validates that label-related attributes have consistent size. + """ + @spec validate_label_options(Bumblebee.ModelSpec.t()) :: Bumblebee.ModelSpec.t() + def validate_label_options(%{num_labels: num_labels, id_to_label: id_to_label} = spec) do + if id_to_label != %{} and map_size(id_to_label) != spec.num_labels do + raise ArgumentError, + "size mismatch between :num_labels (#{inspect(num_labels)}) and :id_to_label (#{inspect(id_to_label)})" + end + + spec + end + + @doc """ + Optionally unwraps a singular list. + """ + @spec normalize_output(list(), boolean()) :: list(term()) | term() + def normalize_output(list, multi?) + + def normalize_output([term], false), do: term + def normalize_output(list, true), do: list + + @doc """ + Validates and normalizes task input. + """ + @spec validate_serving_input!( + term(), + (term() -> {:ok, term()} | {:error, String.t()}) + ) :: {list(term()), multi? :: boolean()} + def validate_serving_input!(input, validator) + + def validate_serving_input!(input, validator) when is_list(input) do + input = + for item <- input do + case validator.(item) do + {:ok, normalized} -> normalized + {:error, message} -> raise ArgumentError, "invalid input in the batch, #{message}" + end + end + + {input, true} + end + + def validate_serving_input!(input, validator) do + case validator.(input) do + {:ok, normalized} -> {[normalized], false} + {:error, message} -> raise ArgumentError, "invalid input, #{message}" + end + end + + def validate_image(input) do + if image?(input) do + {:ok, input} + else + {:error, "expected an image, got: #{inspect(input)}"} + end + end + + def validate_string(input) do + if is_binary(input) do + {:ok, input} + else + {:error, "expected a string, got: #{inspect(input)}"} + end + end + + def validate_string_or_pairs(input) do + case input do + input when is_binary(input) -> {:ok, input} + {left, right} when is_binary(left) and is_binary(right) -> {:ok, input} + _other -> {:error, "expected a string or a pair of strings, got: #{inspect(input)}"} + end + end + + @doc """ + Validates that the input is a single value and not a batch. + """ + @spec validate_input_for_stream!(term()) :: :ok + def validate_input_for_stream!(input) do + if is_list(input) do + raise ArgumentError, + "this serving only accepts singular input when stream is enabled," <> + " call the serving with each input in the batch separately" + end + + :ok + end + + @doc """ + Asserts that the model architecture matches one of the expected + architectures. + """ + def validate_architecture!(spec, architecture) + + def validate_architecture!(spec, architectures) when is_list(architectures) do + unless spec.architecture in architectures do + raise ArgumentError, + "expected a model architecture to be either of #{inspect(architectures)}, got #{inspect(spec.architecture)}" + end + end + + def validate_architecture!(spec, architecture) do + unless spec.architecture == architecture do + raise ArgumentError, + "expected a model with architecture #{inspect(architecture)}, got #{inspect(spec.architecture)}" + end + end + + @doc """ + Asserts that the given options keyword list has all of the given + keys. + """ + def require_options!(opts, keys) do + missing = keys -- Keyword.keys(opts) + + if missing != [] do + raise ArgumentError, "missing keys #{inspect(missing)} in #{inspect(opts)}" + end + + opts + end + + @doc """ + Checks if the given term is an image. + """ + @spec image?(term()) :: boolean() + def image?(image) do + try do + Nx.to_template(image) + rescue + Protocol.UndefinedError -> false + else + %Nx.Tensor{shape: {_, _, channels}} when channels in 1..4 -> true + _ -> false + end + end + + @doc """ + Pads a batch to the given size, if given. + + When the batch exceeds `batch_size`, raises an error. + """ + @spec maybe_pad(Nx.Batch.t(), non_neg_integer() | nil) :: Nx.Batch.t() + def maybe_pad(batch, batch_size) + + def maybe_pad(batch, nil), do: batch + + def maybe_pad(%{size: size}, batch_size) when size > batch_size do + raise ArgumentError, + "input batch size (#{size}) exceeds the maximum configured batch size (#{batch_size})" + end + + def maybe_pad(%{size: size} = batch, batch_size) do + Nx.Batch.pad(batch, batch_size - size) + end + + @doc """ + Shared logic applied after serving computation to the resulting tensor + or container. + """ + @spec serving_post_computation(result) :: result when result: Nx.Tensor.t() | Nx.Container.t() + def serving_post_computation(result) do + # We transfer to binary backend so tensor access in post-processing + # is not blocked by the serving the serving computation. It is also + # necessary when partitions are enabled since we may need to + # concatenate results for input exceeding the expected batch size. + Nx.backend_transfer(result, Nx.BinaryBackend) + end + + @doc """ + Compiles or wraps the function with just-in-time compilation. + + When `compile?` is `true`, runs `template_fun` to get template args + and calls compiles the function upfront. The template function may + return a mix of tensors and templates, all arguments are automatically + converter to templates. + + If `defn_options[:cache]` is set, the given `scope` is used to create + a suffix. + """ + @spec compile_or_jit( + function(), + scope, + keyword(), + boolean(), + (-> list(Nx.Tensor.t())) + ) :: function() + when scope: String.Chars.t() | {scope, scope} + def compile_or_jit(fun, scope, defn_options, compile?, template_fun) do + defn_options = + case defn_options[:cache] do + cache when is_binary(cache) -> + suffix = "__bumblebee_" <> scope_to_string(scope) + Keyword.replace!(defn_options, :cache, cache <> suffix) + + _ -> + defn_options + end + + if compile? do + template_args = template_fun.() |> templates() + Nx.Defn.compile(fun, template_args, defn_options) + else + Nx.Defn.jit(fun, defn_options) + end + end + + defp scope_to_string({left, right}) do + scope_to_string(left) <> "_" <> scope_to_string(right) + end + + defp scope_to_string(scope), do: to_string(scope) + + @doc """ + Returns at template for the given model input. + + Replaces leading axis sizes with `overrides`. + """ + @spec input_template( + Bumblebee.ModelSpec.t(), + String.t(), + list(non_neg_integer()) + ) :: Nx.Tensor.t() + def input_template(%module{} = spec, name, overrides) do + %{^name => template} = module.input_template(spec) + + shape = + overrides + |> Enum.with_index() + |> Enum.reduce(Nx.shape(template), fn {size, idx}, shape -> + put_elem(shape, idx, size) + end) + + Nx.template(shape, Nx.type(template)) + end + + @doc """ + Converts tensors to templates. + """ + @spec templates(list(Nx.Tensor.t())) :: list(Nx.Tensor.t()) + def templates(list) do + Enum.map(list, fn + %Nx.Tensor{data: %Nx.TemplateBackend{}} = template -> template + other -> Nx.to_template(other) + end) + end + + @doc """ + Converts logits to scores as per the given scores function. + + Raises `ArgumentError` if the scores function is invalid. + """ + @spec logits_to_scores(Nx.Tensor.t(), atom()) :: Nx.Tensor.t() + def logits_to_scores(logits, scores_function) do + case scores_function do + :softmax -> + Axon.Activations.softmax(logits) + + :sigmoid -> + Axon.Activations.sigmoid(logits) + + :none -> + logits + + other -> + raise ArgumentError, + "expected :scores_function to be either of :softmax, :sigmoid or :none, got: #{inspect(other)}" + end + end + + @doc """ + Returns batch keys for the given sequence length specified in text + serving compile options. + """ + @spec sequence_batch_keys(nil | non_neg_integer() | list(non_neg_integer())) :: list() + def sequence_batch_keys(sequence_length) + + def sequence_batch_keys(nil), do: [:default] + + def sequence_batch_keys(length) when is_number(length) do + [{:sequence_length, length}] + end + + def sequence_batch_keys(lengths) when is_list(lengths) do + Enum.map(lengths, &{:sequence_length, &1}) + end + + @doc """ + Determines batch key compatible with `sequence_batch_keys/1` based + on tokenized inputs. + """ + @spec sequence_batch_key_for_inputs( + inputs :: any(), + nil | non_neg_integer() | list(non_neg_integer()) + ) :: term() + def sequence_batch_key_for_inputs(inputs, sequence_length) do + if sequence_length do + {:sequence_length, Nx.axis_size(inputs["input_ids"], 1)} + else + :default + end + end + + @doc """ + If `preallocate?` is `true`, allocates `params` using `defn_options`. + """ + @spec maybe_preallocate(map(), boolean(), keyword()) :: map() + def maybe_preallocate(params, preallocate?, defn_options) do + if preallocate? do + backend = Nx.Defn.to_backend(defn_options) + Nx.backend_copy(params, backend) + else + params + end + end + + @doc """ + Slices a subset of dense layer parameters. + + Expects `out_template` to be a tuple representing a "shape" of the + output units. The tuple should include a list in place of the axis + along which the parameters are concatenated. The list should contain + chunk sizes. `chunk_idx` indicates which chunk to slice. + """ + def sliced_dense_params_source(source_layer_name, out_template, chunk_idx) do + out_template = Tuple.to_list(out_template) + chunk_axis = Enum.find_index(out_template, &is_list/1) + chunk_sizes = Enum.at(out_template, chunk_axis) + {prev_chunk_sizes, [chunk_size | _]} = Enum.split(chunk_sizes, chunk_idx) + offset = Enum.sum(prev_chunk_sizes) + out_shape = List.replace_at(out_template, chunk_axis, Enum.sum(chunk_sizes)) + + %{ + "kernel" => { + [{source_layer_name, "weight"}], + fn [kernel] -> + in_size = Nx.axis_size(kernel, -1) + + kernel = + kernel + |> Nx.reshape(List.to_tuple(out_shape ++ [in_size])) + |> Nx.slice_along_axis(offset, chunk_size, axis: chunk_axis) + |> Nx.reshape({:auto, in_size}) + + # Transpose the kernel + [out_features, in_features] = Nx.axes(kernel) + Nx.transpose(kernel, axes: [in_features, out_features]) + end + }, + "bias" => { + [{source_layer_name, "bias"}], + fn [bias] -> + bias + |> Nx.reshape(List.to_tuple(out_shape)) + |> Nx.slice_along_axis(offset, chunk_size, axis: chunk_axis) + |> Nx.flatten() + end + } + } + end + + @type featurizer_image_size :: + %{height: non_neg_integer(), width: non_neg_integer()} + | %{shortest_edge: non_neg_integer()} + + @doc """ + Returns an exact `{height, width}` size to resize images into. + + Accepts a featurizer size map. + """ + @spec featurizer_resize_size(Nx.Tensor.t(), featurizer_image_size()) :: + {height :: non_neg_integer(), width :: non_neg_integer()} + def featurizer_resize_size(images, size) + + def featurizer_resize_size(_images, %{height: height, width: width}), do: {height, width} + + def featurizer_resize_size(images, %{shortest_edge: size}) do + {height, width} = images_spatial_sizes(images) + + {short, long} = if height < width, do: {height, width}, else: {width, height} + + out_short = size + out_long = floor(size * long / short) + + if height < width, do: {out_short, out_long}, else: {out_long, out_short} + end + + defp images_spatial_sizes(images) do + height = Nx.axis_size(images, -3) + width = Nx.axis_size(images, -2) + {height, width} + end + + @doc """ + Checks whether if the given featurizer image size is fixed or depends + on the input size. + """ + @spec featurizer_size_fixed?(featurizer_image_size()) :: boolean() + def featurizer_size_fixed?(size) + + def featurizer_size_fixed?(%{height: _, width: _}), do: true + def featurizer_size_fixed?(%{shortest_edge: _}), do: false +end diff --git a/deps/bumblebee/lib/bumblebee/shared/converters.ex b/deps/bumblebee/lib/bumblebee/shared/converters.ex new file mode 100644 index 0000000000000000000000000000000000000000..0e1aac02397339c09623381b0c44dfa61b65b332 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/shared/converters.ex @@ -0,0 +1,251 @@ +defmodule Bumblebee.Shared.Converters do + @moduledoc false + + @type converter :: + (name :: String.t(), value :: term() -> + {:ok, term()} | {:error, String.t()}) + + @doc """ + Reads and converts data from the given map according to the given + specification. + """ + @spec convert!(map(), keyword({String.t(), converter()})) :: keyword() + def convert!(data, entries) do + for {key, {source, converter}} <- entries, Map.has_key?(data, source) do + case converter.(source, data[source]) do + {:ok, value} -> + {key, value} + + {:error, message} -> + raise "conversion failed, " <> message + end + end + end + + def number() do + fn name, value -> + if is_number(value) do + {:ok, value} + else + {:error, "expected #{inspect(name)} to be a number, got: #{inspect(value)}"} + end + end + end + + def string() do + fn name, value -> + if is_binary(value) do + {:ok, value} + else + {:error, "expected #{inspect(name)} to be a string, got: #{inspect(value)}"} + end + end + end + + def atom() do + fn name, value -> + try do + {:ok, String.to_atom(value)} + rescue + _error -> + {:error, "unsupported value for #{inspect(name)}, got: #{inspect(value)}"} + end + end + end + + def boolean() do + fn name, value -> + if is_boolean(value) do + {:ok, value} + else + {:error, "expected #{inspect(name)} to be a boolean, got: #{inspect(value)}"} + end + end + end + + def integer_as_string() do + fn name, value -> + with true <- is_binary(value), {number, ""} <- Integer.parse(value) do + {:ok, number} + else + _ -> + {:error, + "expected #{inspect(name)} to be a string representing a number, got: #{inspect(value)}"} + end + end + end + + def list(converter) do + fn name, value -> + if is_list(value) do + value + |> Enum.with_index() + |> safe_map(fn {item, index} -> + converter.("#{name}[#{index}]", item) + end) + else + {:error, "expected #{inspect(name)} to be a list, got: #{inspect(value)}"} + end + end + end + + def map(key_converter, value_converter) do + fn name, value -> + if is_map(value) do + value + |> safe_map(fn {key, value} -> + with {:ok, key} <- key_converter.("#{name} key", key), + {:ok, value} <- value_converter.("#{name}.#{value}]", value), + do: {:ok, {key, value}} + end) + |> case do + {:ok, list} -> {:ok, Map.new(list)} + error -> error + end + else + {:error, "expected #{inspect(name)} to be a map, got: #{inspect(value)}"} + end + end + end + + def tuple(converters) do + fn name, value -> + cond do + not is_list(value) -> + {:error, "expected #{inspect(name)} to be a list, got: #{inspect(value)}"} + + length(value) != length(converters) -> + {:error, + "expected #{inspect(name)} to have #{inspect(length(converters))} elements," <> + " but got #{inspect(length(value))}"} + + true -> + value + |> Enum.with_index() + |> Enum.zip(converters) + |> safe_map(fn {{item, index}, converter} -> + converter.("#{name}[#{index}]", item) + end) + |> case do + {:ok, list} -> {:ok, List.to_tuple(list)} + error -> error + end + end + end + end + + defp safe_map(enumerable, fun) do + enumerable + |> Enum.reduce_while([], fn value, acc -> + case fun.(value) do + {:ok, value} -> {:cont, [value | acc]} + {:error, error} -> {:halt, {:error, error}} + end + end) + |> case do + {:error, error} -> {:error, error} + items -> {:ok, Enum.reverse(items)} + end + end + + def mapping(map) do + fn name, value -> + case Map.fetch(map, value) do + {:ok, replacement} -> + {:ok, replacement} + + :error -> + {:error, + "unrecognized value for #{inspect(name)}, got: #{inspect(value)}," <> + " but the supported values are: #{inspect(Map.keys(map))}"} + end + end + end + + def optional(converter) do + fn name, value -> + if value == nil do + {:ok, nil} + else + converter.(name, value) + end + end + end + + def one_of(converters) do + fn name, value -> + default = + {:error, + "value #{inspect(value)} at #{inspect(name)} did not match any of the expected formats"} + + Enum.find_value(converters, default, fn converter -> + with {:error, _} <- converter.(name, value), do: nil + end) + end + end + + def resize_method() do + # See https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Resampling + mapping(%{ + 0 => :nearest, + 1 => :lanczos3, + 2 => :bilinear, + 3 => :bicubic + }) + end + + def padding(rank) do + fn name, value -> + if is_number(value) do + {:ok, List.duplicate({value, value}, rank)} + else + {:error, "expected #{inspect(name)} to be a number, got: #{inspect(value)}"} + end + end + end + + def activation() do + mapping = %{ + "gelu_new" => :gelu_approx_tanh, + "gelu_pytorch_tanh" => :gelu_approx_tanh, + "quick_gelu" => :gelu_approx_sigmoid + } + + fn name, value -> + case Map.fetch(mapping, value) do + {:ok, replacement} -> {:ok, replacement} + :error -> atom().(name, value) + end + end + end + + def image_size(opts \\ []) do + opts = Keyword.validate!(opts, single_as: :both_edges) + single_as = opts[:single_as] + + true = single_as in [:both_edges, :shortest_edge] + + fn name, value -> + case value do + %{"height" => height, "width" => width} -> + {:ok, %{height: height, width: width}} + + [height, width] -> + {:ok, %{height: height, width: width}} + + size when is_number(size) and single_as == :both_edges -> + {:ok, %{height: size, width: size}} + + size when is_number(size) and single_as == :shortest_edge -> + {:ok, %{shortest_edge: size}} + + %{"shortest_edge" => shortest_edge} -> + {:ok, %{shortest_edge: shortest_edge}} + + _ -> + {:error, + "expected #{inspect(name)} to be a number, a list or a map with height and width, got: #{inspect(value)}"} + end + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text.ex b/deps/bumblebee/lib/bumblebee/text.ex new file mode 100644 index 0000000000000000000000000000000000000000..770a21921c23854227fbda9333bfe9904edfc607 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text.ex @@ -0,0 +1,673 @@ +defmodule Bumblebee.Text do + @moduledoc """ + High-level tasks related to text processing. + """ + + @type token_classification_input :: String.t() + @type token_classification_output :: %{entities: list(token_classification_entity())} + + @typedoc """ + A single entity label. + + Note that `start` and `end` indices are expressed in terms of UTF-8 + bytes. + """ + @type token_classification_entity :: %{ + start: non_neg_integer(), + end: non_neg_integer(), + score: float(), + label: String.t(), + phrase: String.t() + } + + @doc """ + Builds serving for token classification. + + The serving accepts `t:token_classification_input/0` and returns + `t:token_classification_output/0`. A list of inputs is also supported. + + This function can be used for tasks such as named entity recognition + (NER) or part of speech tagging (POS). + + The recognized entities can optionally be aggregated into groups + based on the given strategy. + + ## Options + + * `:aggregation` - an optional strategy for aggregating adjacent + tokens. Token classification models output probabilities for + each possible token class. The aggregation strategy takes scores + for each token (which possibly represents subwords) and groups + tokens into phrases which are readily interpretable as entities + of a certain class. Supported aggregation strategies: + + * `nil` (default) - corresponds to no aggregation and returns + the most likely label for each input token + + * `:same` - groups adjacent tokens with the same label. If + the labels use beginning-inside-outside (BIO) tagging, the + boundaries are respected and the prefix is omitted in the + output labels + + * `:word_first` - uses `:same` strategy except that word tokens + cannot end up with different labels. With this strategy word + gets the label of the first token of that word when there + is ambiguity. Note that this works only on word based models + + * `:word_average` - uses `:same` strategy except that word tokens + cannot end up with different labels. With this strategy scores + are averaged across word tokens and then the maximum label + is taken. Note that this works only on word based models + + * `:word_max` - uses `:same` strategy except that word tokens + cannot end up with different labels. With this strategy word + gets the label of the token with the maximum score. Note that + this works only on word based models + + * `:ignored_labels` - the labels to ignore in the final output. + The labels should be specified without BIO prefix. Defaults to + `["O"]` + + * `:compile` - compiles all computations for predefined input shapes + during serving initialization. Should be a keyword list with the + following keys: + + * `:batch_size` - the maximum batch size of the input. Inputs + are optionally padded to always match this batch size + + * `:sequence_length` - the maximum input sequence length. Input + sequences are always padded/truncated to match that length. + A list can be given, in which case the serving compiles + a separate computation for each length and then inputs are + matched to the smallest bounding length + + It is advised to set this option in production and also configure + a defn compiler using `:defn_options` to maximally reduce inference + time. + + * `:scores_function` - the function to use for converting logits to + scores. Should be one of `:softmax`, `:sigmoid`, or `:none`. + Defaults to `:softmax` + + * `:defn_options` - the options for JIT compilation. Defaults to `[]` + + * `:preallocate_params` - when `true`, explicitly allocates params + on the device configured by `:defn_options`. You may want to set + this option when using partitioned serving, to allocate params + on each of the devices. When using this option, you should first + load the parameters into the host. This can be done by passing + `backend: {EXLA.Backend, client: :host}` to `load_model/1` and friends. + Defaults to `false` + + ## Examples + + {:ok, bert} = Bumblebee.load_model({:hf, "dslim/bert-base-NER"}) + {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "google-bert/bert-base-cased"}) + + serving = Bumblebee.Text.token_classification(bert, tokenizer, aggregation: :same) + + text = "Rachel Green works at Ralph Lauren in New York City in the sitcom Friends" + Nx.Serving.run(serving, text) + #=> %{ + #=> entities: [ + #=> %{end: 12, label: "PER", phrase: "Rachel Green", score: 0.9997024834156036, start: 0}, + #=> %{end: 34, label: "ORG", phrase: "Ralph Lauren", score: 0.9968731701374054, start: 22}, + #=> %{end: 51, label: "LOC", phrase: "New York City", score: 0.9995547334353129, start: 38}, + #=> %{end: 73, label: "MISC", phrase: "Friends", score: 0.6997143030166626, start: 66} + #=> ] + #=>} + + """ + @spec token_classification( + Bumblebee.model_info(), + Bumblebee.Tokenizer.t(), + keyword() + ) :: Nx.Serving.t() + defdelegate token_classification(model_info, tokenizer, opts \\ []), + to: Bumblebee.Text.TokenClassification + + @type generation_input :: + String.t() | %{:text => String.t(), optional(:seed) => integer() | nil} + @type generation_output :: %{results: list(generation_result())} + @type generation_result :: %{text: String.t(), token_summary: token_summary()} + @type token_summary :: %{ + input: pos_integer(), + outout: pos_integer(), + padding: non_neg_integer() + } + + @doc """ + Builds serving for prompt-driven text generation. + + The serving accepts `t:generation_input/0` and returns `t:generation_output/0`. + A list of inputs is also supported. + + ## Options + + * `:compile` - compiles all computations for predefined input shapes + during serving initialization. Should be a keyword list with the + following keys: + + * `:batch_size` - the maximum batch size of the input. Inputs + are optionally padded to always match this batch size + + * `:sequence_length` - the maximum input sequence length. Input + sequences are always padded/truncated to match that length. + A list can be given, in which case the serving compiles + a separate computation for each length and then inputs are + matched to the smallest bounding length + + It is advised to set this option in production and also configure + a defn compiler using `:defn_options` to maximally reduce inference + time. + + * `:defn_options` - the options for JIT compilation. Defaults to `[]` + + * `:preallocate_params` - when `true`, explicitly allocates params + on the device configured by `:defn_options`. You may want to set + this option when using partitioned serving, to allocate params + on each of the devices. When using this option, you should first + load the parameters into the host. This can be done by passing + `backend: {EXLA.Backend, client: :host}` to `load_model/1` and friends. + Defaults to `false` + + * `:stream` - when `true`, the serving immediately returns a + stream that emits text chunks as they are generated. Note that + when using streaming, only a single input can be given to the + serving. To process a batch, call the serving with each input + separately. Defaults to `false` + + * `:stream_done` - when `:stream` is enabled, this enables a final + event, after all chunks have been emitted. The event has the + shape `{:done, result}`, where `result` includes the same fields + as `t:generation_result/0`, except for `:text`, which has been + already streamed. Defaults to `false` + + ## Examples + + {:ok, model_info} = Bumblebee.load_model({:hf, "openai-community/gpt2"}) + {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "openai-community/gpt2"}) + {:ok, generation_config} = Bumblebee.load_generation_config({:hf, "openai-community/gpt2"}) + generation_config = Bumblebee.configure(generation_config, max_new_tokens: 15) + + serving = Bumblebee.Text.generation(model_info, tokenizer, generation_config) + + Nx.Serving.run(serving, "Elixir is a functional") + #=> %{ + #=> results: [ + #=> %{ + #=> text: " programming language that is designed to be used in a variety of applications. It", + #=> token_summary: %{input: 5, output: 15, padding: 0} + #=> } + #=> ] + #=> } + + We can stream the result by creating the serving with `stream: true`: + + {:ok, model_info} = Bumblebee.load_model({:hf, "openai-community/gpt2"}) + {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "openai-community/gpt2"}) + {:ok, generation_config} = Bumblebee.load_generation_config({:hf, "openai-community/gpt2"}) + generation_config = Bumblebee.configure(generation_config, max_new_tokens: 15) + + serving = Bumblebee.Text.generation(model_info, tokenizer, generation_config, stream: true) + + Nx.Serving.run(serving, "Elixir is a functional") |> Enum.to_list() + #=> [" programming", " language", " that", " is", " designed", " to", " be", " used", " in", " a", + #=> " variety", " of", " applications.", " It"] + + """ + @spec generation( + Bumblebee.model_info(), + Bumblebee.Tokenizer.t(), + Bumblebee.Text.GenerationConfig.t(), + keyword() + ) :: Nx.Serving.t() + defdelegate generation(model_info, tokenizer, generation_config, opts \\ []), + to: Bumblebee.Text.TextGeneration + + @type translation_input :: + %{ + :text => String.t(), + :source_language_token => String.t(), + :target_language_token => String.t(), + optional(:seed) => integer() | nil + } + @type translation_output :: generation_output() + + @doc """ + Builds serving for text translation. + + The serving accepts `t:translation_input/0` and returns `t:translation_output/0`. + A list of inputs is also supported. + + This serving is an extension of `generation/4` that handles per-input + language configuration. + + Note that this serving is designed for multilingual models that + require source/target language to be specified. Some text models are + trained for specific language pairs, others expect a command such as + "translate English to Spanish", in such cases you most likely want + to use `generation/4`. + + ## Options + + See `generation/4` for available options. + + ## Examples + + repository_id = "facebook/nllb-200-distilled-600M" + + {:ok, model_info} = Bumblebee.load_model({:hf, repository_id}) + {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, repository_id}) + {:ok, generation_config} = Bumblebee.load_generation_config({:hf, repository_id}) + + serving = Bumblebee.Text.translation(model_info, tokenizer, generation_config) + + text = "The bank of the river is beautiful in spring" + + Nx.Serving.run(serving, %{ + text: text, + source_language_token: "eng_Latn", + target_language_token: "pol_Latn" + }) + #=> %{ + #=> results: [ + #=> %{ + #=> text: "W wiosnÄ™ brzeg rzeki jest piÄ™kny", + #=> token_summary: %{input: 11, output: 13, padding: 0} + #=> } + #=> ] + #=> } + """ + @spec translation( + Bumblebee.model_info(), + Bumblebee.Tokenizer.t(), + Bumblebee.Text.GenerationConfig.t(), + keyword() + ) :: Nx.Serving.t() + defdelegate translation(model_info, tokenizer, generation_config, opts \\ []), + to: Bumblebee.Text.Translation + + @type text_classification_input :: String.t() | {String.t(), String.t()} + @type text_classification_output :: %{predictions: list(text_classification_prediction())} + @type text_classification_prediction :: %{score: number(), label: String.t()} + + @doc """ + Builds serving for text classification. + + The serving accepts `t:text_classification_input/0` and returns + `t:text_classification_output/0`. A list of inputs is also supported. + + ## Options + + * `:top_k` - the number of top predictions to include in the output. If + the configured value is higher than the number of labels, all + labels are returned. Defaults to `5` + + * `:compile` - compiles all computations for predefined input shapes + during serving initialization. Should be a keyword list with the + following keys: + + * `:batch_size` - the maximum batch size of the input. Inputs + are optionally padded to always match this batch size + + * `:sequence_length` - the maximum input sequence length. Input + sequences are always padded/truncated to match that length. + A list can be given, in which case the serving compiles + a separate computation for each length and then inputs are + matched to the smallest bounding length + + It is advised to set this option in production and also configure + a defn compiler using `:defn_options` to maximally reduce inference + time. + + * `:scores_function` - the function to use for converting logits to + scores. Should be one of `:softmax`, `:sigmoid`, or `:none`. + Defaults to `:softmax` + + * `:defn_options` - the options for JIT compilation. Defaults to `[]` + + * `:preallocate_params` - when `true`, explicitly allocates params + on the device configured by `:defn_options`. You may want to set + this option when using partitioned serving, to allocate params + on each of the devices. When using this option, you should first + load the parameters into the host. This can be done by passing + `backend: {EXLA.Backend, client: :host}` to `load_model/1` and friends. + Defaults to `false` + + ## Examples + + {:ok, bertweet} = Bumblebee.load_model({:hf, "finiteautomata/bertweet-base-sentiment-analysis"}) + {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "vinai/bertweet-base"}) + + serving = Bumblebee.Text.text_classification(bertweet, tokenizer) + + text = "Cats are cute." + Nx.Serving.run(serving, text) + #=> %{ + #=> predictions: [ + #=> %{label: "POS", score: 0.9876555800437927}, + #=> %{label: "NEU", score: 0.010068908333778381}, + #=> %{label: "NEG", score: 0.002275536535307765} + #=> ] + #=> } + + """ + @spec text_classification( + Bumblebee.model_info(), + Bumblebee.Tokenizer.t(), + keyword() + ) :: Nx.Serving.t() + defdelegate text_classification(model_info, tokenizer, opts \\ []), + to: Bumblebee.Text.TextClassification + + @type text_embedding_input :: String.t() + @type text_embedding_output :: %{embedding: Nx.Tensor.t()} + + @doc """ + Builds serving for text embeddings. + + The serving accepts `t:text_embedding_input/0` and returns + `t:text_embedding_output/0`. A list of inputs is also supported. + + ## Options + + * `:output_attribute` - the attribute of the model output map to + retrieve. When the output is a single tensor (rather than a map), + this option is ignored. Defaults to `:pooled_state` + + * `:output_pool` - pooling to apply on top of the model output, in case + it is not already a pooled embedding. Supported values: + + * `:mean_pooling` - performs a mean across all tokens + + * `cls_token_pooling` - takes the embedding for the special CLS token. + Note that we currently assume that the CLS token is the first token + in the sequence + + By default no pooling is applied + + * `:embedding_processor` - a post-processing step to apply to the + embedding. Supported values: `:l2_norm`. By default the output is + returned as is + + * `:compile` - compiles all computations for predefined input shapes + during serving initialization. Should be a keyword list with the + following keys: + + * `:batch_size` - the maximum batch size of the input. Inputs + are optionally padded to always match this batch size + + * `:sequence_length` - the maximum input sequence length. Input + sequences are always padded/truncated to match that length. + A list can be given, in which case the serving compiles + a separate computation for each length and then inputs are + matched to the smallest bounding length + + It is advised to set this option in production and also configure + a defn compiler using `:defn_options` to maximally reduce inference + time. + + * `:defn_options` - the options for JIT compilation. Defaults to `[]` + + * `:preallocate_params` - when `true`, explicitly allocates params + on the device configured by `:defn_options`. You may want to set + this option when using partitioned serving, to allocate params + on each of the devices. When using this option, you should first + load the parameters into the host. This can be done by passing + `backend: {EXLA.Backend, client: :host}` to `load_model/1` and friends. + Defaults to `false` + + ## Examples + + {:ok, model_info} = Bumblebee.load_model({:hf, "intfloat/e5-large"}) + {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "intfloat/e5-large"}) + + serving = Bumblebee.Text.text_embedding(model_info, tokenizer) + + text = "query: Cats are cute." + Nx.Serving.run(serving, text) + + #=> %{ + #=> embedding: #Nx.Tensor< + #=> f32[1024] + #=> EXLA.Backend + #=> [-0.9789889454841614, -0.9814645051956177, -0.5015208125114441, 0.9867952466011047, 0.9917466640472412, -0.5557178258895874, -0.18618212640285492, 0.797040581703186, 0.8922086954116821, 0.7599573135375977, -0.16524426639080048, -0.8740050792694092, 0.9433475732803345, 0.7217797636985779, 0.9437620639801025, 0.4694959223270416, 0.40594056248664856, -0.20143413543701172, 0.7144518494606018, -0.8689796924591064, 0.94001305103302, 0.17163503170013428, -0.9896315932273865, 0.4455447494983673, 0.41139301657676697, 0.01911175064742565, -0.11275406181812286, -0.734498143196106, -0.6410953402519226, -0.628239095211029, -0.2570168673992157, 0.475137323141098, -0.7534396052360535, -0.9492156505584717, -0.17271563410758972, 0.9081271886825562, -0.4851466119289398, -0.9440935254096985, -0.20976334810256958, -0.684502899646759, -0.11581139266490936, 0.17509342730045319, 0.05547652021050453, 0.31042391061782837, 0.955132007598877, -0.35595986247062683, 0.016105204820632935, -0.3154579997062683, 0.9630348682403564, ...] + #=> > + #=> } + """ + @spec text_embedding( + Bumblebee.model_info(), + Bumblebee.Tokenizer.t(), + keyword() + ) :: Nx.Serving.t() + defdelegate text_embedding(model_info, tokenizer, opts \\ []), + to: Bumblebee.Text.TextEmbedding + + @type fill_mask_input :: String.t() + @type fill_mask_output :: %{predictions: list(fill_mask_prediction())} + @type fill_mask_prediction :: %{score: number(), token: String.t()} + + @doc """ + Builds serving for the fill-mask task. + + The serving accepts `t:fill_mask_input/0` and returns `t:fill_mask_output/0`. + A list of inputs is also supported. + + In the fill-mask task, the objective is to predict a masked word in + the text. The serving expects the input to have exactly one such word, + denoted as `[MASK]`. + + ## Options + + * `:top_k` - the number of top predictions to include in the output. + If the configured value is higher than the number of labels, all + labels are returned. Defaults to `5` + + * `:compile` - compiles all computations for predefined input shapes + during serving initialization. Should be a keyword list with the + following keys: + + * `:batch_size` - the maximum batch size of the input. Inputs + are optionally padded to always match this batch size + + * `:sequence_length` - the maximum input sequence length. Input + sequences are always padded/truncated to match that length. + A list can be given, in which case the serving compiles + a separate computation for each length and then inputs are + matched to the smallest bounding length + + It is advised to set this option in production and also configure + a defn compiler using `:defn_options` to maximally reduce inference + time. + + * `:defn_options` - the options for JIT compilation. Defaults to `[]` + + * `:preallocate_params` - when `true`, explicitly allocates params + on the device configured by `:defn_options`. You may want to set + this option when using partitioned serving, to allocate params + on each of the devices. When using this option, you should first + load the parameters into the host. This can be done by passing + `backend: {EXLA.Backend, client: :host}` to `load_model/1` and friends. + Defaults to `false` + + ## Examples + + {:ok, bert} = Bumblebee.load_model({:hf, "google-bert/bert-base-uncased"}) + {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "google-bert/bert-base-uncased"}) + + serving = Bumblebee.Text.fill_mask(bert, tokenizer) + + text = "The capital of [MASK] is Paris." + Nx.Serving.run(serving, text) + #=> %{ + #=> predictions: [ + #=> %{score: 0.9279842972755432, token: "france"}, + #=> %{score: 0.008412551134824753, token: "brittany"}, + #=> %{score: 0.007433671969920397, token: "algeria"}, + #=> %{score: 0.004957548808306456, token: "department"}, + #=> %{score: 0.004369721747934818, token: "reunion"} + #=> ] + #=> } + + """ + @spec fill_mask(Bumblebee.model_info(), Bumblebee.Tokenizer.t(), keyword()) :: Nx.Serving.t() + defdelegate fill_mask(model_info, tokenizer, opts \\ []), to: Bumblebee.Text.FillMask + + @type question_answering_input :: %{question: String.t(), context: String.t()} + + @type question_answering_output :: %{ + predictions: list(question_answering_result()) + } + + @type question_answering_result :: %{ + text: String.t(), + start: number(), + end: number(), + score: number() + } + + @doc """ + Builds serving for the question answering task. + + The serving accepts `t:question_answering_input/0` and returns + `t:question_answering_output/0`. A list of inputs is also supported. + + The question answering task finds the most probable answer to a + question within the given context text. + + ## Options + + * `:compile` - compiles all computations for predefined input shapes + during serving initialization. Should be a keyword list with the + following keys: + + * `:batch_size` - the maximum batch size of the input. Inputs + are optionally padded to always match this batch size. Note + that the batch size refers to the number of prompts to classify, + while the model prediction is made for every combination of + prompt and label + + * `:sequence_length` - the maximum input sequence length. Input + sequences are always padded/truncated to match that length. + A list can be given, in which case the serving compiles + a separate computation for each length and then inputs are + matched to the smallest bounding length + + It is advised to set this option in production and also configure + a defn compiler using `:defn_options` to maximally reduce inference + time. + + * `:defn_options` - the options for JIT compilation. Defaults to `[]` + + * `:preallocate_params` - when `true`, explicitly allocates params + on the device configured by `:defn_options`. You may want to set + this option when using partitioned serving, to allocate params + on each of the devices. When using this option, you should first + load the parameters into the host. This can be done by passing + `backend: {EXLA.Backend, client: :host}` to `load_model/1` and friends. + Defaults to `false` + + ## Examples + + {:ok, roberta} = Bumblebee.load_model({:hf, "deepset/roberta-base-squad2"}) + {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "FacebookAI/roberta-base"}) + + serving = Bumblebee.Text.question_answering(roberta, tokenizer) + + input = %{question: "What's my name?", context: "My name is Sarah and I live in London."} + Nx.Serving.run(serving, input) + #=> %{results: [%{end: 16, score: 0.81039959192276, start: 11, text: "Sarah"}]} + + """ + @spec question_answering( + Bumblebee.model_info(), + Bumblebee.Tokenizer.t(), + keyword() + ) :: Nx.Serving.t() + defdelegate question_answering(model_info, tokenizer, opts \\ []), + to: Bumblebee.Text.QuestionAnswering + + @type zero_shot_classification_input :: String.t() + @type zero_shot_classification_output :: %{ + predictions: list(zero_shot_classification_prediction()) + } + @type zero_shot_classification_prediction :: %{score: number(), label: String.t()} + + @doc """ + Builds serving for the zero-shot classification task. + + The serving accepts `t:zero_shot_classification_input/0` and returns + `t:zero_shot_classification_output/0`. A list of inputs is also + supported. + + The zero-shot task predicts zero-shot labels for a given sequence by + proposing each label as a premise-hypothesis pairing. + + ## Options + + * `:top_k` - the number of top predictions to include in the output. If + the configured value is higher than the number of labels, all + labels are returned. Defaults to `5` + + * `:hypothesis_template` - an arity-1 function which accepts a label + and returns a hypothesis. The default hypothesis format is: "This example + is #\{label\}". + + * `:compile` - compiles all computations for predefined input shapes + during serving initialization. Should be a keyword list with the + following keys: + + * `:batch_size` - the maximum batch size of the input. Inputs + are optionally padded to always match this batch size. Note + that the batch size refers to the number of prompts to classify, + while the model prediction is made for every combination of + prompt and label + + * `:sequence_length` - the maximum input sequence length. Input + sequences are always padded/truncated to match that length. + A list can be given, in which case the serving compiles + a separate computation for each length and then inputs are + matched to the smallest bounding length + + It is advised to set this option in production and also configure + a defn compiler using `:defn_options` to maximally reduce inference + time. + + * `:defn_options` - the options for JIT compilation. Defaults to `[]` + + * `:preallocate_params` - when `true`, explicitly allocates params + on the device configured by `:defn_options`. You may want to set + this option when using partitioned serving, to allocate params + on each of the devices. When using this option, you should first + load the parameters into the host. This can be done by passing + `backend: {EXLA.Backend, client: :host}` to `load_model/1` and friends. + Defaults to `false` + + ## Examples + + {:ok, model} = Bumblebee.load_model({:hf, "facebook/bart-large-mnli"}) + {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "facebook/bart-large-mnli"}) + + labels = ["cooking", "traveling", "dancing"] + zero_shot_serving = Bumblebee.Text.zero_shot_classification(model, tokenizer, labels) + + output = Nx.Serving.run(zero_shot_serving, "One day I will see the world") + #=> %{ + #=> predictions: [ + #=> %{label: "cooking", score: 0.0070497458800673485}, + #=> %{label: "traveling", score: 0.985000491142273}, + #=> %{label: "dancing", score: 0.007949736900627613} + #=> ] + #=> } + + """ + @spec zero_shot_classification( + Bumblebee.model_info(), + Bumblebee.Tokenizer.t(), + list(String.t()), + keyword() + ) :: Nx.Serving.t() + defdelegate zero_shot_classification(model_info, tokenizer, labels, opts \\ []), + to: Bumblebee.Text.ZeroShotClassification +end diff --git a/deps/bumblebee/lib/bumblebee/text/albert.ex b/deps/bumblebee/lib/bumblebee/text/albert.ex new file mode 100644 index 0000000000000000000000000000000000000000..31a48ec1247baa4dc5a0551530ca993d0cf8d923 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/albert.ex @@ -0,0 +1,531 @@ +defmodule Bumblebee.Text.Albert do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 30000, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 512, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + max_token_types: [ + default: 2, + doc: """ + the vocabulary size of the token type embedding (also referred to as segment embedding). + This corresponds to how many different token groups can be distinguished in the input + """ + ], + embedding_size: [ + default: 128, + doc: "the dimensionality of all input embeddings" + ], + hidden_size: [ + default: 768, + doc: "the dimensionality of hidden layers" + ], + num_blocks: [ + default: 12, + doc: """ + the number of blocks in the encoder. Note that each block contains `:block_depth` + Transformer blocks + """ + ], + num_groups: [ + default: 1, + doc: "the number of groups of encoder blocks. Parameters in the same group are shared" + ], + block_depth: [ + default: 1, + doc: "the number of Transformer blocks in each encoder block" + ], + num_attention_heads: [ + default: 12, + doc: "the number of attention heads for each attention layer in the encoder" + ], + intermediate_size: [ + default: 16384, + doc: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder" + ], + activation: [ + default: :gelu, + doc: "the activation function" + ], + dropout_rate: [ + default: 0.0, + doc: "the dropout rate for embedding and encoder" + ], + attention_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for attention weights" + ], + classifier_dropout_rate: [ + default: nil, + doc: + "the dropout rate for the classification head. If not specified, the value of `:dropout_rate` is used instead" + ], + layer_norm_epsilon: [ + default: 1.0e-12, + doc: "the epsilon used by the layer normalization layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] ++ Shared.common_options([:num_labels, :id_to_label]) + + @moduledoc """ + ALBERT model family. + + ## Architectures + + * `:base` - plain ALBERT without any head on top + + * `:for_masked_language_modeling` - ALBERT with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_sequence_classification` - ALBERT with a sequence + classification head. The head returns logits corresponding to + possible classes + + * `:for_token_classification` - ALBERT with a token classification + head. The head returns logits for each token in the original + sequence + + * `:for_question_answering` - ALBERT with a span classification head. + The head returns logits for the span start and end positions + + * `:for_multiple_choice` - ALBERT with a multiple choice prediction + head. Each input in the batch consists of several sequences to + choose from and the model returns logits corresponding to those + choices + + * `:for_pre_training` - ALBERT with both MLM and NSP heads as done + during the pre-training + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"token_type_ids"` - `{batch_size, sequence_length}` + + Mask distinguishing groups in the input sequence. This is used + in when the input sequence is a semantically a pair of sequences. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + ### Exceptions + + The `:for_multiple_choice` model accepts groups of sequences, so the + expected sequence shape is `{batch_size, num_choices, sequence_length}`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + + ## References + + * [ALBERT: A Lite BERT for Self-supervised Learning of Language Representations](https://arxiv.org/abs/1909.11942) + + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_masked_language_modeling, + :for_sequence_classification, + :for_token_classification, + :for_question_answering, + :for_multiple_choice, + :for_pre_training + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(%{architecture: :for_multiple_choice}) do + %{"input_ids" => Nx.template({1, 1, 1}, :u32)} + end + + def input_template(_spec) do + %{"input_ids" => Nx.template({1, 1}, :u32)} + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs() + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_masked_language_modeling} = spec) do + outputs = core(inputs(), spec) + + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_sequence_classification} = spec) do + outputs = core(inputs(), spec) + + logits = + outputs.pooled_state + |> Axon.dropout( + rate: classifier_dropout_rate(spec), + name: "sequence_classification_head.dropout" + ) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "sequence_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_token_classification} = spec) do + outputs = core(inputs(), spec) + + logits = + outputs.hidden_state + |> Axon.dropout( + rate: classifier_dropout_rate(spec), + name: "token_classification_head.dropout" + ) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "token_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_question_answering} = spec) do + outputs = core(inputs(), spec) + + logits = + Axon.dense(outputs.hidden_state, 2, + kernel_initializer: kernel_initializer(spec), + name: "question_answering_head.output" + ) + + start_logits = Axon.nx(logits, & &1[[.., .., 0]]) + end_logits = Axon.nx(logits, & &1[[.., .., 1]]) + + Layers.output(%{ + start_logits: start_logits, + end_logits: end_logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_multiple_choice} = spec) do + inputs = inputs({nil, nil, nil}) + + group_inputs = ["input_ids", "attention_mask", "token_type_ids", "position_ids"] + + flat_inputs = + Enum.reduce(group_inputs, inputs, fn name, inputs -> + Map.update!(inputs, name, &Layers.flatten_leading/1) + end) + + outputs = core(flat_inputs, spec) + + logits = + outputs.pooled_state + |> Axon.dropout(rate: classifier_dropout_rate(spec), name: "multiple_choice_head.dropout") + |> Axon.dense(1, + kernel_initializer: kernel_initializer(spec), + name: "multiple_choice_head.output" + ) + + # The final shape depends on the dynamic batch size and number + # of choices, so we do a custom reshape at runtime + logits = + Axon.layer( + fn logits, input_ids, _opts -> + num_choices = Nx.axis_size(input_ids, 1) + Nx.reshape(logits, {:auto, num_choices}) + end, + [logits, inputs["input_ids"]] + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + defp inputs(shape \\ {nil, nil}) do + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", shape: shape), + Axon.input("attention_mask", shape: shape, optional: true), + Axon.input("token_type_ids", shape: shape, optional: true), + Axon.input("position_ids", shape: shape, optional: true) + ]) + end + + defp core(inputs, spec, opts \\ []) do + name = opts[:name] + + embeddings = + embedder(inputs["input_ids"], inputs["position_ids"], inputs["token_type_ids"], spec, + name: "embedder" + ) + + {hidden_state, hidden_states, attentions} = + encoder(embeddings, inputs["attention_mask"], spec, name: join(name, "encoder")) + + pooled_state = pooler(hidden_state, spec, name: join(name, "pooler")) + + %{ + hidden_state: hidden_state, + pooled_state: pooled_state, + hidden_states: hidden_states, + attentions: attentions + } + end + + defp embedder(input_ids, position_ids, token_type_ids, spec, opts) do + name = opts[:name] + + position_ids = + Layers.default position_ids do + Layers.default_position_ids(input_ids) + end + + token_type_ids = + Layers.default token_type_ids do + Layers.default_token_type_ids(input_ids) + end + + inputs_embeddings = + Axon.embedding(input_ids, spec.vocab_size, spec.embedding_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "token_embedding") + ) + + position_embeddings = + Axon.embedding(position_ids, spec.max_positions, spec.embedding_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "position_embedding") + ) + + token_type_embeddings = + Axon.embedding(token_type_ids, spec.max_token_types, spec.embedding_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "token_type_embedding") + ) + + Axon.add([inputs_embeddings, position_embeddings, token_type_embeddings]) + |> Axon.layer_norm(epsilon: spec.layer_norm_epsilon, name: join(name, "norm")) + |> Axon.dropout(rate: spec.dropout_rate, name: join(name, "dropout")) + end + + defp encoder(hidden_state, attention_mask, spec, opts) do + name = opts[:name] + + hidden_state = + Axon.dense(hidden_state, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "embedding_projection") + ) + + hidden_states = Axon.container({hidden_state}) + attentions = Axon.container({}) + + for block_idx <- 0..(spec.num_blocks - 1), + inner_idx <- 0..(spec.block_depth - 1), + reduce: {hidden_state, hidden_states, attentions} do + {hidden_state, hidden_states, attentions} -> + group_idx = div(block_idx, div(spec.num_blocks, spec.num_groups)) + + name = name |> join("groups") |> join(group_idx) |> join("blocks") |> join(inner_idx) + + # TODO: wrap encoder block in a layer_drop combinator + {hidden_state, attention, _cross_attention, _block_cache, _position_bias} = + Layers.Transformer.block(hidden_state, + attention_mask: attention_mask, + num_attention_heads: spec.num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: spec.layer_norm_epsilon + ], + ffn: [ + intermediate_size: spec.intermediate_size, + activation: spec.activation + ], + name: name + ) + + { + hidden_state, + Layers.append(hidden_states, hidden_state), + Layers.append(attentions, attention) + } + end + end + + defp pooler(hidden_state, spec, opts) do + name = opts[:name] + + hidden_state + |> Layers.take_token(axis: 1) + |> Axon.dense(spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + |> Axon.tanh(name: join(name, "tanh")) + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: use a shared parameter with embeddings.word_embeddings.kernel + # if spec.tie_word_embeddings is true (relevant for training) + + hidden_state + |> Axon.dense(spec.embedding_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "dense") + ) + |> Layers.activation(spec.activation, name: join(name, "activation")) + |> Axon.layer_norm(epsilon: spec.layer_norm_epsilon, name: join(name, "norm")) + # We reuse the kernel of input embeddings and add bias for each token + |> Layers.dense_transposed(spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + end + + defp classifier_dropout_rate(spec) do + spec.classifier_dropout_rate || spec.dropout_rate + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"max_position_embeddings", number()}, + max_token_types: {"type_vocab_size", number()}, + embedding_size: {"embedding_size", number()}, + hidden_size: {"hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_groups: {"num_hidden_groups", number()}, + block_depth: {"inner_group_num", number()}, + num_attention_heads: {"num_attention_heads", number()}, + intermediate_size: {"intermediate_size", number()}, + activation: {"hidden_act", activation()}, + dropout_rate: {"hidden_dropout_prob", number()}, + attention_dropout_rate: {"attention_probs_dropout_prob", number()}, + classifier_dropout_rate: {"classifier_dropout_prob", optional(number())}, + layer_norm_epsilon: {"layer_norm_eps", number()}, + initializer_scale: {"initializer_range", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.token_embedding" => "albert.embeddings.word_embeddings", + "embedder.position_embedding" => "albert.embeddings.position_embeddings", + "embedder.token_type_embedding" => "albert.embeddings.token_type_embeddings", + "embedder.norm" => "albert.embeddings.LayerNorm", + "encoder.embedding_projection" => "albert.encoder.embedding_hidden_mapping_in", + "encoder.groups.{n}.blocks.{m}.self_attention.query" => + "albert.encoder.albert_layer_groups.{n}.albert_layers.{m}.attention.query", + "encoder.groups.{n}.blocks.{m}.self_attention.key" => + "albert.encoder.albert_layer_groups.{n}.albert_layers.{m}.attention.key", + "encoder.groups.{n}.blocks.{m}.self_attention.value" => + "albert.encoder.albert_layer_groups.{n}.albert_layers.{m}.attention.value", + "encoder.groups.{n}.blocks.{m}.self_attention.output" => + "albert.encoder.albert_layer_groups.{n}.albert_layers.{m}.attention.dense", + "encoder.groups.{n}.blocks.{m}.self_attention_norm" => + "albert.encoder.albert_layer_groups.{n}.albert_layers.{m}.attention.LayerNorm", + "encoder.groups.{n}.blocks.{m}.ffn.intermediate" => + "albert.encoder.albert_layer_groups.{n}.albert_layers.{m}.ffn", + "encoder.groups.{n}.blocks.{m}.ffn.output" => + "albert.encoder.albert_layer_groups.{n}.albert_layers.{m}.ffn_output", + "encoder.groups.{n}.blocks.{m}.output_norm" => + "albert.encoder.albert_layer_groups.{n}.albert_layers.{m}.full_layer_layer_norm", + "pooler.output" => "albert.pooler", + "language_modeling_head.dense" => "predictions.dense", + "language_modeling_head.norm" => "predictions.LayerNorm", + "language_modeling_head.output" => "predictions.decoder", + "sequence_classification_head.output" => "classifier", + "token_classification_head.output" => "classifier", + "multiple_choice_head.output" => "classifier", + "question_answering_head.output" => "qa_outputs" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/bart.ex b/deps/bumblebee/lib/bumblebee/text/bart.ex new file mode 100644 index 0000000000000000000000000000000000000000..b0e4e272a0dd44ae7d1f09727d29f3ba1da72e24 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/bart.ex @@ -0,0 +1,702 @@ +defmodule Bumblebee.Text.Bart do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 50265, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 1024, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + hidden_size: [ + default: 1024, + doc: "the dimensionality of hidden layers" + ], + encoder_num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the encoder" + ], + decoder_num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the decoder" + ], + encoder_num_attention_heads: [ + default: 16, + doc: "the number of attention heads for each attention layer in the encoder" + ], + decoder_num_attention_heads: [ + default: 16, + doc: "the number of attention heads for each attention layer in the decoder" + ], + encoder_intermediate_size: [ + default: 4096, + docs: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder" + ], + decoder_intermediate_size: [ + default: 4096, + docs: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the decoder" + ], + scale_embedding: [ + default: false, + doc: "whether to scale embeddings by dividing by the square root of `:hidden_size`" + ], + activation: [ + default: :gelu, + doc: "the activation function" + ], + dropout_rate: [ + default: 0.1, + doc: "the dropout rate for encoder and decoder" + ], + attention_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for attention weights" + ], + activation_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for activations inside fully connected layers" + ], + classifier_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for the classification head" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] ++ + Shared.common_options([:num_labels, :id_to_label]) ++ + Shared.token_options( + eos_token_id: 2, + decoder_start_token_id: 2 + ) + + @moduledoc """ + BART model family. + + ## Architectures + + * `:base` - plain BART without any head on top + + * `:for_causal_language_modeling` - BART with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_conditional_generation` - BART with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_sequence_classification` - BART with a sequence + classification head. The head returns logits corresponding to + possible classes + + * `:for_question_answering` - BART with a span classification head. + The head returns logits for the span start and end positions + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{encoder_num_blocks, encoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + * `"input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"input_ids"`, which can be specified + for more control over how `"input_ids"` are embedded than the + model's internal embedding lookup. If `"input_embeddings"` are present, + then `"input_ids"` will be ignored. + + * `"decoder_input_ids"` - `{batch_size, target_sequence_length}` + + Indices of decoder input sequence tokens in the vocabulary. If not + present and `"input_ids"` is, it will be generated by shifting + each token in `"input_ids"` to the right once. + + * `"decoder_attention_mask"` - `{batch_size, target_sequence_length}` + + Mask indicating which decoder tokens to attend to. This is used + to ignore padding tokens, which are added when processing a batch + of sequences with different length. + + * `"decoder_position_ids"` - `{batch_size, target_sequence_length}` + + Indices of positions of each decoder input sequence tokens in + the position embeddings. + + * `"decoder_attention_head_mask"` - `{decoder_num_blocks, decoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the decoder. + + * `"decoder_input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"decoder_input_ids"`, which can be + specified for more control over how `"decoder_input_ids"` are + embedded than the model's internal embedding lookup. If + `"decoder_input_embeddings"` are present, then `"decoder_input_ids"` + will be ignored. + + * `"encoder_hidden_state"` - `{batch_size, sequence_length, hidden_size}` + + Last hidden state output from the encoder. This hidden state is + used in cross-attention blocks in the decoder. If specified, the + model will skip the encoding process and use this value directly + for cross-attentions in the decoder. + + * `"cross_attention_head_mask"` - `{decoder_num_blocks, decoder_num_attention_heads}` + + Mask to nullify selected heads of the cross-attention blocks in + the decoder with shape. + + * `"cache"` + + A container with cached layer results used to speed up sequential + decoding (autoregression). With cache, certain hidden states are + taken from the cache, rather than recomputed on every decoding + pass. The cache should be treated as opaque and initialized with + `Bumblebee.Text.Generation.init_cache/4`. + + ### Exceptions + + The `:for_causal_language_modeling` model is just the decoder part and + accepts the following inputs instead: `"input_ids"`, `"attention_mask"`, + `"position_ids"`, `"attention_head_mask"`, `"input_embeddings"`, `"encoder_hidden_state"`, + `"encoder_attention_mask"`, `"cross_attention_head_mask"`, `"cache"`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_causal_language_modeling, + :for_conditional_generation, + :for_sequence_classification, + :for_question_answering + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(_spec) do + %{ + "input_ids" => Nx.template({1, 1}, :u32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = encoder_decoder_inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_conditional_generation} = spec) do + inputs = encoder_decoder_inputs(spec) + outputs = core(inputs, spec) + + logits = + outputs.hidden_state + |> language_modeling_head(spec, name: "language_modeling_head") + |> Axon.bias(name: "language_modeling_head.logits_bias", bias_initializer: :zeros) + + Layers.output(%{ + logits: logits, + decoder_hidden_states: outputs.decoder_hidden_states, + decoder_attentions: outputs.decoder_attentions, + cross_attentions: outputs.cross_attentions, + encoder_hidden_state: outputs.encoder_hidden_state, + encoder_hidden_states: outputs.encoder_hidden_states, + encoder_attentions: outputs.encoder_attentions, + cache: outputs.cache + }) + end + + def model(%__MODULE__{architecture: :for_sequence_classification} = spec) do + inputs = encoder_decoder_inputs(spec) + outputs = core(inputs, spec) + + sentence_representation = + Axon.layer( + fn input_ids, hidden_state, _opts -> + eos_mask = Nx.equal(input_ids, spec.eos_token_id) + eos_idx = Nx.argmax(eos_mask, tie_break: :high, axis: 1) + Bumblebee.Utils.Nx.batched_take(hidden_state, eos_idx) + end, + [inputs["input_ids"], outputs.hidden_state] + ) + + logits = + sentence_representation + |> Axon.dropout(rate: spec.classifier_dropout_rate) + |> Axon.dense(spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: "sequence_classification_head.dense" + ) + |> Axon.activation(:tanh) + |> Axon.dropout(rate: spec.classifier_dropout_rate) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "sequence_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + decoder_hidden_states: outputs.decoder_hidden_states, + decoder_attentions: outputs.decoder_attentions, + cross_attentions: outputs.cross_attentions, + encoder_hidden_state: outputs.encoder_hidden_state, + encoder_hidden_states: outputs.encoder_hidden_states, + encoder_attentions: outputs.encoder_attentions + }) + end + + def model(%__MODULE__{architecture: :for_question_answering} = spec) do + inputs = encoder_decoder_inputs(spec) + outputs = core(inputs, spec) + + logits = + Axon.dense(outputs.hidden_state, 2, + kernel_initializer: kernel_initializer(spec), + name: "question_answering_head.output" + ) + + {start_logits, end_logits} = Layers.split_pair(logits) + + Layers.output(%{ + start_logits: start_logits, + end_logits: end_logits, + decoder_hidden_states: outputs.decoder_hidden_states, + decoder_attentions: outputs.decoder_attentions, + cross_attentions: outputs.cross_attentions, + encoder_hidden_state: outputs.encoder_hidden_state, + encoder_hidden_states: outputs.encoder_hidden_states, + encoder_attentions: outputs.encoder_attentions + }) + end + + def model(%__MODULE__{architecture: :for_causal_language_modeling} = spec) do + shape = {nil, nil} + hidden_shape = {nil, nil, spec.hidden_size} + + decoder_attention_head_mask_shape = + {spec.decoder_num_blocks, spec.decoder_num_attention_heads} + + inputs = + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("input_embeddings", optional: true, shape: hidden_shape), + Axon.input("encoder_hidden_state", optional: true, shape: hidden_shape), + Axon.input("encoder_attention_mask", optional: true, shape: shape), + Axon.input("cross_attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("cache", optional: true) + ]) + + embeddings = + embedder(inputs["input_ids"], inputs["position_ids"], inputs["input_embeddings"], spec, + name: "decoder_embedder" + ) + + outputs = + decoder( + embeddings, + inputs["attention_mask"], + inputs["attention_head_mask"], + inputs["encoder_hidden_state"], + inputs["encoder_attention_mask"], + inputs["cross_attention_head_mask"], + inputs["cache"], + spec, + name: "decoder" + ) + + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cross_attentions: outputs.cross_attentions, + cache: outputs.cache + }) + end + + defp encoder_decoder_inputs(spec) do + shape = {nil, nil} + hidden_shape = {nil, nil, spec.hidden_size} + + encoder_attention_head_mask_shape = + {spec.encoder_num_blocks, spec.encoder_num_attention_heads} + + decoder_attention_head_mask_shape = + {spec.decoder_num_blocks, spec.decoder_num_attention_heads} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: encoder_attention_head_mask_shape), + Axon.input("input_embeddings", optional: true, shape: hidden_shape), + Axon.input("decoder_input_ids", optional: true, shape: shape), + Axon.input("decoder_attention_mask", optional: true, shape: shape), + Axon.input("decoder_position_ids", optional: true, shape: shape), + Axon.input("decoder_attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("decoder_input_embeddings", optional: true, shape: hidden_shape), + Axon.input("encoder_hidden_state", optional: true, shape: hidden_shape), + Axon.input("cross_attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("cache", optional: true) + ]) + end + + @impl true + def init_cache(spec, batch_size, max_length, inputs) do + encoder_sequence_length = + if encoder_hidden_state = inputs["encoder_hidden_state"] do + Nx.axis_size(encoder_hidden_state, 1) + end + + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + decoder_num_attention_heads: spec.decoder_num_attention_heads, + encoder_num_attention_heads: spec.encoder_num_attention_heads, + decoder_num_blocks: spec.decoder_num_blocks, + encoder_sequence_length: encoder_sequence_length + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + defp core(inputs, spec) do + encoder_outputs = + Layers.if_present inputs["encoder_hidden_state"] do + %{ + hidden_state: inputs["encoder_hidden_state"], + hidden_states: Layers.none(), + attentions: Layers.none() + } + else + embeddings = + embedder(inputs["input_ids"], inputs["position_ids"], inputs["input_embeddings"], spec, + name: "encoder_embedder" + ) + + embeddings + |> encoder(inputs["attention_mask"], inputs["attention_head_mask"], spec, name: "encoder") + |> Map.take([:hidden_state, :hidden_states, :attentions]) + end + + decoder_input_ids = + Layers.default inputs["decoder_input_ids"] do + Layers.shift_tokens_right(inputs["input_ids"], spec.decoder_start_token_id) + end + + embeddings = + embedder( + decoder_input_ids, + inputs["decoder_position_ids"], + inputs["decoder_input_embeddings"], + spec, + name: "decoder_embedder" + ) + + decoder_outputs = + decoder( + embeddings, + inputs["decoder_attention_mask"], + inputs["decoder_attention_head_mask"], + encoder_outputs.hidden_state, + inputs["attention_mask"], + inputs["cross_attention_head_mask"], + inputs["cache"], + spec, + name: "decoder" + ) + + %{ + hidden_state: decoder_outputs.hidden_state, + decoder_hidden_states: decoder_outputs.hidden_states, + decoder_attentions: decoder_outputs.attentions, + cross_attentions: decoder_outputs.cross_attentions, + cache: decoder_outputs.cache, + encoder_hidden_state: encoder_outputs.hidden_state, + encoder_hidden_states: encoder_outputs.hidden_states, + encoder_attentions: encoder_outputs.attentions + } + end + + defp embedder(input_ids, position_ids, input_embeddings, spec, opts) do + name = opts[:name] + + input_embeddings = + Layers.default input_embeddings do + token_embedding(input_ids, spec, name: join(name, "token_embedding")) + end + + position_ids = + Layers.default position_ids do + Layers.default_position_ids(input_embeddings) + end + + position_embeddings = + position_embedding(position_ids, spec, name: join(name, "position_embedding")) + + Axon.add([input_embeddings, position_embeddings]) + |> Axon.layer_norm(epsilon: 1.0e-5, name: join(name, "norm")) + |> Axon.dropout(rate: spec.dropout_rate) + end + + defp token_embedding(input_ids, spec, opts) do + name = opts[:name] + + input_embeddings = + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: name + ) + + if spec.scale_embedding do + Axon.nx(input_embeddings, fn x -> Nx.multiply(x, Nx.sqrt(spec.hidden_size)) end) + else + input_embeddings + end + end + + defp position_embedding(position_ids, spec, opts) do + name = opts[:name] + + # For BART we need to offset the embeddings + offset = 2 + + position_ids + |> Axon.add(Axon.constant(Nx.tensor(offset))) + |> Axon.embedding(spec.max_positions + offset, spec.hidden_size, name: name) + end + + defp encoder(hidden_state, attention_mask, attention_head_mask, spec, opts) do + name = opts[:name] + + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + num_blocks: spec.encoder_num_blocks, + num_attention_heads: spec.encoder_num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: 1.0e-5 + ], + ffn: [ + intermediate_size: spec.encoder_intermediate_size, + activation: spec.activation + ], + name: join(name, "blocks") + ) + end + + defp decoder( + hidden_state, + attention_mask, + attention_head_mask, + encoder_hidden_state, + encoder_attention_mask, + cross_attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + cross_hidden_state: encoder_hidden_state, + cross_attention_mask: encoder_attention_mask, + cross_attention_head_mask: cross_attention_head_mask, + cache: cache, + causal: true, + num_blocks: spec.decoder_num_blocks, + num_attention_heads: spec.decoder_num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: 1.0e-5 + ], + ffn: [ + intermediate_size: spec.decoder_intermediate_size, + activation: spec.activation + ], + name: join(name, "blocks") + ) + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: Tie lm-head to word embedding as a spec option + Layers.dense_transposed(hidden_state, spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"max_position_embeddings", number()}, + hidden_size: {"d_model", number()}, + encoder_num_blocks: {"encoder_layers", number()}, + decoder_num_blocks: {"decoder_layers", number()}, + encoder_num_attention_heads: {"encoder_attention_heads", number()}, + decoder_num_attention_heads: {"decoder_attention_heads", number()}, + encoder_intermediate_size: {"encoder_ffn_dim", number()}, + decoder_intermediate_size: {"decoder_ffn_dim", number()}, + scale_embedding: {"scale_embedding", boolean()}, + activation: {"activation_function", activation()}, + dropout_rate: {"dropout", number()}, + attention_dropout_rate: {"attention_dropout", number()}, + activation_dropout_rate: {"activation_dropout", number()}, + classifier_dropout_rate: {"classifier_dropout", number()}, + initializer_scale: {"init_std", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(spec) do + %{ + "encoder_embedder.token_embedding" => "model.encoder.embed_tokens", + "encoder_embedder.position_embedding" => "model.encoder.embed_positions", + "encoder_embedder.norm" => "model.encoder.layernorm_embedding", + "encoder.blocks.{n}.self_attention.query" => "model.encoder.layers.{n}.self_attn.q_proj", + "encoder.blocks.{n}.self_attention.key" => "model.encoder.layers.{n}.self_attn.k_proj", + "encoder.blocks.{n}.self_attention.value" => "model.encoder.layers.{n}.self_attn.v_proj", + "encoder.blocks.{n}.self_attention.output" => + "model.encoder.layers.{n}.self_attn.out_proj", + "encoder.blocks.{n}.self_attention_norm" => + "model.encoder.layers.{n}.self_attn_layer_norm", + "encoder.blocks.{n}.ffn.intermediate" => "model.encoder.layers.{n}.fc1", + "encoder.blocks.{n}.ffn.output" => "model.encoder.layers.{n}.fc2", + "encoder.blocks.{n}.output_norm" => "model.encoder.layers.{n}.final_layer_norm", + "decoder_embedder.token_embedding" => "model.decoder.embed_tokens", + "decoder_embedder.position_embedding" => "model.decoder.embed_positions", + "decoder_embedder.norm" => "model.decoder.layernorm_embedding", + "decoder.blocks.{n}.self_attention.query" => "model.decoder.layers.{n}.self_attn.q_proj", + "decoder.blocks.{n}.self_attention.key" => "model.decoder.layers.{n}.self_attn.k_proj", + "decoder.blocks.{n}.self_attention.value" => "model.decoder.layers.{n}.self_attn.v_proj", + "decoder.blocks.{n}.self_attention.output" => + "model.decoder.layers.{n}.self_attn.out_proj", + "decoder.blocks.{n}.self_attention_norm" => + "model.decoder.layers.{n}.self_attn_layer_norm", + "decoder.blocks.{n}.cross_attention.query" => + "model.decoder.layers.{n}.encoder_attn.q_proj", + "decoder.blocks.{n}.cross_attention.key" => + "model.decoder.layers.{n}.encoder_attn.k_proj", + "decoder.blocks.{n}.cross_attention.value" => + "model.decoder.layers.{n}.encoder_attn.v_proj", + "decoder.blocks.{n}.cross_attention.output" => + "model.decoder.layers.{n}.encoder_attn.out_proj", + "decoder.blocks.{n}.cross_attention_norm" => + "model.decoder.layers.{n}.encoder_attn_layer_norm", + "decoder.blocks.{n}.ffn.intermediate" => "model.decoder.layers.{n}.fc1", + "decoder.blocks.{n}.ffn.output" => "model.decoder.layers.{n}.fc2", + "decoder.blocks.{n}.output_norm" => "model.decoder.layers.{n}.final_layer_norm", + "language_modeling_head.output" => + case spec.architecture do + :for_causal_language_modeling -> "lm_head" + _other -> "model.shared" + end, + "language_modeling_head.logits_bias" => %{ + "bias" => {[{"model", "final_logits_bias"}], fn [value] -> Nx.squeeze(value) end} + }, + "sequence_classification_head.dense" => "classification_head.dense", + "sequence_classification_head.output" => "classification_head.out_proj", + "question_answering_head.output" => "qa_outputs" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/bert.ex b/deps/bumblebee/lib/bumblebee/text/bert.ex new file mode 100644 index 0000000000000000000000000000000000000000..775fb45996db11c43a3e8e3aee0ebfab0094519b --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/bert.ex @@ -0,0 +1,658 @@ +defmodule Bumblebee.Text.Bert do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 30522, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 512, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + max_token_types: [ + default: 2, + doc: """ + the vocabulary size of the token type embedding (also referred to as segment embedding). + This corresponds to how many different token groups can be distinguished in the input + """ + ], + hidden_size: [ + default: 768, + doc: "the dimensionality of hidden layers" + ], + num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the encoder" + ], + num_attention_heads: [ + default: 12, + doc: "the number of attention heads for each attention layer in the encoder" + ], + intermediate_size: [ + default: 3072, + doc: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder" + ], + activation: [ + default: :gelu, + doc: "the activation function" + ], + dropout_rate: [ + default: 0.1, + doc: "the dropout rate for embedding and encoder" + ], + attention_dropout_rate: [ + default: 0.1, + doc: "the dropout rate for attention weights" + ], + classifier_dropout_rate: [ + default: nil, + doc: + "the dropout rate for the classification head. If not specified, the value of `:dropout_rate` is used instead" + ], + layer_norm_epsilon: [ + default: 1.0e-12, + doc: "the epsilon used by the layer normalization layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] ++ Shared.common_options([:use_cross_attention, :num_labels, :id_to_label]) + + @moduledoc """ + BERT model family. + + ## Architectures + + * `:base` - plain BERT without any head on top + + * `:for_masked_language_modeling` - BERT with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_sequence_classification` - BERT with a sequence + classification head. The head returns logits corresponding to + possible classes + + * `:for_token_classification` - BERT with a token classification + head. The head returns logits for each token in the original + sequence + + * `:for_question_answering` - BERT with a span classification head. + The head returns logits for the span start and end positions + + * `:for_multiple_choice` - BERT with a multiple choice prediction + head. Each input in the batch consists of several sequences to + choose from and the model returns logits corresponding to those + choices + + * `:for_next_sentence_prediction` - BERT with a next sentence + prediction head. The head returns logits predicting whether the + second sentence is random or in context + + * `:for_pre_training` - BERT with both MLM and NSP heads as done + during the pre-training + + * `:for_causal_language_modeling` - BERT working as a decoder with + a language modeling head. The head returns logits for each token + in the original sequence + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"token_type_ids"` - `{batch_size, sequence_length}` + + Mask distinguishing groups in the input sequence. This is used + in when the input sequence is a semantically a pair of sequences. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{num_blocks, num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + ### Exceptions + + The `:for_multiple_choice` model accepts groups of sequences, so the + expected sequence shape is `{batch_size, num_choices, sequence_length}`. + + The `:for_causal_language_modeling` model is a decoder and accepts + the following additional inputs: `"encoder_hidden_state"`, + `"encoder_attention_mask"`, `"cross_attention_head_mask"`, `"cache"`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + + ## References + + * [BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805) + + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_masked_language_modeling, + :for_sequence_classification, + :for_token_classification, + :for_question_answering, + :for_multiple_choice, + :for_next_sentence_prediction, + :for_pre_training, + :for_causal_language_modeling + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(%{architecture: :for_multiple_choice}) do + %{"input_ids" => Nx.template({1, 1, 1}, :u32)} + end + + def input_template(_spec) do + %{"input_ids" => Nx.template({1, 1}, :u32)} + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_masked_language_modeling} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_sequence_classification} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + outputs.pooled_state + |> Axon.dropout( + rate: classifier_dropout_rate(spec), + name: "sequence_classification_head.dropout" + ) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "sequence_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_token_classification} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + outputs.hidden_state + |> Axon.dropout( + rate: classifier_dropout_rate(spec), + name: "token_classification_head.dropout" + ) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "token_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_question_answering} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + Axon.dense(outputs.hidden_state, 2, + kernel_initializer: kernel_initializer(spec), + name: "question_answering_head.output" + ) + + {start_logits, end_logits} = Layers.split_pair(logits) + + Layers.output(%{ + start_logits: start_logits, + end_logits: end_logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_multiple_choice} = spec) do + inputs = inputs(spec, shape: {nil, nil, nil}) + + group_inputs = ["input_ids", "attention_mask", "token_type_ids", "position_ids"] + + flat_inputs = + Enum.reduce(group_inputs, inputs, fn name, inputs -> + Map.update!(inputs, name, &Layers.flatten_leading/1) + end) + + outputs = core(flat_inputs, spec) + + logits = + outputs.pooled_state + |> Axon.dropout(rate: classifier_dropout_rate(spec), name: "multiple_choice_head.dropout") + |> Axon.dense(1, + kernel_initializer: kernel_initializer(spec), + name: "multiple_choice_head.output" + ) + + # The final shape depends on the dynamic batch size and number + # of choices, so we do a reshape based on the input shape + logits = + Axon.layer( + fn logits, input_ids, _opts -> + num_choices = Nx.axis_size(input_ids, 1) + Nx.reshape(logits, {:auto, num_choices}) + end, + [logits, inputs["input_ids"]] + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_next_sentence_prediction} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + Axon.dense(outputs.pooled_state, 2, + kernel_initializer: kernel_initializer(spec), + name: "next_sentence_prediction_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_pre_training} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + lm_logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + nsp_logits = + Axon.dense(outputs.pooled_state, 2, + kernel_initializer: kernel_initializer(spec), + name: "next_sentence_prediction_head.output" + ) + + Layers.output(%{ + language_modeling_logits: lm_logits, + next_sentence_prediction_logits: nsp_logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_causal_language_modeling} = spec) do + inputs = inputs(spec, decoder?: true) + outputs = core(inputs, spec, decoder?: true) + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cross_attentions: outputs.cross_attentions, + cache: outputs.cache + }) + end + + @impl true + def init_cache(spec, batch_size, max_length, inputs) do + encoder_sequence_length = + if encoder_hidden_state = inputs["encoder_hidden_state"] do + Nx.axis_size(encoder_hidden_state, 1) + end + + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + decoder_num_attention_heads: spec.num_attention_heads, + encoder_num_attention_heads: spec.num_attention_heads, + decoder_num_blocks: spec.num_blocks, + encoder_sequence_length: encoder_sequence_length + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + defp inputs(spec, opts \\ []) do + shape = Keyword.get(opts, :shape, {nil, nil}) + decoder? = Keyword.get(opts, :decoder?, false) + + hidden_shape = Tuple.insert_at(shape, tuple_size(shape), spec.hidden_size) + attention_head_mask_shape = {spec.num_blocks, spec.num_attention_heads} + + inputs = + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("token_type_ids", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: attention_head_mask_shape) + ]) + + extra_decoder_inputs = + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("encoder_hidden_state", optional: true, shape: hidden_shape), + Axon.input("encoder_attention_mask", optional: true, shape: shape), + Axon.input("cross_attention_head_mask", optional: true, shape: attention_head_mask_shape), + Axon.input("cache", optional: true) + ]) + + extra_decoder_inputs = + if decoder? do + extra_decoder_inputs + else + Map.new(extra_decoder_inputs, fn {name, _input} -> {name, Layers.none()} end) + end + + Map.merge(inputs, extra_decoder_inputs) + end + + defp core(inputs, spec, opts \\ []) do + decoder? = Keyword.get(opts, :decoder?, false) + + embeddings = + embedder(inputs["input_ids"], inputs["position_ids"], inputs["token_type_ids"], spec, + name: "embedder" + ) + + encoder_outputs = + encoder( + embeddings, + inputs["attention_mask"], + inputs["attention_head_mask"], + inputs["encoder_hidden_state"], + inputs["encoder_attention_mask"], + inputs["cross_attention_head_mask"], + inputs["cache"], + spec, + decoder?: decoder?, + name: "encoder" + ) + + pooled_state = pooler(encoder_outputs.hidden_state, spec, name: "pooler") + + %{ + hidden_state: encoder_outputs.hidden_state, + pooled_state: pooled_state, + hidden_states: encoder_outputs.hidden_states, + attentions: encoder_outputs.attentions, + cross_attentions: encoder_outputs.cross_attentions, + cache: encoder_outputs.cache + } + end + + defp embedder(input_ids, position_ids, token_type_ids, spec, opts) do + name = opts[:name] + + position_ids = + Layers.default position_ids do + Layers.default_position_ids(input_ids) + end + + token_type_ids = + Layers.default token_type_ids do + Layers.default_token_type_ids(input_ids) + end + + inputs_embeddings = + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "token_embedding") + ) + + position_embeddings = + Axon.embedding(position_ids, spec.max_positions, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "position_embedding") + ) + + token_type_embeddings = + Axon.embedding(token_type_ids, spec.max_token_types, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "token_type_embedding") + ) + + Axon.add([inputs_embeddings, position_embeddings, token_type_embeddings]) + |> Axon.layer_norm(epsilon: spec.layer_norm_epsilon, name: join(name, "norm")) + |> Axon.dropout(rate: spec.dropout_rate, name: join(name, "dropout")) + end + + defp encoder( + hidden_state, + attention_mask, + attention_head_mask, + encoder_hidden_state, + encoder_attention_mask, + cross_attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + decoder? = opts[:decoder?] + + cross_attention? = decoder? and spec.use_cross_attention + + Layers.Transformer.blocks( + hidden_state, + [ + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + cache: cache, + causal: decoder?, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: spec.layer_norm_epsilon + ], + ffn: [ + intermediate_size: spec.intermediate_size, + activation: spec.activation + ], + name: join(name, "blocks") + ] ++ + if(cross_attention?, + do: [ + cross_hidden_state: encoder_hidden_state, + cross_attention_mask: encoder_attention_mask, + cross_attention_head_mask: cross_attention_head_mask + ], + else: [] + ) + ) + end + + defp pooler(hidden_state, spec, opts) do + name = opts[:name] + + hidden_state + |> Layers.take_token(index: 0, axis: 1) + |> Axon.dense(spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + |> Axon.tanh() + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: use a shared parameter with embeddings.word_embeddings.kernel + # if spec.tie_word_embeddings is true (relevant for training) + + hidden_state + |> Axon.dense(spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "dense") + ) + |> Layers.activation(spec.activation, name: join(name, "activation")) + |> Axon.layer_norm(epsilon: spec.layer_norm_epsilon, name: join(name, "norm")) + # We reuse the kernel of input embeddings and add bias for each token + |> Layers.dense_transposed(spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + |> Axon.bias(name: join(name, "bias")) + end + + defp classifier_dropout_rate(spec) do + spec.classifier_dropout_rate || spec.dropout_rate + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"max_position_embeddings", number()}, + max_token_types: {"type_vocab_size", number()}, + hidden_size: {"hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_attention_heads: {"num_attention_heads", number()}, + intermediate_size: {"intermediate_size", number()}, + activation: {"hidden_act", activation()}, + dropout_rate: {"hidden_dropout_prob", number()}, + attention_dropout_rate: {"attention_probs_dropout_prob", number()}, + classifier_dropout_rate: {"classifier_dropout", optional(number())}, + layer_norm_epsilon: {"layer_norm_eps", number()}, + initializer_scale: {"initializer_range", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.token_embedding" => "bert.embeddings.word_embeddings", + "embedder.position_embedding" => "bert.embeddings.position_embeddings", + "embedder.token_type_embedding" => "bert.embeddings.token_type_embeddings", + "embedder.norm" => "bert.embeddings.LayerNorm", + "encoder.blocks.{n}.self_attention.query" => + "bert.encoder.layer.{n}.attention.self.query", + "encoder.blocks.{n}.self_attention.key" => "bert.encoder.layer.{n}.attention.self.key", + "encoder.blocks.{n}.self_attention.value" => + "bert.encoder.layer.{n}.attention.self.value", + "encoder.blocks.{n}.self_attention.output" => + "bert.encoder.layer.{n}.attention.output.dense", + "encoder.blocks.{n}.self_attention_norm" => + "bert.encoder.layer.{n}.attention.output.LayerNorm", + "encoder.blocks.{n}.cross_attention.query" => + "bert.encoder.layer.{n}.crossattention.self.query", + "encoder.blocks.{n}.cross_attention.key" => + "bert.encoder.layer.{n}.crossattention.self.key", + "encoder.blocks.{n}.cross_attention.value" => + "bert.encoder.layer.{n}.crossattention.self.value", + "encoder.blocks.{n}.cross_attention.output" => + "bert.encoder.layer.{n}.crossattention.output.dense", + "encoder.blocks.{n}.cross_attention_norm" => + "bert.encoder.layer.{n}.crossattention.output.LayerNorm", + "encoder.blocks.{n}.ffn.intermediate" => "bert.encoder.layer.{n}.intermediate.dense", + "encoder.blocks.{n}.ffn.output" => "bert.encoder.layer.{n}.output.dense", + "encoder.blocks.{n}.output_norm" => "bert.encoder.layer.{n}.output.LayerNorm", + "pooler.output" => "bert.pooler.dense", + "language_modeling_head.dense" => "cls.predictions.transform.dense", + "language_modeling_head.norm" => "cls.predictions.transform.LayerNorm", + "language_modeling_head.output" => "cls.predictions.decoder", + "language_modeling_head.bias" => "cls.predictions", + "next_sentence_prediction_head.output" => "cls.seq_relationship", + "sequence_classification_head.output" => "classifier", + "token_classification_head.output" => "classifier", + "multiple_choice_head.output" => "classifier", + "question_answering_head.output" => "qa_outputs" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/blenderbot.ex b/deps/bumblebee/lib/bumblebee/text/blenderbot.ex new file mode 100644 index 0000000000000000000000000000000000000000..18898e8c047ecbd0778e2fc35aa7148746c884ae --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/blenderbot.ex @@ -0,0 +1,561 @@ +defmodule Bumblebee.Text.Blenderbot do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 8008, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 128, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + hidden_size: [ + default: 2560, + doc: "the dimensionality of hidden layers" + ], + encoder_num_blocks: [ + default: 2, + doc: "the number of Transformer blocks in the encoder" + ], + decoder_num_blocks: [ + default: 24, + doc: "the number of Transformer blocks in the decoder" + ], + encoder_num_attention_heads: [ + default: 32, + doc: "the number of attention heads for each attention layer in the encoder" + ], + decoder_num_attention_heads: [ + default: 32, + doc: "the number of attention heads for each attention layer in the decoder" + ], + encoder_intermediate_size: [ + default: 10240, + docs: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder" + ], + decoder_intermediate_size: [ + default: 10240, + docs: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the decoder" + ], + scale_embedding: [ + default: false, + doc: "whether to scale embeddings by dividing by the square root of `:hidden_size`" + ], + activation: [ + default: :gelu, + doc: "the activation function" + ], + dropout_rate: [ + default: 0.1, + doc: "the dropout rate for encoder and decoder" + ], + attention_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for attention weights" + ], + activation_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for activations inside fully connected layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] ++ + Shared.token_options( + pad_token_id: 0, + bos_token_id: 1, + eos_token_id: 2, + decoder_start_token_id: 1 + ) + + @moduledoc """ + Blenderbot model family. + + ## Architectures + + * `:base` - plain Blenderbot without any head on top + + * `:for_conditional_generation` - Blenderbot with a language modeling + head. The head returns logits for each token in the original + sequence + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{encoder_num_blocks, encoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + * `"input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"input_ids"`, which can be specified + for more control over how `"input_ids"` are embedded than the + model's internal embedding lookup. If `"input_embeddings"` are present, + then `"input_ids"` will be ignored. + + * `"decoder_input_ids"` - `{batch_size, target_sequence_length}` + + Indices of decoder input sequence tokens in the vocabulary. If not + present and `"input_ids"` is, it will be generated by shifting + each token in `"input_ids"` to the right once. + + * `"decoder_attention_mask"` - `{batch_size, target_sequence_length}` + + Mask indicating which decoder tokens to attend to. This is used + to ignore padding tokens, which are added when processing a batch + of sequences with different length. + + * `"decoder_position_ids"` - `{batch_size, target_sequence_length}` + + Indices of positions of each decoder input sequence tokens in + the position embeddings. + + * `"decoder_attention_head_mask"` - `{decoder_num_blocks, decoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the decoder. + + * `"decoder_input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"decoder_input_ids"`, which can be + specified for more control over how `"decoder_input_ids"` are + embedded than the model's internal embedding lookup. If + `"decoder_input_embeddings"` are present, then `"decoder_input_ids"` + will be ignored. + + * `"encoder_hidden_state"` - `{batch_size, sequence_length, hidden_size}` + + Last hidden state output from the encoder. This hidden state is + used in cross-attention blocks in the decoder. If specified, the + model will skip the encoding process and use this value directly + for cross-attentions in the decoder. + + * `"cross_attention_head_mask"` - `{decoder_num_blocks, decoder_num_attention_heads}` + + Mask to nullify selected heads of the cross-attention blocks in + the decoder with shape. + + * `"cache"` + + A container with cached layer results used to speed up sequential + decoding (autoregression). With cache, certain hidden states are + taken from the cache, rather than recomputed on every decoding + pass. The cache should be treated as opaque and initialized with + `Bumblebee.Text.Generation.init_cache/4`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), do: [:base, :for_conditional_generation] + + @impl true + def config(spec, opts) do + Shared.put_config_attrs(spec, opts) + end + + @impl true + def input_template(_spec) do + %{ + "input_ids" => Nx.template({1, 1}, :u32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = encoder_decoder_inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_conditional_generation} = spec) do + inputs = encoder_decoder_inputs(spec) + outputs = core(inputs, spec) + + logits = + outputs.hidden_state + |> language_modeling_head(spec, name: "language_modeling_head") + |> Axon.bias(name: "language_modeling_head.logits_bias", bias_initializer: :zeros) + + Layers.output(%{ + logits: logits, + decoder_hidden_states: outputs.decoder_hidden_states, + decoder_attentions: outputs.decoder_attentions, + cross_attentions: outputs.cross_attentions, + encoder_hidden_state: outputs.encoder_hidden_state, + encoder_hidden_states: outputs.encoder_hidden_states, + encoder_attentions: outputs.encoder_attentions, + cache: outputs.cache + }) + end + + defp encoder_decoder_inputs(spec) do + shape = {nil, nil} + hidden_shape = {nil, nil, spec.hidden_size} + + encoder_attention_head_mask_shape = + {spec.encoder_num_blocks, spec.encoder_num_attention_heads} + + decoder_attention_head_mask_shape = + {spec.decoder_num_blocks, spec.decoder_num_attention_heads} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: encoder_attention_head_mask_shape), + Axon.input("input_embeddings", optional: true, shape: hidden_shape), + Axon.input("decoder_input_ids", optional: true, shape: shape), + Axon.input("decoder_attention_mask", optional: true, shape: shape), + Axon.input("decoder_position_ids", optional: true, shape: shape), + Axon.input("decoder_attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("decoder_input_embeddings", optional: true, shape: hidden_shape), + Axon.input("encoder_hidden_state", optional: true, shape: hidden_shape), + Axon.input("cross_attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("cache", optional: true) + ]) + end + + @impl true + def init_cache(spec, batch_size, max_length, inputs) do + encoder_sequence_length = + if encoder_hidden_state = inputs["encoder_hidden_state"] do + Nx.axis_size(encoder_hidden_state, 1) + end + + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + decoder_num_attention_heads: spec.decoder_num_attention_heads, + encoder_num_attention_heads: spec.encoder_num_attention_heads, + decoder_num_blocks: spec.decoder_num_blocks, + encoder_sequence_length: encoder_sequence_length + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + defp core(inputs, spec) do + encoder_outputs = + Layers.if_present inputs["encoder_hidden_state"] do + %{ + hidden_state: inputs["encoder_hidden_state"], + hidden_states: Layers.none(), + attentions: Layers.none() + } + else + embeddings = + embedder(inputs["input_ids"], inputs["position_ids"], inputs["input_embeddings"], spec, + name: "encoder_embedder" + ) + + embeddings + |> encoder(inputs["attention_mask"], inputs["attention_head_mask"], spec, name: "encoder") + |> Map.take([:hidden_state, :hidden_states, :attentions]) + end + + decoder_input_ids = + Layers.default inputs["decoder_input_ids"] do + Layers.shift_tokens_right(inputs["input_ids"], spec.decoder_start_token_id) + end + + embeddings = + embedder( + decoder_input_ids, + inputs["decoder_position_ids"], + inputs["decoder_input_embeddings"], + spec, + name: "decoder_embedder" + ) + + decoder_outputs = + decoder( + embeddings, + inputs["decoder_attention_mask"], + inputs["decoder_attention_head_mask"], + encoder_outputs.hidden_state, + inputs["attention_mask"], + inputs["cross_attention_head_mask"], + inputs["cache"], + spec, + name: "decoder" + ) + + %{ + hidden_state: decoder_outputs.hidden_state, + decoder_hidden_states: decoder_outputs.hidden_states, + decoder_attentions: decoder_outputs.attentions, + cross_attentions: decoder_outputs.cross_attentions, + cache: decoder_outputs.cache, + encoder_hidden_state: encoder_outputs.hidden_state, + encoder_hidden_states: encoder_outputs.hidden_states, + encoder_attentions: encoder_outputs.attentions + } + end + + defp embedder(input_ids, position_ids, input_embeddings, spec, opts) do + name = opts[:name] + + input_embeddings = + Layers.default input_embeddings do + token_embedding(input_ids, spec, name: join(name, "token_embedding")) + end + + position_ids = + Layers.default position_ids do + Layers.default_position_ids(input_embeddings) + end + + position_embeddings = + position_embedding(position_ids, spec, name: join(name, "position_embedding")) + + Axon.add([input_embeddings, position_embeddings]) + |> Axon.dropout(rate: spec.dropout_rate) + end + + defp token_embedding(input_ids, spec, opts) do + name = opts[:name] + + input_embeddings = + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: name + ) + + if spec.scale_embedding do + Axon.nx(input_embeddings, fn x -> Nx.multiply(x, Nx.sqrt(spec.hidden_size)) end) + else + input_embeddings + end + end + + defp position_embedding(position_ids, spec, opts) do + name = opts[:name] + Axon.embedding(position_ids, spec.max_positions, spec.hidden_size, name: name) + end + + defp encoder(hidden_state, attention_mask, attention_head_mask, spec, opts) do + name = opts[:name] + + encoder_outputs = + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + num_blocks: spec.encoder_num_blocks, + num_attention_heads: spec.encoder_num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: 1.0e-5 + ], + ffn: [ + intermediate_size: spec.encoder_intermediate_size, + activation: spec.activation + ], + block_type: :norm_first, + name: join(name, "blocks") + ) + + hidden_state = Axon.layer_norm(encoder_outputs.hidden_state, name: join(name, "norm")) + + %{ + hidden_state: hidden_state, + hidden_states: Layers.append(encoder_outputs.hidden_states, hidden_state), + attentions: encoder_outputs.attentions + } + end + + defp decoder( + hidden_state, + attention_mask, + attention_head_mask, + encoder_hidden_state, + encoder_attention_mask, + cross_attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + + decoder_outputs = + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + cross_hidden_state: encoder_hidden_state, + cross_attention_mask: encoder_attention_mask, + cross_attention_head_mask: cross_attention_head_mask, + cache: cache, + causal: true, + num_blocks: spec.decoder_num_blocks, + num_attention_heads: spec.decoder_num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: 1.0e-5 + ], + ffn: [ + intermediate_size: spec.decoder_intermediate_size, + activation: spec.activation + ], + block_type: :norm_first, + name: join(name, "blocks") + ) + + hidden_state = Axon.layer_norm(decoder_outputs.hidden_state, name: join(name, "norm")) + + %{ + cache: decoder_outputs.cache, + hidden_state: hidden_state, + hidden_states: Layers.append(decoder_outputs.hidden_states, hidden_state), + attentions: decoder_outputs.attentions, + cross_attentions: decoder_outputs.cross_attentions + } + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: Tie lm-head to word embedding as a spec option + Layers.dense_transposed(hidden_state, spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"max_position_embeddings", number()}, + hidden_size: {"d_model", number()}, + encoder_num_blocks: {"encoder_layers", number()}, + decoder_num_blocks: {"decoder_layers", number()}, + encoder_num_attention_heads: {"encoder_attention_heads", number()}, + decoder_num_attention_heads: {"decoder_attention_heads", number()}, + encoder_intermediate_size: {"encoder_ffn_dim", number()}, + decoder_intermediate_size: {"decoder_ffn_dim", number()}, + scale_embedding: {"scale_embedding", boolean()}, + activation: {"activation_function", activation()}, + dropout_rate: {"dropout", number()}, + attention_dropout_rate: {"attention_dropout", number()}, + activation_dropout_rate: {"activation_dropout", number()}, + initializer_scale: {"init_std", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "encoder_embedder.token_embedding" => "model.encoder.embed_tokens", + "encoder_embedder.position_embedding" => "model.encoder.embed_positions", + "encoder.blocks.{n}.self_attention.query" => "model.encoder.layers.{n}.self_attn.q_proj", + "encoder.blocks.{n}.self_attention.key" => "model.encoder.layers.{n}.self_attn.k_proj", + "encoder.blocks.{n}.self_attention.value" => "model.encoder.layers.{n}.self_attn.v_proj", + "encoder.blocks.{n}.self_attention.output" => + "model.encoder.layers.{n}.self_attn.out_proj", + "encoder.blocks.{n}.self_attention_norm" => + "model.encoder.layers.{n}.self_attn_layer_norm", + "encoder.blocks.{n}.ffn.intermediate" => "model.encoder.layers.{n}.fc1", + "encoder.blocks.{n}.ffn.output" => "model.encoder.layers.{n}.fc2", + "encoder.blocks.{n}.output_norm" => "model.encoder.layers.{n}.final_layer_norm", + "encoder.norm" => "model.encoder.layer_norm", + "decoder_embedder.token_embedding" => "model.decoder.embed_tokens", + "decoder_embedder.position_embedding" => "model.decoder.embed_positions", + "decoder.blocks.{n}.self_attention.query" => "model.decoder.layers.{n}.self_attn.q_proj", + "decoder.blocks.{n}.self_attention.key" => "model.decoder.layers.{n}.self_attn.k_proj", + "decoder.blocks.{n}.self_attention.value" => "model.decoder.layers.{n}.self_attn.v_proj", + "decoder.blocks.{n}.self_attention.output" => + "model.decoder.layers.{n}.self_attn.out_proj", + "decoder.blocks.{n}.self_attention_norm" => + "model.decoder.layers.{n}.self_attn_layer_norm", + "decoder.blocks.{n}.cross_attention.query" => + "model.decoder.layers.{n}.encoder_attn.q_proj", + "decoder.blocks.{n}.cross_attention.key" => + "model.decoder.layers.{n}.encoder_attn.k_proj", + "decoder.blocks.{n}.cross_attention.value" => + "model.decoder.layers.{n}.encoder_attn.v_proj", + "decoder.blocks.{n}.cross_attention.output" => + "model.decoder.layers.{n}.encoder_attn.out_proj", + "decoder.blocks.{n}.cross_attention_norm" => + "model.decoder.layers.{n}.encoder_attn_layer_norm", + "decoder.blocks.{n}.ffn.intermediate" => "model.decoder.layers.{n}.fc1", + "decoder.blocks.{n}.ffn.output" => "model.decoder.layers.{n}.fc2", + "decoder.blocks.{n}.output_norm" => "model.decoder.layers.{n}.final_layer_norm", + "decoder.norm" => "model.decoder.layer_norm", + "language_modeling_head.output" => "model.shared", + "language_modeling_head.logits_bias" => %{ + "bias" => {[{"model", "final_logits_bias"}], fn [value] -> Nx.squeeze(value) end} + } + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/blip_text.ex b/deps/bumblebee/lib/bumblebee/text/blip_text.ex new file mode 100644 index 0000000000000000000000000000000000000000..e21fa191e7f64de9e4a3a04181f6e1c6e8228d05 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/blip_text.ex @@ -0,0 +1,460 @@ +defmodule Bumblebee.Text.BlipText do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 30524, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 512, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + hidden_size: [ + default: 768, + doc: "the dimensionality of hidden layers" + ], + encoder_hidden_size: [ + default: 768, + doc: "the dimensionality of hidden layers in the vision encoder" + ], + num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the encoder" + ], + num_attention_heads: [ + default: 8, + doc: "the number of attention heads for each attention layer in the encoder" + ], + intermediate_size: [ + default: 3072, + doc: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder" + ], + activation: [ + default: :gelu, + doc: "the activation function" + ], + dropout_rate: [ + default: 0.0, + doc: "the dropout rate for embedding and encoder" + ], + attention_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for attention weights" + ], + layer_norm_epsilon: [ + default: 1.0e-12, + doc: "the epsilon used by the layer normalization layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] + + @moduledoc """ + The BLIP model for text encoding. + + ## Architectures + + * `:base` - the base text model + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{encoder_num_blocks, encoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + * `"input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"input_ids"`, which can be specified + for more control over how `"input_ids"` are embedded than the + model's internal embedding lookup. If `"input_embeddings"` are present, + then `"input_ids"` will be ignored. + + * `"encoder_hidden_state"` - `{batch_size, encoder_sequence_length, encoder_hidden_size}` + + Last hidden state output from the encoder. This hidden state is + used in cross-attention blocks in the decoder. If specified, the + model will skip the encoding process and use this value directly + for cross-attentions in the decoder. + + * `"encoder_attention_mask"` - `{batch_size, encoder_sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"cross_attention_head_mask"` - `{num_blocks, num_attention_heads}` + + Mask to nullify selected heads of the cross-attention blocks in + the decoder with shape. + + * `"cache"` + + A container with cached layer results used to speed up sequential + decoding (autoregression). With cache, certain hidden states are + taken from the cache, rather than recomputed on every decoding + pass. The cache should be treated as opaque and initialized with + `Bumblebee.Text.Generation.init_cache/4`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), do: [:base, :for_causal_language_modeling] + + @impl true + def config(spec, opts) do + Shared.put_config_attrs(spec, opts) + end + + @impl true + def input_template(_spec) do + %{ + "input_ids" => Nx.template({1, 1}, :u32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_causal_language_modeling} = spec) do + inputs = inputs(spec, decoder?: true) + outputs = core(inputs, spec, decoder?: true) + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cross_attentions: outputs.cross_attentions, + cache: outputs.cache + }) + end + + @impl true + def init_cache(spec, batch_size, max_length, inputs) do + encoder_sequence_length = + if encoder_hidden_state = inputs["encoder_hidden_state"] do + Nx.axis_size(encoder_hidden_state, 1) + end + + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + decoder_num_attention_heads: spec.num_attention_heads, + encoder_num_attention_heads: spec.num_attention_heads, + decoder_num_blocks: spec.num_blocks, + encoder_sequence_length: encoder_sequence_length + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + defp inputs(spec, opts \\ []) do + shape = {nil, nil} + decoder? = Keyword.get(opts, :decoder?, false) + hidden_shape = {nil, nil, spec.hidden_size} + encoder_hidden_shape = {nil, nil, spec.encoder_hidden_size} + attention_head_mask_shape = {spec.num_blocks, spec.num_attention_heads} + + inputs = + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: attention_head_mask_shape), + Axon.input("input_embeddings", optional: true, shape: hidden_shape) + ]) + + extra_decoder_inputs = + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("encoder_hidden_state", optional: true, shape: encoder_hidden_shape), + Axon.input("encoder_attention_mask", optional: true, shape: shape), + Axon.input("cross_attention_head_mask", optional: true, shape: attention_head_mask_shape), + Axon.input("cache", optional: true) + ]) + + extra_decoder_inputs = + if decoder? do + extra_decoder_inputs + else + Map.new(extra_decoder_inputs, fn {name, _input} -> {name, Layers.none()} end) + end + + Map.merge(inputs, extra_decoder_inputs) + end + + defp core(inputs, spec, opts \\ []) do + decoder? = Keyword.get(opts, :decoder?, false) + + embeddings = + embedder(inputs["input_ids"], inputs["position_ids"], inputs["input_embeddings"], spec, + name: "embedder" + ) + + encoder_outputs = + encoder( + embeddings, + inputs["attention_mask"], + inputs["attention_head_mask"], + inputs["encoder_hidden_state"], + inputs["encoder_attention_mask"], + inputs["cross_attention_head_mask"], + inputs["cache"], + spec, + decoder?: decoder?, + name: "encoder" + ) + + pooled_state = pooler(encoder_outputs.hidden_state, spec, name: "pooler") + + %{ + hidden_state: encoder_outputs.hidden_state, + pooled_state: pooled_state, + hidden_states: encoder_outputs.hidden_states, + attentions: encoder_outputs.attentions, + cross_attentions: encoder_outputs.cross_attentions, + cache: encoder_outputs.cache + } + end + + defp embedder(input_ids, position_ids, input_embeddings, spec, opts) do + name = opts[:name] + + input_embeddings = + Layers.default input_embeddings do + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "token_embedding") + ) + end + + position_ids = + Layers.default position_ids do + Layers.default_position_ids(input_embeddings) + end + + position_embeddings = + Axon.embedding(position_ids, spec.max_positions, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "position_embedding") + ) + + input_embeddings + |> Axon.add(position_embeddings) + |> Axon.layer_norm(epsilon: spec.layer_norm_epsilon, name: join(name, "norm")) + |> Axon.dropout(rate: spec.dropout_rate) + end + + defp encoder( + hidden_state, + attention_mask, + attention_head_mask, + encoder_hidden_state, + encoder_attention_mask, + cross_attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + decoder? = opts[:decoder?] + + cross_attention? = decoder? + + Layers.Transformer.blocks( + hidden_state, + [ + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + cache: cache, + causal: decoder?, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: spec.layer_norm_epsilon + ], + ffn: [ + intermediate_size: spec.intermediate_size, + activation: spec.activation + ], + name: join(name, "blocks") + ] ++ + if(cross_attention?, + do: [ + cross_hidden_state: encoder_hidden_state, + cross_attention_mask: encoder_attention_mask, + cross_attention_head_mask: cross_attention_head_mask + ], + else: [] + ) + ) + end + + defp pooler(hidden_state, spec, opts) do + name = opts[:name] + + hidden_state + |> Layers.take_token(index: 0, axis: 1) + |> Axon.dense(spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + |> Axon.tanh() + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: use a shared parameter with embeddings.word_embeddings.kernel + # if spec.tie_word_embeddings is true (relevant for training) + + hidden_state + |> Axon.dense(spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "dense") + ) + |> Layers.activation(spec.activation, name: join(name, "activation")) + |> Axon.layer_norm(epsilon: spec.layer_norm_epsilon, name: join(name, "norm")) + # We reuse the kernel of input embeddings and add bias for each token + |> Layers.dense_transposed(spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + |> Axon.bias(name: join(name, "bias")) + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + # Support loading from the entire Blip configuration + def load(spec, %{"model_type" => "blip", "text_config" => data}) do + load(spec, data) + end + + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"max_position_embeddings", number()}, + hidden_size: {"hidden_size", number()}, + encoder_hidden_size: {"encoder_hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_attention_heads: {"num_attention_heads", number()}, + intermediate_size: {"intermediate_size", number()}, + activation: {"hidden_act", activation()}, + dropout_rate: {"hidden_dropout_prob", number()}, + attention_dropout_rate: {"attention_probs_dropout_prob", number()}, + layer_norm_epsilon: {"layer_norm_eps", number()}, + initializer_scale: {"initializer_range", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(spec) do + prefix = + case spec.architecture do + :base -> "text_model." + :for_causal_language_modeling -> "text_decoder.bert." + end + + %{ + "embedder.token_embedding" => prefix <> "embeddings.word_embeddings", + "embedder.position_embedding" => prefix <> "embeddings.position_embeddings", + "embedder.token_type_embedding" => prefix <> "embeddings.token_type_embeddings", + "embedder.norm" => prefix <> "embeddings.LayerNorm", + "encoder.blocks.{n}.self_attention.query" => + prefix <> "encoder.layer.{n}.attention.self.query", + "encoder.blocks.{n}.self_attention.key" => + prefix <> "encoder.layer.{n}.attention.self.key", + "encoder.blocks.{n}.self_attention.value" => + prefix <> "encoder.layer.{n}.attention.self.value", + "encoder.blocks.{n}.self_attention.output" => + prefix <> "encoder.layer.{n}.attention.output.dense", + "encoder.blocks.{n}.self_attention_norm" => + prefix <> "encoder.layer.{n}.attention.output.LayerNorm", + "encoder.blocks.{n}.cross_attention.query" => + prefix <> "encoder.layer.{n}.crossattention.self.query", + "encoder.blocks.{n}.cross_attention.key" => + prefix <> "encoder.layer.{n}.crossattention.self.key", + "encoder.blocks.{n}.cross_attention.value" => + prefix <> "encoder.layer.{n}.crossattention.self.value", + "encoder.blocks.{n}.cross_attention.output" => + prefix <> "encoder.layer.{n}.crossattention.output.dense", + "encoder.blocks.{n}.cross_attention_norm" => + prefix <> "encoder.layer.{n}.crossattention.output.LayerNorm", + "encoder.blocks.{n}.ffn.intermediate" => prefix <> "encoder.layer.{n}.intermediate.dense", + "encoder.blocks.{n}.ffn.output" => prefix <> "encoder.layer.{n}.output.dense", + "encoder.blocks.{n}.output_norm" => prefix <> "encoder.layer.{n}.output.LayerNorm", + "pooler.output" => prefix <> "pooler.dense", + "language_modeling_head.dense" => "text_decoder.cls.predictions.transform.dense", + "language_modeling_head.norm" => "text_decoder.cls.predictions.transform.LayerNorm", + "language_modeling_head.output" => "text_decoder.cls.predictions.decoder", + "language_modeling_head.bias" => "text_decoder.cls.predictions" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/clip_text.ex b/deps/bumblebee/lib/bumblebee/text/clip_text.ex new file mode 100644 index 0000000000000000000000000000000000000000..91abbe81a96d8f5b5c9f27c43c1e4009a5694479 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/clip_text.ex @@ -0,0 +1,281 @@ +defmodule Bumblebee.Text.ClipText do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 49408, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 77, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + hidden_size: [ + default: 512, + doc: "the dimensionality of hidden layers" + ], + num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the encoder" + ], + num_attention_heads: [ + default: 8, + doc: "the number of attention heads for each attention layer in the encoder" + ], + intermediate_size: [ + default: 2048, + doc: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder" + ], + projection_size: [ + default: 512, + doc: "the dimensionality of the projection layer" + ], + activation: [ + default: :gelu_approx_sigmoid, + doc: "the activation function" + ], + attention_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for attention weights" + ], + layer_norm_epsilon: [ + default: 1.0e-5, + doc: "the epsilon used by the layer normalization layers" + ] + ] ++ Shared.common_options([:num_labels, :id_to_label]) + + @moduledoc """ + The CLIP model for text encoding. + + ## Architectures + + * `:base` - the base text model + + * `:for_embedding` - the base model with a single projection layer + on top. The head returns a vector embedded in the joint text-image + CLIP space + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), do: [:base, :for_embedding] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(_spec) do + %{ + "input_ids" => Nx.template({1, 1}, :u32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs() + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_embedding} = spec) do + inputs = inputs() + + outputs = core(inputs, spec) + + embedding = + outputs.pooled_state + |> Axon.dense(spec.projection_size, use_bias: false, name: "embedding_head.output") + + Layers.output(%{ + embedding: embedding, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + defp inputs() do + shape = {nil, nil} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape) + ]) + end + + defp core(inputs, spec) do + input_ids = inputs["input_ids"] + + embeddings = embedder(input_ids, inputs["position_ids"], spec, name: "embedder") + encoder_outputs = encoder(embeddings, inputs["attention_mask"], spec, name: "encoder") + + hidden_state = + Axon.layer_norm( + encoder_outputs.hidden_state, + epsilon: spec.layer_norm_epsilon, + name: "norm" + ) + + pooled_state = + Axon.layer( + fn hidden_state, input_ids, _opts -> + eos_idx = Nx.argmax(input_ids, axis: -1) + Bumblebee.Utils.Nx.batched_take(hidden_state, eos_idx) + end, + [hidden_state, input_ids] + ) + + %{ + hidden_state: hidden_state, + pooled_state: pooled_state, + hidden_states: encoder_outputs.hidden_states, + attentions: encoder_outputs.attentions + } + end + + defp embedder(input_ids, position_ids, spec, opts) do + name = opts[:name] + + position_ids = + Layers.default position_ids do + Layers.default_position_ids(input_ids) + end + + input_embeddings = + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + kernel_initializer: Axon.Initializers.normal(), + name: join(name, "token_embedding") + ) + + position_embeddings = + Axon.embedding(position_ids, spec.max_positions, spec.hidden_size, + kernel_initializer: Axon.Initializers.normal(), + name: join(name, "position_embedding") + ) + + Axon.add(input_embeddings, position_embeddings) + end + + defp encoder(embeddings, attention_mask, spec, opts) do + name = opts[:name] + + Layers.Transformer.blocks(embeddings, + attention_mask: attention_mask, + causal: true, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: Axon.Initializers.normal(scale: 0.01), + dropout_rate: 0.0, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: spec.layer_norm_epsilon + ], + ffn: [ + intermediate_size: spec.intermediate_size, + activation: spec.activation + ], + block_type: :norm_first, + name: join(name, "blocks") + ) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + # Support loading from the entire Clip configuration + def load(spec, %{"model_type" => "clip", "text_config" => data}) do + load(spec, data) + end + + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"max_position_embeddings", number()}, + hidden_size: {"hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_attention_heads: {"num_attention_heads", number()}, + intermediate_size: {"intermediate_size", number()}, + projection_size: {"projection_dim", number()}, + activation: {"hidden_act", activation()}, + attention_dropout_rate: {"attention_dropout", number()}, + layer_norm_epsilon: {"layer_norm_eps", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.token_embedding" => "text_model.embeddings.token_embedding", + "embedder.position_embedding" => "text_model.embeddings.position_embedding", + "encoder.blocks.{n}.self_attention.query" => + "text_model.encoder.layers.{n}.self_attn.q_proj", + "encoder.blocks.{n}.self_attention.key" => + "text_model.encoder.layers.{n}.self_attn.k_proj", + "encoder.blocks.{n}.self_attention.value" => + "text_model.encoder.layers.{n}.self_attn.v_proj", + "encoder.blocks.{n}.self_attention.output" => + "text_model.encoder.layers.{n}.self_attn.out_proj", + "encoder.blocks.{n}.self_attention_norm" => "text_model.encoder.layers.{n}.layer_norm1", + "encoder.blocks.{n}.ffn.intermediate" => "text_model.encoder.layers.{n}.mlp.fc1", + "encoder.blocks.{n}.ffn.output" => "text_model.encoder.layers.{n}.mlp.fc2", + "encoder.blocks.{n}.output_norm" => "text_model.encoder.layers.{n}.layer_norm2", + "norm" => "text_model.final_layer_norm", + "embedding_head.output" => "text_projection" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/distilbert.ex b/deps/bumblebee/lib/bumblebee/text/distilbert.ex new file mode 100644 index 0000000000000000000000000000000000000000..2a5b7c2d869d640e84354707d66bc17deb3fecbd --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/distilbert.ex @@ -0,0 +1,487 @@ +defmodule Bumblebee.Text.Distilbert do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 30522, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 512, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + hidden_size: [ + default: 768, + doc: "the dimensionality of hidden layers" + ], + num_blocks: [ + default: 6, + doc: "the number of Transformer blocks in the encoder" + ], + num_attention_heads: [ + default: 12, + doc: "the number of attention heads for each attention layer in the encoder" + ], + intermediate_size: [ + default: 3072, + doc: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder" + ], + activation: [ + default: :gelu, + doc: "the activation function" + ], + dropout_rate: [ + default: 0.1, + doc: "the dropout rate for embedding and encoder" + ], + attention_dropout_rate: [ + default: 0.1, + doc: "the dropout rate for attention weights" + ], + classifier_dropout_rate: [ + default: nil, + doc: + "the dropout rate for the classification head. If not specified, the value of `:dropout_rate` is used instead" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] ++ Shared.common_options([:use_cross_attention, :num_labels, :id_to_label]) + + @moduledoc """ + DistilBERT model family. + + ## Architectures + + * `:base` - plain DistilBERT without any head on top + + * `:for_masked_language_modeling` - DistilBERT with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_sequence_classification` - DistilBERT with a sequence + classification head. The head returns logits corresponding to + possible classes + + * `:for_token_classification` - DistilBERT with a token classification + head. The head returns logits for each token in the original + sequence + + * `:for_question_answering` - DistilBERT with a span classification head. + The head returns logits for the span start and end positions + + * `:for_multiple_choice` - DistilBERT with a multiple choice prediction + head. Each input in the batch consists of several sequences to + choose from and the model returns logits corresponding to those + choices + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + Mask distinguishing groups in the input sequence. This is used + in when the input sequence is a semantically a pair of sequences. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{num_blocks, num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + ### Exceptions + + The `:for_multiple_choice` model accepts groups of sequences, so the + expected sequence shape is `{batch_size, num_choices, sequence_length}`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + + ## References + + * [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter](https://arxiv.org/abs/1910.01108) + + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_masked_language_modeling, + :for_sequence_classification, + :for_token_classification, + :for_question_answering, + :for_multiple_choice + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(%{architecture: :for_multiple_choice}) do + %{"input_ids" => Nx.template({1, 1, 1}, :u32)} + end + + def input_template(_spec) do + %{"input_ids" => Nx.template({1, 1}, :u32)} + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_masked_language_modeling} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_sequence_classification} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + outputs.pooled_state + |> Axon.dropout( + rate: classifier_dropout_rate(spec), + name: "sequence_classification_head.dropout" + ) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "sequence_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_token_classification} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + outputs.hidden_state + |> Axon.dropout( + rate: classifier_dropout_rate(spec), + name: "token_classification_head.dropout" + ) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "token_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_question_answering} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + outputs.hidden_state + |> Axon.dropout( + rate: classifier_dropout_rate(spec), + name: "question_answering_head.dropout" + ) + |> Axon.dense(2, + kernel_initializer: kernel_initializer(spec), + name: "question_answering_head.output" + ) + + {start_logits, end_logits} = Layers.split_pair(logits) + + Layers.output(%{ + start_logits: start_logits, + end_logits: end_logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_multiple_choice} = spec) do + inputs = inputs(spec, shape: {nil, nil, nil}) + + group_inputs = ["input_ids", "attention_mask", "position_ids"] + + flat_inputs = + Enum.reduce(group_inputs, inputs, fn name, inputs -> + Map.update!(inputs, name, &Layers.flatten_leading/1) + end) + + outputs = core(flat_inputs, spec) + + logits = + outputs.pooled_state + |> Axon.dropout(rate: classifier_dropout_rate(spec), name: "multiple_choice_head.dropout") + |> Axon.dense(1, + kernel_initializer: kernel_initializer(spec), + name: "multiple_choice_head.output" + ) + + # The final shape depends on the dynamic batch size and number + # of choices, so we do a reshape based on the input shape + logits = + Axon.layer( + fn logits, input_ids, _opts -> + num_choices = Nx.axis_size(input_ids, 1) + Nx.reshape(logits, {:auto, num_choices}) + end, + [logits, inputs["input_ids"]] + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + defp inputs(spec, opts \\ []) do + shape = Keyword.get(opts, :shape, {nil, nil}) + + attention_head_mask_shape = {spec.num_blocks, spec.num_attention_heads} + + inputs = + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: attention_head_mask_shape) + ]) + + inputs + end + + defp core(inputs, spec) do + embeddings = embedder(inputs["input_ids"], inputs["position_ids"], spec, name: "embedder") + + encoder_outputs = + encoder( + embeddings, + inputs["attention_mask"], + inputs["attention_head_mask"], + spec, + name: "encoder" + ) + + pooled_state = pooler(encoder_outputs.hidden_state, spec, name: "pooler") + + %{ + hidden_state: encoder_outputs.hidden_state, + pooled_state: pooled_state, + hidden_states: encoder_outputs.hidden_states, + attentions: encoder_outputs.attentions + } + end + + defp embedder(input_ids, position_ids, spec, opts) do + name = opts[:name] + + position_ids = + Layers.default position_ids do + Layers.default_position_ids(input_ids) + end + + inputs_embeddings = + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "token_embedding") + ) + + position_embeddings = + Axon.embedding(position_ids, spec.max_positions, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "position_embedding") + ) + + Axon.add([inputs_embeddings, position_embeddings]) + |> Axon.layer_norm(epsilon: 1.0e-12, name: join(name, "norm")) + |> Axon.dropout(rate: spec.dropout_rate, name: join(name, "dropout")) + end + + defp encoder( + hidden_state, + attention_mask, + attention_head_mask, + spec, + opts + ) do + name = opts[:name] + + Layers.Transformer.blocks( + hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: 1.0e-12 + ], + ffn: [ + intermediate_size: spec.intermediate_size, + activation: spec.activation + ], + name: join(name, "blocks") + ) + end + + defp pooler(hidden_state, spec, opts) do + name = opts[:name] + + hidden_state + |> Layers.take_token(index: 0, axis: 1) + |> Axon.dense(spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + |> Axon.relu() + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: use a shared parameter with embeddings.word_embeddings.kernel + # if spec.tie_word_embeddings is true (relevant for training) + + hidden_state + |> Axon.dense(spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "dense") + ) + |> Layers.activation(spec.activation, name: join(name, "activation")) + |> Axon.layer_norm(epsilon: 1.0e-12, name: join(name, "norm")) + # We reuse the kernel of input embeddings and add bias for each token + |> Layers.dense_transposed(spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + |> Axon.bias(name: join(name, "bias")) + end + + defp classifier_dropout_rate(spec) do + spec.classifier_dropout_rate || spec.dropout_rate + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"max_position_embeddings", number()}, + hidden_size: {"dim", number()}, + num_blocks: {"n_layers", number()}, + num_attention_heads: {"n_heads", number()}, + intermediate_size: {"hidden_dim", number()}, + activation: {"activation", activation()}, + dropout_rate: {"dropout", number()}, + attention_dropout_rate: {"attention_dropout", number()}, + classifier_dropout_rate: {"seq_classif_dropout", optional(number())}, + initializer_scale: {"initializer_range", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.token_embedding" => "distilbert.embeddings.word_embeddings", + "embedder.position_embedding" => "distilbert.embeddings.position_embeddings", + "embedder.norm" => "distilbert.embeddings.LayerNorm", + "encoder.blocks.{n}.self_attention.query" => + "distilbert.transformer.layer.{n}.attention.q_lin", + "encoder.blocks.{n}.self_attention.key" => + "distilbert.transformer.layer.{n}.attention.k_lin", + "encoder.blocks.{n}.self_attention.value" => + "distilbert.transformer.layer.{n}.attention.v_lin", + "encoder.blocks.{n}.self_attention.output" => + "distilbert.transformer.layer.{n}.attention.out_lin", + "encoder.blocks.{n}.self_attention_norm" => + "distilbert.transformer.layer.{n}.sa_layer_norm", + "encoder.blocks.{n}.ffn.intermediate" => "distilbert.transformer.layer.{n}.ffn.lin1", + "encoder.blocks.{n}.ffn.output" => "distilbert.transformer.layer.{n}.ffn.lin2", + "encoder.blocks.{n}.output_norm" => "distilbert.transformer.layer.{n}.output_layer_norm", + "pooler.output" => "pre_classifier", + "language_modeling_head.dense" => "vocab_transform", + "language_modeling_head.norm" => "vocab_layer_norm", + "language_modeling_head.output" => "vocab_projector", + "language_modeling_head.bias" => "vocab_projector", + "next_sentence_prediction_head.output" => "cls.seq_relationship", + "sequence_classification_head.output" => "classifier", + "token_classification_head.output" => "classifier", + "multiple_choice_head.output" => "classifier", + "question_answering_head.output" => "qa_outputs" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/fill_mask.ex b/deps/bumblebee/lib/bumblebee/text/fill_mask.ex new file mode 100644 index 0000000000000000000000000000000000000000..91ea8dcefbbfbbf2f8182f456250951b45c798fe --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/fill_mask.ex @@ -0,0 +1,146 @@ +defmodule Bumblebee.Text.FillMask do + @moduledoc false + + alias Bumblebee.Shared + + def fill_mask(model_info, tokenizer, opts \\ []) do + %{model: model, params: params, spec: spec} = model_info + Shared.validate_architecture!(spec, :for_masked_language_modeling) + + opts = + Keyword.validate!(opts, [:compile, top_k: 5, defn_options: [], preallocate_params: false]) + + top_k = opts[:top_k] + preallocate_params = opts[:preallocate_params] + defn_options = opts[:defn_options] + + compile = + if compile = opts[:compile] do + compile + |> Keyword.validate!([:batch_size, :sequence_length]) + |> Shared.require_options!([:batch_size, :sequence_length]) + end + + batch_size = compile[:batch_size] + sequence_length = compile[:sequence_length] + + mask_token_id = Bumblebee.Tokenizer.special_token_id(tokenizer, :mask) + mask_token = Bumblebee.Tokenizer.id_to_token(tokenizer, mask_token_id) + + tokenizer = + Bumblebee.configure(tokenizer, length: sequence_length, return_token_type_ids: false) + + {_init_fun, predict_fun} = Axon.build(model) + + scores_fun = fn params, inputs -> + outputs = predict_fun.(params, inputs) + scores = Axon.Activations.softmax(outputs.logits) + + mask_idx = + inputs["input_ids"] + |> Nx.equal(mask_token_id) + |> Nx.argmax(axis: 1) + + {batch_size, _sequence_length, num_tokens} = Nx.shape(scores) + + mask_idx = + mask_idx + |> Nx.reshape({batch_size, 1, 1}) + |> Nx.broadcast({batch_size, 1, num_tokens}) + + scores = + scores + |> Nx.take_along_axis(mask_idx, axis: 1) + |> Nx.squeeze(axes: [1]) + + k = min(top_k, Nx.axis_size(scores, 1)) + {top_scores, top_indices} = Nx.top_k(scores, k: k) + {top_scores, top_indices} + end + + batch_keys = Shared.sequence_batch_keys(sequence_length) + + Nx.Serving.new( + fn batch_key, defn_options -> + params = Shared.maybe_preallocate(params, preallocate_params, defn_options) + + scope = {:scores, batch_key} + + scores_fun = + Shared.compile_or_jit(scores_fun, scope, defn_options, compile != nil, fn -> + {:sequence_length, sequence_length} = batch_key + + inputs = %{ + "input_ids" => Nx.template({batch_size, sequence_length}, :u32), + "attention_mask" => Nx.template({batch_size, sequence_length}, :u32) + } + + [params, inputs] + end) + + fn inputs -> + inputs = Shared.maybe_pad(inputs, batch_size) + scores_fun.(params, inputs) |> Shared.serving_post_computation() + end + end, + defn_options + ) + |> Nx.Serving.batch_size(batch_size) + |> Nx.Serving.process_options(batch_keys: batch_keys) + |> Nx.Serving.client_preprocessing(fn input -> + {texts, multi?} = Shared.validate_serving_input!(input, &Shared.validate_string/1) + + texts = for text <- texts, do: validate_text!(text, mask_token) + + inputs = + Nx.with_default_backend(Nx.BinaryBackend, fn -> + Bumblebee.apply_tokenizer(tokenizer, texts) + end) + + batch_key = Shared.sequence_batch_key_for_inputs(inputs, sequence_length) + batch = [inputs] |> Nx.Batch.concatenate() |> Nx.Batch.key(batch_key) + + {batch, multi?} + end) + |> Nx.Serving.client_postprocessing(fn {{top_scores, top_indices}, _metadata}, multi? -> + Enum.zip_with( + Nx.to_list(top_scores), + Nx.to_list(top_indices), + fn top_scores, top_indices -> + predictions = + Enum.zip_with(top_scores, top_indices, fn score, token_id -> + # Certain tokenizers distinguish tokens with a leading space, + # so we normalize the result to a consistent string + token = + tokenizer + |> Bumblebee.Tokenizer.decode([token_id]) + |> String.trim_leading() + + %{score: score, token: token} + end) + + %{predictions: predictions} + end + ) + |> Shared.normalize_output(multi?) + end) + end + + defp validate_text!(text, mask_token) do + mask_count = count_occurrences(text, "[MASK]") + + unless mask_count == 1 do + raise ArgumentError, + "expected exactly one occurrence of [MASK], got: #{mask_count} in #{inspect(text)}" + end + + String.replace(text, "[MASK]", mask_token) + end + + defp count_occurrences(string, substring) do + string + |> String.split(substring) + |> length() + |> Kernel.-(1) + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/gemma.ex b/deps/bumblebee/lib/bumblebee/text/gemma.ex new file mode 100644 index 0000000000000000000000000000000000000000..fe718dd26f7a1be8f8b839ccd1bd60c407836386 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/gemma.ex @@ -0,0 +1,464 @@ +defmodule Bumblebee.Text.Gemma do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 256_000, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 8192, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + hidden_size: [ + default: 3072, + doc: "the dimensionality of hidden layers" + ], + intermediate_size: [ + default: 24576, + doc: "the dimensionality of intermediate layers" + ], + attention_head_size: [ + default: 256, + doc: "the size of the key, value, and query projection per attention head" + ], + num_blocks: [ + default: 28, + doc: "the number of Transformer blocks in the model" + ], + num_attention_heads: [ + default: 16, + doc: "the number of attention heads for each attention layer in the model" + ], + num_key_value_heads: [ + default: 16, + doc: "the number of key value heads for each attention layer in the model" + ], + activation: [ + default: :gelu_approx_tanh, + doc: "the activation function" + ], + rotary_embedding_base: [ + default: 10_000, + doc: "base for computing rotary embedding frequency" + ], + rotary_embedding_scaling_strategy: [ + default: nil, + doc: """ + scaling configuration for rotary embedding. Currently the supported values are: + + * `%{type: :linear, factor: number()}` + + * `%{type: :dynamic, factor: number()}` + + For more details see https://www.reddit.com/r/LocalLlama/comments/14mrgpr/dynamically_scaled_rope_further_increases + """ + ], + use_attention_bias: [ + default: false, + doc: + "whether or not to use bias in the query, key, value, and output projections in attention layers" + ], + layer_norm_epsilon: [ + default: 1.0e-6, + doc: "the epsilon used by RMS normalization layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] ++ + Shared.common_options([:num_labels, :id_to_label]) ++ Shared.token_options(pad_token_id: 0) + + @moduledoc """ + Gemma model family. + + ## Architectures + + * `:base` - plain Gemma without any head on top + + * `:for_causal_language_modeling` - Gemma with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_sequence_classification` - Gemma with a sequence + classification head. The head returns logits corresponding to + possible classes + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{encoder_num_blocks, encoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + * `"input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"input_ids"`, which can be specified + for more control over how `"input_ids"` are embedded than the + model's internal embedding lookup. If `"input_embeddings"` are present, + then `"input_ids"` will be ignored. + + * `"cache"` + + A container with cached layer results used to speed up sequential + decoding (autoregression). With cache, certain hidden states are + taken from the cache, rather than recomputed on every decoding + pass. The cache should be treated as opaque and initialized with + `Bumblebee.Text.Generation.init_cache/4`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_causal_language_modeling, + :for_sequence_classification + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(_spec) do + %{ + "input_ids" => Nx.template({1, 1}, :s64) + } + end + + @impl true + def init_cache(spec, batch_size, max_length, _inputs) do + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + attention_head_size: spec.attention_head_size, + decoder_num_attention_heads: spec.num_attention_heads, + decoder_num_blocks: spec.num_blocks + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_causal_language_modeling} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cache: outputs.cache + }) + end + + def model(%__MODULE__{architecture: :for_sequence_classification} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + + logits = + Axon.dense(outputs.hidden_state, spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "sequence_classification_head.output", + use_bias: false + ) + + pooled_logits = + Layers.if_present inputs["input_ids"] do + Axon.layer( + fn logits, input_ids, _opts -> + indices = + input_ids + |> Nx.not_equal(spec.pad_token_id) + |> Nx.sum(axes: [-1]) + |> Nx.subtract(1) + |> Nx.as_type({:s, 64}) + + Bumblebee.Utils.Nx.batched_take(logits, indices) + end, + [logits, inputs["input_ids"]] + ) + else + Layers.take_token(logits, axis: 1, index: -1) + end + + Layers.output(%{ + logits: pooled_logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cache: outputs.cache + }) + end + + defp inputs(spec) do + shape = {nil, nil} + hidden_shape = {nil, nil, spec.hidden_size} + + attention_head_mask_shape = {spec.num_blocks, spec.num_attention_heads} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: attention_head_mask_shape), + Axon.input("input_embeddings", optional: true, shape: hidden_shape), + Axon.input("cache", optional: true) + ]) + end + + defp core(inputs, spec) do + embeddings = + embedder( + inputs["input_ids"], + inputs["input_embeddings"], + spec, + name: "embedder" + ) + + position_ids = + Layers.default inputs["position_ids"] do + Layers.default_position_ids(embeddings) + end + + decoder_outputs = + decoder( + embeddings, + position_ids, + inputs["attention_mask"], + inputs["attention_head_mask"], + inputs["cache"], + spec, + name: "decoder" + ) + + hidden_state = + Layers.rms_norm(decoder_outputs.hidden_state, + name: "output_norm", + shift: 1.0, + epsilon: spec.layer_norm_epsilon, + upcast: :all + ) + + %{ + hidden_state: hidden_state, + hidden_states: Layers.append(decoder_outputs.hidden_states, hidden_state), + attentions: decoder_outputs.attentions, + cache: decoder_outputs.cache + } + end + + defp embedder(input_ids, input_embeddings, spec, opts) do + name = opts[:name] + + Layers.default input_embeddings do + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "token_embedding") + ) + end + |> Axon.nx(fn x -> + normalization_factor = + spec.hidden_size + |> Nx.tensor(type: Nx.type(x)) + |> Nx.sqrt() + + Nx.multiply(x, normalization_factor) + end) + end + + defp decoder( + hidden_state, + position_ids, + attention_mask, + attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + attention_head_size: spec.attention_head_size, + cache: cache, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + num_key_value_heads: spec.num_key_value_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + layer_norm: + &Layers.rms_norm(&1, shift: 1.0, name: &2, epsilon: spec.layer_norm_epsilon, upcast: :all), + ffn: + &gated_ffn(&1, spec.intermediate_size, spec.hidden_size, + name: &2, + activation: spec.activation + ), + block_type: :norm_first, + causal: true, + rotary_embedding: [ + position_ids: position_ids, + max_positions: spec.max_positions, + base: spec.rotary_embedding_base, + scaling_strategy: spec.rotary_embedding_scaling_strategy + ], + query_use_bias: spec.use_attention_bias, + key_use_bias: spec.use_attention_bias, + value_use_bias: spec.use_attention_bias, + output_use_bias: spec.use_attention_bias, + name: join(name, "blocks") + ) + end + + defp gated_ffn(hidden_state, intermediate_size, output_size, opts) do + name = opts[:name] + activation = opts[:activation] + + intermediate = + Axon.dense(hidden_state, intermediate_size, + name: join(name, "intermediate"), + use_bias: false + ) + + gate = Axon.dense(hidden_state, intermediate_size, name: join(name, "gate"), use_bias: false) + + hidden_state = Axon.multiply(intermediate, Axon.activation(gate, activation)) + + Axon.dense(hidden_state, output_size, name: join(name, "output"), use_bias: false) + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: Tie lm-head to word embedding as a spec option + Layers.dense_transposed(hidden_state, spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + scaling_strategy_converter = fn name, value -> + case value do + %{"type" => "linear", "factor" => factor} when is_number(factor) -> + {:ok, %{type: :linear, factor: factor}} + + %{"type" => "dynamic", "factor" => factor} when is_number(factor) -> + {:ok, %{type: :dynamic, factor: factor}} + + _other -> + {:error, "invalid format for #{inspect(name)}, got: #{inspect(value)}"} + end + end + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"max_position_embeddings", number()}, + hidden_size: {"hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_attention_heads: {"num_attention_heads", number()}, + num_key_value_heads: {"num_key_value_heads", number()}, + attention_head_size: {"head_dim", number()}, + intermediate_size: {"intermediate_size", number()}, + activation: {"hidden_act", activation()}, + use_attention_bias: {"attention_bias", boolean()}, + rotary_embedding_base: {"rope_theta", number()}, + rotary_embedding_scaling_strategy: + {"rope_scaling", optional(scaling_strategy_converter)}, + initializer_scale: {"initializer_range", number()}, + layer_norm_epsilon: {"rms_norm_eps", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.token_embedding" => "model.embed_tokens", + "decoder.blocks.{n}.self_attention.query" => "model.layers.{n}.self_attn.q_proj", + "decoder.blocks.{n}.self_attention.key" => "model.layers.{n}.self_attn.k_proj", + "decoder.blocks.{n}.self_attention.value" => "model.layers.{n}.self_attn.v_proj", + "decoder.blocks.{n}.self_attention.output" => "model.layers.{n}.self_attn.o_proj", + "decoder.blocks.{n}.self_attention_norm" => "model.layers.{n}.input_layernorm", + "decoder.blocks.{n}.self_attention.rotary_embedding" => + "model.layers.{n}.self_attn.rotary_emb", + "decoder.blocks.{n}.ffn.gate" => "model.layers.{n}.mlp.gate_proj", + "decoder.blocks.{n}.ffn.intermediate" => "model.layers.{n}.mlp.up_proj", + "decoder.blocks.{n}.ffn.output" => "model.layers.{n}.mlp.down_proj", + "decoder.blocks.{n}.output_norm" => "model.layers.{n}.post_attention_layernorm", + "output_norm" => "model.norm", + "language_modeling_head.output" => "model.embed_tokens", + "sequence_classification_head.output" => "score" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/generation.ex b/deps/bumblebee/lib/bumblebee/text/generation.ex new file mode 100644 index 0000000000000000000000000000000000000000..935c49213749cdb31f6deeab1e675a4f9b236f6f --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/generation.ex @@ -0,0 +1,915 @@ +defmodule Bumblebee.Text.Generation do + @moduledoc """ + An interface for language models supporting sequence generation. + """ + + @type cache :: Nx.Tensor.t() | Nx.Container.t() + + @doc """ + Initializes an opaque cache input for iterative inference. + """ + @callback init_cache( + spec :: Bumblebee.ModelSpec.t(), + batch_size :: pos_integer(), + max_length :: pos_integer(), + inputs :: map() + ) :: cache() + + @doc """ + Traverses all batched tensors in the cache. + + This function is used when the cache needs to be inflated or + deflated for a different batch size. + """ + @callback traverse_cache( + spec :: Bumblebee.ModelSpec.t(), + cache(), + (Nx.Tensor.t() -> Nx.Tensor.t()) + ) :: cache() + + @doc """ + Returns a configuration module for extra model-specific generation + attributes to extend the base `Bumblebee.Text.GenerationConfig`. + """ + @callback extra_config_module(spec :: Bumblebee.ModelSpec.t()) :: module() + + @optional_callbacks extra_config_module: 1 + + import Nx.Defn + + alias Bumblebee.Utils + + @doc """ + Initializes an opaque cache input for iterative inference. + """ + @spec init_cache(Bumblebee.ModelSpec.t(), pos_integer(), pos_integer(), map()) :: cache() + def init_cache(%module{} = spec, batch_size, max_length, inputs) do + module.init_cache(spec, batch_size, max_length, inputs) + end + + @doc """ + Calls `fun` for every batched tensor in the cache. + """ + @spec traverse_cache( + Bumblebee.ModelSpec.t(), + cache, + (Nx.Tensor.t() -> Nx.Tensor.t()) + ) :: cache() + def traverse_cache(%module{} = spec, cache, fun) do + module.traverse_cache(spec, cache, fun) + end + + @doc """ + Returns a configuration module for extra model-specific generation + attributes to extend the base `Bumblebee.Text.GenerationConfig`. + """ + @spec extra_config_module(Bumblebee.ModelSpec.t()) :: module() | nil + def extra_config_module(%module{} = spec) do + if Code.ensure_loaded?(module) and function_exported?(module, :extra_config_module, 1) do + module.extra_config_module(spec) + end + end + + @doc """ + Builds a numerical definition that generates sequences of tokens using + the given language model. + + The model should be either a decoder or an encoder-decoder. The tokens + are generated by iterative inference using the decoder (autoregression), + until the termination criteria are met. + + In case of encoder-decoder models, the corresponding encoder is run + only once and the intermediate state is reused during all iterations. + + The generation is controlled by a number of options given as + `%Bumblebee.Text.GenerationConfig{}`, see the corresponding docs + for more details. + + Returns a defn JIT-compatible anonymous function, which expects the + model params as the first argument and inputs map as the second + argument. Note that the inputs map should additionally include a + `"seed"` tensor, with one value per input in the batch. + + ## Streaming + + This function sets up a hook that is invoked after every generated + token. The hook receives a map with the following attributes: + + * `:token_id` - the newly generated token + + * `:finished?` - a boolean indicating if the sequence is finished + + * `:length` - the current length of the generated sequence. Once + the sequence is finished, the length does not increase + + Each of the attributes is a tensor with a leading batch dimension. + + When streaming you may not care about the output result, in which + case you can enable `:ignore_output` to reduce the output size. + + ## Options + + * `:logits_processors` - a list of numerical functions to modify + predicted scores at each generation step. The functions are + applied in order, after all default processors + + * `:ignore_output` - if true, returns a dummy tensor that should + be ignored. This is useful when you consume the generated tokens + in a stream fashion via the hook, so that the full output does + not need to be transferred unnecessarily after the computation. + Defaults to `false` + + """ + @spec build_generate( + Axon.t(), + Bumblebee.ModelSpec.t(), + Bumblebee.Text.GenerationConfig.t(), + keyword() + ) :: + (params :: map(), inputs :: map() -> + %{token_ids: Nx.Tensor.t(), length: Nx.Tensor.t()} | (ignored :: Nx.Tensor.t())) + def build_generate(model, spec, config, opts \\ []) do + opts = Keyword.validate!(opts, logits_processors: [], ignore_output: false) + + decoder_start_token_id = config.decoder_start_token_id || config.bos_token_id + eos_token_id = config.eos_token_id + + pad_token_id = + config.pad_token_id || + case config.eos_token_id do + [eos_token_id | _] -> eos_token_id + eos_token_id -> eos_token_id + end + + unless pad_token_id do + raise ArgumentError, + "expected :pad_token_id (or :eos_token_id as a fallback) to be present in" <> + " generation config, but it was not set. Make sure to load a complete" <> + " generation config or update it accordingly using Bumblebee.configure/2" + end + + {max_length_fun, min_length_fun} = lazy_lengths_from_opts(config) + + {prepare_inputs_fun, update_inputs_fun} = + input_callbacks(model, spec, max_length_fun, decoder_start_token_id) + + traverse_cache_fun = &traverse_cache(spec, &1, &2) + + global_layer_options = + if config.strategy.type == :contrastive_search do + [output_hidden_states: true] + else + [] + end + + {_init_fun, predict_fun} = Axon.build(model, global_layer_options: global_layer_options) + + logits_processor_fun = get_logits_processor(min_length_fun, config, opts[:logits_processors]) + + &generate_impl( + &2, + predict_fun, + &1, + logits_processor_fun, + prepare_inputs_fun, + update_inputs_fun, + traverse_cache_fun, + pad_token_id: pad_token_id, + eos_token_id: eos_token_id, + strategy: config.strategy, + ignore_output: opts[:ignore_output] + ) + end + + defp lazy_lengths_from_opts(opts) do + max_length_fun = + case {opts.max_new_tokens, opts.max_length} do + {nil, nil} -> + raise ArgumentError, + "expected either :max_new_tokens or :max_length option, but neither was given" + + {max_new_tokens, nil} -> + fn input_length -> input_length + max_new_tokens end + + {nil, max_length} -> + fn _ -> max_length end + end + + min_length_fun = + case {opts.min_new_tokens, opts.min_length} do + {nil, nil} -> + nil + + {min_new_tokens, nil} -> + fn input_length -> input_length + min_new_tokens end + + {nil, min_length} -> + fn _ -> min_length end + end + + {max_length_fun, min_length_fun} + end + + defp encoder_from_encoder_decoder(model) do + # We cherry-pick encoder outputs from the encoder-decoder outputs. + # The expanded expression will have no decoder bits, so it will + # effectively be the same as an encoder built from scratch + + Axon.nx(model, fn outputs -> + case outputs do + %{ + encoder_hidden_state: hidden_state, + encoder_hidden_states: hidden_states, + encoder_attentions: attentions + } -> + %{ + hidden_state: hidden_state, + hidden_states: hidden_states, + attentions: attentions + } + + _ -> + raise ArgumentError, + "expected an encoder-decoder model, but it does not have the expected outputs" + end + end) + end + + defp input_callbacks(model, spec, max_length_fun, decoder_start_token_id) do + if encoder_decoder?(model) do + encoder = encoder_from_encoder_decoder(model) + {_encoder_init_fun, encoder_predict_fun} = Axon.build(encoder) + + prepare_inputs_fun = fn inputs, params -> + encoder_outputs = encoder_predict_fun.(params, inputs) + + padded_batch_item? = padded_batch_item?(encoder_input(inputs)) + batch_size = Nx.axis_size(encoder_input(inputs), 0) + + inputs = Map.put(inputs, "encoder_hidden_state", encoder_outputs.hidden_state) + + inputs = + Map.put_new_lazy(inputs, "decoder_input_ids", fn -> + Nx.broadcast(decoder_start_token_id, {batch_size, 1}) + end) + + max_length = max_length_fun.(1) + inputs = prepare_decoder_inputs(inputs, "decoder_", spec, model, max_length) + {inputs, inputs["decoder_input_ids"], padded_batch_item?, max_length} + end + + update_inputs_fun = &update_decoder_inputs("decoder_", &1, &2, &3) + + {prepare_inputs_fun, update_inputs_fun} + else + prepare_inputs_fun = fn inputs, _params -> + padded_batch_item? = padded_batch_item?(inputs["input_ids"]) + sequence_length = Nx.axis_size(inputs["input_ids"], 1) + max_length = max_length_fun.(sequence_length) + inputs = prepare_decoder_inputs(inputs, "", spec, model, max_length) + {inputs, inputs["input_ids"], padded_batch_item?, max_length} + end + + update_inputs_fun = &update_decoder_inputs("", &1, &2, &3) + + {prepare_inputs_fun, update_inputs_fun} + end + end + + defp encoder_decoder?(model) do + inputs = Axon.get_inputs(model) + encoder_input(inputs) != nil and Map.has_key?(inputs, "decoder_input_ids") + end + + defp encoder_input(inputs) do + inputs["input_ids"] || inputs["input_features"] || inputs["pixel_values"] + end + + defp padded_batch_item?(input) do + [_ | non_batch_axes] = Nx.axes(input) + # We check each batch item if it is full of zeros, in which case + # case we assume it's padding, not an actual input. + input |> Nx.equal(0) |> Nx.all(axes: non_batch_axes) + end + + defp prepare_decoder_inputs(inputs, prefix, spec, model, max_length) do + input_ids = inputs[prefix <> "input_ids"] + attention_mask = inputs[prefix <> "attention_mask"] || Nx.broadcast(1, input_ids) + + position_ids = + attention_mask + |> Nx.cumulative_sum(axis: 1) + # Position ids are zero-indexed, so we want to subtract 1. + # However, attention mask may have zeros on the left, in which + # case cumulative sum leaves zeros there as well and we don't + # want to subtract from these. + |> Nx.subtract(Nx.select(attention_mask, 1, 0)) + + inputs = + inputs + |> Map.put(prefix <> "attention_mask", attention_mask) + |> Map.put(prefix <> "position_ids", position_ids) + + batch_size = Nx.axis_size(input_ids, 0) + cache = init_cache(spec, batch_size, max_length, inputs) + + output_policy = model_output_policy(model) + + # Cast all float cache tensors to match the model output. This way + # we make sure the cache we pass as input has the same types as + # the updated cache returned from the model + cache = + Bumblebee.Utils.Nx.map(cache, fn tensor -> + Axon.MixedPrecision.cast(output_policy, tensor, :output) + end) + + Map.put(inputs, "cache", cache) + end + + defp model_output_policy(model) do + {node, _} = Axon.pop_node(model) + node.policy + end + + defp update_decoder_inputs(prefix, inputs, cache, token_ids) do + inputs + |> Map.replace!(prefix <> "input_ids", token_ids) + |> Map.replace!(prefix <> "attention_mask", Nx.broadcast(1, token_ids)) + |> Map.update!(prefix <> "position_ids", fn position_ids -> + position_ids + |> Nx.slice_along_axis(Nx.axis_size(position_ids, -1) - 1, 1, axis: -1) + |> Nx.add(1) + end) + |> Map.replace!("cache", cache) + end + + defp get_logits_processor(min_length_fun, config, logits_processors) do + import Bumblebee.Text.Generation.LogitsProcessing + + processors = + [ + if config.no_repeat_ngram_length && config.no_repeat_ngram_length > 0 do + &no_repeat_ngram_processor(&1, &2, ngram_length: config.no_repeat_ngram_length) + end, + if min_length_fun && config.eos_token_id do + &min_length_processor(&1, &2, + min_length_fun: min_length_fun, + eos_token_ids: List.wrap(config.eos_token_id) + ) + end, + if config.suppressed_token_ids != [] do + &suppressed_tokens_processor(&1, &2, suppressed_token_ids: config.suppressed_token_ids) + end, + if config.forced_bos_token_id do + &bos_token_processor(&1, &2, bos_token_id: config.forced_bos_token_id) + end, + if config.forced_eos_token_id do + &eos_token_processor(&1, &2, eos_token_id: config.forced_eos_token_id) + end, + if config.forced_token_ids do + &forced_tokens_processor(&1, &2, forced_token_ids: config.forced_token_ids) + end, + if config.temperature && config.temperature != 1.0 do + &temperature_processor(&1, &2, temperature: config.temperature) + end + ] ++ + if config.strategy.type == :multinomial_sampling do + [ + if top_k = config.strategy[:top_k] do + &top_k_processor(&1, &2, top_k: top_k) + end, + if top_p = config.strategy[:top_p] do + &top_p_processor(&1, &2, top_p: top_p) + end + ] + else + [] + end ++ logits_processors + + fn logits, context -> + for processor <- processors, processor, reduce: logits do + logits -> processor.(logits, context) + end + end + end + + defnp generate_impl( + inputs, + predict_fun, + params, + logits_processor_fun, + prepare_inputs_fun, + update_inputs_fun, + traverse_cache_fun, + opts \\ [] + ) do + {seed, inputs} = pop_seed(inputs) + + {decoder_inputs, decoder_input_ids, padded_batch_item?, max_length} = + prepare_inputs_fun.(inputs, params) + + length = Nx.axis_size(decoder_input_ids, 1) + + if length >= max_length do + raise ArgumentError, + "the input sequence has #{length} tokens, but max_length is set to #{max_length}." <> + " Consider increasing :max_new_tokens (or :max_length), or padding the input to a shorter length" + end + + strategy = opts[:strategy] + + state = + case strategy.type do + :greedy_search -> + greedy( + decoder_inputs, + decoder_input_ids, + padded_batch_item?, + predict_fun, + params, + logits_processor_fun, + update_inputs_fun, + merge_options([max_length: max_length], opts) + ) + + :contrastive_search -> + contrastive( + decoder_inputs, + decoder_input_ids, + padded_batch_item?, + predict_fun, + params, + logits_processor_fun, + update_inputs_fun, + traverse_cache_fun, + merge_options( + [max_length: max_length, top_k: strategy.top_k, penalty_alpha: strategy.alpha], + opts + ) + ) + + :multinomial_sampling -> + sampling( + decoder_inputs, + decoder_input_ids, + padded_batch_item?, + predict_fun, + params, + seed, + logits_processor_fun, + update_inputs_fun, + merge_options([max_length: max_length], opts) + ) + end + + if opts[:ignore_output] do + state.ignored + else + %{ + # Output only the newly generated tokens + token_ids: state.sequences[[.., length..-1//1]], + length: state.finished_length - length + } + end + end + + deftransformp pop_seed(inputs), do: Map.pop!(inputs, "seed") + + deftransformp merge_options(left, right), do: left ++ right + + # Greedy search + + defnp greedy( + inputs, + decoder_input_ids, + padded_batch_item?, + predict_fun, + params, + logits_processor_fun, + update_inputs_fun, + opts \\ [] + ) do + max_length = opts[:max_length] + pad_token_id = opts[:pad_token_id] + eos_token_id = opts[:eos_token_id] + + state = init_sequences(decoder_input_ids, padded_batch_item?, max_length, pad_token_id) + + # The loop works with inputs of length 1, so if the initial input + # is longer, we make the initial pass outside + {state, inputs} = + if state.length > 1 do + greedy_step( + state, + inputs, + predict_fun, + params, + logits_processor_fun, + update_inputs_fun, + pad_token_id: pad_token_id, + eos_token_id: eos_token_id + ) + else + {state, inputs} + end + + {state, _inputs, _params} = + while {state, inputs, params}, continue?(state.finished_length) do + {state, inputs} = + greedy_step( + state, + inputs, + predict_fun, + params, + logits_processor_fun, + update_inputs_fun, + pad_token_id: pad_token_id, + eos_token_id: eos_token_id + ) + + {state, inputs, params} + end + + state + end + + defnp init_sequences(decoder_input_ids, padded_batch_item?, max_length, pad_token_id) do + {batch_size, length} = Nx.shape(decoder_input_ids) + + sequences = Nx.broadcast(pad_token_id, {batch_size, max_length}) + sequences = Nx.put_slice(sequences, [0, 0], decoder_input_ids) + + # For each sequence, we keep track of its final length, where 0 + # means that it has not been finished yet. If there are padding + # batch inputs, we immediately mark them as finished, otherwise + # they could produce arbitrary tokens until we reach max length. + finished_length = Nx.select(padded_batch_item?, 1, 0) + + %{ + sequences: sequences, + input_length: length, + length: length, + finished_length: finished_length, + # The ignored return value that we attach all hooks to + ignored: Nx.broadcast(0, {batch_size}) + } + end + + defnp continue?(finished_length) do + Nx.any(finished_length == 0) + end + + defnp greedy_step( + state, + inputs, + predict_fun, + params, + logits_processor_fun, + update_inputs_fun, + opts + ) do + pad_token_id = opts[:pad_token_id] + eos_token_id = opts[:eos_token_id] + + outputs = predict_fun.(params, inputs) + + logits = outputs.logits[[.., -1]] + logits = batch_process_logits(logits_processor_fun, logits, state) + token_id = Nx.argmax(logits, axis: -1) + + state = update_sequences(state, token_id, pad_token_id, eos_token_id) + + inputs = update_inputs_fun.(inputs, outputs.cache, Nx.new_axis(token_id, -1)) + + {state, inputs} + end + + defnp update_sequences(state, token_id, pad_token_id, eos_token_id) do + %{ + sequences: sequences, + length: length, + input_length: input_length, + finished_length: finished_length + } = state + + token_id = Nx.select(finished_length > 0, pad_token_id, token_id) + + token_ids = Nx.new_axis(token_id, -1) + sequences = Nx.put_slice(sequences, [0, length], token_ids) + length = length + 1 + + {batch_size, max_length} = Nx.shape(sequences) + + finished_length = + Nx.select( + finished_length == 0 and (eos_token?(token_id, eos_token_id) or length == max_length), + length, + finished_length + ) + + finished? = finished_length > 0 + output_length = Nx.broadcast(length - input_length, {batch_size}) + data = %{token_id: token_id, finished?: finished?, length: output_length} + token = create_token() + {token, _} = hook_token(token, data, :token) + + state = %{state | sequences: sequences, length: length, finished_length: finished_length} + attach_token(token, state) + end + + deftransformp eos_token?(token_id, eos_token_id) do + if eos_token_id do + eos_token_ids = List.wrap(eos_token_id) + + token_id + |> Nx.vectorize(:batch) + |> Nx.equal(Nx.tensor(eos_token_ids)) + |> Nx.any() + |> Nx.devectorize() + else + Nx.tensor(false) + end + end + + defnp batch_process_logits(logits_processor_fun, logits, state) do + logits + |> Nx.vectorize(:batch) + |> logits_processor_fun.(%{ + sequence: Nx.vectorize(state.sequences, :batch), + length: state.length, + input_length: state.input_length + }) + |> Nx.devectorize(keep_names: false) + end + + # Contrastive search + + defnp contrastive( + inputs, + decoder_input_ids, + padded_batch_item?, + predict_fun, + params, + logits_processor_fun, + update_inputs_fun, + traverse_cache_fun, + opts \\ [] + ) do + max_length = opts[:max_length] + pad_token_id = opts[:pad_token_id] + eos_token_id = opts[:eos_token_id] + top_k = opts[:top_k] + penalty_alpha = opts[:penalty_alpha] + + state = init_sequences(decoder_input_ids, padded_batch_item?, max_length, pad_token_id) + + # Step (1) + # Initial pass to obtain hidden state and expand inputs to top-k + + outputs = predict_fun.(params, inputs) + + # Later, we feed model a single token at a time and reuse previous + # results using cache. Here we need the final hidden state, so we + # need to keep track of it in a similar way + initial_hidden_state = decoder_hidden_state(outputs) + batch_size = Nx.axis_size(initial_hidden_state, 0) + hidden_size = Nx.axis_size(initial_hidden_state, -1) + + joint_hidden_state = + Nx.broadcast( + Nx.tensor(0, type: Nx.type(initial_hidden_state)), + {batch_size, max_length, hidden_size} + ) + + joint_hidden_state = Nx.put_slice(joint_hidden_state, [0, 0, 0], initial_hidden_state) + + logits = outputs.logits[[.., -1]] + logits = batch_process_logits(logits_processor_fun, logits, state) + scores = Axon.Activations.softmax(logits, axis: -1) + {top_k_scores, top_k_token_ids} = Nx.top_k(scores, k: top_k) + + # For subsequent model passes we consider several (top-k) paths + # for each batch item, so we duplicate inputs and cache accordingly + inputs = expand_inputs(inputs, top_k) + cache = expand_cache(outputs.cache, top_k, traverse_cache_fun) + inputs = update_inputs_fun.(inputs, cache, Nx.reshape(top_k_token_ids, {:auto, 1})) + + # Step (2) + # In the loop we make prediction for top-k continuation tokens and + # pick the best one using the contrastive rank. From the same model + # pass we also get the next top-k continuation tokens + + {state, _inputs, _params, _joint_hidden_state, _top_k_values} = + while {state, inputs, params, joint_hidden_state, {top_k_scores, top_k_token_ids}}, + continue?(state.finished_length) do + outputs = predict_fun.(params, inputs) + + hidden_state = decoder_hidden_state(outputs) + + context_hidden_state = Utils.Nx.repeat_interleave(joint_hidden_state, top_k) + + selected_idx = + contrastive_rank( + context_hidden_state, + hidden_state, + state.length, + top_k_scores, + penalty_alpha, + top_k + ) + + hidden_state = Utils.Nx.chunked_take(hidden_state, top_k, selected_idx) + joint_hidden_state = Nx.put_slice(joint_hidden_state, [0, state.length, 0], hidden_state) + + token_id = top_k_token_ids |> Nx.flatten() |> Utils.Nx.chunked_take(top_k, selected_idx) + + state = update_sequences(state, token_id, pad_token_id, eos_token_id) + + logits = outputs.logits[[.., -1]] + logits = Utils.Nx.chunked_take(logits, top_k, selected_idx) + logits = batch_process_logits(logits_processor_fun, logits, state) + + scores = Axon.Activations.softmax(logits, axis: -1) + {top_k_scores, top_k_token_ids} = Nx.top_k(scores, k: top_k) + + # Mirror the selected idx to other entries within each chunk + cache = reflect_cache(outputs.cache, top_k, selected_idx, traverse_cache_fun) + inputs = update_inputs_fun.(inputs, cache, Nx.reshape(top_k_token_ids, {:auto, 1})) + + {state, inputs, params, joint_hidden_state, {top_k_scores, top_k_token_ids}} + end + + state + end + + deftransformp decoder_hidden_state(outputs) do + hidden_states = + case outputs do + %{decoder_hidden_states: hidden_states} -> hidden_states + %{hidden_states: hidden_states} -> hidden_states + end + + elem(hidden_states, tuple_size(hidden_states) - 1) + end + + deftransformp expand_inputs(inputs, times) do + Map.new(inputs, fn + {key, value} when key in ["cache"] -> + {key, value} + + {key, %Nx.Tensor{} = value} -> + {key, Utils.Nx.repeat_interleave(value, times)} + end) + end + + deftransformp expand_cache(cache, times, traverse_cache_fun) do + traverse_cache_fun.(cache, &Utils.Nx.repeat_interleave(&1, times)) + end + + deftransformp reflect_cache(cache, times, idx, traverse_cache_fun) do + traverse_cache_fun.( + cache, + &(&1 + |> Utils.Nx.chunked_take(times, idx) + |> Utils.Nx.repeat_interleave(times)) + ) + end + + defnp contrastive_rank( + context_hidden_state, + hidden_state, + length, + top_k_scores, + penalty_alpha, + top_k + ) do + similarity_matrix = + context_hidden_state + |> Bumblebee.Utils.Nx.cosine_similarity(hidden_state, batched?: true) + # hidden_state has sequence length of 1, so the batch of similarity + # matrices has shape {batch_size * top_k, max_length, 1} and we + # flatten out the last dimension + |> Nx.squeeze(axes: [-1]) + + # context_hidden_state includes placeholder values for tokens up + # to max_length, so we need to ignore these + current_sequence? = Nx.iota(Nx.shape(similarity_matrix), axis: -1) < length + + degeneration_penalty = + current_sequence? + |> Nx.select(similarity_matrix, Nx.Constants.neg_infinity()) + |> Nx.reduce_max(axes: [-1]) + + contrastive_score = + (1.0 - penalty_alpha) * Nx.flatten(top_k_scores) - penalty_alpha * degeneration_penalty + + contrastive_score + |> Nx.reshape({:auto, top_k}) + |> Nx.argmax(axis: -1) + end + + # Multinomial sampling + + defnp sampling( + inputs, + decoder_input_ids, + padded_batch_item?, + predict_fun, + params, + seed, + logits_processor_fun, + update_inputs_fun, + opts \\ [] + ) do + max_length = opts[:max_length] + pad_token_id = opts[:pad_token_id] + eos_token_id = opts[:eos_token_id] + + state = init_sequences(decoder_input_ids, padded_batch_item?, max_length, pad_token_id) + + prng_key = seed |> Nx.vectorize(:batch) |> Nx.Random.key() + + # The loop works with inputs of length 1, so if the initial input + # is longer, we make the initial pass outside + {state, inputs, prng_key} = + if state.length > 1 do + sampling_step( + state, + inputs, + predict_fun, + params, + prng_key, + logits_processor_fun, + update_inputs_fun, + pad_token_id: pad_token_id, + eos_token_id: eos_token_id + ) + else + {state, inputs, prng_key} + end + + {state, _inputs, _params, _key} = + while {state, inputs, params, prng_key}, continue?(state.finished_length) do + {state, inputs, prng_key} = + sampling_step( + state, + inputs, + predict_fun, + params, + prng_key, + logits_processor_fun, + update_inputs_fun, + pad_token_id: pad_token_id, + eos_token_id: eos_token_id + ) + + {state, inputs, params, prng_key} + end + + state + end + + defnp sampling_step( + state, + inputs, + predict_fun, + params, + prng_key, + logits_processor_fun, + update_inputs_fun, + opts \\ [] + ) do + pad_token_id = opts[:pad_token_id] + eos_token_id = opts[:eos_token_id] + + key = Nx.Random.split(prng_key) + {key, prng_key} = {key[1], key[0]} + + outputs = predict_fun.(params, inputs) + + logits = outputs.logits[[.., -1]] + logits = batch_process_logits(logits_processor_fun, logits, state) + scores = Axon.Activations.softmax(logits) + token_id = batched_choice(key, scores) + + state = update_sequences(state, token_id, pad_token_id, eos_token_id) + + inputs = update_inputs_fun.(inputs, outputs.cache, Nx.new_axis(token_id, -1)) + + {state, inputs, prng_key} + end + + deftransformp batched_choice(key, scores) do + vocab_size = Nx.axis_size(scores, 1) + + vocab = Nx.iota({vocab_size}) + + probabilities = Nx.vectorize(scores, :batch) + + {tokens, _} = Nx.Random.choice(key, vocab, probabilities, samples: 1) + + tokens + |> Nx.squeeze() + |> Nx.devectorize() + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/generation/logits_processing.ex b/deps/bumblebee/lib/bumblebee/text/generation/logits_processing.ex new file mode 100644 index 0000000000000000000000000000000000000000..eff38e526f07aedface34633b277a3945c9e8720 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/generation/logits_processing.ex @@ -0,0 +1,262 @@ +defmodule Bumblebee.Text.Generation.LogitsProcessing do + @moduledoc false + + import Nx.Defn + + deftransform suppressed_tokens_processor(logits, _context, opts \\ []) do + opts = Keyword.validate!(opts, [:suppressed_token_ids]) + + indices = opts[:suppressed_token_ids] |> Nx.tensor() |> Nx.new_axis(-1) + values = Nx.broadcast(Nx.Constants.neg_infinity(Nx.type(logits)), {Nx.size(indices)}) + Nx.indexed_put(logits, indices, values) + end + + defn bos_token_processor(logits, context, opts \\ []) do + opts = keyword!(opts, [:bos_token_id]) + bos_token_id = opts[:bos_token_id] + + if context.length == 1 do + force_token_id(logits, bos_token_id) + else + logits + end + end + + defn eos_token_processor(logits, context, opts \\ []) do + opts = keyword!(opts, [:eos_token_id]) + eos_token_id = opts[:eos_token_id] + + max_length = Nx.axis_size(context.sequence, 0) + + if context.length == max_length - 1 do + force_token_id(logits, eos_token_id) + else + logits + end + end + + defn forced_tokens_processor(logits, context, opts \\ []) do + opts = keyword!(opts, [:forced_token_ids]) + forced_token_ids(logits, context, opts[:forced_token_ids]) + end + + deftransformp forced_token_ids(logits, context, forced_token_ids) do + clauses = + for {idx, token_id} <- forced_token_ids do + {Nx.equal(context.length, idx), force_token_id(logits, token_id)} + end + + # Note that we can't use defn ifs inside transform, so we build + # the expression directly + Nx.Defn.Expr.cond(clauses, logits) + end + + defn min_length_processor(logits, context, opts \\ []) do + opts = keyword!(opts, [:eos_token_ids, :min_length_fun]) + eos_token_ids = opts[:eos_token_ids] + min_length_fun = opts[:min_length_fun] + + min_length = min_length_fun.(context.input_length) + + if context.length < min_length do + ignore_token_ids(logits, eos_token_ids) + else + logits + end + end + + defn no_repeat_ngram_processor(logits, context, opts \\ []) do + opts = keyword!(opts, [:ngram_length]) + ngram_length = opts[:ngram_length] + + if context.length + 1 < ngram_length do + logits + else + # Given a sequence of last {ngram_length - 1} tokens, we look + # for prior occurrences of that sequence and we want to make the + # subsequent token ignored. This way the n-gram is not repeated + # this time around + + ngram_but_one_length = ngram_length - 1 + + last_ngram_but_one = + Nx.slice_along_axis( + context.sequence, + context.length - ngram_but_one_length, + ngram_but_one_length, + axis: 0 + ) + + {_, _, _, _, logits} = + while {i = 0, last_ngram_but_one, sequence = context.sequence, length = context.length, + logits}, + i + ngram_but_one_length < length do + ngram_but_one = Nx.slice_along_axis(sequence, i, ngram_but_one_length, axis: 0) + + token_id = sequence[i + ngram_but_one_length] + indices = Nx.new_axis(token_id, -1) + + match? = Nx.all(ngram_but_one == last_ngram_but_one) + updates = Nx.select(match?, Nx.Constants.neg_infinity(Nx.type(logits)), 0) + logits = Nx.indexed_add(logits, indices, updates) + + {i + 1, last_ngram_but_one, sequence, length, logits} + end + + logits + end + end + + deftransformp force_token_id(logits, token_id) do + logits + |> Nx.fill(Nx.Constants.neg_infinity(), type: Nx.type(logits)) + |> Nx.put_slice([token_id], Nx.tensor([0], type: Nx.type(logits))) + end + + deftransformp ignore_token_id(logits, token_id) do + Nx.put_slice( + logits, + [token_id], + Nx.broadcast(Nx.Constants.neg_infinity(Nx.type(logits)), {1}) + ) + end + + deftransformp ignore_token_ids(logits, token_ids) do + Enum.reduce(token_ids, logits, &ignore_token_id(&2, &1)) + end + + defn temperature_processor(logits, _context, opts \\ []) do + opts = keyword!(opts, [:temperature]) + temperature = opts[:temperature] + + logits / temperature + end + + # Processors manipulating the probability distribution + + defn top_k_processor(logits, _context, opts \\ []) do + opts = keyword!(opts, [:top_k]) + top_k = opts[:top_k] + + {top_k_logits, _} = Nx.top_k(logits, k: top_k) + kth_logit = top_k_logits[-1] + Nx.select(logits < kth_logit, Nx.Constants.neg_infinity(Nx.type(logits)), logits) + end + + defn top_p_processor(logits, _context, opts \\ []) do + opts = keyword!(opts, [:top_p]) + top_p = opts[:top_p] + + sorted_idx = Nx.argsort(logits) + + cumulative_scores = + logits + |> Nx.take_along_axis(sorted_idx) + |> Axon.Activations.softmax() + |> Nx.cumulative_sum() + + ordered_ignore_mask = cumulative_scores <= 1 - top_p + + # Arrange the mask back into the original logits order + ignore_mask = + Nx.indexed_put( + Nx.fill(ordered_ignore_mask, 0), + Nx.new_axis(sorted_idx, -1), + Nx.flatten(ordered_ignore_mask) + ) + + Nx.select(ignore_mask, Nx.Constants.neg_infinity(Nx.type(logits)), logits) + end + + defn whisper_timestamp_processor(logits, context, opts \\ []) do + opts = + keyword!(opts, [ + :eos_token_id, + :forced_token_ids, + :no_timestamps_token_id, + :timestamp_begin_id + ]) + + eos_token_id = opts[:eos_token_id] + no_timestamps_token_id = opts[:no_timestamps_token_id] + timestamp_begin_id = opts[:timestamp_begin_id] + + begin_idx = begin_idx(opts[:forced_token_ids]) + + # Ensure the no-timestamps token is never taken + logits = ignore_token_id(logits, no_timestamps_token_id) + + cond do + context.length < begin_idx -> + logits + + context.length == begin_idx -> + # Output the starting timestamp + force_token_id(logits, timestamp_begin_id) + + true -> + logits + |> force_timestamp_pair(context, begin_idx, eos_token_id, timestamp_begin_id) + |> maybe_force_timestamp(timestamp_begin_id) + end + end + + defnp force_timestamp_pair(logits, context, begin_idx, eos_token_id, timestamp_begin_id) do + # Force timestamp tokens to appear in pairs, end followed by + # start, except directly before the EOS token + + prev_was_timestamp? = + if context.length - begin_idx >= 1 do + context.sequence[context.length - 1] >= timestamp_begin_id + else + Nx.tensor(false) + end + + # Either second to last was timestamp or is out of range + prev_was_timestamp_start? = + if context.length - begin_idx >= 2 do + context.sequence[context.length - 2] >= timestamp_begin_id + else + Nx.tensor(true) + end + + ignore_mask = + Nx.logical_and( + prev_was_timestamp?, + Nx.select( + Nx.broadcast(Nx.new_axis(prev_was_timestamp_start?, -1), Nx.shape(logits)), + # Force non-timestamp + Nx.iota(Nx.shape(logits)) >= timestamp_begin_id, + # Force non-normal token + Nx.iota(Nx.shape(logits)) < eos_token_id + ) + ) + + Nx.select(ignore_mask, Nx.Constants.neg_infinity(Nx.type(logits)), logits) + end + + defnp maybe_force_timestamp(logits, timestamp_begin_id) do + # If the total probability of all timestamps exceeds any regular + # token, we force a timestamp + + log_probabilities = Axon.Activations.log_softmax(logits) + timestamp_log_probabilities = log_probabilities[timestamp_begin_id..-1//1] + # TODO: use log_sumexp on Axon v0.6.1 + # timestamp_log_probability = Axon.Activations.log_sumexp(timestamp_log_probabilities) + timestamp_log_probability = timestamp_log_probabilities |> Nx.exp() |> Nx.sum() |> Nx.log() + token_log_probabilities = log_probabilities[0..(timestamp_begin_id - 1)//1] + + max_token_log_probability = Nx.reduce_max(token_log_probabilities) + force_timestamp_mask = timestamp_log_probability > max_token_log_probability + tokens_mask = Nx.iota(Nx.shape(logits)) < timestamp_begin_id + ignore_mask = force_timestamp_mask and tokens_mask + Nx.select(ignore_mask, Nx.Constants.neg_infinity(Nx.type(logits)), logits) + end + + deftransformp begin_idx(forced_token_ids) do + case List.last(forced_token_ids) do + nil -> 1 + {idx, _token_id} -> idx + 1 + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/generation_config.ex b/deps/bumblebee/lib/bumblebee/text/generation_config.ex new file mode 100644 index 0000000000000000000000000000000000000000..d7a6a9a0a81805c72524dd855f8c07cef0a003e1 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/generation_config.ex @@ -0,0 +1,338 @@ +defmodule Bumblebee.Text.GenerationConfig do + alias Bumblebee.Shared + + length_options = [ + max_new_tokens: [ + default: 20, + doc: + "the maximum number of tokens to be generated, ignoring the number of tokens in the prompt" + ], + min_new_tokens: [ + default: nil, + doc: + "the minimum number of tokens to be generated, ignoring the number of tokens in the prompt" + ], + max_length: [ + default: nil, + doc: """ + the maximum length of the sequence to be generated. Note that this length includes the + length of the input prompt (including padding). In general, prefer `:max_new_tokens`, + which ignores the number of tokens in the prompt + """ + ], + min_length: [ + default: nil, + doc: """ + the minimum length of the sequence to be generated. Note that this length includes the + length of the input prompt (including padding). In general, prefer `:min_new_tokens`, + which ignores the number of tokens in the prompt + """ + ] + ] + + strategy_options = [ + strategy: [ + default: %{type: :greedy_search}, + doc: """ + the method deciding how tokens are selected, it has a significant impact on the quality + of the generated sequence. Should be a map with `:type` and strategy-specific options. + + * `:greedy_search` - the most straightforward approach, where in + every iteration the most probable token (as given by the model) + is taken. + + Example: `%{type: :greedy_search}`. + + * `:contrastive_search` - state-of-the-art decoding method, capable + of producing high quality, coherent sequences. The results are + deterministic. See [this article](https://huggingface.co/blog/introducing-csearch) + for more details. + + * `:top_k` (required) - the number of highest probability vocabulary tokens considered + as a continuation + + * `:alpha` (required) - the weight of degeneration penalty. It balances the model + confidence and the penalty + + Example: `%{type: :contrastive_search, top_k: 4, alpha: 0.6}`. + + * `:multinomial_sampling` - this method samples tokens according to the probability + distribution given by the model. The results are nondeterministic, unless a seed + is specified. + + * `:top_k` (optional) - when specified, restricts sampling to top-k most probable + candidates + + * `:top_p` (optional) - when specified, restricts sampling to tokens which probabilities + add up to top-p + """ + ] + ] + + token_options = [ + decoder_start_token_id: [ + default: nil, + doc: + "the id of the initial token when generating from scratch, in case of encoder-decoder models" + ], + forced_bos_token_id: [ + default: nil, + doc: "the id of the token to force as the first generated token" + ], + forced_eos_token_id: [ + default: nil, + doc: + "the id of the token to force as the last generated token when `:max_length` is reached" + ], + forced_token_ids: [ + default: [], + doc: + "a list of `{index, token_id}` pairs forcing `token_id` to appear at `index` in the generated sequence" + ], + suppressed_token_ids: [ + default: [], + doc: "a list of token ids to suppress during generation" + ], + no_repeat_ngram_length: [ + default: nil, + doc: "when set, n-grams of the given length can occur only once in the generated sequence" + ], + temperature: [ + default: nil, + doc: """ + enables exponential scaling of the output probability distribution. The temperature value effectively + determines the randomness of the predicted tokens. Values smaller than 1.0 decrease the randomness, + while bigger values increase it. Note that this is only relevant for generation `:strategy` that does + sampling based on the output probability distribution + """ + ] + ] + + special_token_options = [ + bos_token_id: [ + default: nil, + doc: "the id of the beginning-of-sequence token" + ], + eos_token_id: [ + default: nil, + doc: + "the id of the end-of-sequence token. This can also be a list, in case multiple tokens should be recognized as EOS" + ], + pad_token_id: [ + default: nil, + doc: "the id of the padding token" + ] + ] + + other_options = [ + extra_config: [ + default: nil, + doc: "additional configuration specific to the given model" + ] + ] + + options = + length_options ++ strategy_options ++ token_options ++ special_token_options ++ other_options + + @moduledoc """ + A set of configuration options controlling text generation. + + This struct is expected by `Bumblebee.Text.Generation.build_generate/3`. + + ## Configuration + + ### Options controlling length + + #{Shared.options_doc(length_options)} + + ### Options controlling strategy + + #{Shared.options_doc(strategy_options)} + + ### Options controlling generated tokens + + #{Shared.options_doc(token_options)} + + ### Special tokens used during generation + + #{Shared.options_doc(special_token_options)} + """ + + defstruct Shared.option_defaults(options) + + @behaviour Bumblebee.Configurable + + @type t :: %__MODULE__{} + + @impl true + def config(config, opts \\ []) do + opts = + case {opts[:max_new_tokens], opts[:max_length]} do + {nil, nil} -> + opts + + {_, nil} -> + put_in(opts[:max_length], nil) + + {nil, _} -> + put_in(opts[:max_new_tokens], nil) + + _ -> + raise ArgumentError, + "only one of :max_new_tokens or :max_length options must be given, but got both" + end + + opts = + case {opts[:min_new_tokens], opts[:min_length]} do + {nil, nil} -> + opts + + {_, nil} -> + put_in(opts[:min_length], nil) + + {nil, _} -> + put_in(opts[:min_new_tokens], nil) + + _ -> + raise ArgumentError, + "only one of :min_new_tokens or :min_length options must be given, but got both" + end + + with {:ok, strategy} <- Keyword.fetch(opts, :strategy) do + validate_strategy!(strategy) + end + + Shared.put_config_attrs(config, opts) + end + + defp validate_strategy!(%{type: :greedy_search} = strategy) do + validate_strategy_keys!(strategy, [:type], []) + end + + defp validate_strategy!(%{type: :contrastive_search} = strategy) do + validate_strategy_keys!(strategy, [:type, :top_k, :alpha], []) + end + + defp validate_strategy!(%{type: :multinomial_sampling} = strategy) do + validate_strategy_keys!(strategy, [:type], [:top_k, :top_p]) + end + + defp validate_strategy!(%{type: type}) do + raise ArgumentError, + "expected strategy type to be either :greedy_search or :contrastive_search, got: #{inspect(type)}" + end + + defp validate_strategy!(%{} = other) do + raise ArgumentError, + "expected strategy to have :type, but was not present in #{inspect(other)}" + end + + defp validate_strategy!(other) do + raise ArgumentError, "expected strategy to be a map, but got: #{inspect(other)}" + end + + defp validate_strategy_keys!(strategy, required_keys, optional_keys) do + actual = strategy |> Map.keys() |> Enum.sort() + + missing_keys = Enum.sort(required_keys -- actual) + + if missing_keys != [] do + raise ArgumentError, + "missing keys #{inspect(missing_keys)} for strategy #{inspect(strategy.type)}" + end + + extra_keys = Enum.sort((actual -- required_keys) -- optional_keys) + + if extra_keys != [] do + raise ArgumentError, + "unexpected keys #{inspect(extra_keys)} for strategy #{inspect(strategy.type)}" + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(config, data) do + import Shared.Converters + + # Special case joint configurations + data = + case data do + %{"model_type" => "blip", "text_config" => data} -> data + data -> data + end + + data = + case data do + # During generation BLIP uses SEP token as the EOS token + %{"model_type" => "blip_text_model", "sep_token_id" => sep_token_id} -> + put_in(data["eos_token_id"], sep_token_id) + + data -> + data + end + + data = + case data do + %{"forced_decoder_ids" => ids} -> + ids = Enum.reject(ids, &match?([_idx, nil], &1)) + put_in(data["forced_decoder_ids"], ids) + + data -> + data + end + + data = + case data do + %{"suppress_tokens" => nil} -> Map.delete(data, "suppress_tokens") + data -> data + end + + opts = + convert!(data, + max_new_tokens: {"max_new_tokens", optional(number())}, + min_new_tokens: {"min_new_tokens", optional(number())}, + max_length: {"max_length", optional(number())}, + min_length: {"min_length", optional(number())}, + decoder_start_token_id: {"decoder_start_token_id", optional(number())}, + bos_token_id: {"bos_token_id", optional(number())}, + eos_token_id: {"eos_token_id", optional(one_of([number(), list(number())]))}, + pad_token_id: {"pad_token_id", optional(number())}, + forced_bos_token_id: {"forced_bos_token_id", optional(number())}, + forced_eos_token_id: {"forced_eos_token_id", optional(number())}, + forced_token_ids: {"forced_decoder_ids", list(tuple([number(), number()]))}, + suppressed_token_ids: {"suppress_tokens", list(number())}, + no_repeat_ngram_length: {"no_repeat_ngram_size", number()}, + temperature: {"temperature", number()} + ) + + strategy_opts = + data + |> convert!( + sample: {"do_sample", boolean()}, + top_k: {"top_k", optional(number())}, + top_p: {"top_p", optional(number())}, + alpha: {"penalty_alpha", optional(number())} + ) + |> Enum.reject(fn {_key, value} -> value == nil end) + |> Map.new() + |> case do + %{sample: true} = opts -> + options = + Map.filter(opts, fn + {:top_k, k} when k > 0 -> true + {:top_p, p} when p < 1.0 -> true + _ -> false + end) + + [strategy: Map.merge(%{type: :multinomial_sampling}, options)] + + %{top_k: top_k, alpha: alpha} when top_k > 1 and alpha > 0 -> + [strategy: %{type: :contrastive_search, top_k: top_k, alpha: alpha}] + + _ -> + [] + end + + @for.config(config, opts ++ strategy_opts) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/gpt2.ex b/deps/bumblebee/lib/bumblebee/text/gpt2.ex new file mode 100644 index 0000000000000000000000000000000000000000..13b8a6aaabd7931864f8f7ab3a95687366e9bbbb --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/gpt2.ex @@ -0,0 +1,519 @@ +defmodule Bumblebee.Text.Gpt2 do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 50257, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 1024, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + hidden_size: [ + default: 768, + doc: "the dimensionality of hidden layers" + ], + num_blocks: [ + default: 24, + doc: "the number of Transformer blocks in the decoder" + ], + num_attention_heads: [ + default: 16, + doc: "the number of attention heads for each attention layer in the decoder" + ], + intermediate_size: [ + default: nil, + doc: """ + the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the decoder. + If not specified, defaults to 4 times `:hidden_size` + """ + ], + activation: [ + default: :gelu_approx_tanh, + doc: "the activation function" + ], + scale_attention_weights: [ + default: true, + doc: "whether to scale attention weights to have variance of 1" + ], + dropout_rate: [ + default: 0.1, + doc: "the dropout rate for embedding and encoder" + ], + embeddings_dropout_rate: [ + default: 0.1, + doc: "the dropout rate for embeddings" + ], + attention_dropout_rate: [ + default: 0.1, + doc: "the dropout rate for attention weights" + ], + classifier_dropout_rate: [ + default: 0.1, + doc: "the dropout rate for the classification head" + ], + layer_norm_epsilon: [ + default: 1.0e-5, + doc: "the epsilon used by the layer normalization layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] ++ + Shared.common_options([:use_cross_attention, :num_labels, :id_to_label]) ++ + Shared.token_options(pad_token_id: 50256) + + @moduledoc """ + GPT-2 model family. + + ## Architectures + + * `:base` - plain GPT-2 without any head on top + + * `:for_causal_language_modeling` - GPT-2 with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_sequence_classification` - GPT-2 with a sequence + classification head. The head returns logits corresponding to + possible classes + + * `:for_token_classification` - GPT-2 with a token classification + head. The head returns logits for each token in the original + sequence + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{num_blocks, num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + * `"input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"input_ids"`, which can be specified + for more control over how `"input_ids"` are embedded than the + model's internal embedding lookup. If `"input_embeddings"` are present, + then `"input_ids"` will be ignored. + + * `"encoder_hidden_state"` - `{batch_size, encoder_sequence_length, hidden_size}` + + Last hidden state output from the encoder. This hidden state is + used in cross-attention blocks in the decoder. If specified, the + model will skip the encoding process and use this value directly + for cross-attentions in the decoder. + + * `"encoder_attention_mask"` - `{batch_size, encoder_sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"cross_attention_head_mask"` - `{num_blocks, num_attention_heads}` + + Mask to nullify selected heads of the cross-attention blocks in + the decoder with shape. + + * `"cache"` + + A container with cached layer results used to speed up sequential + decoding (autoregression). With cache, certain hidden states are + taken from the cache, rather than recomputed on every decoding + pass. The cache should be treated as opaque and initialized with + `Bumblebee.Text.Generation.init_cache/4`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_causal_language_modeling, + :for_sequence_classification, + :for_token_classification + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(_spec) do + %{"input_ids" => Nx.template({1, 1}, :u32)} + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_causal_language_modeling} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + + # TODO: Tie lm-head to word embedding as a spec option + logits = + Layers.dense_transposed(outputs.hidden_state, spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: "language_modeling_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cross_attentions: outputs.cross_attentions, + cache: outputs.cache + }) + end + + def model(%__MODULE__{architecture: :for_token_classification} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + + logits = + outputs.hidden_state + |> Axon.dropout( + rate: classifier_dropout_rate(spec), + name: "token_classification_head.dropout" + ) + |> Axon.dense(spec.num_labels, + name: "token_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_sequence_classification} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + + logits = + Layers.dense_transposed(outputs.hidden_state, spec.num_labels, + name: "sequence_classification_head.output" + ) + + pooled_logits = + Layers.if_present inputs["input_ids"] do + Axon.layer( + fn logits, input_ids, _opts -> + indices = + input_ids + |> Nx.not_equal(spec.pad_token_id) + |> Nx.sum(axes: [-1]) + |> Nx.subtract(1) + |> Nx.as_type({:s, 64}) + + Bumblebee.Utils.Nx.batched_take(logits, indices) + end, + [logits, inputs["input_ids"]] + ) + else + Layers.take_token(logits, axis: 1, index: -1) + end + + Layers.output(%{ + logits: pooled_logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cross_attentions: outputs.cross_attentions + }) + end + + @impl true + def init_cache(spec, batch_size, max_length, inputs) do + encoder_sequence_length = + if encoder_hidden_state = inputs["encoder_hidden_state"] do + Nx.axis_size(encoder_hidden_state, 1) + end + + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + decoder_num_attention_heads: spec.num_attention_heads, + encoder_num_attention_heads: spec.num_attention_heads, + decoder_num_blocks: spec.num_blocks, + encoder_sequence_length: encoder_sequence_length + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + defp inputs(spec) do + shape = {nil, nil} + hidden_shape = {nil, nil, spec.hidden_size} + decoder_attention_head_mask_shape = {spec.num_blocks, spec.num_attention_heads} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: decoder_attention_head_mask_shape), + Axon.input("input_embeddings", optional: true, shape: hidden_shape), + Axon.input("encoder_hidden_state", optional: true, shape: hidden_shape), + Axon.input("encoder_attention_mask", optional: true, shape: shape), + Axon.input("cross_attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("cache", optional: true) + ]) + end + + defp core(inputs, spec) do + embeddings = + embedder(inputs["input_ids"], inputs["position_ids"], inputs["input_embeddings"], spec, + name: "embedder" + ) + + outputs = + decoder( + embeddings, + inputs["attention_mask"], + inputs["attention_head_mask"], + inputs["encoder_hidden_state"], + inputs["encoder_attention_mask"], + inputs["cross_attention_head_mask"], + inputs["cache"], + spec, + name: "decoder" + ) + + hidden_state = + Axon.layer_norm(outputs.hidden_state, + epsilon: spec.layer_norm_epsilon, + name: "norm" + ) + + %{ + hidden_state: hidden_state, + hidden_states: Layers.replace(outputs.hidden_states, -1, hidden_state), + attentions: outputs.attentions, + cross_attentions: outputs.cross_attentions, + cache: outputs.cache + } + end + + defp embedder(input_ids, position_ids, input_embeddings, spec, opts) do + name = opts[:name] + + input_embeddings = + Layers.default input_embeddings do + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + name: join(name, "token_embedding") + ) + end + + position_ids = + Layers.default position_ids do + Layers.default_position_ids(input_embeddings) + end + + position_embeddings = + Axon.embedding(position_ids, spec.max_positions, spec.hidden_size, + name: join(name, "position_embedding") + ) + + input_embeddings + |> Axon.add(position_embeddings) + |> Axon.dropout(rate: spec.embeddings_dropout_rate) + end + + defp decoder( + hidden_state, + attention_mask, + attention_head_mask, + encoder_hidden_state, + encoder_attention_mask, + cross_attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + + Layers.Transformer.blocks( + hidden_state, + [ + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + cache: cache, + causal: true, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: spec.layer_norm_epsilon + ], + ffn: [ + intermediate_size: spec.intermediate_size || 4 * spec.hidden_size, + activation: spec.activation + ], + block_type: :norm_first, + scale_attention_weights: spec.scale_attention_weights, + name: join(name, "blocks") + ] ++ + if(spec.use_cross_attention, + do: [ + cross_hidden_state: encoder_hidden_state, + cross_attention_mask: encoder_attention_mask, + cross_attention_head_mask: cross_attention_head_mask + ], + else: [] + ) + ) + end + + defp classifier_dropout_rate(spec) do + spec.classifier_dropout_rate || spec.dropout_rate + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"n_positions", number()}, + hidden_size: {"n_embd", number()}, + num_blocks: {"n_layer", number()}, + num_attention_heads: {"n_head", number()}, + intermediate_size: {"n_inner", optional(number())}, + activation: {"activation_function", activation()}, + scale_attention_weights: {"scale_attn_weights", boolean()}, + dropout_rate: {"resid_pdrop", number()}, + embeddings_dropout_rate: {"embd_pdrop", number()}, + attention_dropout_rate: {"attn_pdrop", number()}, + classifier_dropout_rate: {"classifier_dropout", number()}, + layer_norm_epsilon: {"layer_norm_epsilon", number()}, + initializer_scale: {"initializer_range", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.token_embedding" => "transformer.wte", + "embedder.position_embedding" => "transformer.wpe", + "decoder.blocks.{n}.self_attention.query" => + dense_from_conv1d("transformer.h.{n}.attn.c_attn", 3, 0), + "decoder.blocks.{n}.self_attention.key" => + dense_from_conv1d("transformer.h.{n}.attn.c_attn", 3, 1), + "decoder.blocks.{n}.self_attention.value" => + dense_from_conv1d("transformer.h.{n}.attn.c_attn", 3, 2), + "decoder.blocks.{n}.self_attention.output" => + dense_from_conv1d("transformer.h.{n}.attn.c_proj", 1, 0), + "decoder.blocks.{n}.self_attention_norm" => "transformer.h.{n}.ln_1", + "decoder.blocks.{n}.cross_attention.query" => + dense_from_conv1d("transformer.h.{n}.crossattention.q_attn", 1, 0), + "decoder.blocks.{n}.cross_attention.key" => + dense_from_conv1d("transformer.h.{n}.crossattention.c_attn", 2, 0), + "decoder.blocks.{n}.cross_attention.value" => + dense_from_conv1d("transformer.h.{n}.crossattention.c_attn", 2, 1), + "decoder.blocks.{n}.cross_attention.output" => + dense_from_conv1d("transformer.h.{n}.crossattention.c_proj", 1, 0), + "decoder.blocks.{n}.ffn.intermediate" => + dense_from_conv1d("transformer.h.{n}.mlp.c_fc", 1, 0), + "decoder.blocks.{n}.ffn.output" => + dense_from_conv1d("transformer.h.{n}.mlp.c_proj", 1, 0), + "decoder.blocks.{n}.cross_attention_norm" => "transformer.h.{n}.ln_cross_attn", + "decoder.blocks.{n}.output_norm" => "transformer.h.{n}.ln_2", + "norm" => "transformer.ln_f", + "language_modeling_head.output" => "transformer.wte", + "token_classification_head.output" => "classifier", + "sequence_classification_head.output" => "score" + } + end + + defp dense_from_conv1d(source_layer_name, num_chunks, chunk_idx) do + %{ + "kernel" => { + [{source_layer_name, "weight"}], + fn [kernel] -> + size = Nx.axis_size(kernel, 1) + step = div(size, num_chunks) + Nx.slice_along_axis(kernel, chunk_idx * step, step, axis: 1) + end + }, + "bias" => { + [{source_layer_name, "bias"}], + fn [bias] -> + size = Nx.axis_size(bias, 0) + step = div(size, num_chunks) + Nx.slice_along_axis(bias, chunk_idx * step, step) + end + } + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/gpt_big_code.ex b/deps/bumblebee/lib/bumblebee/text/gpt_big_code.ex new file mode 100644 index 0000000000000000000000000000000000000000..37223d6b42a0b0ad80cbfbd66d47107402aba9fe --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/gpt_big_code.ex @@ -0,0 +1,516 @@ +defmodule Bumblebee.Text.GptBigCode do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 50257, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 1024, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + hidden_size: [ + default: 768, + doc: "the dimensionality of hidden layers" + ], + num_blocks: [ + default: 24, + doc: "the number of Transformer blocks in the decoder" + ], + num_attention_heads: [ + default: 16, + doc: "the number of attention heads for each attention layer in the decoder" + ], + num_key_value_heads: [ + default: nil, + doc: "the number of key value heads for each attention layer in the model" + ], + intermediate_size: [ + default: nil, + doc: """ + the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the decoder. + If not specified, defaults to 4 times `:hidden_size` + """ + ], + activation: [ + default: :gelu_approx_tanh, + doc: "the activation function" + ], + scale_attention_weights: [ + default: true, + doc: "whether to scale attention weights to have variance of 1" + ], + dropout_rate: [ + default: 0.1, + doc: "the dropout rate for embedding and encoder" + ], + embeddings_dropout_rate: [ + default: 0.1, + doc: "the dropout rate for embeddings" + ], + attention_dropout_rate: [ + default: 0.1, + doc: "the dropout rate for attention weights" + ], + classifier_dropout_rate: [ + default: 0.1, + doc: "the dropout rate for the classification head" + ], + layer_norm_epsilon: [ + default: 1.0e-5, + doc: "the epsilon used by the layer normalization layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] ++ + Shared.common_options([:use_cross_attention, :num_labels, :id_to_label]) ++ + Shared.token_options(pad_token_id: 50256) + + @moduledoc """ + GPT-BigCode model family. + + ## Architectures + + * `:base` - plain GPT-BigCode without any head on top + + * `:for_causal_language_modeling` - GPT-BigCode with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_sequence_classification` - GPT-BigCode with a sequence + classification head. The head returns logits corresponding to + possible classes + + * `:for_token_classification` - GPT-BigCode with a token classification + head. The head returns logits for each token in the original + sequence + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{num_blocks, num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + * `"input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"input_ids"`, which can be specified + for more control over how `"input_ids"` are embedded than the + model's internal embedding lookup. If `"input_embeddings"` are present, + then `"input_ids"` will be ignored. + + * `"encoder_hidden_state"` - `{batch_size, encoder_sequence_length, hidden_size}` + + Last hidden state output from the encoder. This hidden state is + used in cross-attention blocks in the decoder. If specified, the + model will skip the encoding process and use this value directly + for cross-attentions in the decoder. + + * `"encoder_attention_mask"` - `{batch_size, encoder_sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"cross_attention_head_mask"` - `{num_blocks, num_attention_heads}` + + Mask to nullify selected heads of the cross-attention blocks in + the decoder with shape. + + * `"cache"` + + A container with cached layer results used to speed up sequential + decoding (autoregression). With cache, certain hidden states are + taken from the cache, rather than recomputed on every decoding + pass. The cache should be treated as opaque and initialized with + `Bumblebee.Text.Generation.init_cache/4`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_causal_language_modeling, + :for_sequence_classification, + :for_token_classification + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(_spec) do + %{"input_ids" => Nx.template({1, 1}, :u32)} + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_causal_language_modeling} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + + # TODO: Tie lm-head to word embedding as a spec option + logits = + Layers.dense_transposed(outputs.hidden_state, spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: "language_modeling_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cross_attentions: outputs.cross_attentions, + cache: outputs.cache + }) + end + + def model(%__MODULE__{architecture: :for_token_classification} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + + logits = + outputs.hidden_state + |> Axon.dropout( + rate: classifier_dropout_rate(spec), + name: "token_classification_head.dropout" + ) + |> Axon.dense(spec.num_labels, + name: "token_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_sequence_classification} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + + logits = + Layers.dense_transposed(outputs.hidden_state, spec.num_labels, + name: "sequence_classification_head.output" + ) + + pooled_logits = + Layers.if_present inputs["input_ids"] do + Axon.layer( + fn logits, input_ids, _opts -> + indices = + input_ids + |> Nx.not_equal(spec.pad_token_id) + |> Nx.sum(axes: [-1]) + |> Nx.subtract(1) + |> Nx.as_type({:s, 64}) + + Bumblebee.Utils.Nx.batched_take(logits, indices) + end, + [logits, inputs["input_ids"]] + ) + else + Layers.take_token(logits, axis: 1, index: -1) + end + + Layers.output(%{ + logits: pooled_logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cross_attentions: outputs.cross_attentions + }) + end + + @impl true + def init_cache(spec, batch_size, max_length, inputs) do + encoder_sequence_length = + if encoder_hidden_state = inputs["encoder_hidden_state"] do + Nx.axis_size(encoder_hidden_state, 1) + end + + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + decoder_num_attention_heads: spec.num_attention_heads, + encoder_num_attention_heads: spec.num_attention_heads, + decoder_num_blocks: spec.num_blocks, + encoder_sequence_length: encoder_sequence_length + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + defp inputs(spec) do + shape = {nil, nil} + hidden_shape = {nil, nil, spec.hidden_size} + decoder_attention_head_mask_shape = {spec.num_blocks, spec.num_attention_heads} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: decoder_attention_head_mask_shape), + Axon.input("input_embeddings", optional: true, shape: hidden_shape), + Axon.input("encoder_hidden_state", optional: true, shape: hidden_shape), + Axon.input("encoder_attention_mask", optional: true, shape: shape), + Axon.input("cross_attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("cache", optional: true) + ]) + end + + defp core(inputs, spec) do + embeddings = + embedder(inputs["input_ids"], inputs["position_ids"], inputs["input_embeddings"], spec, + name: "embedder" + ) + + outputs = + decoder( + embeddings, + inputs["attention_mask"], + inputs["attention_head_mask"], + inputs["encoder_hidden_state"], + inputs["encoder_attention_mask"], + inputs["cross_attention_head_mask"], + inputs["cache"], + spec, + name: "decoder" + ) + + hidden_state = + Axon.layer_norm(outputs.hidden_state, + epsilon: spec.layer_norm_epsilon, + name: "norm" + ) + + %{ + hidden_state: hidden_state, + hidden_states: Layers.replace(outputs.hidden_states, -1, hidden_state), + attentions: outputs.attentions, + cross_attentions: outputs.cross_attentions, + cache: outputs.cache + } + end + + defp embedder(input_ids, position_ids, input_embeddings, spec, opts) do + name = opts[:name] + + input_embeddings = + Layers.default input_embeddings do + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + name: join(name, "token_embedding") + ) + end + + position_ids = + Layers.default position_ids do + Layers.default_position_ids(input_embeddings) + end + + position_embeddings = + Axon.embedding(position_ids, spec.max_positions, spec.hidden_size, + name: join(name, "position_embedding") + ) + + input_embeddings + |> Axon.add(position_embeddings) + |> Axon.dropout(rate: spec.embeddings_dropout_rate) + end + + defp decoder( + hidden_state, + attention_mask, + attention_head_mask, + encoder_hidden_state, + encoder_attention_mask, + cross_attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + + Layers.Transformer.blocks( + hidden_state, + [ + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + cache: cache, + causal: true, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + num_key_value_heads: spec.num_key_value_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: spec.layer_norm_epsilon + ], + ffn: [ + intermediate_size: spec.intermediate_size || 4 * spec.hidden_size, + activation: spec.activation + ], + block_type: :norm_first, + scale_attention_weights: spec.scale_attention_weights, + name: join(name, "blocks") + ] ++ + if(spec.use_cross_attention, + do: [ + cross_hidden_state: encoder_hidden_state, + cross_attention_mask: encoder_attention_mask, + cross_attention_head_mask: cross_attention_head_mask + ], + else: [] + ) + ) + end + + defp classifier_dropout_rate(spec) do + spec.classifier_dropout_rate || spec.dropout_rate + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"n_positions", number()}, + hidden_size: {"n_embd", number()}, + num_blocks: {"n_layer", number()}, + num_attention_heads: {"n_head", number()}, + num_key_value_heads: {"multi_query", mapping(%{true => 1, false => nil})}, + intermediate_size: {"n_inner", optional(number())}, + activation: {"activation_function", activation()}, + scale_attention_weights: {"scale_attn_weights", boolean()}, + dropout_rate: {"resid_pdrop", number()}, + embeddings_dropout_rate: {"embd_pdrop", number()}, + attention_dropout_rate: {"attn_pdrop", number()}, + classifier_dropout_rate: {"classifier_dropout", number()}, + layer_norm_epsilon: {"layer_norm_epsilon", number()}, + initializer_scale: {"initializer_range", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(spec) do + # The QKV parameters are joint, but they have different layout + # depending on the "multi_query" option, so we slice accordingly + out_template = + if spec.num_key_value_heads == 1 do + {[spec.num_attention_heads, spec.num_key_value_heads, spec.num_key_value_heads], :auto} + else + {spec.num_attention_heads, [1, 1, 1], :auto} + end + + %{ + "embedder.token_embedding" => "transformer.wte", + "embedder.position_embedding" => "transformer.wpe", + "decoder.blocks.{n}.self_attention.query" => + Shared.sliced_dense_params_source("transformer.h.{n}.attn.c_attn", out_template, 0), + "decoder.blocks.{n}.self_attention.key" => + Shared.sliced_dense_params_source("transformer.h.{n}.attn.c_attn", out_template, 1), + "decoder.blocks.{n}.self_attention.value" => + Shared.sliced_dense_params_source("transformer.h.{n}.attn.c_attn", out_template, 2), + "decoder.blocks.{n}.self_attention.output" => "transformer.h.{n}.attn.c_proj", + "decoder.blocks.{n}.self_attention_norm" => "transformer.h.{n}.ln_1", + "decoder.blocks.{n}.cross_attention.query" => "transformer.h.{n}.crossattention.q_attn", + "decoder.blocks.{n}.cross_attention.key" => + Shared.sliced_dense_params_source( + "transformer.h.{n}.crossattention.c_attn", + {spec.num_attention_heads, [1, 1], :auto}, + 0 + ), + "decoder.blocks.{n}.cross_attention.value" => + Shared.sliced_dense_params_source( + "transformer.h.{n}.crossattention.c_attn", + {spec.num_attention_heads, [1, 1], :auto}, + 1 + ), + "decoder.blocks.{n}.cross_attention.output" => "transformer.h.{n}.crossattention.c_proj", + "decoder.blocks.{n}.ffn.intermediate" => "transformer.h.{n}.mlp.c_fc", + "decoder.blocks.{n}.ffn.output" => "transformer.h.{n}.mlp.c_proj", + "decoder.blocks.{n}.cross_attention_norm" => "transformer.h.{n}.ln_cross_attn", + "decoder.blocks.{n}.output_norm" => "transformer.h.{n}.ln_2", + "norm" => "transformer.ln_f", + "language_modeling_head.output" => "transformer.wte", + "token_classification_head.output" => "classifier", + "sequence_classification_head.output" => "score" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/gpt_neo_x.ex b/deps/bumblebee/lib/bumblebee/text/gpt_neo_x.ex new file mode 100644 index 0000000000000000000000000000000000000000..1124154f68b2cac2c6ba3e938cc33b26cc21176f --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/gpt_neo_x.ex @@ -0,0 +1,441 @@ +defmodule Bumblebee.Text.GptNeoX do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 32000, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + hidden_size: [ + default: 4096, + doc: "the dimensionality of hidden layers" + ], + intermediate_size: [ + default: 11008, + doc: "the dimensionality of intermediate layers" + ], + num_blocks: [ + default: 32, + doc: "the number of Transformer blocks in the model" + ], + num_attention_heads: [ + default: 32, + doc: "the number of attention heads for each attention layer in the model" + ], + activation: [ + default: :silu, + doc: "the activation function" + ], + rotary_embedding_percentage: [ + default: 0.25, + doc: "percentage of hidden dimensions to allocate to rotary embeddings" + ], + rotary_embedding_base: [ + default: 10_000, + doc: "base for computing rotary embedding frequency" + ], + classifier_dropout_rate: [ + default: 0.1, + doc: "the dropout rate for the classification head" + ], + layer_norm_epsilon: [ + default: 1.0e-12, + doc: "the epsilon used by RMS normalization layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ], + use_parallel_transformer_block: [ + default: true, + doc: + "whether to use the parallel formulation of the Transformer block, where attention and FFN is computed independently" + ] + ] ++ + Shared.common_options([:num_labels, :id_to_label]) ++ + Shared.token_options(pad_token_id: nil) + + @moduledoc """ + GPT-NeoX model family. + + ## Architectures + + * `:base` - plain GPT-NeoX without any head on top + + * `:for_causal_language_modeling` - GPT-NeoX with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_sequence_classification` - GPT-NeoX with a sequence + classification head. The head returns logits corresponding to + possible classes + + * `:for_token_classification` - GPT-NeoX with a token classification + head. The head returns logits for each token in the original + sequence + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{encoder_num_blocks, encoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + * `"input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"input_ids"`, which can be specified + for more control over how `"input_ids"` are embedded than the + model's internal embedding lookup. If `"input_embeddings"` are present, + then `"input_ids"` will be ignored. + + * `"cache"` + + A container with cached layer results used to speed up sequential + decoding (autoregression). With cache, certain hidden states are + taken from the cache, rather than recomputed on every decoding + pass. The cache should be treated as opaque and initialized with + `Bumblebee.Text.Generation.init_cache/4`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_causal_language_modeling, + :for_sequence_classification, + :for_token_classification + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(_spec) do + %{ + "input_ids" => Nx.template({1, 1}, :s64) + } + end + + @impl true + def init_cache(spec, batch_size, max_length, _inputs) do + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + decoder_num_attention_heads: spec.num_attention_heads, + decoder_num_blocks: spec.num_blocks + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_causal_language_modeling} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cache: outputs.cache + }) + end + + def model(%__MODULE__{architecture: :for_sequence_classification} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + + logits = + Axon.dense(outputs.hidden_state, spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "sequence_classification_head.output" + ) + + pooled_logits = + Layers.if_present inputs["input_ids"] do + Axon.layer( + fn logits, input_ids, _opts -> + indices = + input_ids + |> Nx.not_equal(spec.pad_token_id) + |> Nx.sum(axes: [-1]) + |> Nx.subtract(1) + |> Nx.as_type({:s, 64}) + + Bumblebee.Utils.Nx.batched_take(logits, indices) + end, + [logits, inputs["input_ids"]] + ) + else + Layers.take_token(logits, axis: 1, index: -1) + end + + Layers.output(%{ + logits: pooled_logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cache: outputs.cache + }) + end + + def model(%__MODULE__{architecture: :for_token_classification} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + + logits = + outputs.hidden_state + |> Axon.dropout( + rate: spec.classifier_dropout_rate, + name: "token_classification_head.dropout" + ) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "token_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cache: outputs.cache + }) + end + + defp inputs(spec) do + shape = {nil, nil} + hidden_shape = {nil, nil, spec.hidden_size} + + attention_head_mask_shape = {spec.num_blocks, spec.num_attention_heads} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: attention_head_mask_shape), + Axon.input("input_embeddings", optional: true, shape: hidden_shape), + Axon.input("cache", optional: true) + ]) + end + + defp core(inputs, spec) do + embeddings = + embedder( + inputs["input_ids"], + inputs["input_embeddings"], + spec, + name: "embedder" + ) + + position_ids = + Layers.default inputs["position_ids"] do + Layers.default_position_ids(embeddings) + end + + decoder_outputs = + decoder( + embeddings, + position_ids, + inputs["attention_mask"], + inputs["attention_head_mask"], + inputs["cache"], + spec, + name: "decoder" + ) + + hidden_state = + Axon.layer_norm(decoder_outputs.hidden_state, + name: "output_norm", + epsilon: spec.layer_norm_epsilon + ) + + %{ + hidden_state: hidden_state, + hidden_states: Layers.append(decoder_outputs.hidden_states, hidden_state), + attentions: decoder_outputs.attentions, + cache: decoder_outputs.cache + } + end + + defp embedder(input_ids, input_embeddings, spec, opts) do + name = opts[:name] + + Layers.default input_embeddings do + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "token_embedding") + ) + end + end + + defp decoder( + hidden_state, + position_ids, + attention_mask, + attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + cache: cache, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + layer_norm: [ + epsilon: spec.layer_norm_epsilon + ], + ffn: [ + intermediate_size: spec.intermediate_size + ], + block_type: if(spec.use_parallel_transformer_block, do: :parallel, else: :norm_first), + causal: true, + rotary_embedding: [ + position_ids: position_ids, + percentage: spec.rotary_embedding_percentage, + base: spec.rotary_embedding_base + ], + query_use_bias: true, + key_use_bias: true, + value_use_bias: true, + output_use_bias: true, + name: join(name, "blocks") + ) + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: Tie lm-head to word embedding as a spec option + Layers.dense_transposed(hidden_state, spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"max_positions", number()}, + hidden_size: {"hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_attention_heads: {"num_attention_heads", number()}, + intermediate_size: {"intermediate_size", number()}, + activation: {"hidden_act", activation()}, + rotary_embedding_percentage: {"rotary_pct", number()}, + rotary_embedding_base: {"rotary_emb_base", number()}, + classifier_dropout_rate: {"classifier_dropout", number()}, + layer_norm_epsilon: {"layer_norm_eps", number()}, + initializer_scale: {"init_std", number()}, + use_parallel_transformer_block: {"use_parallel_residual", boolean()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(spec) do + %{ + "embedder.token_embedding" => "gpt_neox.embed_in", + "decoder.blocks.{n}.self_attention.query" => + Shared.sliced_dense_params_source( + "gpt_neox.layers.{n}.attention.query_key_value", + {spec.num_attention_heads, [1, 1, 1], :auto}, + 0 + ), + "decoder.blocks.{n}.self_attention.key" => + Shared.sliced_dense_params_source( + "gpt_neox.layers.{n}.attention.query_key_value", + {spec.num_attention_heads, [1, 1, 1], :auto}, + 1 + ), + "decoder.blocks.{n}.self_attention.value" => + Shared.sliced_dense_params_source( + "gpt_neox.layers.{n}.attention.query_key_value", + {spec.num_attention_heads, [1, 1, 1], :auto}, + 2 + ), + "decoder.blocks.{n}.self_attention.output" => "gpt_neox.layers.{n}.attention.dense", + "decoder.blocks.{n}.self_attention_norm" => "gpt_neox.layers.{n}.input_layernorm", + "decoder.blocks.{n}.self_attention.rotary_embedding" => + "gpt_neox.layers.{n}.self_attn.rotary_emb", + "decoder.blocks.{n}.ffn.intermediate" => "gpt_neox.layers.{n}.mlp.dense_h_to_4h", + "decoder.blocks.{n}.ffn.output" => "gpt_neox.layers.{n}.mlp.dense_4h_to_h", + "decoder.blocks.{n}.output_norm" => "gpt_neox.layers.{n}.post_attention_layernorm", + "output_norm" => "gpt_neox.final_layer_norm", + "language_modeling_head.output" => "embed_out", + "sequence_classification_head.output" => "score", + "token_classification_head.output" => "classifier" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/llama.ex b/deps/bumblebee/lib/bumblebee/text/llama.ex new file mode 100644 index 0000000000000000000000000000000000000000..b06a03156d619828c861e78ad6c4b3f04ea4be55 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/llama.ex @@ -0,0 +1,485 @@ +defmodule Bumblebee.Text.Llama do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 32000, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 1024, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + hidden_size: [ + default: 4096, + doc: "the dimensionality of hidden layers" + ], + intermediate_size: [ + default: 11008, + doc: "the dimensionality of intermediate layers" + ], + attention_head_size: [ + default: nil, + doc: """ + the size of the key, value, and query projection per attention head. + Defaults to `div(hidden_size, num_attention_heads)` + """ + ], + num_blocks: [ + default: 32, + doc: "the number of Transformer blocks in the model" + ], + num_attention_heads: [ + default: 32, + doc: "the number of attention heads for each attention layer in the model" + ], + num_key_value_heads: [ + default: nil, + doc: "the number of key value heads for each attention layer in the model" + ], + activation: [ + default: :silu, + doc: "the activation function" + ], + rotary_embedding_base: [ + default: 10_000, + doc: "base for computing rotary embedding frequency" + ], + rotary_embedding_scaling_strategy: [ + default: nil, + doc: """ + scaling configuration for rotary embedding. Currently the supported values are: + + * `%{type: :linear, factor: number()}` + + * `%{type: :dynamic, factor: number()}` + + * `%{type: :llama3, factor: number(), low_frequency_factor: number(), high_frequency_factor: number(), original_max_positions: pos_integer()}` + + For more details see https://www.reddit.com/r/LocalLLaMA/comments/14mrgpr/dynamically_scaled_rope_further_increases + """ + ], + layer_norm_epsilon: [ + default: 1.0e-12, + doc: "the epsilon used by RMS normalization layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ], + tie_word_embeddings: [ + default: false, + doc: "whether to tie input and output embedding weights" + ] + ] ++ + Shared.common_options([:num_labels, :id_to_label]) ++ Shared.token_options(pad_token_id: 0) + + @moduledoc """ + LLaMA model family. + + ## Architectures + + * `:base` - plain LLaMA without any head on top + + * `:for_causal_language_modeling` - LLaMA with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_sequence_classification` - LLaMA with a sequence + classification head. The head returns logits corresponding to + possible classes + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{encoder_num_blocks, encoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + * `"input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"input_ids"`, which can be specified + for more control over how `"input_ids"` are embedded than the + model's internal embedding lookup. If `"input_embeddings"` are present, + then `"input_ids"` will be ignored. + + * `"cache"` + + A container with cached layer results used to speed up sequential + decoding (autoregression). With cache, certain hidden states are + taken from the cache, rather than recomputed on every decoding + pass. The cache should be treated as opaque and initialized with + `Bumblebee.Text.Generation.init_cache/4`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_causal_language_modeling, + :for_sequence_classification + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(_spec) do + %{ + "input_ids" => Nx.template({1, 1}, :s64) + } + end + + @impl true + def init_cache(spec, batch_size, max_length, _inputs) do + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + attention_head_size: spec.attention_head_size, + decoder_num_attention_heads: spec.num_attention_heads, + decoder_num_blocks: spec.num_blocks + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_causal_language_modeling} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cache: outputs.cache + }) + end + + def model(%__MODULE__{architecture: :for_sequence_classification} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + + logits = + Axon.dense(outputs.hidden_state, spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "sequence_classification_head.output", + use_bias: false + ) + + pooled_logits = + Layers.if_present inputs["input_ids"] do + Axon.layer( + fn logits, input_ids, _opts -> + indices = + input_ids + |> Nx.not_equal(spec.pad_token_id) + |> Nx.sum(axes: [-1]) + |> Nx.subtract(1) + |> Nx.as_type({:s, 64}) + + Bumblebee.Utils.Nx.batched_take(logits, indices) + end, + [logits, inputs["input_ids"]] + ) + else + Layers.take_token(logits, axis: 1, index: -1) + end + + Layers.output(%{ + logits: pooled_logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cache: outputs.cache + }) + end + + defp inputs(spec) do + shape = {nil, nil} + hidden_shape = {nil, nil, spec.hidden_size} + + attention_head_mask_shape = {spec.num_blocks, spec.num_attention_heads} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: attention_head_mask_shape), + Axon.input("input_embeddings", optional: true, shape: hidden_shape), + Axon.input("cache", optional: true) + ]) + end + + defp core(inputs, spec) do + embeddings = + embedder( + inputs["input_ids"], + inputs["input_embeddings"], + spec, + name: "embedder" + ) + + position_ids = + Layers.default inputs["position_ids"] do + Layers.default_position_ids(embeddings) + end + + decoder_outputs = + decoder( + embeddings, + position_ids, + inputs["attention_mask"], + inputs["attention_head_mask"], + inputs["cache"], + spec, + name: "decoder" + ) + + hidden_state = + Layers.rms_norm(decoder_outputs.hidden_state, + name: "output_norm", + epsilon: spec.layer_norm_epsilon + ) + + %{ + hidden_state: hidden_state, + hidden_states: Layers.append(decoder_outputs.hidden_states, hidden_state), + attentions: decoder_outputs.attentions, + cache: decoder_outputs.cache + } + end + + defp embedder(input_ids, input_embeddings, spec, opts) do + name = opts[:name] + + Layers.default input_embeddings do + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "token_embedding") + ) + end + end + + defp decoder( + hidden_state, + position_ids, + attention_mask, + attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + attention_head_size: spec.attention_head_size, + cache: cache, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + num_key_value_heads: spec.num_key_value_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + layer_norm: &Layers.rms_norm(&1, name: &2, epsilon: spec.layer_norm_epsilon), + ffn: + &gated_ffn(&1, spec.intermediate_size, spec.hidden_size, + name: &2, + activation: spec.activation + ), + block_type: :norm_first, + causal: true, + rotary_embedding: [ + position_ids: position_ids, + max_positions: spec.max_positions, + base: spec.rotary_embedding_base, + scaling_strategy: spec.rotary_embedding_scaling_strategy + ], + query_use_bias: false, + key_use_bias: false, + value_use_bias: false, + output_use_bias: false, + name: join(name, "blocks") + ) + end + + defp gated_ffn(hidden_state, intermediate_size, output_size, opts) do + name = opts[:name] + activation = opts[:activation] + + intermediate = + Axon.dense(hidden_state, intermediate_size, + name: join(name, "intermediate"), + use_bias: false + ) + + gate = Axon.dense(hidden_state, intermediate_size, name: join(name, "gate"), use_bias: false) + + hidden_state = Axon.multiply(intermediate, Axon.activation(gate, activation)) + + Axon.dense(hidden_state, output_size, name: join(name, "output"), use_bias: false) + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: Tie lm-head to word embedding as a spec option + Layers.dense_transposed(hidden_state, spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + scaling_strategy_converter = fn name, value -> + # "type" has been renamed to "rope_type" + value = + case Map.pop(value, "type") do + {nil, value} -> value + {type, value} -> Map.put(value, "rope_type", type) + end + + case value do + %{"rope_type" => "linear", "factor" => factor} when is_number(factor) -> + {:ok, %{type: :linear, factor: factor}} + + %{"rope_type" => "dynamic", "factor" => factor} when is_number(factor) -> + {:ok, %{type: :dynamic, factor: factor}} + + %{ + "rope_type" => "llama3", + "factor" => factor, + "low_freq_factor" => low_frequency_factor, + "high_freq_factor" => high_frequency_factor, + "original_max_position_embeddings" => original_max_positions + } + when is_number(factor) and is_number(low_frequency_factor) and + is_number(high_frequency_factor) and + is_number(original_max_positions) -> + {:ok, + %{ + type: :llama3, + factor: factor, + low_frequency_factor: low_frequency_factor, + high_frequency_factor: high_frequency_factor, + original_max_positions: original_max_positions + }} + + _other -> + {:error, "invalid format for #{inspect(name)}, got: #{inspect(value)}"} + end + end + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + tie_word_embeddings: {"tie_word_embeddings", boolean()}, + max_positions: {"max_position_embeddings", number()}, + hidden_size: {"hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_attention_heads: {"num_attention_heads", number()}, + num_key_value_heads: {"num_key_value_heads", number()}, + attention_head_size: {"head_dim", number()}, + intermediate_size: {"intermediate_size", number()}, + activation: {"hidden_act", activation()}, + rotary_embedding_base: {"rope_theta", number()}, + rotary_embedding_scaling_strategy: + {"rope_scaling", optional(scaling_strategy_converter)}, + initializer_scale: {"initializer_range", number()}, + layer_norm_epsilon: {"rms_norm_eps", number()}, + tie_word_embeddings: {"tie_word_embeddings", boolean()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(spec) do + %{ + "embedder.token_embedding" => "model.embed_tokens", + "decoder.blocks.{n}.self_attention.query" => "model.layers.{n}.self_attn.q_proj", + "decoder.blocks.{n}.self_attention.key" => "model.layers.{n}.self_attn.k_proj", + "decoder.blocks.{n}.self_attention.value" => "model.layers.{n}.self_attn.v_proj", + "decoder.blocks.{n}.self_attention.output" => "model.layers.{n}.self_attn.o_proj", + "decoder.blocks.{n}.self_attention_norm" => "model.layers.{n}.input_layernorm", + "decoder.blocks.{n}.self_attention.rotary_embedding" => + "model.layers.{n}.self_attn.rotary_emb", + "decoder.blocks.{n}.ffn.gate" => "model.layers.{n}.mlp.gate_proj", + "decoder.blocks.{n}.ffn.intermediate" => "model.layers.{n}.mlp.up_proj", + "decoder.blocks.{n}.ffn.output" => "model.layers.{n}.mlp.down_proj", + "decoder.blocks.{n}.output_norm" => "model.layers.{n}.post_attention_layernorm", + "output_norm" => "model.norm", + "language_modeling_head.output" => + if(spec.tie_word_embeddings, do: "model.embed_tokens", else: "lm_head"), + "sequence_classification_head.output" => "score" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/m2m100.ex b/deps/bumblebee/lib/bumblebee/text/m2m100.ex new file mode 100644 index 0000000000000000000000000000000000000000..5f06474133389dd550c3236a537d8b1c463a167e --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/m2m100.ex @@ -0,0 +1,594 @@ +defmodule Bumblebee.Text.M2m100 do + alias Bumblebee.Shared + + import Nx.Defn + + options = + [ + vocab_size: [ + default: 128_112, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 1024, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + hidden_size: [ + default: 1024, + doc: "the dimensionality of hidden layers" + ], + encoder_num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the encoder" + ], + decoder_num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the decoder" + ], + encoder_num_attention_heads: [ + default: 16, + doc: "the number of attention heads for each attention layer in the encoder" + ], + decoder_num_attention_heads: [ + default: 16, + doc: "the number of attention heads for each attention layer in the decoder" + ], + encoder_intermediate_size: [ + default: 4096, + doc: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder" + ], + decoder_intermediate_size: [ + default: 4096, + doc: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the decoder" + ], + scale_embedding: [ + default: true, + doc: "scale embeddings by dividing by sqrt(hidden_size)" + ], + activation: [ + default: :relu, + doc: "the activation function" + ], + dropout_rate: [ + default: 0.1, + doc: "the dropout rate for encoder and decoder" + ], + attention_dropout_rate: [ + default: 0.1, + doc: "the dropout rate for attention weights" + ], + activation_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for activations inside fully connected layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] ++ Shared.token_options(pad_token_id: 1, eos_token_id: 2, decoder_start_token_id: 2) + + @moduledoc """ + M2M100 model family. + + ## Architectures + + * `:base` - plain M2M100 without any head on top + + * `:for_conditional_generation` - M2M100 with a language modeling + head. The head returns logits for each token in the original + sequence + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{encoder_num_blocks, encoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + * `"input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"input_ids"`, which can be specified + for more control over how `"input_ids"` are embedded than the + model's internal embedding lookup. If `"input_embeddings"` are present, + then `"input_ids"` will be ignored. + + * `"decoder_input_ids"` - `{batch_size, target_sequence_length}` + + Indices of decoder input sequence tokens in the vocabulary. If not + present and `"input_ids"` is, it will be generated by shifting + each token in `"input_ids"` to the right once. + + * `"decoder_attention_mask"` - `{batch_size, target_sequence_length}` + + Mask indicating which decoder tokens to attend to. This is used + to ignore padding tokens, which are added when processing a batch + of sequences with different length. + + * `"decoder_position_ids"` - `{batch_size, target_sequence_length}` + + Indices of positions of each decoder input sequence tokens in + the position embeddings. + + * `"decoder_attention_head_mask"` - `{decoder_num_blocks, decoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the decoder. + + * `"decoder_input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"decoder_input_ids"`, which can be + specified for more control over how `"decoder_input_ids"` are + embedded than the model's internal embedding lookup. If + `"decoder_input_embeddings"` are present, then `"decoder_input_ids"` + will be ignored. + + * `"encoder_hidden_state"` - `{batch_size, sequence_length, hidden_size}` + + Last hidden state output from the encoder. This hidden state is + used in cross-attention blocks in the decoder. If specified, the + model will skip the encoding process and use this value directly + for cross-attentions in the decoder. + + * `"cross_attention_head_mask"` - `{decoder_num_blocks, decoder_num_attention_heads}` + + Mask to nullify selected heads of the cross-attention blocks in + the decoder with shape. + + * `"cache"` + + A container with cached layer results used to speed up sequential + decoding (autoregression). With cache, certain hidden states are + taken from the cache, rather than recomputed on every decoding + pass. The cache should be treated as opaque and initialized with + `Bumblebee.Text.Generation.init_cache/4`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_conditional_generation + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + end + + @impl true + def input_template(_spec) do + %{ + "input_ids" => Nx.template({1, 1}, :s64), + "decoder_input_ids" => Nx.template({1, 1}, :s64) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = encoder_decoder_inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_conditional_generation} = spec) do + inputs = encoder_decoder_inputs(spec) + outputs = core(inputs, spec) + + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + decoder_hidden_states: outputs.decoder_hidden_states, + decoder_attentions: outputs.decoder_attentions, + cross_attentions: outputs.cross_attentions, + encoder_hidden_state: outputs.encoder_hidden_state, + encoder_hidden_states: outputs.encoder_hidden_states, + encoder_attentions: outputs.encoder_attentions, + cache: outputs.cache + }) + end + + defp encoder_decoder_inputs(spec) do + shape = {nil, nil} + hidden_shape = {nil, nil, spec.hidden_size} + + encoder_attention_head_mask_shape = + {spec.encoder_num_blocks, spec.encoder_num_attention_heads} + + decoder_attention_head_mask_shape = + {spec.decoder_num_blocks, spec.decoder_num_attention_heads} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: encoder_attention_head_mask_shape), + Axon.input("input_embeddings", optional: true, shape: hidden_shape), + Axon.input("decoder_input_ids", optional: true, shape: shape), + Axon.input("decoder_attention_mask", optional: true, shape: shape), + Axon.input("decoder_position_ids", optional: true, shape: shape), + Axon.input("decoder_attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("decoder_input_embeddings", optional: true, shape: hidden_shape), + Axon.input("encoder_hidden_state", optional: true, shape: hidden_shape), + Axon.input("cross_attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("cache", optional: true) + ]) + end + + @impl true + def init_cache(spec, batch_size, max_length, inputs) do + encoder_sequence_length = + if encoder_hidden_state = inputs["encoder_hidden_state"] do + Nx.axis_size(encoder_hidden_state, 1) + end + + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + decoder_num_attention_heads: spec.decoder_num_attention_heads, + encoder_num_attention_heads: spec.encoder_num_attention_heads, + decoder_num_blocks: spec.decoder_num_blocks, + encoder_sequence_length: encoder_sequence_length + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + defp core(inputs, spec) do + encoder_outputs = + Layers.if_present inputs["encoder_hidden_state"] do + %{ + hidden_state: inputs["encoder_hidden_state"], + hidden_states: Layers.none(), + attentions: Layers.none() + } + else + embeddings = + embedder(inputs["input_ids"], inputs["position_ids"], inputs["input_embeddings"], spec, + name: "encoder_embedder" + ) + + embeddings + |> encoder(inputs["attention_mask"], inputs["attention_head_mask"], spec, name: "encoder") + |> Map.take([:hidden_state, :hidden_states, :attentions]) + end + + decoder_input_ids = + Layers.default inputs["decoder_input_ids"] do + Layers.shift_tokens_right(inputs["input_ids"], spec.decoder_start_token_id) + end + + embeddings = + embedder( + decoder_input_ids, + inputs["decoder_position_ids"], + inputs["decoder_input_embeddings"], + spec, + name: "decoder_embedder" + ) + + decoder_outputs = + decoder( + embeddings, + inputs["decoder_attention_mask"], + inputs["decoder_attention_head_mask"], + encoder_outputs.hidden_state, + inputs["attention_mask"], + inputs["cross_attention_head_mask"], + inputs["cache"], + spec, + name: "decoder" + ) + + %{ + hidden_state: decoder_outputs.hidden_state, + decoder_hidden_states: decoder_outputs.hidden_states, + decoder_attentions: decoder_outputs.attentions, + cross_attentions: decoder_outputs.cross_attentions, + cache: decoder_outputs.cache, + encoder_hidden_state: encoder_outputs.hidden_state, + encoder_hidden_states: encoder_outputs.hidden_states, + encoder_attentions: encoder_outputs.attentions + } + end + + defp encoder(hidden_state, attention_mask, attention_head_mask, spec, opts) do + name = opts[:name] + + encoder_outputs = + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + num_blocks: spec.encoder_num_blocks, + num_attention_heads: spec.encoder_num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: 1.0e-5 + ], + block_type: :norm_first, + ffn: [ + intermediate_size: spec.encoder_intermediate_size, + activation: spec.activation + ], + name: join(name, "blocks") + ) + + hidden_state = Axon.layer_norm(encoder_outputs.hidden_state, name: join(name, "norm")) + + %{ + hidden_state: hidden_state, + hidden_states: Layers.replace(encoder_outputs.hidden_states, -1, hidden_state), + attentions: encoder_outputs.attentions + } + end + + defp embedder(input_ids, position_ids, input_embeddings, spec, opts) do + name = opts[:name] + + input_embeddings = + Layers.default input_embeddings do + token_embedding(input_ids, spec, name: join(name, "token_embedding")) + end + + position_ids = + Layers.default position_ids do + Axon.nx(input_ids, fn input_ids -> + mask = Nx.not_equal(input_ids, spec.pad_token_id) + + mask + |> Nx.cumulative_sum(axis: 1) + |> Nx.multiply(mask) + |> Nx.subtract(1) + end) + end + + position_embeddings = + position_embedding(position_ids, spec, name: join(name, "position_embedding")) + + Axon.add([input_embeddings, position_embeddings]) + |> Axon.dropout(rate: spec.dropout_rate) + end + + defp token_embedding(input_ids, spec, opts) do + name = opts[:name] + + input_embeddings = + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: name + ) + + if spec.scale_embedding do + Axon.nx(input_embeddings, fn x -> Nx.multiply(x, Nx.sqrt(spec.hidden_size)) end) + else + input_embeddings + end + end + + defp position_embedding(position_ids, spec, opts) do + name = opts[:name] + + # For M2M100 we need to offset the embeddings + offset = 2 + + position_ids = Axon.add(position_ids, Axon.constant(Nx.tensor(offset))) + + Axon.layer(&sinusoidal_position_embedding_impl/2, [position_ids], + size: spec.hidden_size, + name: name + ) + end + + defnp sinusoidal_position_embedding_impl(position_ids, opts \\ []) do + position_ids = Nx.vectorize(position_ids, :batch) + + size = opts[:size] + + half_size = div(size, 2) + base = 10_000 + range = Nx.iota({half_size}) / (half_size - 1) + inv_frequency = 1 / Nx.pow(base, range) + angle = Nx.outer(position_ids, inv_frequency) + sin_cos = Nx.concatenate([Nx.sin(angle), Nx.cos(angle)], axis: -1) + + Nx.devectorize(sin_cos) + end + + defp decoder( + hidden_state, + attention_mask, + attention_head_mask, + encoder_hidden_state, + encoder_attention_mask, + cross_attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + + decoder_outputs = + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + cross_hidden_state: encoder_hidden_state, + cross_attention_mask: encoder_attention_mask, + cross_attention_head_mask: cross_attention_head_mask, + cache: cache, + causal: true, + num_blocks: spec.decoder_num_blocks, + num_attention_heads: spec.decoder_num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: 1.0e-5 + ], + block_type: :norm_first, + ffn: [ + intermediate_size: spec.decoder_intermediate_size, + activation: spec.activation + ], + name: join(name, "blocks") + ) + + hidden_state = Axon.layer_norm(decoder_outputs.hidden_state, name: join(name, "norm")) + + %{ + cache: decoder_outputs.cache, + hidden_state: hidden_state, + hidden_states: Layers.replace(decoder_outputs.hidden_states, -1, hidden_state), + attentions: decoder_outputs.attentions, + cross_attentions: decoder_outputs.cross_attentions + } + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: Tie lm-head to word embedding as a spec option + Layers.dense_transposed(hidden_state, spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"max_position_embeddings", number()}, + hidden_size: {"d_model", number()}, + encoder_num_blocks: {"encoder_layers", number()}, + decoder_num_blocks: {"decoder_layers", number()}, + encoder_num_attention_heads: {"encoder_attention_heads", number()}, + decoder_num_attention_heads: {"decoder_attention_heads", number()}, + encoder_intermediate_size: {"encoder_ffn_dim", number()}, + decoder_intermediate_size: {"decoder_ffn_dim", number()}, + scale_embedding: {"scale_embedding", boolean()}, + activation: {"activation_function", activation()}, + dropout_rate: {"dropout", number()}, + attention_dropout_rate: {"attention_dropout", number()}, + activation_dropout_rate: {"activation_dropout", number()}, + classifier_dropout_rate: {"classifier_dropout", number()}, + initializer_scale: {"init_std", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "encoder_embedder.token_embedding" => "model.encoder.embed_tokens", + "encoder_embedder.position_embedding" => "model.encoder.embed_positions", + "encoder_embedder.norm" => "model.encoder.layernorm_embedding", + "encoder.blocks.{n}.self_attention.query" => "model.encoder.layers.{n}.self_attn.q_proj", + "encoder.blocks.{n}.self_attention.key" => "model.encoder.layers.{n}.self_attn.k_proj", + "encoder.blocks.{n}.self_attention.value" => "model.encoder.layers.{n}.self_attn.v_proj", + "encoder.blocks.{n}.self_attention.output" => + "model.encoder.layers.{n}.self_attn.out_proj", + "encoder.blocks.{n}.self_attention_norm" => + "model.encoder.layers.{n}.self_attn_layer_norm", + "encoder.blocks.{n}.ffn.intermediate" => "model.encoder.layers.{n}.fc1", + "encoder.blocks.{n}.ffn.output" => "model.encoder.layers.{n}.fc2", + "encoder.blocks.{n}.output_norm" => "model.encoder.layers.{n}.final_layer_norm", + "encoder.norm" => "model.encoder.layer_norm", + "decoder_embedder.token_embedding" => "model.decoder.embed_tokens", + "decoder_embedder.position_embedding" => "model.decoder.embed_positions", + "decoder_embedder.norm" => "model.decoder.layernorm_embedding", + "decoder.blocks.{n}.self_attention.query" => "model.decoder.layers.{n}.self_attn.q_proj", + "decoder.blocks.{n}.self_attention.key" => "model.decoder.layers.{n}.self_attn.k_proj", + "decoder.blocks.{n}.self_attention.value" => "model.decoder.layers.{n}.self_attn.v_proj", + "decoder.blocks.{n}.self_attention.output" => + "model.decoder.layers.{n}.self_attn.out_proj", + "decoder.blocks.{n}.self_attention_norm" => + "model.decoder.layers.{n}.self_attn_layer_norm", + "decoder.blocks.{n}.cross_attention.query" => + "model.decoder.layers.{n}.encoder_attn.q_proj", + "decoder.blocks.{n}.cross_attention.key" => + "model.decoder.layers.{n}.encoder_attn.k_proj", + "decoder.blocks.{n}.cross_attention.value" => + "model.decoder.layers.{n}.encoder_attn.v_proj", + "decoder.blocks.{n}.cross_attention.output" => + "model.decoder.layers.{n}.encoder_attn.out_proj", + "decoder.blocks.{n}.cross_attention_norm" => + "model.decoder.layers.{n}.encoder_attn_layer_norm", + "decoder.blocks.{n}.ffn.intermediate" => "model.decoder.layers.{n}.fc1", + "decoder.blocks.{n}.ffn.output" => "model.decoder.layers.{n}.fc2", + "decoder.blocks.{n}.output_norm" => "model.decoder.layers.{n}.final_layer_norm", + "decoder.norm" => "model.decoder.layer_norm", + "language_modeling_head.output" => "lm_head", + "sequence_classification_head.dense" => "classification_head.dense", + "sequence_classification_head.output" => "classification_head.out_proj", + "question_answering_head.output" => "qa_outputs" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/mbart.ex b/deps/bumblebee/lib/bumblebee/text/mbart.ex new file mode 100644 index 0000000000000000000000000000000000000000..3b93a0a7209965d5d805aa50ecf6d4c49eb694d9 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/mbart.ex @@ -0,0 +1,742 @@ +defmodule Bumblebee.Text.Mbart do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 50265, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 1024, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + hidden_size: [ + default: 1024, + doc: "the dimensionality of hidden layers" + ], + encoder_num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the encoder" + ], + decoder_num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the decoder" + ], + encoder_num_attention_heads: [ + default: 16, + doc: "the number of attention heads for each attention layer in the encoder" + ], + decoder_num_attention_heads: [ + default: 16, + doc: "the number of attention heads for each attention layer in the decoder" + ], + encoder_intermediate_size: [ + default: 4096, + doc: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder" + ], + decoder_intermediate_size: [ + default: 4096, + doc: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the decoder" + ], + scale_embedding: [ + default: false, + doc: "scale embeddings by dividing by sqrt(hidden_size)" + ], + activation: [ + default: :gelu, + doc: "the activation function" + ], + dropout_rate: [ + default: 0.1, + doc: "the dropout rate for encoder and decoder" + ], + attention_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for attention weights" + ], + activation_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for activations inside fully connected layers" + ], + classifier_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for the classification head" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] ++ + Shared.common_options([:num_labels, :id_to_label]) ++ + Shared.token_options(pad_token_id: 1, eos_token_id: 2) + + @moduledoc """ + mBART model family. + + ## Architectures + + * `:base` - plain mBART without any head on top + + * `:for_causal_language_modeling` - mBART with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_conditional_generation` - mBART with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_sequence_classification` - mBART with a sequence + classification head. The head returns logits corresponding to + possible classes + + * `:for_question_answering` - mBART with a span classification head. + The head returns logits for the span start and end positions + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{encoder_num_blocks, encoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + * `"input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"input_ids"`, which can be specified + for more control over how `"input_ids"` are embedded than the + model's internal embedding lookup. If `"input_embeddings"` are present, + then `"input_ids"` will be ignored. + + * `"decoder_input_ids"` - `{batch_size, target_sequence_length}` + + Indices of decoder input sequence tokens in the vocabulary. If not + present and `"input_ids"` is, it will be generated by shifting + each token in `"input_ids"` to the right once. + + * `"decoder_attention_mask"` - `{batch_size, target_sequence_length}` + + Mask indicating which decoder tokens to attend to. This is used + to ignore padding tokens, which are added when processing a batch + of sequences with different length. + + * `"decoder_position_ids"` - `{batch_size, target_sequence_length}` + + Indices of positions of each decoder input sequence tokens in + the position embeddings. + + * `"decoder_attention_head_mask"` - `{decoder_num_blocks, decoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the decoder. + + * `"decoder_input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"decoder_input_ids"`, which can be + specified for more control over how `"decoder_input_ids"` are + embedded than the model's internal embedding lookup. If + `"decoder_input_embeddings"` are present, then `"decoder_input_ids"` + will be ignored. + + * `"encoder_hidden_state"` - `{batch_size, sequence_length, hidden_size}` + + Last hidden state output from the encoder. This hidden state is + used in cross-attention blocks in the decoder. If specified, the + model will skip the encoding process and use this value directly + for cross-attentions in the decoder. + + * `"cross_attention_head_mask"` - `{decoder_num_blocks, decoder_num_attention_heads}` + + Mask to nullify selected heads of the cross-attention blocks in + the decoder with shape. + + * `"cache"` + + A container with cached layer results used to speed up sequential + decoding (autoregression). With cache, certain hidden states are + taken from the cache, rather than recomputed on every decoding + pass. The cache should be treated as opaque and initialized with + `Bumblebee.Text.Generation.init_cache/4`. + + ### Exceptions + + The `:for_causal_language_modeling` model is just the decoder part and + accepts the following inputs instead: `"input_ids"`, `"attention_mask"`, + `"position_ids"`, `"attention_head_mask"`, `"input_embeddings"`, `"encoder_hidden_state"`, + `"encoder_attention_mask"`, `"cross_attention_head_mask"`, `"cache"`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_causal_language_modeling, + :for_conditional_generation, + :for_sequence_classification, + :for_question_answering + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(_spec) do + %{ + "input_ids" => Nx.template({1, 1}, :u32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = encoder_decoder_inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_conditional_generation} = spec) do + inputs = encoder_decoder_inputs(spec) + outputs = core(inputs, spec) + + logits = + outputs.hidden_state + |> language_modeling_head(spec, name: "language_modeling_head") + |> Axon.bias(name: "language_modeling_head.logits_bias", bias_initializer: :zeros) + + Layers.output(%{ + logits: logits, + decoder_hidden_states: outputs.decoder_hidden_states, + decoder_attentions: outputs.decoder_attentions, + cross_attentions: outputs.cross_attentions, + encoder_hidden_state: outputs.encoder_hidden_state, + encoder_hidden_states: outputs.encoder_hidden_states, + encoder_attentions: outputs.encoder_attentions, + cache: outputs.cache + }) + end + + def model(%__MODULE__{architecture: :for_sequence_classification} = spec) do + inputs = encoder_decoder_inputs(spec) + outputs = core(inputs, spec) + + sentence_representation = + Axon.layer( + fn input_ids, hidden_state, _opts -> + eos_mask = Nx.equal(input_ids, spec.eos_token_id) + eos_idx = Nx.argmax(eos_mask, tie_break: :high, axis: 1) + Bumblebee.Utils.Nx.batched_take(hidden_state, eos_idx) + end, + [inputs["input_ids"], outputs.hidden_state] + ) + + logits = + sentence_representation + |> Axon.dropout(rate: spec.classifier_dropout_rate) + |> Axon.dense(spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: "sequence_classification_head.dense" + ) + |> Axon.activation(:tanh) + |> Axon.dropout(rate: spec.classifier_dropout_rate) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "sequence_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + decoder_hidden_states: outputs.decoder_hidden_states, + decoder_attentions: outputs.decoder_attentions, + cross_attentions: outputs.cross_attentions, + encoder_hidden_state: outputs.encoder_hidden_state, + encoder_hidden_states: outputs.encoder_hidden_states, + encoder_attentions: outputs.encoder_attentions + }) + end + + def model(%__MODULE__{architecture: :for_question_answering} = spec) do + inputs = encoder_decoder_inputs(spec) + outputs = core(inputs, spec) + + logits = + Axon.dense(outputs.hidden_state, 2, + kernel_initializer: kernel_initializer(spec), + name: "question_answering_head.output" + ) + + {start_logits, end_logits} = Layers.split_pair(logits) + + Layers.output(%{ + start_logits: start_logits, + end_logits: end_logits, + decoder_hidden_states: outputs.decoder_hidden_states, + decoder_attentions: outputs.decoder_attentions, + cross_attentions: outputs.cross_attentions, + encoder_hidden_state: outputs.encoder_hidden_state, + encoder_hidden_states: outputs.encoder_hidden_states, + encoder_attentions: outputs.encoder_attentions + }) + end + + def model(%__MODULE__{architecture: :for_causal_language_modeling} = spec) do + shape = {nil, nil} + hidden_shape = {nil, nil, spec.hidden_size} + + decoder_attention_head_mask_shape = + {spec.decoder_num_blocks, spec.decoder_num_attention_heads} + + inputs = + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("input_embeddings", optional: true, shape: hidden_shape), + Axon.input("encoder_hidden_state", optional: true, shape: hidden_shape), + Axon.input("encoder_attention_mask", optional: true, shape: shape), + Axon.input("cross_attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("cache", optional: true) + ]) + + embeddings = + embedder(inputs["input_ids"], inputs["position_ids"], inputs["input_embeddings"], spec, + name: "decoder_embedder" + ) + + outputs = + decoder( + embeddings, + inputs["attention_mask"], + inputs["attention_head_mask"], + inputs["encoder_hidden_state"], + inputs["encoder_attention_mask"], + inputs["cross_attention_head_mask"], + inputs["cache"], + spec, + name: "decoder" + ) + + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cross_attentions: outputs.cross_attentions, + cache: outputs.cache + }) + end + + defp encoder_decoder_inputs(spec) do + shape = {nil, nil} + hidden_shape = {nil, nil, spec.hidden_size} + + encoder_attention_head_mask_shape = + {spec.encoder_num_blocks, spec.encoder_num_attention_heads} + + decoder_attention_head_mask_shape = + {spec.decoder_num_blocks, spec.decoder_num_attention_heads} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: encoder_attention_head_mask_shape), + Axon.input("input_embeddings", optional: true, shape: hidden_shape), + Axon.input("decoder_input_ids", optional: true, shape: shape), + Axon.input("decoder_attention_mask", optional: true, shape: shape), + Axon.input("decoder_position_ids", optional: true, shape: shape), + Axon.input("decoder_attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("decoder_input_embeddings", optional: true, shape: hidden_shape), + Axon.input("encoder_hidden_state", optional: true, shape: hidden_shape), + Axon.input("cross_attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("cache", optional: true) + ]) + end + + @impl true + def init_cache(spec, batch_size, max_length, inputs) do + encoder_sequence_length = + if encoder_hidden_state = inputs["encoder_hidden_state"] do + Nx.axis_size(encoder_hidden_state, 1) + end + + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + decoder_num_attention_heads: spec.decoder_num_attention_heads, + encoder_num_attention_heads: spec.encoder_num_attention_heads, + decoder_num_blocks: spec.decoder_num_blocks, + encoder_sequence_length: encoder_sequence_length + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + defp core(inputs, spec) do + encoder_outputs = + Layers.if_present inputs["encoder_hidden_state"] do + %{ + hidden_state: inputs["encoder_hidden_state"], + hidden_states: Layers.none(), + attentions: Layers.none() + } + else + embeddings = + embedder(inputs["input_ids"], inputs["position_ids"], inputs["input_embeddings"], spec, + name: "encoder_embedder" + ) + + embeddings + |> encoder(inputs["attention_mask"], inputs["attention_head_mask"], spec, name: "encoder") + |> Map.take([:hidden_state, :hidden_states, :attentions]) + end + + decoder_input_ids = + Layers.default inputs["decoder_input_ids"] do + Axon.nx(inputs["input_ids"], fn input_ids -> + sequence_length = Nx.axis_size(input_ids, 1) + + eos_indices = + input_ids + |> Nx.not_equal(spec.pad_token_id) + |> Nx.sum(axes: [-1]) + |> Nx.subtract(1) + |> Nx.reshape({:auto, 1}) + |> Nx.as_type({:s, 64}) + + # Use the last non-padding token as the decoder start token + start_ids = Bumblebee.Utils.Nx.batched_take(input_ids, eos_indices) + + if sequence_length == 1 do + start_ids + else + Nx.concatenate([start_ids, input_ids[[.., 0..-2//1]]], axis: 1) + end + end) + end + + embeddings = + embedder( + decoder_input_ids, + inputs["decoder_position_ids"], + inputs["decoder_input_embeddings"], + spec, + name: "decoder_embedder" + ) + + decoder_outputs = + decoder( + embeddings, + inputs["decoder_attention_mask"], + inputs["decoder_attention_head_mask"], + encoder_outputs.hidden_state, + inputs["attention_mask"], + inputs["cross_attention_head_mask"], + inputs["cache"], + spec, + name: "decoder" + ) + + %{ + hidden_state: decoder_outputs.hidden_state, + decoder_hidden_states: decoder_outputs.hidden_states, + decoder_attentions: decoder_outputs.attentions, + cross_attentions: decoder_outputs.cross_attentions, + cache: decoder_outputs.cache, + encoder_hidden_state: encoder_outputs.hidden_state, + encoder_hidden_states: encoder_outputs.hidden_states, + encoder_attentions: encoder_outputs.attentions + } + end + + defp encoder(hidden_state, attention_mask, attention_head_mask, spec, opts) do + name = opts[:name] + + encoder_outputs = + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + num_blocks: spec.encoder_num_blocks, + num_attention_heads: spec.encoder_num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: 1.0e-5 + ], + block_type: :norm_first, + ffn: [ + intermediate_size: spec.encoder_intermediate_size, + activation: spec.activation + ], + name: join(name, "blocks") + ) + + hidden_state = Axon.layer_norm(encoder_outputs.hidden_state, name: join(name, "norm")) + + %{ + hidden_state: hidden_state, + hidden_states: Layers.replace(encoder_outputs.hidden_states, -1, hidden_state), + attentions: encoder_outputs.attentions + } + end + + defp embedder(input_ids, position_ids, input_embeddings, spec, opts) do + name = opts[:name] + + input_embeddings = + Layers.default input_embeddings do + token_embedding(input_ids, spec, name: join(name, "token_embedding")) + end + + position_ids = + Layers.default position_ids do + Layers.default_position_ids(input_embeddings) + end + + position_embeddings = + position_embedding(position_ids, spec, name: join(name, "position_embedding")) + + Axon.add([input_embeddings, position_embeddings]) + |> Axon.layer_norm(epsilon: 1.0e-5, name: join(name, "norm")) + |> Axon.dropout(rate: spec.dropout_rate) + end + + defp token_embedding(input_ids, spec, opts) do + name = opts[:name] + + input_embeddings = + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: name + ) + + if spec.scale_embedding do + Axon.nx(input_embeddings, fn x -> Nx.multiply(x, Nx.sqrt(spec.hidden_size)) end) + else + input_embeddings + end + end + + defp position_embedding(position_ids, spec, opts) do + name = opts[:name] + + # For mBART we need to offset the embeddings + offset = 2 + + position_ids + |> Axon.add(Axon.constant(Nx.tensor(offset))) + |> Axon.embedding(spec.max_positions + offset, spec.hidden_size, name: name) + end + + defp decoder( + hidden_state, + attention_mask, + attention_head_mask, + encoder_hidden_state, + encoder_attention_mask, + cross_attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + + decoder_outputs = + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + cross_hidden_state: encoder_hidden_state, + cross_attention_mask: encoder_attention_mask, + cross_attention_head_mask: cross_attention_head_mask, + cache: cache, + causal: true, + num_blocks: spec.decoder_num_blocks, + num_attention_heads: spec.decoder_num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: 1.0e-5 + ], + block_type: :norm_first, + ffn: [ + intermediate_size: spec.decoder_intermediate_size, + activation: spec.activation + ], + name: join(name, "blocks") + ) + + hidden_state = Axon.layer_norm(decoder_outputs.hidden_state, name: join(name, "norm")) + + %{ + cache: decoder_outputs.cache, + hidden_state: hidden_state, + hidden_states: Layers.replace(decoder_outputs.hidden_states, -1, hidden_state), + attentions: decoder_outputs.attentions, + cross_attentions: decoder_outputs.cross_attentions + } + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: Tie lm-head to word embedding as a spec option + Layers.dense_transposed(hidden_state, spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"max_position_embeddings", number()}, + hidden_size: {"d_model", number()}, + encoder_num_blocks: {"encoder_layers", number()}, + decoder_num_blocks: {"decoder_layers", number()}, + encoder_num_attention_heads: {"encoder_attention_heads", number()}, + decoder_num_attention_heads: {"decoder_attention_heads", number()}, + encoder_intermediate_size: {"encoder_ffn_dim", number()}, + decoder_intermediate_size: {"decoder_ffn_dim", number()}, + scale_embedding: {"scale_embedding", boolean()}, + activation: {"activation_function", activation()}, + dropout_rate: {"dropout", number()}, + attention_dropout_rate: {"attention_dropout", number()}, + activation_dropout_rate: {"activation_dropout", number()}, + classifier_dropout_rate: {"classifier_dropout", number()}, + initializer_scale: {"init_std", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(spec) do + %{ + "encoder_embedder.token_embedding" => "model.encoder.embed_tokens", + "encoder_embedder.position_embedding" => "model.encoder.embed_positions", + "encoder_embedder.norm" => "model.encoder.layernorm_embedding", + "encoder.blocks.{n}.self_attention.query" => "model.encoder.layers.{n}.self_attn.q_proj", + "encoder.blocks.{n}.self_attention.key" => "model.encoder.layers.{n}.self_attn.k_proj", + "encoder.blocks.{n}.self_attention.value" => "model.encoder.layers.{n}.self_attn.v_proj", + "encoder.blocks.{n}.self_attention.output" => + "model.encoder.layers.{n}.self_attn.out_proj", + "encoder.blocks.{n}.self_attention_norm" => + "model.encoder.layers.{n}.self_attn_layer_norm", + "encoder.blocks.{n}.ffn.intermediate" => "model.encoder.layers.{n}.fc1", + "encoder.blocks.{n}.ffn.output" => "model.encoder.layers.{n}.fc2", + "encoder.blocks.{n}.output_norm" => "model.encoder.layers.{n}.final_layer_norm", + "encoder.norm" => "model.encoder.layer_norm", + "decoder_embedder.token_embedding" => "model.decoder.embed_tokens", + "decoder_embedder.position_embedding" => "model.decoder.embed_positions", + "decoder_embedder.norm" => "model.decoder.layernorm_embedding", + "decoder.blocks.{n}.self_attention.query" => "model.decoder.layers.{n}.self_attn.q_proj", + "decoder.blocks.{n}.self_attention.key" => "model.decoder.layers.{n}.self_attn.k_proj", + "decoder.blocks.{n}.self_attention.value" => "model.decoder.layers.{n}.self_attn.v_proj", + "decoder.blocks.{n}.self_attention.output" => + "model.decoder.layers.{n}.self_attn.out_proj", + "decoder.blocks.{n}.self_attention_norm" => + "model.decoder.layers.{n}.self_attn_layer_norm", + "decoder.blocks.{n}.cross_attention.query" => + "model.decoder.layers.{n}.encoder_attn.q_proj", + "decoder.blocks.{n}.cross_attention.key" => + "model.decoder.layers.{n}.encoder_attn.k_proj", + "decoder.blocks.{n}.cross_attention.value" => + "model.decoder.layers.{n}.encoder_attn.v_proj", + "decoder.blocks.{n}.cross_attention.output" => + "model.decoder.layers.{n}.encoder_attn.out_proj", + "decoder.blocks.{n}.cross_attention_norm" => + "model.decoder.layers.{n}.encoder_attn_layer_norm", + "decoder.blocks.{n}.ffn.intermediate" => "model.decoder.layers.{n}.fc1", + "decoder.blocks.{n}.ffn.output" => "model.decoder.layers.{n}.fc2", + "decoder.blocks.{n}.output_norm" => "model.decoder.layers.{n}.final_layer_norm", + "decoder.norm" => "model.decoder.layer_norm", + "language_modeling_head.output" => + case spec.architecture do + :for_causal_language_modeling -> "lm_head" + _other -> "model.shared" + end, + "language_modeling_head.logits_bias" => %{ + "bias" => {[{"model", "final_logits_bias"}], fn [value] -> Nx.squeeze(value) end} + }, + "sequence_classification_head.dense" => "classification_head.dense", + "sequence_classification_head.output" => "classification_head.out_proj", + "question_answering_head.output" => "qa_outputs" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/mistral.ex b/deps/bumblebee/lib/bumblebee/text/mistral.ex new file mode 100644 index 0000000000000000000000000000000000000000..97401197634d2e991524cfaec0dcdd794859bea3 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/mistral.ex @@ -0,0 +1,426 @@ +defmodule Bumblebee.Text.Mistral do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 32000, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 131_072, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + hidden_size: [ + default: 4096, + doc: "the dimensionality of hidden layers" + ], + intermediate_size: [ + default: 14336, + doc: "the dimensionality of intermediate layers" + ], + num_blocks: [ + default: 32, + doc: "the number of Transformer blocks in the model" + ], + num_attention_heads: [ + default: 32, + doc: "the number of attention heads for each attention layer in the model" + ], + num_key_value_heads: [ + default: 8, + doc: """ + the number of key-value heads used to implement Grouped Query Attention. If + this value is set to the same as the number of attention heads, it will use + regular MHA. If it's set to 1, it will use MQA, otherwise it uses Grouped Query + Attention + """ + ], + attention_window_size: [ + default: 4096, + doc: "window size for both sides of the sliding attention window" + ], + activation: [ + default: :silu, + doc: "the activation function" + ], + layer_norm_epsilon: [ + default: 1.0e-12, + doc: "the epsilon used by RMS normalization layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ], + rotary_embedding_base: [ + default: 10_000, + doc: "base for computing rotary embedding frequency" + ] + ] ++ + Shared.common_options([:num_labels, :id_to_label]) ++ Shared.token_options(pad_token_id: 0) + + @moduledoc """ + Mistral model family. + + ## Architectures + + * `:base` - plain Mistral without any head on top + + * `:for_causal_language_modeling` - Mistral with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_sequence_classification` - Mistral with a sequence + classification head. The head returns logits corresponding to + possible classes + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{encoder_num_blocks, encoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + * `"input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"input_ids"`, which can be specified + for more control over how `"input_ids"` are embedded than the + model's internal embedding lookup. If `"input_embeddings"` are present, + then `"input_ids"` will be ignored. + + * `"cache"` + + A container with cached layer results used to speed up sequential + decoding (autoregression). With cache, certain hidden states are + taken from the cache, rather than recomputed on every decoding + pass. The cache should be treated as opaque and initialized with + `Bumblebee.Text.Generation.init_cache/4`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_causal_language_modeling, + :for_sequence_classification + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(_spec) do + %{ + "input_ids" => Nx.template({1, 1}, :s64) + } + end + + @impl true + def init_cache(spec, batch_size, max_length, _inputs) do + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + decoder_num_attention_heads: spec.num_attention_heads, + decoder_num_blocks: spec.num_blocks + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_causal_language_modeling} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cache: outputs.cache + }) + end + + def model(%__MODULE__{architecture: :for_sequence_classification} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + + logits = + Axon.dense(outputs.hidden_state, spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "sequence_classification_head.output", + use_bias: false + ) + + pooled_logits = + Layers.if_present inputs["input_ids"] do + Axon.layer( + fn logits, input_ids, _opts -> + indices = + input_ids + |> Nx.not_equal(spec.pad_token_id) + |> Nx.sum(axes: [-1]) + |> Nx.subtract(1) + |> Nx.as_type({:s, 64}) + + Bumblebee.Utils.Nx.batched_take(logits, indices) + end, + [logits, inputs["input_ids"]] + ) + else + Layers.take_token(logits, axis: 1, index: -1) + end + + Layers.output(%{ + logits: pooled_logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cache: outputs.cache + }) + end + + defp inputs(spec) do + shape = {nil, nil} + hidden_shape = {nil, nil, spec.hidden_size} + + attention_head_mask_shape = {spec.num_blocks, spec.num_attention_heads} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: attention_head_mask_shape), + Axon.input("input_embeddings", optional: true, shape: hidden_shape), + Axon.input("cache", optional: true) + ]) + end + + defp core(inputs, spec) do + embeddings = + embedder( + inputs["input_ids"], + inputs["input_embeddings"], + spec, + name: "embedder" + ) + + position_ids = + Layers.default inputs["position_ids"] do + Layers.default_position_ids(embeddings) + end + + decoder_outputs = + decoder( + embeddings, + position_ids, + inputs["attention_mask"], + inputs["attention_head_mask"], + inputs["cache"], + spec, + name: "decoder" + ) + + hidden_state = + Layers.rms_norm(decoder_outputs.hidden_state, + name: "output_norm", + epsilon: spec.layer_norm_epsilon + ) + + %{ + hidden_state: hidden_state, + hidden_states: Layers.append(decoder_outputs.hidden_states, hidden_state), + attentions: decoder_outputs.attentions, + cache: decoder_outputs.cache + } + end + + defp embedder(input_ids, input_embeddings, spec, opts) do + name = opts[:name] + + # TODO: Axon needs a way to specify ignoring pad tokens + # in gradient + Layers.default input_embeddings do + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "token_embedding") + ) + end + end + + defp decoder( + hidden_state, + position_ids, + attention_mask, + attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + cache: cache, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + num_key_value_heads: spec.num_key_value_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + layer_norm: &Layers.rms_norm(&1, name: &2, epsilon: spec.layer_norm_epsilon), + ffn: + &gated_ffn(&1, spec.intermediate_size, spec.hidden_size, + name: &2, + activation: spec.activation + ), + block_type: :norm_first, + causal: true, + attention_window_size: + spec.attention_window_size && {spec.attention_window_size, spec.attention_window_size}, + rotary_embedding: [ + position_ids: position_ids, + max_positions: spec.max_positions, + base: spec.rotary_embedding_base + ], + query_use_bias: false, + key_use_bias: false, + value_use_bias: false, + output_use_bias: false, + name: join(name, "blocks") + ) + end + + defp gated_ffn(hidden_state, intermediate_size, output_size, opts) do + name = opts[:name] + activation = opts[:activation] + + intermediate = + Axon.dense(hidden_state, intermediate_size, + name: join(name, "intermediate"), + use_bias: false + ) + + gate = Axon.dense(hidden_state, intermediate_size, name: join(name, "gate"), use_bias: false) + + hidden_state = Axon.multiply(intermediate, Layers.activation(gate, activation)) + + Axon.dense(hidden_state, output_size, name: join(name, "output"), use_bias: false) + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: Tie lm-head to word embedding as a spec option + Layers.dense_transposed(hidden_state, spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"max_position_embeddings", number()}, + hidden_size: {"hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_attention_heads: {"num_attention_heads", number()}, + num_key_value_heads: {"num_key_value_heads", number()}, + attention_window_size: {"sliding_window", optional(number())}, + intermediate_size: {"intermediate_size", number()}, + activation: {"hidden_act", activation()}, + rotary_embedding_base: {"rope_theta", number()}, + initializer_scale: {"initializer_range", number()}, + layer_norm_epsilon: {"rms_norm_eps", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.token_embedding" => "model.embed_tokens", + "decoder.blocks.{n}.self_attention.query" => "model.layers.{n}.self_attn.q_proj", + "decoder.blocks.{n}.self_attention.key" => "model.layers.{n}.self_attn.k_proj", + "decoder.blocks.{n}.self_attention.value" => "model.layers.{n}.self_attn.v_proj", + "decoder.blocks.{n}.self_attention.output" => "model.layers.{n}.self_attn.o_proj", + "decoder.blocks.{n}.self_attention_norm" => "model.layers.{n}.input_layernorm", + "decoder.blocks.{n}.self_attention.rotary_embedding" => + "model.layers.{n}.self_attn.rotary_emb", + "decoder.blocks.{n}.ffn.gate" => "model.layers.{n}.mlp.gate_proj", + "decoder.blocks.{n}.ffn.intermediate" => "model.layers.{n}.mlp.up_proj", + "decoder.blocks.{n}.ffn.output" => "model.layers.{n}.mlp.down_proj", + "decoder.blocks.{n}.output_norm" => "model.layers.{n}.post_attention_layernorm", + "output_norm" => "model.norm", + "language_modeling_head.output" => "lm_head", + "sequence_classification_head.output" => "score" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/phi.ex b/deps/bumblebee/lib/bumblebee/text/phi.ex new file mode 100644 index 0000000000000000000000000000000000000000..8f1f7226b423c00548222039c1370bbd55898dde --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/phi.ex @@ -0,0 +1,456 @@ +defmodule Bumblebee.Text.Phi do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 51200, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 2048, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + hidden_size: [ + default: 2048, + doc: "the dimensionality of hidden layers" + ], + intermediate_size: [ + default: 8192, + doc: "the dimensionality of intermediate layers" + ], + num_blocks: [ + default: 24, + doc: "the number of Transformer blocks in the model" + ], + num_attention_heads: [ + default: 32, + doc: "the number of attention heads for each attention layer in the model" + ], + num_key_value_heads: [ + default: nil, + doc: """ + the number of key-value heads used to implement Grouped Query Attention. If + this value is set to the same as the number of attention heads, it will use + regular MHA. If it's set to 1, it will use MQA, otherwise it uses Grouped Query + Attention + """ + ], + activation: [ + default: :gelu_approx_tanh, + doc: "the activation function" + ], + rotary_embedding_percentage: [ + default: 0.5, + doc: "percentage of the query and keys that will have rotary embedding" + ], + rotary_embedding_base: [ + default: 10_000, + doc: "base for computing rotary embedding frequency" + ], + layer_norm_epsilon: [ + default: 1.0e-12, + doc: "the epsilon used by RMS normalization layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] ++ + Shared.common_options([:num_labels, :id_to_label]) ++ Shared.token_options(pad_token_id: 0) + + @moduledoc """ + Phi model family. + + ## Architectures + + * `:base` - plain Phi without any head on top + + * `:for_causal_language_modeling` - Phi with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_sequence_classification` - Phi with a sequence + classification head. The head returns logits corresponding to + possible classes + + * `:for_token_classification` - Phi with a token classification + head. The head returns logits for each token in the original + sequence + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{encoder_num_blocks, encoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + * `"input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"input_ids"`, which can be specified + for more control over how `"input_ids"` are embedded than the + model's internal embedding lookup. If `"input_embeddings"` are present, + then `"input_ids"` will be ignored. + + * `"cache"` + + A container with cached layer results used to speed up sequential + decoding (autoregression). With cache, certain hidden states are + taken from the cache, rather than recomputed on every decoding + pass. The cache should be treated as opaque and initialized with + `Bumblebee.Text.Generation.init_cache/4`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_causal_language_modeling, + :for_sequence_classification, + :for_token_classification + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(_spec) do + %{ + "input_ids" => Nx.template({1, 1}, :s64) + } + end + + @impl true + def init_cache(spec, batch_size, max_length, _inputs) do + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + decoder_num_attention_heads: spec.num_attention_heads, + decoder_num_blocks: spec.num_blocks + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_causal_language_modeling} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cache: outputs.cache + }) + end + + def model(%__MODULE__{architecture: :for_sequence_classification} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + + logits = + Axon.dense(outputs.hidden_state, spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "sequence_classification_head.output", + use_bias: false + ) + + pooled_logits = + Layers.if_present inputs["input_ids"] do + Axon.layer( + fn logits, input_ids, _opts -> + indices = + input_ids + |> Nx.not_equal(spec.pad_token_id) + |> Nx.sum(axes: [-1]) + |> Nx.subtract(1) + |> Nx.as_type({:s, 64}) + + Bumblebee.Utils.Nx.batched_take(logits, indices) + end, + [logits, inputs["input_ids"]] + ) + else + Layers.take_token(logits, axis: 1, index: -1) + end + + Layers.output(%{ + logits: pooled_logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cache: outputs.cache + }) + end + + def model(%__MODULE__{architecture: :for_token_classification} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + outputs.hidden_state + |> Axon.dropout( + rate: 0.1, + name: "token_classification_head.dropout" + ) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "token_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + defp inputs(spec) do + shape = {nil, nil} + hidden_shape = {nil, nil, spec.hidden_size} + + attention_head_mask_shape = {spec.num_blocks, spec.num_attention_heads} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: attention_head_mask_shape), + Axon.input("input_embeddings", optional: true, shape: hidden_shape), + Axon.input("cache", optional: true) + ]) + end + + defp core(inputs, spec) do + embeddings = + embedder( + inputs["input_ids"], + inputs["input_embeddings"], + spec, + name: "embedder" + ) + + position_ids = + Layers.default inputs["position_ids"] do + Layers.default_position_ids(embeddings) + end + + decoder_outputs = + decoder( + embeddings, + position_ids, + inputs["attention_mask"], + inputs["attention_head_mask"], + inputs["cache"], + spec, + name: "decoder" + ) + + hidden_state = + Axon.layer_norm(decoder_outputs.hidden_state, + name: "output_norm", + epsilon: spec.layer_norm_epsilon + ) + + %{ + hidden_state: hidden_state, + hidden_states: Layers.append(decoder_outputs.hidden_states, hidden_state), + attentions: decoder_outputs.attentions, + cache: decoder_outputs.cache + } + end + + defp embedder(input_ids, input_embeddings, spec, opts) do + name = opts[:name] + + # TODO: Axon needs a way to specify ignoring pad tokens + # in gradient + Layers.default input_embeddings do + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "token_embedding") + ) + end + end + + defp decoder( + hidden_state, + position_ids, + attention_mask, + attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + cache: cache, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + num_key_value_heads: spec.num_key_value_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + layer_norm: [ + epsilon: spec.layer_norm_epsilon + ], + ffn: [ + intermediate_size: spec.intermediate_size, + activation: spec.activation + ], + block_type: &block_impl/3, + causal: true, + rotary_embedding: [ + position_ids: position_ids, + max_positions: spec.max_positions, + base: spec.rotary_embedding_base, + percentage: spec.rotary_embedding_percentage + ], + query_use_bias: true, + key_use_bias: true, + value_use_bias: true, + output_use_bias: true, + name: join(name, "blocks") + ) + end + + # :parallel block with attention norm applied earlier and without ffn norm + defp block_impl(hidden_state, steps, _name) do + shortcut = hidden_state + + hidden_state = steps.self_attention_norm.(hidden_state) + + {attention_hidden_state, attention_info} = steps.self_attention.(hidden_state) + + {_hidden_state, cross_attention_info} = + steps.cross_attention_maybe.(hidden_state, fn _hidden_state -> + raise "cross attention not supported" + end) + + ffn_hidden_state = steps.ffn.(hidden_state) + + hidden_state = Axon.add([shortcut, attention_hidden_state, ffn_hidden_state]) + + {hidden_state, attention_info, cross_attention_info} + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: Tie lm-head to word embedding as a spec option + Layers.dense_transposed(hidden_state, spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output"), + use_bias: true + ) + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"max_position_embeddings", number()}, + hidden_size: {"hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_attention_heads: {"num_attention_heads", number()}, + num_key_value_heads: {"num_key_value_heads", number()}, + intermediate_size: {"intermediate_size", number()}, + activation: {"hidden_act", activation()}, + rotary_embedding_base: {"rope_theta", number()}, + rotary_embedding_percentage: {"partial_rotary_factor", number()}, + initializer_scale: {"initializer_range", number()}, + layer_norm_epsilon: {"layer_norm_eps", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.token_embedding" => "model.embed_tokens", + "decoder.blocks.{n}.self_attention.query" => "model.layers.{n}.self_attn.q_proj", + "decoder.blocks.{n}.self_attention.key" => "model.layers.{n}.self_attn.k_proj", + "decoder.blocks.{n}.self_attention.value" => "model.layers.{n}.self_attn.v_proj", + "decoder.blocks.{n}.self_attention.output" => "model.layers.{n}.self_attn.dense", + "decoder.blocks.{n}.self_attention_norm" => "model.layers.{n}.input_layernorm", + "decoder.blocks.{n}.self_attention.rotary_embedding" => + "model.layers.{n}.self_attn.rotary_emb", + "decoder.blocks.{n}.ffn.intermediate" => "model.layers.{n}.mlp.fc1", + "decoder.blocks.{n}.ffn.output" => "model.layers.{n}.mlp.fc2", + "output_norm" => "model.final_layernorm", + "language_modeling_head.output" => "lm_head", + "sequence_classification_head.output" => "score", + "token_classification_head.output" => "classifier" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/phi3.ex b/deps/bumblebee/lib/bumblebee/text/phi3.ex new file mode 100644 index 0000000000000000000000000000000000000000..712800a657e91af4445cd01a692f54a662f39a0c --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/phi3.ex @@ -0,0 +1,523 @@ +defmodule Bumblebee.Text.Phi3 do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 51200, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 2048, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + hidden_size: [ + default: 2048, + doc: "the dimensionality of hidden layers" + ], + intermediate_size: [ + default: 8192, + doc: "the dimensionality of intermediate layers" + ], + num_blocks: [ + default: 24, + doc: "the number of Transformer blocks in the model" + ], + num_attention_heads: [ + default: 32, + doc: "the number of attention heads for each attention layer in the model" + ], + num_key_value_heads: [ + default: nil, + doc: """ + the number of key-value heads used to implement Grouped Query Attention. If + this value is set to the same as the number of attention heads, it will use + regular MHA. If it's set to 1, it will use MQA, otherwise it uses Grouped Query + Attention + """ + ], + attention_window_size: [ + default: 262_144, + doc: "window size for both sides of the sliding attention window" + ], + activation: [ + default: :gelu_approx_tanh, + doc: "the activation function" + ], + rotary_embedding_percentage: [ + default: 1.0, + doc: "percentage of hidden dimensions to allocate to rotary embeddings" + ], + rotary_embedding_base: [ + default: 10_000, + doc: "base for computing rotary embedding frequency" + ], + rotary_embedding_scaling_strategy: [ + default: nil, + doc: """ + scaling configuration for rotary embedding. Currently the supported values are: + + * `%{type: :longrope, short_factor: list(number()), long_factor: list(number()), original_max_positions: pos_integer()}` + + """ + ], + layer_norm_epsilon: [ + default: 1.0e-12, + doc: "the epsilon used by RMS normalization layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] ++ + Shared.common_options([:num_labels, :id_to_label]) ++ + Shared.token_options(pad_token_id: 32000) + + @moduledoc """ + Phi-3 model family. + + ## Architectures + + * `:base` - plain Phi-3 without any head on top + + * `:for_causal_language_modeling` - Phi-3 with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_sequence_classification` - Phi-3 with a sequence + classification head. The head returns logits corresponding to + possible classes + + * `:for_token_classification` - Phi-3 with a token classification + head. The head returns logits for each token in the original + sequence + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{encoder_num_blocks, encoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + * `"input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"input_ids"`, which can be specified + for more control over how `"input_ids"` are embedded than the + model's internal embedding lookup. If `"input_embeddings"` are present, + then `"input_ids"` will be ignored. + + * `"cache"` + + A container with cached layer results used to speed up sequential + decoding (autoregression). With cache, certain hidden states are + taken from the cache, rather than recomputed on every decoding + pass. The cache should be treated as opaque and initialized with + `Bumblebee.Text.Generation.init_cache/4`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_causal_language_modeling, + :for_sequence_classification, + :for_token_classification + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(_spec) do + %{ + "input_ids" => Nx.template({1, 1}, :s64) + } + end + + @impl true + def init_cache(spec, batch_size, max_length, _inputs) do + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + decoder_num_attention_heads: spec.num_attention_heads, + decoder_num_blocks: spec.num_blocks + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_causal_language_modeling} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cache: outputs.cache + }) + end + + def model(%__MODULE__{architecture: :for_sequence_classification} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + + logits = + Axon.dense(outputs.hidden_state, spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "sequence_classification_head.output", + use_bias: false + ) + + pooled_logits = + Layers.if_present inputs["input_ids"] do + Axon.layer( + fn logits, input_ids, _opts -> + indices = + input_ids + |> Nx.not_equal(spec.pad_token_id) + |> Nx.sum(axes: [-1]) + |> Nx.subtract(1) + |> Nx.as_type({:s, 64}) + + Bumblebee.Utils.Nx.batched_take(logits, indices) + end, + [logits, inputs["input_ids"]] + ) + else + Layers.take_token(logits, axis: 1, index: -1) + end + + Layers.output(%{ + logits: pooled_logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cache: outputs.cache + }) + end + + def model(%__MODULE__{architecture: :for_token_classification} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + outputs.hidden_state + |> Axon.dropout( + rate: 0.1, + name: "token_classification_head.dropout" + ) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "token_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + defp inputs(spec) do + shape = {nil, nil} + hidden_shape = {nil, nil, spec.hidden_size} + + attention_head_mask_shape = {spec.num_blocks, spec.num_attention_heads} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: attention_head_mask_shape), + Axon.input("input_embeddings", optional: true, shape: hidden_shape), + Axon.input("cache", optional: true) + ]) + end + + defp core(inputs, spec) do + embeddings = + embedder( + inputs["input_ids"], + inputs["input_embeddings"], + spec, + name: "embedder" + ) + + position_ids = + Layers.default inputs["position_ids"] do + Layers.default_position_ids(embeddings) + end + + decoder_outputs = + decoder( + embeddings, + position_ids, + inputs["attention_mask"], + inputs["attention_head_mask"], + inputs["cache"], + spec, + name: "decoder" + ) + + hidden_state = + Layers.rms_norm(decoder_outputs.hidden_state, + name: "output_norm", + epsilon: spec.layer_norm_epsilon + ) + + %{ + hidden_state: hidden_state, + hidden_states: Layers.append(decoder_outputs.hidden_states, hidden_state), + attentions: decoder_outputs.attentions, + cache: decoder_outputs.cache + } + end + + defp embedder(input_ids, input_embeddings, spec, opts) do + name = opts[:name] + + # TODO: Axon needs a way to specify ignoring pad tokens + # in gradient + Layers.default input_embeddings do + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "token_embedding") + ) + end + end + + defp decoder( + hidden_state, + position_ids, + attention_mask, + attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + cache: cache, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + num_key_value_heads: spec.num_key_value_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + layer_norm: &Layers.rms_norm(&1, name: &2, epsilon: spec.layer_norm_epsilon), + ffn: + &gated_ffn(&1, spec.intermediate_size, spec.hidden_size, + name: &2, + activation: spec.activation + ), + block_type: :norm_first, + causal: true, + attention_window_size: + spec.attention_window_size && {spec.attention_window_size, spec.attention_window_size}, + rotary_embedding: [ + position_ids: position_ids, + max_positions: spec.max_positions, + base: spec.rotary_embedding_base, + percentage: spec.rotary_embedding_percentage, + scaling_strategy: spec.rotary_embedding_scaling_strategy + ], + query_use_bias: false, + key_use_bias: false, + value_use_bias: false, + output_use_bias: false, + name: join(name, "blocks") + ) + end + + defp gated_ffn(hidden_state, intermediate_size, output_size, opts) do + name = opts[:name] + activation = opts[:activation] + + intermediate = + Axon.dense(hidden_state, intermediate_size, + name: join(name, "intermediate"), + use_bias: false + ) + + gate = Axon.dense(hidden_state, intermediate_size, name: join(name, "gate"), use_bias: false) + + hidden_state = Axon.multiply(intermediate, Axon.activation(gate, activation)) + + Axon.dense(hidden_state, output_size, name: join(name, "output"), use_bias: false) + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: Tie lm-head to word embedding as a spec option + Layers.dense_transposed(hidden_state, spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output"), + use_bias: false + ) + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + scaling_strategy_converter = fn name, value -> + original_max_positions = data["original_max_position_embeddings"] + + case value do + %{"type" => type, "long_factor" => long_factor, "short_factor" => short_factor} + when type in ["longrope", "su", "yarn"] and + is_list(long_factor) and is_list(short_factor) and + is_number(original_max_positions) -> + {:ok, + %{ + type: :longrope, + long_factor: long_factor, + short_factor: short_factor, + original_max_positions: original_max_positions + }} + + _other -> + {:error, "invalid format for #{inspect(name)}, got: #{inspect(value)}"} + end + end + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"max_position_embeddings", number()}, + hidden_size: {"hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_attention_heads: {"num_attention_heads", number()}, + num_key_value_heads: {"num_key_value_heads", number()}, + attention_window_size: {"sliding_window", optional(number())}, + intermediate_size: {"intermediate_size", number()}, + activation: {"hidden_act", activation()}, + rotary_embedding_percentage: {"partial_rotary_factor", number()}, + rotary_embedding_base: {"rope_theta", number()}, + rotary_embedding_scaling_strategy: + {"rope_scaling", optional(scaling_strategy_converter)}, + initializer_scale: {"initializer_range", number()}, + layer_norm_epsilon: {"rms_norm_eps", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(spec) do + out_template = + {[spec.num_attention_heads, spec.num_key_value_heads, spec.num_key_value_heads], :auto} + + %{ + "embedder.token_embedding" => "model.embed_tokens", + "decoder.blocks.{n}.self_attention.query" => + Shared.sliced_dense_params_source( + "model.layers.{n}.self_attn.qkv_proj", + out_template, + 0 + ), + "decoder.blocks.{n}.self_attention.key" => + Shared.sliced_dense_params_source( + "model.layers.{n}.self_attn.qkv_proj", + out_template, + 1 + ), + "decoder.blocks.{n}.self_attention.value" => + Shared.sliced_dense_params_source( + "model.layers.{n}.self_attn.qkv_proj", + out_template, + 2 + ), + "decoder.blocks.{n}.self_attention.output" => "model.layers.{n}.self_attn.o_proj", + "decoder.blocks.{n}.self_attention_norm" => "model.layers.{n}.input_layernorm", + "decoder.blocks.{n}.self_attention.rotary_embedding" => + "model.layers.{n}.self_attn.rotary_emb", + "decoder.blocks.{n}.ffn.gate" => + Shared.sliced_dense_params_source( + "model.layers.{n}.mlp.gate_up_proj", + {[1, 1], :auto}, + 0 + ), + "decoder.blocks.{n}.ffn.intermediate" => + Shared.sliced_dense_params_source( + "model.layers.{n}.mlp.gate_up_proj", + {[1, 1], :auto}, + 1 + ), + "decoder.blocks.{n}.ffn.output" => "model.layers.{n}.mlp.down_proj", + "decoder.blocks.{n}.output_norm" => "model.layers.{n}.post_attention_layernorm", + "output_norm" => "model.norm", + "language_modeling_head.output" => "lm_head", + "sequence_classification_head.output" => "score", + "token_classification_head.output" => "classifier" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/pre_trained_tokenizer.ex b/deps/bumblebee/lib/bumblebee/text/pre_trained_tokenizer.ex new file mode 100644 index 0000000000000000000000000000000000000000..59ab346886aa23eb40602c737b1fa2a15a212617 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/pre_trained_tokenizer.ex @@ -0,0 +1,577 @@ +defmodule Bumblebee.Text.PreTrainedTokenizer do + alias Bumblebee.Shared + + options = [ + add_special_tokens: [ + default: true, + doc: "whether to add special tokens during tokenization" + ], + length: [ + default: nil, + doc: """ + applies fixed length padding or truncation to the given input if set. Can be either + a specific number or a list of numbers. When a list is given, the smallest number + that exceeds all input lengths is used as the padding length + """ + ], + pad_direction: [ + default: :right, + doc: "the padding direction, either `:right` or `:left`" + ], + truncate_direction: [ + default: :right, + doc: "the truncation direction, either `:right` or `:left`" + ], + return_attention_mask: [ + default: true, + doc: """ + whether to return attention mask for encoded sequence. The mask is a boolean tensor + indicating which tokens are padding and should effectively be ignored by the model + """ + ], + return_token_type_ids: [ + default: true, + doc: "whether to return token type ids for encoded sequence" + ], + return_special_tokens_mask: [ + default: false, + doc: """ + whether to return special tokens mask for encoded sequence. The mask is a boolean + tensor indicating which tokens are special + """ + ], + return_offsets: [ + default: false, + doc: """ + whether to return token offsets for encoded sequence. This tensor includes a list of + position pairs that map tokens to the input text + """ + ], + return_length: [ + default: false, + doc: """ + whether to return the sequence length. The length is the effective number of tokens, + so it is calculated after truncation, but does not include padding + """ + ], + template_options: [ + default: [], + doc: """ + options configuring the tokenization template, specific to the given tokenizer type. + Recognised options are: + + * `:language_token` - for tokenizers: `:nllb` + + """ + ] + ] + + @moduledoc """ + Wraps a pre-trained tokenizer from the `Tokenizers` library. + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [ + :native_tokenizer, + :type, + special_tokens: %{}, + additional_special_tokens: [] + ] ++ Shared.option_defaults(options) + + alias Tokenizers.{Tokenizer, Encoding} + + @behaviour Bumblebee.Tokenizer + @behaviour Bumblebee.Configurable + + @tokenizer_types %{ + albert: %{ + special_tokens: %{ + bos: "[CLS]", + eos: "[SEP]", + unk: "", + sep: "[SEP]", + pad: "", + cls: "[CLS]", + mask: "[MASK]" + } + }, + bart: %{ + special_tokens: %{ + bos: "", + eos: "", + unk: "", + sep: "", + pad: "", + cls: "", + mask: "" + } + }, + bert: %{ + special_tokens: %{unk: "[UNK]", sep: "[SEP]", pad: "[PAD]", cls: "[CLS]", mask: "[MASK]"} + }, + blenderbot: %{ + special_tokens: %{ + unk: "", + bos: "", + eos: "", + pad: "", + sep: "", + cls: "", + mask: "" + } + }, + camembert: %{ + special_tokens: %{ + bos: "", + eos: "", + unk: "", + sep: "", + pad: "", + cls: "", + mask: "" + } + }, + clip: %{ + special_tokens: %{unk: "<|endoftext|>", pad: "<|endoftext|>", eos: "<|endoftext|>"} + }, + code_gen: %{ + special_tokens: %{ + unk: "<|endoftext|>", + bos: "<|endoftext|>", + eos: "<|endoftext|>" + } + }, + distilbert: %{ + special_tokens: %{unk: "[UNK]", sep: "[SEP]", pad: "[PAD]", cls: "[CLS]", mask: "[MASK]"} + }, + gemma: %{ + special_tokens: %{ + unk: "", + bos: "", + eos: "", + pad: "" + } + }, + gpt_neo_x: %{ + special_tokens: %{ + unk: "<|endoftext|>", + bos: "<|endoftext|>", + eos: "<|endoftext|>" + } + }, + gpt2: %{ + special_tokens: %{ + unk: "<|endoftext|>", + bos: "<|endoftext|>", + eos: "<|endoftext|>" + } + }, + layout_lm: %{ + special_tokens: %{unk: "[UNK]", sep: "[SEP]", pad: "[PAD]", cls: "[CLS]", mask: "[MASK]"} + }, + llama: %{ + special_tokens: %{ + eos: "", + unk: "", + sep: "" + } + }, + mbart: %{ + special_tokens: %{ + eos: "", + unk: "", + sep: "", + pad: "", + cls: "", + mask: "" + } + }, + nllb: %{ + special_tokens: %{ + eos: "", + unk: "", + sep: "", + pad: "", + cls: "", + mask: "" + }, + default_template_options: [language_token: "eng_Latn"] + }, + roberta: %{ + special_tokens: %{ + bos: "", + eos: "", + unk: "", + sep: "", + pad: "", + cls: "", + mask: "" + } + }, + t5: %{ + special_tokens: %{ + bos: "", + eos: "", + unk: "", + sep: "", + pad: "", + cls: "", + mask: "" + } + }, + whisper: %{ + special_tokens: %{ + unk: "<|endoftext|>", + bos: "<|endoftext|>", + eos: "<|endoftext|>", + pad: "<|endoftext|>" + } + }, + xlm_roberta: %{ + special_tokens: %{ + bos: "", + eos: "", + unk: "", + sep: "", + pad: "", + cls: "", + mask: "" + } + } + } + + @impl true + def config(%{native_tokenizer: nil}, _opts) do + raise ArgumentError, + "configuring #{inspect(__MODULE__)} from scratch is not supported," <> + " you need to load an existing tokenizer first" + end + + def config(tokenizer, opts) do + tokenizer = Shared.put_config_attrs(tokenizer, opts) + + # Doing truncation manually after tokenization could truncate + # special tokens added by a template post-processor. By setting + # truncation upfront, the tokenizer will apply it before the + # post-processor accounting for the extra special tokens + tokenizer = + if Keyword.has_key?(opts, :length) or Keyword.has_key?(opts, :truncation_direction) do + update_truncation(tokenizer) + else + tokenizer + end + + if Keyword.has_key?(opts, :template_options) do + set_template(tokenizer) + else + tokenizer + end + end + + defp update_truncation(%{length: nil} = tokenizer) do + update_in(tokenizer.native_tokenizer, &Tokenizer.disable_truncation/1) + end + + defp update_truncation(%{length: length} = tokenizer) do + upper_bound_length = length |> List.wrap() |> Enum.max() + + update_in( + tokenizer.native_tokenizer, + &Tokenizer.set_truncation(&1, + max_length: upper_bound_length, + direction: tokenizer.truncate_direction + ) + ) + end + + defp set_template(%{type: :nllb} = tokenizer) do + language_token = Keyword.fetch!(tokenizer.template_options, :language_token) + eos_token = tokenizer.special_tokens.eos + + set_template_postprocessor( + tokenizer, + "#{language_token} $A #{eos_token}", + "#{language_token} $A $B #{eos_token}", + [language_token, eos_token] + ) + end + + defp set_template(%{type: type} = tokenizer) do + if tokenizer.template_options != [] do + raise ArgumentError, + "#{inspect(type)} tokenizer expects no :template_options," <> + " got: #{inspect(tokenizer.template_options)}" + end + + tokenizer + end + + defp set_template_postprocessor(tokenizer, single, pair, special_tokens) do + post_processor = + Tokenizers.PostProcessor.template( + single: single, + pair: pair, + special_tokens: + for token <- special_tokens do + {token, Tokenizer.token_to_id(tokenizer.native_tokenizer, token)} + end + ) + + update_in(tokenizer.native_tokenizer, &Tokenizer.set_post_processor(&1, post_processor)) + end + + @impl true + def apply(tokenizer, input) do + input = List.wrap(input) + + # Some tokenizers don't specify a PAD token, in which case we use + # the EOS token for padding by default + pad_token = + tokenizer.special_tokens[:pad] || + tokenizer.special_tokens[:eos] || + raise ArgumentError, + "expected the tokenizer to defined a padding token, but none was found" + + {:ok, encodings} = + Tokenizer.encode_batch(tokenizer.native_tokenizer, input, + add_special_tokens: tokenizer.add_special_tokens + ) + + lengths = Enum.map(encodings, &Encoding.n_tokens/1) + + pad_length = + if is_number(tokenizer.length) do + tokenizer.length + else + max_length = Enum.max(lengths) + + case tokenizer.length do + nil -> max_length + lengths when is_list(lengths) -> find_bounding_length(max_length, lengths) + end + end + + pad_id = Tokenizer.token_to_id(tokenizer.native_tokenizer, pad_token) + + encodings = + Enum.map(encodings, fn encoding -> + Encoding.pad(encoding, pad_length, + pad_id: pad_id, + pad_token: pad_token, + direction: tokenizer.pad_direction + ) + end) + + input_ids = encodings |> Enum.map(&Encoding.get_u32_ids/1) |> u32_binaries_to_tensor() + + encoded = %{"input_ids" => input_ids} + + encoded + |> maybe_put_attention_mask(encodings, tokenizer.return_attention_mask) + |> maybe_put_token_type_ids(encodings, tokenizer.return_token_type_ids) + |> maybe_put_return_special_tokens_mask(encodings, tokenizer.return_special_tokens_mask) + |> maybe_put_offsets(encodings, tokenizer.return_offsets) + |> maybe_put_lengths(lengths, tokenizer.return_length) + end + + defp find_bounding_length(max_length, lengths) do + find_bounding_length(max_length, lengths, :infinity, 0) + end + + defp find_bounding_length(max_length, [length | rest], bound, max) when length >= max_length do + find_bounding_length(max_length, rest, min(bound, length), max(length, max)) + end + + defp find_bounding_length(max_length, [length | rest], bound, max) do + find_bounding_length(max_length, rest, bound, max(length, max)) + end + + defp find_bounding_length(_max_length, [], bound, max), do: min(bound, max) + + defp maybe_put_attention_mask(encoded, encodings, return_attention_mask) do + if return_attention_mask do + attention_mask = + encodings + |> Enum.map(&Encoding.get_u32_attention_mask/1) + |> u32_binaries_to_tensor() + + Map.put(encoded, "attention_mask", attention_mask) + else + encoded + end + end + + defp maybe_put_token_type_ids(encoded, encodings, return_token_type_ids) do + if return_token_type_ids do + token_type_ids = + encodings + |> Enum.map(&Encoding.get_u32_type_ids/1) + |> u32_binaries_to_tensor() + + Map.put(encoded, "token_type_ids", token_type_ids) + else + encoded + end + end + + defp maybe_put_return_special_tokens_mask(encoded, encodings, return_special_tokens_mask) do + if return_special_tokens_mask do + special_tokens_mask = + encodings + |> Enum.map(&Encoding.get_u32_special_tokens_mask/1) + |> u32_binaries_to_tensor() + + Map.put(encoded, "special_tokens_mask", special_tokens_mask) + else + encoded + end + end + + defp maybe_put_offsets(encoded, encodings, return_offsets) do + if return_offsets do + {batch_start_offsets, batch_end_offsets} = + encodings + |> Enum.map(fn seq -> + seq |> Encoding.get_offsets() |> Enum.unzip() + end) + |> Enum.unzip() + + encoded + |> Map.put("start_offsets", Nx.tensor(batch_start_offsets)) + |> Map.put("end_offsets", Nx.tensor(batch_end_offsets)) + else + encoded + end + end + + defp maybe_put_lengths(encoded, lengths, return_length) do + if return_length do + Map.put(encoded, "length", Nx.tensor(lengths)) + else + encoded + end + end + + defp u32_binaries_to_tensor(list) do + binary = IO.iodata_to_binary(list) + + if binary == <<>> do + raise ArgumentError, + "the tokenizer returned zero tokens. Depending on the tokenizer," <> + " this may happen for blank input. You should check if the input is blank" <> + " before attempting tokenization" + end + + binary + |> Nx.from_binary(:u32) + |> Nx.reshape({length(list), :auto}) + end + + @impl true + def decode(tokenizer, [ids | _] = batch_ids) when is_list(ids) do + case Tokenizer.decode_batch(tokenizer.native_tokenizer, batch_ids) do + {:ok, decoded} -> decoded + {:error, term} -> raise "decoding failed with error: #{inspect(term)}" + end + end + + def decode(tokenizer, ids) do + case Tokenizer.decode(tokenizer.native_tokenizer, ids) do + {:ok, decoded} -> decoded + {:error, term} -> raise "decoding failed with error: #{inspect(term)}" + end + end + + @impl true + def id_to_token(tokenizer, id) do + Tokenizer.id_to_token(tokenizer.native_tokenizer, id) + end + + @impl true + def token_to_id(tokenizer, token) do + Tokenizer.token_to_id(tokenizer.native_tokenizer, token) + end + + @impl true + def special_tokens(tokenizer) do + tokenizer.special_tokens + end + + @impl true + def additional_special_tokens(tokenizer) do + tokenizer.additional_special_tokens + end + + @doc false + def tokenizer_types(), do: @tokenizer_types + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(tokenizer, %{ + "tokenizer_file" => path, + "special_tokens_map" => special_tokens_map + }) do + native_tokenizer = + case Tokenizer.from_file(path) do + {:ok, tokenizer} -> + tokenizer + |> Tokenizer.disable_padding() + |> Tokenizer.disable_truncation() + + {:error, error} -> + raise "failed to read tokenizer from file, reason: #{error}" + end + + tokenizer_types = Bumblebee.Text.PreTrainedTokenizer.tokenizer_types() + + unless Map.has_key?(tokenizer_types, tokenizer.type) do + types = tokenizer_types |> Map.keys() |> Enum.sort() + + raise ArgumentError, + "expected tokenizer type to be one of: #{Enum.map_join(types, ", ", &inspect/1)}," <> + " but got: #{inspect(tokenizer.type)}" + end + + tokenizer_type = %{special_tokens: special_tokens} = tokenizer_types[tokenizer.type] + + special_tokens = load_special_tokens(special_tokens, special_tokens_map) + + additional_special_tokens = + case special_tokens_map do + %{"additional_special_tokens" => tokens} -> + for token <- tokens, do: load_token(token), into: MapSet.new() + + _ -> + [] + end + + template_options = tokenizer_type[:default_template_options] || [] + + %{ + tokenizer + | native_tokenizer: native_tokenizer, + special_tokens: special_tokens, + additional_special_tokens: additional_special_tokens + } + |> @for.config(template_options: template_options) + end + + defp load_special_tokens(special_tokens, data) do + for {key, default_token} <- special_tokens, into: %{} do + token = + if token = data["#{key}_token"] do + load_token(token) + else + default_token + end + + {key, token} + end + end + + defp load_token(token) when is_binary(token), do: token + defp load_token(%{"content" => token}) when is_binary(token), do: token + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/question_answering.ex b/deps/bumblebee/lib/bumblebee/text/question_answering.ex new file mode 100644 index 0000000000000000000000000000000000000000..20c8d077100d836a266835ca8c20f477198ad915 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/question_answering.ex @@ -0,0 +1,131 @@ +defmodule Bumblebee.Text.QuestionAnswering do + @moduledoc false + + alias Bumblebee.Utils + alias Bumblebee.Shared + + def question_answering(model_info, tokenizer, opts \\ []) do + %{model: model, params: params, spec: spec} = model_info + Shared.validate_architecture!(spec, :for_question_answering) + + opts = Keyword.validate!(opts, [:compile, defn_options: [], preallocate_params: false]) + + preallocate_params = opts[:preallocate_params] + defn_options = opts[:defn_options] + + compile = + if compile = opts[:compile] do + compile + |> Keyword.validate!([:batch_size, :sequence_length]) + |> Shared.require_options!([:batch_size, :sequence_length]) + end + + batch_size = compile[:batch_size] + sequence_length = compile[:sequence_length] + + tokenizer = + Bumblebee.configure(tokenizer, + length: sequence_length, + return_token_type_ids: true, + return_offsets: true + ) + + {_init_fun, predict_fun} = Axon.build(model) + + scores_fun = fn params, input -> + outputs = predict_fun.(params, input) + start_scores = Axon.Activations.softmax(outputs.start_logits) + end_scores = Axon.Activations.softmax(outputs.end_logits) + + start_idx = Nx.argmax(start_scores, axis: -1, keep_axis: true) + end_idx = Nx.argmax(end_scores, axis: -1, keep_axis: true) + + start_score = Nx.take_along_axis(start_scores, start_idx, axis: -1) + end_score = Nx.take_along_axis(end_scores, end_idx, axis: -1) + + score = Nx.multiply(start_score, end_score) + + %{ + score: Nx.squeeze(score, axes: [-1]), + start_idx: Nx.squeeze(start_idx, axes: [-1]), + end_idx: Nx.squeeze(end_idx, axes: [-1]) + } + end + + batch_keys = Shared.sequence_batch_keys(sequence_length) + + Nx.Serving.new( + fn batch_key, defn_options -> + params = Shared.maybe_preallocate(params, preallocate_params, defn_options) + + scope = {:predict, batch_key} + + predict_fun = + Shared.compile_or_jit(scores_fun, scope, defn_options, compile != nil, fn -> + {:sequence_length, sequence_length} = batch_key + + inputs = %{ + "input_ids" => Nx.template({batch_size, sequence_length}, :u32), + "attention_mask" => Nx.template({batch_size, sequence_length}, :u32), + "token_type_ids" => Nx.template({batch_size, sequence_length}, :u32) + } + + [params, inputs] + end) + + fn inputs -> + inputs = Shared.maybe_pad(inputs, batch_size) + predict_fun.(params, inputs) |> Shared.serving_post_computation() + end + end, + defn_options + ) + |> Nx.Serving.batch_size(batch_size) + |> Nx.Serving.process_options(batch_keys: batch_keys) + |> Nx.Serving.client_preprocessing(fn raw_input -> + {raw_inputs, multi?} = + Shared.validate_serving_input!(raw_input, fn + %{question: question, context: context} + when is_binary(question) and is_binary(context) -> + {:ok, {question, context}} + + other -> + {:error, + "expected input map with :question and :context keys, got: #{inspect(other)}"} + end) + + all_inputs = + Nx.with_default_backend(Nx.BinaryBackend, fn -> + Bumblebee.apply_tokenizer(tokenizer, raw_inputs) + end) + + inputs = Map.take(all_inputs, ["input_ids", "attention_mask", "token_type_ids"]) + + batch_key = Shared.sequence_batch_key_for_inputs(inputs, sequence_length) + batch = [inputs] |> Nx.Batch.concatenate() |> Nx.Batch.key(batch_key) + + {batch, {all_inputs, raw_inputs, multi?}} + end) + |> Nx.Serving.client_postprocessing(fn {outputs, _metadata}, {inputs, raw_inputs, multi?} -> + Enum.zip_with( + [raw_inputs, Utils.Nx.batch_to_list(inputs), Utils.Nx.batch_to_list(outputs)], + fn [{_question_text, context_text}, inputs, outputs] -> + start_idx = Nx.to_number(outputs.start_idx) + end_idx = Nx.to_number(outputs.end_idx) + score = Nx.to_number(outputs.score) + start = Nx.to_number(inputs["start_offsets"][start_idx]) + ending = Nx.to_number(inputs["end_offsets"][end_idx]) + + answer_text = binary_part(context_text, start, ending - start) + + results = [ + %{text: answer_text, start: start, end: ending, score: score} + ] + + %{results: results} + end + ) + |> Shared.normalize_output(multi?) + end) + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/roberta.ex b/deps/bumblebee/lib/bumblebee/text/roberta.ex new file mode 100644 index 0000000000000000000000000000000000000000..4db674f3b5ccd841c8f8e93aea2438939bbba28c --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/roberta.ex @@ -0,0 +1,615 @@ +defmodule Bumblebee.Text.Roberta do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 30522, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + max_positions: [ + default: 512, + doc: """ + the vocabulary size of the position embedding. This corresponds to the maximum sequence + length that this model can process. Typically this is set to a large value just in case, + such as 512, 1024 or 2048 + """ + ], + max_token_types: [ + default: 2, + doc: """ + the vocabulary size of the token type embedding (also referred to as segment embedding). + This corresponds to how many different token groups can be distinguished in the input + """ + ], + hidden_size: [ + default: 768, + doc: "the dimensionality of hidden layers" + ], + num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the encoder" + ], + num_attention_heads: [ + default: 12, + doc: "the number of attention heads for each attention layer in the encoder" + ], + intermediate_size: [ + default: 3072, + doc: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder" + ], + activation: [ + default: :gelu, + doc: "the activation function" + ], + dropout_rate: [ + default: 0.1, + doc: "the dropout rate for embedding and encoder" + ], + attention_dropout_rate: [ + default: 0.1, + doc: "the dropout rate for attention weights" + ], + classifier_dropout_rate: [ + default: nil, + doc: + "the dropout rate for the classification head. If not specified, the value of `:dropout_rate` is used instead" + ], + layer_norm_epsilon: [ + default: 1.0e-12, + doc: "the epsilon used by the layer normalization layers" + ], + initializer_range: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] ++ + Shared.common_options([:use_cross_attention, :num_labels, :id_to_label]) ++ + Shared.token_options(pad_token_id: 1) + + @moduledoc """ + RoBERTa model family. + + ## Architectures + + * `:base` - plain RoBERTa without any head on top + + * `:for_masked_language_modeling` - RoBERTa with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:for_sequence_classification` - RoBERTa with a sequence + classification head. The head returns logits corresponding to + possible classes + + * `:for_token_classification` - RoBERTa with a token classification + head. The head returns logits for each token in the original + sequence + + * `:for_question_answering` - RoBERTa with a span classification head. + The head returns logits for the span start and end positions + + * `:for_multiple_choice` - RoBERTa with a multiple choice prediction + head. Each input in the batch consists of several sequences to + choose from and the model returns logits corresponding to those + choices + + * `:for_causal_language_modeling` - RoBERTa working as a decoder with + a language modeling head. The head returns logits for each token in + the original sequence + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"token_type_ids"` - `{batch_size, sequence_length}` + + Mask distinguishing groups in the input sequence. This is used + in when the input sequence is a semantically a pair of sequences. + + * `"position_ids"` - `{batch_size, sequence_length}` + + Indices of positions of each input sequence tokens in the position + embeddings. + + * `"attention_head_mask"` - `{num_blocks, num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + ### Exceptions + + The `:for_multiple_choice` model accepts groups of sequences, so the + expected sequence shape is `{batch_size, num_choices, sequence_length}`. + + The `:for_causal_language_modeling` model is a decoder and accepts + the following additional inputs: `"encoder_hidden_state"`, + `"encoder_attention_mask"`, `"cross_attention_head_mask"`, `"cache"`. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_masked_language_modeling, + :for_sequence_classification, + :for_token_classification, + :for_question_answering, + :for_multiple_choice, + :for_causal_language_modeling + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(%{architecture: :for_multiple_choice}) do + %{"input_ids" => Nx.template({1, 1, 1}, :u32)} + end + + def input_template(_spec) do + %{"input_ids" => Nx.template({1, 1}, :u32)} + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_masked_language_modeling} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_sequence_classification} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + outputs.hidden_state + |> Layers.take_token(index: 0, axis: 1) + |> Axon.dropout(rate: classifier_dropout_rate(spec)) + |> Axon.dense(spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: "sequence_classification_head.dense" + ) + |> Axon.tanh() + |> Axon.dropout(rate: classifier_dropout_rate(spec)) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "sequence_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_token_classification} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + outputs.hidden_state + |> Axon.dropout( + rate: classifier_dropout_rate(spec), + name: "token_classification_head.dropout" + ) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "token_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_question_answering} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + Axon.dense(outputs.hidden_state, 2, + kernel_initializer: kernel_initializer(spec), + name: "question_answering_head.output" + ) + + {start_logits, end_logits} = Layers.split_pair(logits) + + Layers.output(%{ + start_logits: start_logits, + end_logits: end_logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_multiple_choice} = spec) do + inputs = inputs(spec, shape: {nil, nil, nil}) + + group_inputs = ["input_ids", "attention_mask", "token_type_ids", "position_ids"] + + flat_inputs = + Enum.reduce(group_inputs, inputs, fn name, inputs -> + Map.update!(inputs, name, &Layers.flatten_leading/1) + end) + + outputs = core(flat_inputs, spec) + + logits = + outputs.pooled_state + |> Axon.dropout(rate: classifier_dropout_rate(spec), name: "multiple_choice_head.dropout") + |> Axon.dense(1, + kernel_initializer: kernel_initializer(spec), + name: "multiple_choice_head.output" + ) + + # The final shape depends on the dynamic batch size and number + # of choices, so we do a reshape based on the input shape + logits = + Axon.layer( + fn logits, input_ids, _opts -> + num_choices = Nx.axis_size(input_ids, 1) + Nx.reshape(logits, {:auto, num_choices}) + end, + [logits, inputs["input_ids"]] + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_causal_language_modeling} = spec) do + inputs = inputs(spec, decoder?: true) + outputs = core(inputs, spec, decoder?: true) + + logits = language_modeling_head(outputs.hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions, + cross_attentions: outputs.cross_attentions, + cache: outputs.cache + }) + end + + @impl true + def init_cache(spec, batch_size, max_length, inputs) do + encoder_sequence_length = + if encoder_hidden_state = inputs["encoder_hidden_state"] do + Nx.axis_size(encoder_hidden_state, 1) + end + + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + decoder_num_attention_heads: spec.num_attention_heads, + encoder_num_attention_heads: spec.num_attention_heads, + decoder_num_blocks: spec.num_blocks, + encoder_sequence_length: encoder_sequence_length + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + defp inputs(spec, opts \\ []) do + shape = Keyword.get(opts, :shape, {nil, nil}) + decoder? = Keyword.get(opts, :decoder?, false) + + hidden_shape = Tuple.insert_at(shape, tuple_size(shape), spec.hidden_size) + attention_head_mask_shape = {spec.num_blocks, spec.num_attention_heads} + + inputs = + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("token_type_ids", optional: true, shape: shape), + Axon.input("position_ids", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: attention_head_mask_shape) + ]) + + extra_decoder_inputs = + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("encoder_hidden_state", optional: true, shape: hidden_shape), + Axon.input("encoder_attention_mask", optional: true, shape: shape), + Axon.input("cross_attention_head_mask", optional: true, shape: attention_head_mask_shape), + Axon.input("cache", optional: true) + ]) + + extra_decoder_inputs = + if decoder? do + extra_decoder_inputs + else + Map.new(extra_decoder_inputs, fn {name, _input} -> {name, Layers.none()} end) + end + + Map.merge(inputs, extra_decoder_inputs) + end + + defp core(inputs, spec, opts \\ []) do + decoder? = Keyword.get(opts, :decoder?, false) + + embeddings = + embedder(inputs["input_ids"], inputs["position_ids"], inputs["token_type_ids"], spec, + name: "embedder" + ) + + encoder_outputs = + encoder( + embeddings, + inputs["attention_mask"], + inputs["attention_head_mask"], + inputs["encoder_hidden_state"], + inputs["encoder_attention_mask"], + inputs["cross_attention_head_mask"], + inputs["cache"], + spec, + decoder?: decoder?, + name: "encoder" + ) + + pooled_state = pooler(encoder_outputs.hidden_state, spec, name: "pooler") + + %{ + hidden_state: encoder_outputs.hidden_state, + pooled_state: pooled_state, + hidden_states: encoder_outputs.hidden_states, + attentions: encoder_outputs.attentions, + cross_attentions: encoder_outputs.cross_attentions, + cache: encoder_outputs.cache + } + end + + defp embedder(input_ids, position_ids, token_type_ids, spec, opts) do + name = opts[:name] + + position_ids = + Layers.default position_ids do + # Position numbers begin at padding token id + 1 + Layers.default_position_ids(input_ids, offset: spec.pad_token_id + 1) + end + + token_type_ids = + Layers.default token_type_ids do + Layers.default_token_type_ids(input_ids) + end + + inputs_embeddings = + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "token_embedding") + ) + + position_embeddings = + Axon.embedding(position_ids, spec.max_positions, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "position_embedding") + ) + + token_type_embeddings = + Axon.embedding(token_type_ids, spec.max_token_types, spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "token_type_embedding") + ) + + Axon.add([inputs_embeddings, position_embeddings, token_type_embeddings]) + |> Axon.layer_norm(epsilon: spec.layer_norm_epsilon, name: join(name, "norm")) + |> Axon.dropout(rate: spec.dropout_rate, name: join(name, "dropout")) + end + + defp encoder( + hidden_state, + attention_mask, + attention_head_mask, + encoder_hidden_state, + encoder_attention_mask, + cross_attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + decoder? = opts[:decoder?] + + cross_attention? = decoder? and spec.use_cross_attention + + Layers.Transformer.blocks( + hidden_state, + [ + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + cache: cache, + causal: decoder?, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: spec.layer_norm_epsilon + ], + ffn: [ + intermediate_size: spec.intermediate_size, + activation: spec.activation + ], + name: join(name, "blocks") + ] ++ + if(cross_attention?, + do: [ + cross_hidden_state: encoder_hidden_state, + cross_attention_mask: encoder_attention_mask, + cross_attention_head_mask: cross_attention_head_mask + ], + else: [] + ) + ) + end + + defp pooler(hidden_state, spec, opts) do + name = opts[:name] + + hidden_state + |> Layers.take_token(index: 0, axis: 1) + |> Axon.dense(spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + |> Axon.tanh() + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: use a shared parameter with embeddings.word_embeddings.kernel + # if spec.tie_word_embeddings is true (relevant for training) + + hidden_state + |> Axon.dense(spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "dense") + ) + |> Layers.activation(spec.activation, name: join(name, "activation")) + |> Axon.layer_norm(epsilon: spec.layer_norm_epsilon, name: join(name, "norm")) + # We reuse the kernel of input embeddings and add bias for each token + |> Layers.dense_transposed(spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + |> Axon.bias(name: join(name, "bias")) + end + + defp classifier_dropout_rate(spec) do + spec.classifier_dropout_rate || spec.dropout_rate + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_range) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + max_positions: {"max_position_embeddings", number()}, + max_token_types: {"type_vocab_size", number()}, + hidden_size: {"hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_attention_heads: {"num_attention_heads", number()}, + intermediate_size: {"intermediate_size", number()}, + activation: {"hidden_act", activation()}, + dropout_rate: {"hidden_dropout_prob", number()}, + attention_dropout_rate: {"attention_probs_dropout_prob", number()}, + classifier_dropout_rate: {"classifier_dropout", optional(number())}, + layer_norm_epsilon: {"layer_norm_eps", number()}, + initializer_range: {"initializer_range", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.token_embedding" => "roberta.embeddings.word_embeddings", + "embedder.position_embedding" => "roberta.embeddings.position_embeddings", + "embedder.token_type_embedding" => "roberta.embeddings.token_type_embeddings", + "embedder.norm" => "roberta.embeddings.LayerNorm", + "encoder.blocks.{n}.self_attention.query" => + "roberta.encoder.layer.{n}.attention.self.query", + "encoder.blocks.{n}.self_attention.key" => "roberta.encoder.layer.{n}.attention.self.key", + "encoder.blocks.{n}.self_attention.value" => + "roberta.encoder.layer.{n}.attention.self.value", + "encoder.blocks.{n}.self_attention.output" => + "roberta.encoder.layer.{n}.attention.output.dense", + "encoder.blocks.{n}.self_attention_norm" => + "roberta.encoder.layer.{n}.attention.output.LayerNorm", + "encoder.blocks.{n}.cross_attention.query" => + "roberta.encoder.layer.{n}.crossattention.self.query", + "encoder.blocks.{n}.cross_attention.key" => + "roberta.encoder.layer.{n}.crossattention.self.key", + "encoder.blocks.{n}.cross_attention.value" => + "roberta.encoder.layer.{n}.crossattention.self.value", + "encoder.blocks.{n}.cross_attention.output" => + "roberta.encoder.layer.{n}.crossattention.output.dense", + "encoder.blocks.{n}.cross_attention_norm" => + "roberta.encoder.layer.{n}.crossattention.output.LayerNorm", + "encoder.blocks.{n}.ffn.intermediate" => "roberta.encoder.layer.{n}.intermediate.dense", + "encoder.blocks.{n}.ffn.output" => "roberta.encoder.layer.{n}.output.dense", + "encoder.blocks.{n}.output_norm" => "roberta.encoder.layer.{n}.output.LayerNorm", + "pooler.output" => "roberta.pooler.dense", + "language_modeling_head.dense" => "lm_head.dense", + "language_modeling_head.norm" => "lm_head.layer_norm", + "language_modeling_head.output" => "lm_head.decoder", + "language_modeling_head.bias" => "lm_head", + "sequence_classification_head.dense" => "classifier.dense", + "sequence_classification_head.output" => "classifier.out_proj", + "token_classification_head.output" => "classifier", + "question_answering_head.output" => "qa_outputs", + "multiple_choice_head.output" => "classifier" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/t5.ex b/deps/bumblebee/lib/bumblebee/text/t5.ex new file mode 100644 index 0000000000000000000000000000000000000000..3f9cabb5ea7e35d00bc9da7bffb7b631db26853d --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/t5.ex @@ -0,0 +1,626 @@ +defmodule Bumblebee.Text.T5 do + alias Bumblebee.Shared + + options = + [ + vocab_size: [ + default: 32128, + doc: """ + the vocabulary size of the token embedding. This corresponds to the number of distinct + tokens that can be represented in model input and output + """ + ], + hidden_size: [ + default: 512, + doc: "the dimensionality of hidden layers" + ], + attention_head_size: [ + default: 64, + doc: "the size of the key, value, and query projection per attention head" + ], + encoder_num_blocks: [ + default: 6, + doc: "the number of Transformer blocks in the encoder" + ], + decoder_num_blocks: [ + default: 6, + doc: "the number of Transformer blocks in the decoder" + ], + encoder_num_attention_heads: [ + default: 8, + doc: "the number of attention heads for each attention layer in the encoder" + ], + decoder_num_attention_heads: [ + default: 8, + doc: "the number of attention heads for each attention layer in the decoder" + ], + intermediate_size: [ + default: 2048, + docs: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder" + ], + relative_attention_num_buckets: [ + default: 32, + docs: "the number of buckets to use for the relative attention bias" + ], + relative_attention_max_distance: [ + default: 128, + docs: "the maximum distance of the relative attention bias" + ], + activation: [ + default: :relu, + doc: "the activation function" + ], + ffn_gated_activation: [ + default: false, + doc: + "whether to use a gated variant of the activation function in the feed-forward network (FFN)" + ], + dropout_rate: [ + default: 0.1, + doc: "the dropout rate for encoder and decoder" + ], + initializer_scale: [ + default: 1.0, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ], + layer_norm_epsilon: [ + default: 1.0e-6, + doc: "the epsilon used by the layer normalization layers" + ], + tie_word_embeddings: [ + default: true, + doc: "whether or not to tie encoder and decoder token embedding" + ] + ] ++ + Shared.common_options([:num_labels, :id_to_label]) ++ + Shared.token_options(decoder_start_token_id: 0) + + @moduledoc """ + T5 model family. + + ## Architectures + + * `:base` - plain T5 without any head on top + + * `:for_conditional_generation` - T5 with a language modeling + head. The head returns logits for each token in the original + sequence + + * `:encoder` - just the encoder part of the base model + + ## Inputs + + * `"input_ids"` - `{batch_size, sequence_length}` + + Indices of input sequence tokens in the vocabulary. + + * `"attention_mask"` - `{batch_size, sequence_length}` + + Mask indicating which tokens to attend to. This is used to ignore + padding tokens, which are added when processing a batch of sequences + with different length. + + * `"attention_head_mask"` - `{encoder_num_blocks, encoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the encoder. + + * `"input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"input_ids"`, which can be specified + for more control over how `"input_ids"` are embedded than the + model's internal embedding lookup. If `"input_embeddings"` are present, + then `"input_ids"` will be ignored. + + * `"decoder_input_ids"` - `{batch_size, target_sequence_length}` + + Indices of decoder input sequence tokens in the vocabulary. If not + present and `"input_ids"` is, it will be generated by shifting + each token in `"input_ids"` to the right once. + + * `"decoder_attention_mask"` - `{batch_size, target_sequence_length}` + + Mask indicating which decoder tokens to attend to. This is used + to ignore padding tokens, which are added when processing a batch + of sequences with different length. + + * `"decoder_attention_head_mask"` - `{decoder_num_blocks, decoder_num_attention_heads}` + + Mask to nullify selected heads of the self-attention blocks in + the decoder. + + * `"decoder_input_embeddings"` - `{batch_size, sequence_length, hidden_size}` + + Embedded representation of `"decoder_input_ids"`, which can be + specified for more control over how `"decoder_input_ids"` are + embedded than the model's internal embedding lookup. If + `"decoder_input_embeddings"` are present, then `"decoder_input_ids"` + will be ignored. + + * `"encoder_hidden_state"` - `{batch_size, sequence_length, hidden_size}` + + Last hidden state output from the encoder. This hidden state is + used in cross-attention blocks in the decoder. If specified, the + model will skip the encoding process and use this value directly + for cross-attentions in the decoder. + + * `"cross_attention_head_mask"` - `{decoder_num_blocks, decoder_num_attention_heads}` + + Mask to nullify selected heads of the cross-attention blocks in + the decoder with shape. + + * `"cache"` + + A container with cached layer results used to speed up sequential + decoding (autoregression). With cache, certain hidden states are + taken from the cache, rather than recomputed on every decoding + pass. The cache should be treated as opaque and initialized with + `Bumblebee.Text.Generation.init_cache/4`. + + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + @behaviour Bumblebee.Text.Generation + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [:base, :for_conditional_generation, :encoder] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(_spec) do + %{ + "input_ids" => Nx.template({1, 1}, :u32) + } + end + + @impl true + def init_cache(spec, batch_size, max_length, inputs) do + encoder_sequence_length = + if encoder_hidden_state = inputs["encoder_hidden_state"] do + Nx.axis_size(encoder_hidden_state, 1) + end + + Layers.Decoder.init_cache(batch_size, max_length, + hidden_size: spec.hidden_size, + attention_head_size: spec.attention_head_size, + decoder_num_attention_heads: spec.decoder_num_attention_heads, + encoder_num_attention_heads: spec.encoder_num_attention_heads, + decoder_num_blocks: spec.decoder_num_blocks, + encoder_sequence_length: encoder_sequence_length + ) + end + + @impl true + def traverse_cache(_spec, cache, fun) do + Layers.Decoder.traverse_cache(cache, fun) + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = encoder_decoder_inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_conditional_generation} = spec) do + inputs = encoder_decoder_inputs(spec) + outputs = core(inputs, spec) + + hidden_state = + if spec.tie_word_embeddings do + Axon.nx(outputs.hidden_state, &Nx.multiply(&1, Nx.rsqrt(spec.hidden_size))) + else + outputs.hidden_state + end + + logits = language_modeling_head(hidden_state, spec, name: "language_modeling_head") + + Layers.output(%{ + logits: logits, + decoder_hidden_states: outputs.decoder_hidden_states, + decoder_attentions: outputs.decoder_attentions, + cross_attentions: outputs.cross_attentions, + encoder_hidden_state: outputs.encoder_hidden_state, + encoder_hidden_states: outputs.encoder_hidden_states, + encoder_attentions: outputs.encoder_attentions, + cache: outputs.cache + }) + end + + def model(%__MODULE__{architecture: :encoder} = spec) do + inputs = encoder_inputs(spec) + + embeddings = + embedder(inputs["input_ids"], inputs["input_embeddings"], spec, name: "encoder_embedder") + + outputs = + encoder(embeddings, inputs["attention_mask"], inputs["attention_head_mask"], spec, + name: "encoder" + ) + + Layers.output(%{ + hidden_state: outputs.hidden_state, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + defp encoder_inputs(spec) do + shape = {nil, nil} + hidden_shape = {nil, nil, spec.hidden_size} + + attention_head_mask_shape = {spec.encoder_num_blocks, spec.encoder_num_attention_heads} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: attention_head_mask_shape), + Axon.input("input_embeddings", optional: true, shape: hidden_shape) + ]) + end + + defp encoder_decoder_inputs(spec) do + shape = {nil, nil} + hidden_shape = {nil, nil, spec.hidden_size} + + encoder_attention_head_mask_shape = + {spec.encoder_num_blocks, spec.encoder_num_attention_heads} + + decoder_attention_head_mask_shape = + {spec.decoder_num_blocks, spec.decoder_num_attention_heads} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("input_ids", optional: true, shape: shape), + Axon.input("attention_mask", optional: true, shape: shape), + Axon.input("attention_head_mask", optional: true, shape: encoder_attention_head_mask_shape), + Axon.input("input_embeddings", optional: true, shape: hidden_shape), + Axon.input("decoder_input_ids", optional: true, shape: shape), + Axon.input("decoder_attention_mask", optional: true, shape: shape), + Axon.input("decoder_attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("decoder_input_embeddings", optional: true, shape: hidden_shape), + Axon.input("encoder_hidden_state", optional: true, shape: hidden_shape), + Axon.input("cross_attention_head_mask", + optional: true, + shape: decoder_attention_head_mask_shape + ), + Axon.input("cache", optional: true) + ]) + end + + defp core(inputs, spec) do + encoder_outputs = + Layers.if_present inputs["encoder_hidden_state"] do + %{ + hidden_state: inputs["encoder_hidden_state"], + hidden_states: Layers.none(), + attentions: Layers.none() + } + else + embeddings = + embedder( + inputs["input_ids"], + inputs["input_embeddings"], + spec, + name: "encoder_embedder" + ) + + embeddings + |> encoder(inputs["attention_mask"], inputs["attention_head_mask"], spec, name: "encoder") + |> Map.take([:hidden_state, :hidden_states, :attentions]) + end + + decoder_input_ids = + Layers.default inputs["decoder_input_ids"] do + Layers.shift_tokens_right(inputs["input_ids"], spec.decoder_start_token_id) + end + + embeddings = + embedder(decoder_input_ids, inputs["decoder_input_embeddings"], spec, + name: "decoder_embedder" + ) + + decoder_outputs = + decoder( + embeddings, + inputs["decoder_attention_mask"], + inputs["decoder_attention_head_mask"], + encoder_outputs.hidden_state, + inputs["attention_mask"], + inputs["cross_attention_head_mask"], + inputs["cache"], + spec, + name: "decoder" + ) + + %{ + hidden_state: decoder_outputs.hidden_state, + decoder_hidden_states: decoder_outputs.hidden_states, + decoder_attentions: decoder_outputs.attentions, + cross_attentions: decoder_outputs.cross_attentions, + cache: decoder_outputs.cache, + encoder_hidden_state: encoder_outputs.hidden_state, + encoder_hidden_states: encoder_outputs.hidden_states, + encoder_attentions: encoder_outputs.attentions + } + end + + defp embedder(input_ids, input_embeddings, spec, opts) do + name = opts[:name] + + input_embeddings = + Layers.default input_embeddings do + Axon.embedding(input_ids, spec.vocab_size, spec.hidden_size, + name: join(name, "token_embedding") + ) + end + + input_embeddings + end + + defp encoder(hidden_state, attention_mask, attention_head_mask, spec, opts) do + name = opts[:name] + + encoder_outputs = + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + num_blocks: spec.encoder_num_blocks, + num_attention_heads: spec.encoder_num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + layer_norm: &Layers.rms_norm(&1, name: &2, epsilon: spec.layer_norm_epsilon), + ffn: &ffn(&1, spec, name: &2), + block_type: :norm_first, + attention_head_size: spec.attention_head_size, + query_use_bias: false, + key_use_bias: false, + value_use_bias: false, + output_use_bias: false, + attention_relative_bias: [ + bidirectional: true, + num_buckets: spec.relative_attention_num_buckets, + max_distance: spec.relative_attention_max_distance + ], + share_attention_relative_bias: true, + scale_attention_weights: false, + name: join(name, "blocks") + ) + + hidden_state = + encoder_outputs.hidden_state + |> Layers.rms_norm(epsilon: spec.layer_norm_epsilon, name: join(name, "output_norm")) + |> Axon.dropout(rate: spec.dropout_rate) + + %{ + hidden_state: hidden_state, + hidden_states: Layers.replace(encoder_outputs.hidden_states, -1, hidden_state), + attentions: encoder_outputs.attentions + } + end + + defp decoder( + hidden_state, + attention_mask, + attention_head_mask, + encoder_hidden_state, + encoder_attention_mask, + cross_attention_head_mask, + cache, + spec, + opts + ) do + name = opts[:name] + + decoder_outputs = + Layers.Transformer.blocks(hidden_state, + attention_mask: attention_mask, + attention_head_mask: attention_head_mask, + cross_hidden_state: encoder_hidden_state, + cross_attention_mask: encoder_attention_mask, + cross_attention_head_mask: cross_attention_head_mask, + cache: cache, + causal: true, + num_blocks: spec.decoder_num_blocks, + num_attention_heads: spec.decoder_num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_head_size: spec.attention_head_size, + layer_norm: &Layers.rms_norm(&1, name: &2, epsilon: spec.layer_norm_epsilon), + ffn: &ffn(&1, spec, name: &2), + block_type: :norm_first, + query_use_bias: false, + key_use_bias: false, + value_use_bias: false, + output_use_bias: false, + attention_relative_bias: [ + bidirectional: false, + num_buckets: spec.relative_attention_num_buckets, + max_distance: spec.relative_attention_max_distance + ], + share_attention_relative_bias: true, + scale_attention_weights: false, + name: join(name, "blocks") + ) + + hidden_state = + decoder_outputs.hidden_state + |> Layers.rms_norm(epsilon: spec.layer_norm_epsilon, name: join(name, "output_norm")) + |> Axon.dropout(rate: spec.dropout_rate) + + %{ + cache: decoder_outputs.cache, + hidden_state: hidden_state, + hidden_states: Layers.replace(decoder_outputs.hidden_states, -1, hidden_state), + attentions: decoder_outputs.attentions, + cross_attentions: decoder_outputs.cross_attentions + } + end + + defp ffn(hidden_state, spec, opts) do + name = opts[:name] + + intermediate = + Axon.dense(hidden_state, spec.intermediate_size, + name: join(name, "intermediate"), + use_bias: false + ) + + hidden_state = + if spec.ffn_gated_activation do + gate = + Axon.dense(hidden_state, spec.intermediate_size, + name: join(name, "gate"), + use_bias: false + ) + + Axon.multiply(intermediate, Layers.activation(gate, spec.activation)) + else + Layers.activation(intermediate, spec.activation) + end + + hidden_state + |> Axon.dropout(rate: spec.dropout_rate) + |> Axon.dense(spec.hidden_size, name: join(name, "output"), use_bias: false) + |> Axon.dropout(rate: spec.dropout_rate) + end + + defp language_modeling_head(hidden_state, spec, opts) do + name = opts[:name] + + # TODO: Tie lm-head to word embedding as a spec option + Layers.dense_transposed(hidden_state, spec.vocab_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + vocab_size: {"vocab_size", number()}, + hidden_size: {"d_model", number()}, + attention_head_size: {"d_kv", number()}, + encoder_num_blocks: {"num_layers", number()}, + decoder_num_blocks: {"num_decoder_layers", number()}, + encoder_num_attention_heads: {"num_heads", number()}, + decoder_num_attention_heads: {"num_heads", number()}, + relative_attention_num_buckets: {"relative_attention_num_buckets", number()}, + relative_attention_max_distance: {"relative_attention_max_distance", number()}, + intermediate_size: {"d_ff", number()}, + activation: {"feed_forward_proj", t5_activation()}, + ffn_gated_activation: {"feed_forward_proj", ffn_gated_activation()}, + dropout_rate: {"dropout", number()}, + initializer_scale: {"initializer_factor", number()}, + tie_word_embeddings: {"tie_word_embeddings", boolean()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + + defp t5_activation() do + fn name, value -> + case String.replace_prefix(value, "gated-", "") do + # See https://github.com/huggingface/transformers/pull/17420 + "gelu" -> {:ok, :gelu_approx_tanh} + value -> Shared.Converters.activation().(name, value) + end + end + end + + defp ffn_gated_activation() do + fn _name, value -> + {:ok, String.starts_with?(value, "gated-")} + end + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(spec) do + %{ + # Encoder and decoder embeddings are always shared + "encoder_embedder.token_embedding" => "shared", + "encoder.blocks.{n}.self_attention_norm" => "encoder.block.{n}.layer.0.layer_norm", + "encoder.blocks.{n}.self_attention.query" => "encoder.block.{n}.layer.0.SelfAttention.q", + "encoder.blocks.{n}.self_attention.key" => "encoder.block.{n}.layer.0.SelfAttention.k", + "encoder.blocks.{n}.self_attention.value" => "encoder.block.{n}.layer.0.SelfAttention.v", + "encoder.blocks.{n}.self_attention.output" => "encoder.block.{n}.layer.0.SelfAttention.o", + "encoder.blocks.0.self_attention.relative_attention_bias" => + "encoder.block.0.layer.0.SelfAttention.relative_attention_bias", + "encoder.blocks.{n}.output_norm" => "encoder.block.{n}.layer.1.layer_norm", + "encoder.blocks.{n}.ffn.gate" => "encoder.block.{n}.layer.1.DenseReluDense.wi_0", + "encoder.blocks.{n}.ffn.intermediate" => + if(spec.ffn_gated_activation, + do: "encoder.block.{n}.layer.1.DenseReluDense.wi_1", + else: "encoder.block.{n}.layer.1.DenseReluDense.wi" + ), + "encoder.blocks.{n}.ffn.output" => "encoder.block.{n}.layer.1.DenseReluDense.wo", + "encoder.output_norm" => "encoder.final_layer_norm", + "decoder_embedder.token_embedding" => "shared", + "decoder.blocks.{n}.self_attention_norm" => "decoder.block.{n}.layer.0.layer_norm", + "decoder.blocks.{n}.self_attention.query" => "decoder.block.{n}.layer.0.SelfAttention.q", + "decoder.blocks.{n}.self_attention.key" => "decoder.block.{n}.layer.0.SelfAttention.k", + "decoder.blocks.{n}.self_attention.value" => "decoder.block.{n}.layer.0.SelfAttention.v", + "decoder.blocks.{n}.self_attention.output" => "decoder.block.{n}.layer.0.SelfAttention.o", + "decoder.blocks.0.self_attention.relative_attention_bias" => + "decoder.block.0.layer.0.SelfAttention.relative_attention_bias", + "decoder.blocks.{n}.cross_attention_norm" => "decoder.block.{n}.layer.1.layer_norm", + "decoder.blocks.{n}.cross_attention.key" => "decoder.block.{n}.layer.1.EncDecAttention.k", + "decoder.blocks.{n}.cross_attention.query" => + "decoder.block.{n}.layer.1.EncDecAttention.q", + "decoder.blocks.{n}.cross_attention.value" => + "decoder.block.{n}.layer.1.EncDecAttention.v", + "decoder.blocks.{n}.cross_attention.output" => + "decoder.block.{n}.layer.1.EncDecAttention.o", + "decoder.blocks.{n}.output_norm" => "decoder.block.{n}.layer.2.layer_norm", + "decoder.blocks.{n}.ffn.gate" => "decoder.block.{n}.layer.2.DenseReluDense.wi_0", + "decoder.blocks.{n}.ffn.intermediate" => + if(spec.ffn_gated_activation, + do: "decoder.block.{n}.layer.2.DenseReluDense.wi_1", + else: "decoder.block.{n}.layer.2.DenseReluDense.wi" + ), + "decoder.blocks.{n}.ffn.output" => "decoder.block.{n}.layer.2.DenseReluDense.wo", + "decoder.output_norm" => "decoder.final_layer_norm", + "language_modeling_head.output" => + if(spec.tie_word_embeddings, do: "shared", else: "lm_head") + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/text_classification.ex b/deps/bumblebee/lib/bumblebee/text/text_classification.ex new file mode 100644 index 0000000000000000000000000000000000000000..be054ae82fb6042ff1ed55b7b6c0e64329172ab5 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/text_classification.ex @@ -0,0 +1,106 @@ +defmodule Bumblebee.Text.TextClassification do + @moduledoc false + + alias Bumblebee.Shared + + def text_classification(model_info, tokenizer, opts \\ []) do + %{model: model, params: params, spec: spec} = model_info + Shared.validate_architecture!(spec, :for_sequence_classification) + + opts = + Keyword.validate!(opts, [ + :compile, + top_k: 5, + scores_function: :softmax, + defn_options: [], + preallocate_params: false + ]) + + top_k = opts[:top_k] + scores_function = opts[:scores_function] + preallocate_params = opts[:preallocate_params] + defn_options = opts[:defn_options] + + compile = + if compile = opts[:compile] do + compile + |> Keyword.validate!([:batch_size, :sequence_length]) + |> Shared.require_options!([:batch_size, :sequence_length]) + end + + batch_size = compile[:batch_size] + sequence_length = compile[:sequence_length] + + tokenizer = + Bumblebee.configure(tokenizer, length: sequence_length, return_token_type_ids: false) + + {_init_fun, predict_fun} = Axon.build(model) + + scores_fun = fn params, input -> + outputs = predict_fun.(params, input) + scores = Shared.logits_to_scores(outputs.logits, scores_function) + k = min(top_k, Nx.axis_size(scores, 1)) + {top_scores, top_indices} = Nx.top_k(scores, k: k) + {top_scores, top_indices} + end + + batch_keys = Shared.sequence_batch_keys(sequence_length) + + Nx.Serving.new( + fn batch_key, defn_options -> + params = Shared.maybe_preallocate(params, preallocate_params, defn_options) + + scope = {:scores, batch_key} + + scores_fun = + Shared.compile_or_jit(scores_fun, scope, defn_options, compile != nil, fn -> + {:sequence_length, sequence_length} = batch_key + + inputs = %{ + "input_ids" => Nx.template({batch_size, sequence_length}, :u32), + "attention_mask" => Nx.template({batch_size, sequence_length}, :u32) + } + + [params, inputs] + end) + + fn inputs -> + inputs = Shared.maybe_pad(inputs, batch_size) + scores_fun.(params, inputs) |> Shared.serving_post_computation() + end + end, + defn_options + ) + |> Nx.Serving.batch_size(batch_size) + |> Nx.Serving.process_options(batch_keys: batch_keys) + |> Nx.Serving.client_preprocessing(fn input -> + {texts, multi?} = Shared.validate_serving_input!(input, &Shared.validate_string_or_pairs/1) + + inputs = + Nx.with_default_backend(Nx.BinaryBackend, fn -> + Bumblebee.apply_tokenizer(tokenizer, texts) + end) + + batch_key = Shared.sequence_batch_key_for_inputs(inputs, sequence_length) + batch = [inputs] |> Nx.Batch.concatenate() |> Nx.Batch.key(batch_key) + + {batch, multi?} + end) + |> Nx.Serving.client_postprocessing(fn {{top_scores, top_indices}, _metadata}, multi? -> + Enum.zip_with( + Nx.to_list(top_scores), + Nx.to_list(top_indices), + fn top_scores, top_indices -> + predictions = + Enum.zip_with(top_scores, top_indices, fn score, idx -> + label = spec.id_to_label[idx] || "LABEL_#{idx}" + %{score: score, label: label} + end) + + %{predictions: predictions} + end + ) + |> Shared.normalize_output(multi?) + end) + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/text_embedding.ex b/deps/bumblebee/lib/bumblebee/text/text_embedding.ex new file mode 100644 index 0000000000000000000000000000000000000000..34f4127986f277a6c66c025a6a81a6d032f07639 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/text_embedding.ex @@ -0,0 +1,151 @@ +defmodule Bumblebee.Text.TextEmbedding do + @moduledoc false + + alias Bumblebee.Shared + + def text_embedding(model_info, tokenizer, opts \\ []) do + %{model: model, params: params, spec: _spec} = model_info + + opts = + Keyword.validate!(opts, [ + :compile, + output_attribute: :pooled_state, + output_pool: nil, + embedding_processor: nil, + defn_options: [], + preallocate_params: false + ]) + + output_attribute = opts[:output_attribute] + output_pool = opts[:output_pool] + embedding_processor = opts[:embedding_processor] + preallocate_params = opts[:preallocate_params] + defn_options = opts[:defn_options] + + compile = + if compile = opts[:compile] do + compile + |> Keyword.validate!([:batch_size, :sequence_length]) + |> Shared.require_options!([:batch_size, :sequence_length]) + end + + batch_size = compile[:batch_size] + sequence_length = compile[:sequence_length] + + tokenizer = + Bumblebee.configure(tokenizer, length: sequence_length, return_token_type_ids: false) + + {_init_fun, encoder} = Axon.build(model) + + embedding_fun = fn params, inputs -> + output = encoder.(params, inputs) + + output = + case output do + %{^output_attribute => output} -> + output + + %{} -> + keys = output |> Map.keys() |> Enum.sort() + + raise ArgumentError, + "key #{inspect(output_attribute)} not found in the output map," <> + " you may want to set :output_attribute to one of the map keys: #{inspect(keys)}" + + _ -> + output + end + + if output_pool != nil and Nx.rank(output) != 3 do + raise ArgumentError, + "expected the output tensor to have rank 3 to apply :output_pool, got: #{Nx.rank(output)}." <> + " You should either disable pooling or pick a different output using :output_attribute" + end + + output = + case output_pool do + nil -> + output + + :cls_token_pooling -> + Nx.take(output, 0, axis: 1) + + :mean_pooling -> + input_mask_expanded = Nx.new_axis(inputs["attention_mask"], -1) + + output + |> Nx.multiply(input_mask_expanded) + |> Nx.sum(axes: [1]) + |> Nx.divide(Nx.sum(input_mask_expanded, axes: [1])) + + other -> + raise ArgumentError, + "expected :output_pool to be one of :cls_token_pooling, :mean_pooling or nil, got: #{inspect(other)}" + end + + output = + case embedding_processor do + nil -> + output + + :l2_norm -> + Bumblebee.Utils.Nx.normalize(output) + + other -> + raise ArgumentError, + "expected :embedding_processor to be one of nil or :l2_norm, got: #{inspect(other)}" + end + + output + end + + batch_keys = Shared.sequence_batch_keys(sequence_length) + + Nx.Serving.new( + fn batch_key, defn_options -> + params = Shared.maybe_preallocate(params, preallocate_params, defn_options) + + scope = {:embedding, batch_key} + + embedding_fun = + Shared.compile_or_jit(embedding_fun, scope, defn_options, compile != nil, fn -> + {:sequence_length, sequence_length} = batch_key + + inputs = %{ + "input_ids" => Nx.template({batch_size, sequence_length}, :u32), + "attention_mask" => Nx.template({batch_size, sequence_length}, :u32) + } + + [params, inputs] + end) + + fn inputs -> + inputs = Shared.maybe_pad(inputs, batch_size) + embedding_fun.(params, inputs) |> Shared.serving_post_computation() + end + end, + defn_options + ) + |> Nx.Serving.batch_size(batch_size) + |> Nx.Serving.process_options(batch_keys: batch_keys) + |> Nx.Serving.client_preprocessing(fn input -> + {texts, multi?} = Shared.validate_serving_input!(input, &Shared.validate_string/1) + + inputs = + Nx.with_default_backend(Nx.BinaryBackend, fn -> + Bumblebee.apply_tokenizer(tokenizer, texts) + end) + + batch_key = Shared.sequence_batch_key_for_inputs(inputs, sequence_length) + batch = [inputs] |> Nx.Batch.concatenate() |> Nx.Batch.key(batch_key) + + {batch, multi?} + end) + |> Nx.Serving.client_postprocessing(fn {embeddings, _metadata}, multi? -> + for embedding <- Bumblebee.Utils.Nx.batch_to_list(embeddings) do + %{embedding: embedding} + end + |> Shared.normalize_output(multi?) + end) + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/text_generation.ex b/deps/bumblebee/lib/bumblebee/text/text_generation.ex new file mode 100644 index 0000000000000000000000000000000000000000..2ae331023676d8347ecfedd87919f7c8e76c601e --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/text_generation.ex @@ -0,0 +1,245 @@ +defmodule Bumblebee.Text.TextGeneration do + @moduledoc false + + alias Bumblebee.Shared + alias Bumblebee.Text + + def generation(model_info, tokenizer, %Text.GenerationConfig{} = generation_config, opts \\ []) do + opts = + Keyword.validate!(opts, [ + :compile, + defn_options: [], + preallocate_params: false, + stream: false, + stream_done: false + ]) + + %{model: model, params: params, spec: spec} = model_info + + Shared.validate_architecture!(spec, [ + :for_conditional_generation, + :for_causal_language_modeling + ]) + + preallocate_params = opts[:preallocate_params] + defn_options = opts[:defn_options] + + compile = + if compile = opts[:compile] do + compile + |> Keyword.validate!([:batch_size, :sequence_length]) + |> Shared.require_options!([:batch_size, :sequence_length]) + end + + batch_size = compile[:batch_size] + sequence_length = compile[:sequence_length] + + tokenizer = + Bumblebee.configure(tokenizer, + length: sequence_length, + pad_direction: :left, + return_token_type_ids: false, + return_length: true + ) + + generate_fun = + Bumblebee.Text.Generation.build_generate(model, spec, generation_config, + ignore_output: opts[:stream] + ) + + batch_keys = Shared.sequence_batch_keys(sequence_length) + + Nx.Serving.new( + fn batch_key, defn_options -> + params = Shared.maybe_preallocate(params, preallocate_params, defn_options) + + scope = {:generate, batch_key} + + generate_fun = + Shared.compile_or_jit(generate_fun, scope, defn_options, compile != nil, fn -> + {:sequence_length, sequence_length} = batch_key + + inputs = %{ + "input_ids" => Nx.template({batch_size, sequence_length}, :u32), + "attention_mask" => Nx.template({batch_size, sequence_length}, :u32), + "seed" => Nx.template({batch_size}, :s64) + } + + [params, inputs] + end) + + fn inputs -> + inputs = Shared.maybe_pad(inputs, batch_size) + generate_fun.(params, inputs) |> Shared.serving_post_computation() + end + end, + defn_options + ) + |> Nx.Serving.batch_size(batch_size) + |> Nx.Serving.process_options(batch_keys: batch_keys) + |> Nx.Serving.client_preprocessing(fn input -> + if opts[:stream] do + Shared.validate_input_for_stream!(input) + end + + {inputs, multi?} = Shared.validate_serving_input!(input, &validate_input/1) + + texts = Enum.map(inputs, & &1.text) + seed = Enum.map(inputs, & &1.seed) |> Nx.tensor(type: :s64, backend: Nx.BinaryBackend) + + inputs = + Nx.with_default_backend(Nx.BinaryBackend, fn -> + Bumblebee.apply_tokenizer(tokenizer, texts) + end) + + {input_length, inputs} = Map.pop!(inputs, "length") + input_padded_length = Nx.axis_size(inputs["input_ids"], 1) + + inputs = Map.put(inputs, "seed", seed) + + batch_key = Shared.sequence_batch_key_for_inputs(inputs, sequence_length) + batch = [inputs] |> Nx.Batch.concatenate() |> Nx.Batch.key(batch_key) + + {batch, {multi?, input_length, input_padded_length}} + end) + |> add_postprocessing(opts[:stream], opts[:stream_done], tokenizer) + end + + defp validate_input(text) when is_binary(text), do: validate_input(%{text: text}) + + defp validate_input(%{text: text} = input) do + {:ok, %{text: text, seed: input[:seed] || :erlang.system_time()}} + end + + defp validate_input(%{} = input) do + {:error, "expected the input map to have :text key, got: #{inspect(input)}"} + end + + defp validate_input(input) do + {:error, "expected either a string or a map, got: #{inspect(input)}"} + end + + @doc false + def add_postprocessing(serving, stream, stream_done, tokenizer) + + def add_postprocessing(serving, false, _stream_done, tokenizer) do + Nx.Serving.client_postprocessing( + serving, + fn {%{token_ids: token_ids, length: length}, _metadata}, + {multi?, input_length, input_padded_length} -> + decoded = Bumblebee.Tokenizer.decode(tokenizer, token_ids) + output_length = Nx.to_flat_list(length) + input_length = Nx.to_flat_list(input_length) + + Enum.zip_with( + [decoded, output_length, input_length], + fn [decoded, output_length, input_length] -> + token_summary = token_summary(input_length, input_padded_length, output_length) + %{results: [%{text: decoded, token_summary: token_summary}]} + end + ) + |> Shared.normalize_output(multi?) + end + ) + end + + def add_postprocessing(serving, true, stream_done, tokenizer) do + serving + |> Nx.Serving.streaming(hooks: [:token]) + |> Nx.Serving.client_postprocessing(fn stream, + {false = _multi?, input_length, input_padded_length} -> + [input_length] = Nx.to_flat_list(input_length) + + Stream.transform(stream, %{tokens: [], consumed_size: 0, finished?: false}, fn + _event, %{finished?: true} = state -> + {:halt, state} + + {:token, %{token_id: token_id, finished?: finished?, length: output_length}}, state -> + token_id = Nx.to_number(token_id[0]) + finished? = Nx.to_number(finished?[0]) == 1 + + state = %{state | tokens: state.tokens ++ [token_id], finished?: finished?} + + chunk = pending_chunk(tokenizer, state) + + {items, state} = + cond do + # When the sequence is finished early or we reach a newline, + # we flush the cache + finished? or String.ends_with?(chunk, "\n") -> + {[chunk], %{state | tokens: [], consumed_size: 0}} + + # CJK characters are tokenized atomically, so we can emit + # the chunk + chunk != "" and cjk_codepoint?(last_codepoint(chunk)) -> + state = update_in(state.consumed_size, &(&1 + byte_size(chunk))) + {[chunk], state} + + # Emit chunk until the space. We need to keep tokens, + # because certain tokenizers do not encode whitespace in + # tokens and they add a space based on previous tokens + space_idx = find_last_occurrence(chunk, " ") -> + if space_idx > 0 do + chunk = binary_slice(chunk, 0, space_idx) + state = update_in(state.consumed_size, &(&1 + space_idx)) + {[chunk], state} + else + {[], state} + end + + true -> + {[], state} + end + + if finished? and stream_done do + output_length = Nx.to_number(output_length[0]) + token_summary = token_summary(input_length, input_padded_length, output_length) + done = {:done, %{token_summary: token_summary}} + {items ++ [done], state} + else + {items, state} + end + end) + end) + end + + defp token_summary(input_length, input_padded_length, output_length) do + %{ + input: input_length, + output: output_length, + padding: input_padded_length - input_length + } + end + + defp pending_chunk(tokenizer, state) do + text = Bumblebee.Tokenizer.decode(tokenizer, state.tokens) + binary_slice(text, state.consumed_size..-1//1) + end + + defp find_last_occurrence(string, pattern) do + case :binary.matches(string, pattern) do + [] -> nil + matches -> matches |> List.last() |> elem(0) + end + end + + defp last_codepoint(<>), do: codepoint + defp last_codepoint(<<_::utf8, rest::binary>>), do: last_codepoint(rest) + + defp cjk_codepoint?(codepoint) do + # The specific ranges originated in [1] and are generally mirrored + # in other tokenizers using WordPiece. Also see [2]. + # + # [1]: https://github.com/google-research/bert/blob/eedf5716ce1268e56f0a50264a88cafad334ac61/tokenization.py#L264-L284 + # [2]: https://github.com/google-research/bert/blob/eedf5716ce1268e56f0a50264a88cafad334ac61/multilingual.md#tokenization + + codepoint in 0x4E00..0x9FFF or + codepoint in 0x3400..0x4DBF or + codepoint in 0x20000..0x2A6DF or + codepoint in 0x2A700..0x2B73F or + codepoint in 0x2B740..0x2B81F or + codepoint in 0x2B820..0x2CEAF or + codepoint in 0xF900..0xFAFF or + codepoint in 0x2F800..0x2FA1F + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/token_classification.ex b/deps/bumblebee/lib/bumblebee/text/token_classification.ex new file mode 100644 index 0000000000000000000000000000000000000000..b0f97cd80a22ce740ae2c19291810700652b6249 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/token_classification.ex @@ -0,0 +1,301 @@ +defmodule Bumblebee.Text.TokenClassification do + @moduledoc false + + alias Bumblebee.Utils + alias Bumblebee.Shared + + def token_classification(model_info, tokenizer, opts \\ []) do + %{model: model, params: params, spec: spec} = model_info + Shared.validate_architecture!(spec, :for_token_classification) + + opts = + Keyword.validate!(opts, [ + :aggregation, + :compile, + scores_function: :softmax, + ignored_labels: ["O"], + defn_options: [], + preallocate_params: false + ]) + + aggregation = opts[:aggregation] + ignored_labels = opts[:ignored_labels] + scores_function = opts[:scores_function] + preallocate_params = opts[:preallocate_params] + defn_options = opts[:defn_options] + + compile = + if compile = opts[:compile] do + compile + |> Keyword.validate!([:batch_size, :sequence_length]) + |> Shared.require_options!([:batch_size, :sequence_length]) + end + + batch_size = compile[:batch_size] + sequence_length = compile[:sequence_length] + + tokenizer = + Bumblebee.configure(tokenizer, + length: sequence_length, + return_special_tokens_mask: true, + return_offsets: true + ) + + {_init_fun, predict_fun} = Axon.build(model) + + scores_fun = fn params, input -> + outputs = predict_fun.(params, input) + Shared.logits_to_scores(outputs.logits, scores_function) + end + + batch_keys = Shared.sequence_batch_keys(sequence_length) + + Nx.Serving.new( + fn batch_key, defn_options -> + params = Shared.maybe_preallocate(params, preallocate_params, defn_options) + + scope = {:scores, batch_key} + + scores_fun = + Shared.compile_or_jit(scores_fun, scope, defn_options, compile != nil, fn -> + {:sequence_length, sequence_length} = batch_key + + inputs = %{ + "input_ids" => Nx.template({batch_size, sequence_length}, :u32), + "attention_mask" => Nx.template({batch_size, sequence_length}, :u32) + } + + [params, inputs] + end) + + fn inputs -> + inputs = Shared.maybe_pad(inputs, batch_size) + scores_fun.(params, inputs) |> Shared.serving_post_computation() + end + end, + defn_options + ) + |> Nx.Serving.batch_size(batch_size) + |> Nx.Serving.process_options(batch_keys: batch_keys) + |> Nx.Serving.client_preprocessing(fn input -> + {texts, multi?} = Shared.validate_serving_input!(input, &Shared.validate_string/1) + + all_inputs = + Nx.with_default_backend(Nx.BinaryBackend, fn -> + Bumblebee.apply_tokenizer(tokenizer, texts) + end) + + inputs = Map.take(all_inputs, ["input_ids", "attention_mask"]) + + batch_key = Shared.sequence_batch_key_for_inputs(inputs, sequence_length) + batch = [inputs] |> Nx.Batch.concatenate() |> Nx.Batch.key(batch_key) + + {batch, {all_inputs, multi?}} + end) + |> Nx.Serving.client_postprocessing(fn {scores, _metadata}, {inputs, multi?} -> + Enum.zip_with( + Utils.Nx.batch_to_list(inputs), + Utils.Nx.batch_to_list(scores), + fn inputs, scores -> + entities = + scores + |> gather_raw_entities(tokenizer, inputs) + |> aggregate(spec, tokenizer, aggregation) + |> filter_entities(ignored_labels) + + %{entities: entities} + end + ) + |> Shared.normalize_output(multi?) + end) + end + + defp gather_raw_entities(scores, tokenizer, inputs) do + {sequence_length, _} = Nx.shape(scores) + flat_special_tokens_mask = Nx.to_flat_list(inputs["special_tokens_mask"]) + flat_input_ids = Nx.to_flat_list(inputs["input_ids"]) + flat_start_offsets = Nx.to_flat_list(inputs["start_offsets"]) + flat_end_offsets = Nx.to_flat_list(inputs["end_offsets"]) + + # TODO: Optional offset mapping + # TODO: Non-BPE tokenizers + token_infos = + Enum.zip([ + 0..(sequence_length - 1), + flat_input_ids, + flat_start_offsets, + flat_end_offsets, + flat_special_tokens_mask + ]) + + for {token_idx, token_id, start_idx, end_idx, _special? = 0} <- token_infos do + token = Bumblebee.Tokenizer.id_to_token(tokenizer, token_id) + # Indices are expressed in terms of utf8 bytes + token_reference_length = end_idx - start_idx + + token_scores = scores[token_idx] + + %{ + token: token, + token_id: token_id, + scores: token_scores, + start: start_idx, + end: end_idx, + index: token_idx, + # Subword tokens usually have the ## prefix, so they are longer + # than the actual word piece + is_subword: byte_size(token) != token_reference_length + } + end + end + + defp aggregate(entities, spec, _tokenizer, nil) do + entities + |> add_token_labels(spec) + |> Enum.map(fn entity -> + %{ + start: entity.start, + end: entity.end, + label: entity.label, + score: entity.score, + phrase: entity.token + } + end) + end + + defp aggregate(entities, spec, tokenizer, :same) do + entities + |> add_token_labels(spec) + |> group_entities(tokenizer) + end + + defp aggregate(entities, spec, tokenizer, strategy) + when strategy in [:word_max, :word_average, :word_first] do + entities + |> add_token_labels(spec) + |> override_token_labels(spec, strategy) + |> group_entities(tokenizer) + end + + defp aggregate(_, _, _, strategy) do + raise ArgumentError, + "unrecognized aggregation strategy #{inspect(strategy)}," <> + " currently supported strategies are :same or nil for no aggregation" + end + + defp filter_entities(entities, ignored_labels) do + Enum.filter(entities, fn entity -> + {_prefix, label} = parse_label(entity.label) + label not in ignored_labels + end) + end + + defp add_token_labels(entities, spec) do + Enum.map(entities, fn entity -> + entity_idx = entity.scores |> Nx.argmax() |> Nx.to_number() + score = Nx.to_number(entity.scores[entity_idx]) + label = spec.id_to_label[entity_idx] + Map.merge(entity, %{label: label, score: score}) + end) + end + + defp override_token_labels([], _spec, _strategy), do: [] + + defp override_token_labels([entity | entities], spec, strategy) do + {final_group, word_entities} = + Enum.reduce(entities, {[entity], []}, fn entity, {word_group, word_entities} -> + if entity.is_subword do + {[entity | word_group], word_entities} + else + {[entity], [Enum.reverse(word_group) | word_entities]} + end + end) + + [final_group | word_entities] + |> Enum.reverse() + |> Enum.flat_map(fn group -> + {idx, score} = aggregate_word(group, strategy) + label = spec.id_to_label[idx] + + Enum.with_index(group, fn entity, idx -> + label = + if idx == 0 do + label + else + force_inside_label(label) + end + + %{entity | label: label, score: score} + end) + end) + end + + defp aggregate_word([first_entity | _], :word_first) do + idx = Nx.argmax(first_entity.scores) |> Nx.to_number() + score = Nx.to_number(Nx.squeeze(first_entity.scores[[idx]])) + {idx, score} + end + + defp aggregate_word(group, :word_max) do + max_entity = Enum.max_by(group, &Nx.to_number(Nx.argmax(&1.scores))) + idx = Nx.argmax(max_entity.scores) |> Nx.to_number() + score = Nx.to_number(Nx.squeeze(max_entity.scores[[idx]])) + {idx, score} + end + + defp aggregate_word(group, :word_average) do + scores = + group + |> Enum.map(& &1.scores) + |> Nx.stack() + |> Nx.mean(axes: [0]) + + idx = Nx.argmax(scores) |> Nx.to_number() + score = Nx.to_number(Nx.squeeze(scores[[idx]])) + {idx, score} + end + + defp group_entities([], _tokenizer), do: [] + + defp group_entities([entity | entities], tokenizer) do + {_prefix, label} = parse_label(entity.label) + + {groups, _} = + Enum.reduce(entities, {[[entity]], label}, fn entity, {[group | groups], prev_label} -> + case parse_label(entity.label) do + {:i, ^prev_label} -> + {[[entity | group] | groups], prev_label} + + {_, label} -> + {[[entity], group | groups], label} + end + end) + + groups + |> Enum.map(&finish_group(&1, tokenizer)) + |> Enum.reverse() + end + + defp finish_group([last_entity | _] = rev_group, tokenizer) do + [first_entity | _] = group = Enum.reverse(rev_group) + {_, label} = parse_label(first_entity.label) + scores = Enum.map(group, & &1.score) + token_ids = Enum.map(group, & &1.token_id) + + %{ + start: first_entity.start, + end: last_entity.end, + label: label, + score: Enum.sum(scores) / length(scores), + phrase: Bumblebee.Tokenizer.decode(tokenizer, token_ids) + } + end + + # Parse the BIO tagging format + defp parse_label("B-" <> label), do: {:b, label} + defp parse_label("I-" <> label), do: {:i, label} + defp parse_label(label), do: {:i, label} + + defp force_inside_label("B-" <> label), do: "I-" <> label + defp force_inside_label(label), do: label +end diff --git a/deps/bumblebee/lib/bumblebee/text/translation.ex b/deps/bumblebee/lib/bumblebee/text/translation.ex new file mode 100644 index 0000000000000000000000000000000000000000..64a3dbff56b5c045090eaf44ee4615ec411747c6 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/translation.ex @@ -0,0 +1,178 @@ +defmodule Bumblebee.Text.Translation do + @moduledoc false + + alias Bumblebee.Shared + alias Bumblebee.Text + + def translation(model_info, tokenizer, %Text.GenerationConfig{} = generation_config, opts \\ []) do + opts = + Keyword.validate!(opts, [ + :compile, + defn_options: [], + preallocate_params: false, + stream: false, + stream_done: false + ]) + + %{model: model, params: params, spec: spec} = model_info + + Shared.validate_architecture!(spec, [:for_conditional_generation]) + + preallocate_params = opts[:preallocate_params] + defn_options = opts[:defn_options] + + compile = + if compile = opts[:compile] do + compile + |> Keyword.validate!([:batch_size, :sequence_length]) + |> Shared.require_options!([:batch_size, :sequence_length]) + end + + batch_size = compile[:batch_size] + sequence_length = compile[:sequence_length] + + tokenizer = + Bumblebee.configure(tokenizer, + length: sequence_length, + pad_direction: :left, + return_token_type_ids: false, + return_length: true + ) + + generate_fun = + Bumblebee.Text.Generation.build_generate(model, spec, generation_config, + ignore_output: opts[:stream] + ) + + batch_keys = Shared.sequence_batch_keys(sequence_length) + + Nx.Serving.new( + fn batch_key, defn_options -> + params = Shared.maybe_preallocate(params, preallocate_params, defn_options) + + scope = {:generate, batch_key} + + generate_fun = + Shared.compile_or_jit(generate_fun, scope, defn_options, compile != nil, fn -> + {:sequence_length, sequence_length} = batch_key + + inputs = %{ + "input_ids" => Nx.template({batch_size, sequence_length}, :u32), + "attention_mask" => Nx.template({batch_size, sequence_length}, :u32), + "decoder_input_ids" => Nx.template({batch_size, 2}, :u32), + "seed" => Nx.template({batch_size}, :s64) + } + + [params, inputs] + end) + + fn inputs -> + inputs = Shared.maybe_pad(inputs, batch_size) + generate_fun.(params, inputs) |> Shared.serving_post_computation() + end + end, + defn_options + ) + |> Nx.Serving.batch_size(batch_size) + |> Nx.Serving.process_options(batch_keys: batch_keys) + |> Nx.Serving.client_preprocessing(fn input -> + if opts[:stream] do + Shared.validate_input_for_stream!(input) + end + + {inputs, multi?} = Shared.validate_serving_input!(input, &validate_input/1) + + texts = Enum.map(inputs, & &1.text) + seed = Enum.map(inputs, & &1.seed) |> Nx.tensor(type: :s64, backend: Nx.BinaryBackend) + + source_language_token = source_language_token!(inputs) + + validate_language_token!(source_language_token, tokenizer) + + tokenizer = + Bumblebee.configure(tokenizer, template_options: [language_token: source_language_token]) + + # We specify custom decoder_input_ids input to include the dynamic + # language token id after the start token + decoder_input_ids = + inputs + |> Enum.map(fn %{target_language_token: target_language_token} -> + validate_language_token!(target_language_token, tokenizer) + token_id = Bumblebee.Tokenizer.token_to_id(tokenizer, target_language_token) + + decoder_start_token_id = + generation_config.decoder_start_token_id || generation_config.bos_token_id + + [decoder_start_token_id, token_id] + end) + |> Nx.tensor(type: :u32, backend: Nx.BinaryBackend) + + inputs = + Nx.with_default_backend(Nx.BinaryBackend, fn -> + Bumblebee.apply_tokenizer(tokenizer, texts) + end) + + {input_length, inputs} = Map.pop!(inputs, "length") + input_padded_length = Nx.axis_size(inputs["input_ids"], 1) + + inputs = Map.put(inputs, "seed", seed) + inputs = Map.put(inputs, "decoder_input_ids", decoder_input_ids) + + batch_key = Shared.sequence_batch_key_for_inputs(inputs, sequence_length) + batch = [inputs] |> Nx.Batch.concatenate() |> Nx.Batch.key(batch_key) + + {batch, {multi?, input_length, input_padded_length}} + end) + |> Text.TextGeneration.add_postprocessing(opts[:stream], opts[:stream_done], tokenizer) + end + + defp validate_input( + %{ + text: text, + source_language_token: source_language_token, + target_language_token: target_language_token + } = input + ) do + {:ok, + %{ + text: text, + source_language_token: source_language_token, + target_language_token: target_language_token, + seed: input[:seed] || :erlang.system_time() + }} + end + + defp validate_input(%{} = input) do + {:error, + "expected the input map to have :text, :source_language_token and :target_language_token keys, got: #{inspect(input)}"} + end + + defp validate_input(input) do + {:error, "expected a map, got: #{inspect(input)}"} + end + + defp source_language_token!(inputs) do + source_language_tokens = for input <- inputs, uniq: true, do: input.source_language_token + + case source_language_tokens do + [token] -> + token + + _tokens -> + raise ArgumentError, + "the translation serving supports a list of inputs only when all" <> + " of them have the same :source_language_token. To process multiple" <> + " inputs with different source language, configure :compile options" <> + " with a desired batch size, start a serving process and use" <> + " Task.async_stream/1 with Nx.Serving.batched_run/1" + end + end + + defp validate_language_token!(language_token, tokenizer) do + unless Bumblebee.Tokenizer.token_to_id(tokenizer, language_token) do + raise ArgumentError, + "the specified language token #{inspect(language_token)} is not" <> + " a valid token for this tokenizer" + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/whisper_generation_config.ex b/deps/bumblebee/lib/bumblebee/text/whisper_generation_config.ex new file mode 100644 index 0000000000000000000000000000000000000000..f8909dddb194e35c98f6f1ca5be354f2c46bb6d8 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/whisper_generation_config.ex @@ -0,0 +1,65 @@ +defmodule Bumblebee.Text.WhisperGenerationConfig do + alias Bumblebee.Shared + + options = [ + no_timestamps_token_id: [ + default: nil, + doc: "the id of the no-timestamps token" + ], + language_to_token_id: [ + default: %{}, + doc: "a map from language code to token id corresponding to that language" + ], + task_to_token_id: [ + default: %{}, + doc: "a map from task to token id corresponding to that task" + ] + ] + + @moduledoc """ + A set of Whisper-specific configuration options controlling text + generation. + + This struct is used in the `Bumblebee.Text.GenerationConfig` struct + under the `:extra_config` attribute. + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct Shared.option_defaults(options) + + @behaviour Bumblebee.Configurable + + @type t :: %__MODULE__{} + + @impl true + def config(config, opts \\ []) do + Shared.put_config_attrs(config, opts) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(config, data) do + import Shared.Converters + + language_converter = fn name, value -> + with {:ok, value} <- string().(name, value) do + {:ok, + value + |> String.replace_prefix("<|", "") + |> String.replace_suffix("|>", "")} + end + end + + opts = + convert!(data, + no_timestamps_token_id: {"no_timestamps_token_id", number()}, + language_to_token_id: {"lang_to_id", map(language_converter, number())}, + task_to_token_id: {"task_to_id", map(atom(), number())} + ) + + @for.config(config, opts) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/text/zero_shot_classification.ex b/deps/bumblebee/lib/bumblebee/text/zero_shot_classification.ex new file mode 100644 index 0000000000000000000000000000000000000000..4f18fdb8beeee68c97f35968caf647512650c307 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/text/zero_shot_classification.ex @@ -0,0 +1,133 @@ +defmodule Bumblebee.Text.ZeroShotClassification do + @moduledoc false + + alias Bumblebee.Utils + alias Bumblebee.Shared + + def zero_shot_classification(model_info, tokenizer, labels, opts \\ []) do + %{model: model, params: params, spec: spec} = model_info + Shared.validate_architecture!(spec, :for_sequence_classification) + + opts = + Keyword.validate!(opts, [ + :compile, + hypothesis_template: &default_hypothesis_template/1, + top_k: 5, + defn_options: [], + preallocate_params: false + ]) + + hypothesis_template = opts[:hypothesis_template] + top_k = opts[:top_k] + preallocate_params = opts[:preallocate_params] + defn_options = opts[:defn_options] + + hypotheses = Enum.map(labels, hypothesis_template) + + sequences_per_batch = length(labels) + + compile = + if compile = opts[:compile] do + compile + |> Keyword.validate!([:batch_size, :sequence_length]) + |> Shared.require_options!([:batch_size, :sequence_length]) + end + + sequence_length = compile[:sequence_length] + batch_size = compile[:batch_size] + + entailment_id = + Enum.find_value(spec.id_to_label, fn {id, label} -> + String.downcase(label) == "entailment" && id + end) + + unless entailment_id do + raise ArgumentError, + ~s/expected model specification to include "entailment" label in :id_to_label/ + end + + tokenizer = + Bumblebee.configure(tokenizer, length: sequence_length, return_token_type_ids: false) + + {_init_fun, predict_fun} = Axon.build(model) + + logits_fun = fn params, input -> + input = Utils.Nx.composite_flatten_batch(input) + %{logits: logits} = predict_fun.(params, input) + logits + end + + batch_keys = Shared.sequence_batch_keys(sequence_length) + + Nx.Serving.new( + fn batch_key, defn_options -> + params = Shared.maybe_preallocate(params, preallocate_params, defn_options) + + scope = {:logits, batch_key} + + logits_fun = + Shared.compile_or_jit(logits_fun, scope, defn_options, compile != nil, fn -> + {:sequence_length, sequence_length} = batch_key + + inputs = %{ + "input_ids" => + Nx.template({batch_size, sequences_per_batch, sequence_length}, :u32), + "attention_mask" => + Nx.template({batch_size, sequences_per_batch, sequence_length}, :u32) + } + + [params, inputs] + end) + + fn inputs -> + inputs = Shared.maybe_pad(inputs, batch_size) + logits = logits_fun.(params, inputs) + logits = Utils.Nx.composite_unflatten_batch(logits, Utils.Nx.batch_size(inputs)) + scores = Axon.Activations.softmax(logits[[.., .., entailment_id]]) + k = min(top_k, Nx.axis_size(scores, 1)) + {top_scores, top_indices} = Nx.top_k(scores, k: k) + {top_scores, top_indices} |> Shared.serving_post_computation() + end + end, + defn_options + ) + |> Nx.Serving.batch_size(batch_size) + |> Nx.Serving.process_options(batch_keys: batch_keys) + |> Nx.Serving.client_preprocessing(fn input -> + {texts, multi?} = Shared.validate_serving_input!(input, &Shared.validate_string/1) + + pairs = for text <- texts, hypothesis <- hypotheses, do: {text, hypothesis} + + inputs = + Nx.with_default_backend(Nx.BinaryBackend, fn -> + Bumblebee.apply_tokenizer(tokenizer, pairs) + end) + + batch_key = Shared.sequence_batch_key_for_inputs(inputs, sequence_length) + + inputs = Utils.Nx.composite_unflatten_batch(inputs, length(texts)) + + batch = [inputs] |> Nx.Batch.concatenate() |> Nx.Batch.key(batch_key) + + {batch, multi?} + end) + |> Nx.Serving.client_postprocessing(fn {{top_scores, top_indices}, _metadata}, multi? -> + Enum.zip_with( + Nx.to_list(top_scores), + Nx.to_list(top_indices), + fn top_scores, top_indices -> + predictions = + Enum.zip_with(top_scores, top_indices, fn score, idx -> + label = Enum.fetch!(labels, idx) + %{score: score, label: label} + end) + + %{predictions: predictions} + end + ) + |> Shared.normalize_output(multi?) + end) + end + + defp default_hypothesis_template(label), do: "This example is #{label}." +end diff --git a/deps/bumblebee/lib/bumblebee/tokenizer.ex b/deps/bumblebee/lib/bumblebee/tokenizer.ex new file mode 100644 index 0000000000000000000000000000000000000000..bfcfac1751a5e971b7181b617d7698637899709e --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/tokenizer.ex @@ -0,0 +1,130 @@ +defmodule Bumblebee.Tokenizer do + @moduledoc """ + An interface for configuring and applying tokenizers. + + A tokenizer is used to convert raw text data into model input. + + Every module implementing this behaviour is expected to also define + a configuration struct. + """ + + @type t :: struct() + + @type input :: String.t() | {String.t(), String.t()} + @type token :: String.t() + @type token_id :: non_neg_integer() + + @typedoc """ + A type corresponding to a special token in the vocabulary. + + ## Common types + + * `:bos` - a token representing the beginning of a sentence + + * `:eos` - a token representing the end of a sentence + + * `:unk` - a token representing an out-of-vocabulary token + + * `:sep` - a token separating two different sentences in the same + input + + * `:pad` - a token added when processing a batch of sequences with + different length + + * `:cls` - a token representing the class of the input + + * `:mask` - a token representing a masked token, used for masked + language modeling tasks + + """ + @type special_token_type :: atom() + + @doc """ + Performs tokenization and encoding on the given input. + """ + @callback apply(t(), input() | list(input())) :: any() + + @doc """ + Decodes a list of token ids into a sentence. + """ + @callback decode(t(), list(token_id()) | list(list(token_id()))) :: String.t() + + @doc """ + Converts the given token into the corresponding numeric id. + """ + @callback token_to_id(t(), token()) :: token_id() | nil + + @doc """ + Converts the given token id the corresponding token. + """ + @callback id_to_token(t(), token_id()) :: token() | nil + + @doc """ + Returns a map with special tokens. + """ + @callback special_tokens(t()) :: %{special_token_type() => token()} + + @doc """ + Returns a list with extra special tokens, in addition to the named + `special_tokens/1`. + """ + @callback additional_special_tokens(t()) :: MapSet.t(token()) + + @doc """ + Decodes a list of token ids into a sentence. + """ + @spec decode( + t(), + token() | list(token_id()) | list(list(token_id())) | Nx.Tensor.t() + ) :: String.t() + def decode(%module{} = tokenizer, ids) do + ids = with %Nx.Tensor{} <- ids, do: Nx.to_list(ids) + ids = List.wrap(ids) + module.decode(tokenizer, ids) + end + + @doc """ + Converts the given token into the corresponding numeric id. + """ + @spec token_to_id(t(), token()) :: token_id() | nil + def token_to_id(%module{} = tokenizer, token) do + module.token_to_id(tokenizer, token) + end + + @doc """ + Converts the given token id to the corresponding token. + """ + @spec id_to_token(t(), token_id()) :: token() | nil + def id_to_token(%module{} = tokenizer, id) do + module.id_to_token(tokenizer, id) + end + + @doc """ + Returns a special token by name. + """ + @spec special_token(t(), special_token_type()) :: token() | nil + def special_token(%module{} = tokenizer, type) do + special_tokens = module.special_tokens(tokenizer) + special_tokens[type] + end + + @doc """ + Returns id of a special token by name. + """ + @spec special_token_id(t(), special_token_type()) :: token_id() | nil + def special_token_id(tokenizer, type) do + if token = special_token(tokenizer, type) do + token_to_id(tokenizer, token) + end + end + + @doc """ + Returns all special tokens, including any extra tokens. + """ + @spec all_special_tokens(t()) :: list(token_id()) + def all_special_tokens(%module{} = tokenizer) do + special_tokens = module.special_tokens(tokenizer) + additional_special_tokens = module.additional_special_tokens(tokenizer) + for {_type, token} <- special_tokens, do: token, into: additional_special_tokens + end +end diff --git a/deps/bumblebee/lib/bumblebee/utils.ex b/deps/bumblebee/lib/bumblebee/utils.ex new file mode 100644 index 0000000000000000000000000000000000000000..a4aa89fc94c790ce653ead6349b2f67b3b85e7bd --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/utils.ex @@ -0,0 +1,11 @@ +defmodule Bumblebee.Utils do + @moduledoc false + + @doc """ + Checks if the progress bar is enabled globally. + """ + @spec progress_bar_enabled? :: boolean() + def progress_bar_enabled?() do + Application.get_env(:bumblebee, :progress_bar_enabled, true) + end +end diff --git a/deps/bumblebee/lib/bumblebee/utils/axon.ex b/deps/bumblebee/lib/bumblebee/utils/axon.ex new file mode 100644 index 0000000000000000000000000000000000000000..0ddfb75fb1103faa70178fe8b391d9b3b2ca558a --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/utils/axon.ex @@ -0,0 +1,155 @@ +defmodule Bumblebee.Utils.Axon do + @moduledoc false + + @doc """ + Returns a list with all nodes in the given model and their names. + """ + @spec nodes_with_names(Axon.t()) :: list({Axon.t(), String.t()}) + def nodes_with_names(%Axon{nodes: nodes}) do + nodes + |> Map.values() + |> Enum.map_reduce(%{}, fn axon, op_counts -> + name = axon.name.(axon.op, op_counts) + op_counts = Map.update(op_counts, axon.op, 1, &(&1 + 1)) + {{axon, name}, op_counts} + end) + |> elem(0) + end + + @doc """ + Recursively zips matching `Nx.Container`s by applying `fun` to + corresponding `Axon` nodes in these containers. + """ + @spec container_zip_with( + Nx.Container.t(), + Nx.Container.t(), + (Axon.t(), Axon.t() -> Axon.t()) + ) :: Nx.Container.t() + def container_zip_with(left, right, fun) do + case Nx.Container.traverse(left, leaves(right), &do_zip_with(&1, &2, fun)) do + {merged, []} -> + merged + + {_merged, _leftover} -> + raise ArgumentError, "cannot zip containers with incompatible structure" + end + end + + defp leaves(container) do + container + |> Nx.Container.reduce([], fn x, acc -> [x | acc] end) + |> Enum.reverse() + end + + defp do_zip_with(left, [right | right_leaves], fun) do + case {left, right} do + {%Axon{} = left, %Axon{} = right} -> + {fun.(left, right), right_leaves} + + {left, right} -> + {container_zip_with(left, right, fun), right_leaves} + end + end + + @doc """ + Recursively maps `Axon` nodes in the given `Nx.Container`. + """ + @spec container_map(Nx.Container.t(), (Axon.t() -> Axon.t())) :: Nx.Container.t() + def container_map(container, fun) do + container + |> Nx.Container.traverse(nil, fn + %Axon{} = x, acc -> + {fun.(x), acc} + + container, acc -> + {container_map(container, fun), acc} + end) + |> elem(0) + end + + @doc """ + Adds the given prefix to all layer names. + + Note that input nodes are kept intact. + """ + @spec prefix_names(Axon.t(), String.t()) :: Axon.t() + def prefix_names(%Axon{} = model, prefix) do + Axon.map_nodes(model, fn + %{op: :input} = node -> + node + + node -> + update_in(node.name, fn name -> + fn op, op_counts -> + prefix <> name.(op, op_counts) + end + end) + end) + end + + @doc """ + Replaces input nodes with nodes given in the input map. + """ + @spec plug_inputs(Axon.t(), %{String.t() => Axon.t()}) :: Axon.t() + def plug_inputs(%Axon{} = model, inputs) do + replace_nodes(model, fn + %{op: :input} = node -> + name = node.name.(:input, %{}) + inputs[name] || Bumblebee.Layers.none() + + _node -> + :keep + end) + end + + @doc """ + Optionally replaces nodes in the given graph. + + `fun` is applied exactly once to each node. The node is replaced + completely, including the node parents. + """ + @spec replace_nodes(Axon.t(), (Axon.t() -> Axon.t() | :keep)) :: Axon.t() + def replace_nodes(%Axon{} = axon, fun) when is_function(fun, 1) do + {id_mapping, new_nodes} = + Axon.reduce_nodes(axon, {%{}, %{}}, fn node, {id_mapping, new_nodes} -> + case fun.(node) do + :keep -> + {id_mapping, new_nodes} + + %Axon{} = new_node -> + {Map.put(id_mapping, node.id, new_node.output), Map.merge(new_nodes, new_node.nodes)} + end + end) + + nodes = + axon.nodes + |> Map.drop(Map.keys(id_mapping)) + |> Map.new(fn {id, node} -> + {parent, :ok} = + deep_map_reduce(node.parent, :ok, fn id, :ok -> + {id_mapping[id] || id, :ok} + end) + + {id, %{node | parent: parent}} + end) + |> Map.merge(new_nodes) + + %Axon{output: id_mapping[axon.output] || axon.output, nodes: nodes} + end + + defp deep_map_reduce(%Axon{} = node, acc, fun) do + fun.(node, acc) + end + + defp deep_map_reduce(id, acc, fun) when is_integer(id) do + fun.(id, acc) + end + + defp deep_map_reduce(nodes, acc, fun) when is_list(nodes) do + Enum.map_reduce(nodes, acc, &deep_map_reduce(&1, &2, fun)) + end + + defp deep_map_reduce(container, acc, fun) do + Nx.Container.traverse(container, acc, &deep_map_reduce(&1, &2, fun)) + end +end diff --git a/deps/bumblebee/lib/bumblebee/utils/http.ex b/deps/bumblebee/lib/bumblebee/utils/http.ex new file mode 100644 index 0000000000000000000000000000000000000000..b47fbd6961d43e4fea4ce91d9cd0093f9bde6f14 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/utils/http.ex @@ -0,0 +1,244 @@ +defmodule Bumblebee.Utils.HTTP do + @moduledoc false + + @type response :: %{status: status(), headers: headers(), body: binary()} + @type status :: non_neg_integer() + @type headers :: list(header()) + @type header :: {String.t(), String.t()} + + @doc """ + Retrieves the header value from response headers. + """ + @spec get_header(response(), String.t()) :: String.t() | nil + def get_header(response, key) do + with {^key, value} <- List.keyfind(response.headers, key, 0), do: value + end + + @doc """ + Downloads resource at the given URL to a file. + + ## Options + + * `:headers` - request headers + + """ + @spec download(String.t(), Path.t(), keyword()) :: :ok | {:error, String.t()} + def download(url, path, opts \\ []) do + path = IO.chardata_to_string(path) + headers = build_headers(opts[:headers] || []) + + case File.open(path, [:write]) do + {:ok, file} -> + try do + request = {url, headers} + http_opts = [ssl: http_ssl_opts()] + + caller = self() + + receiver = fn reply_info -> + request_id = elem(reply_info, 0) + + # Cancel the request if the caller terminates + if Process.alive?(caller) do + send(caller, {:http, reply_info}) + else + :httpc.cancel_request(request_id, :bumblebee) + end + end + + opts = [stream: :self, sync: false, receiver: receiver] + + {:ok, request_id} = :httpc.request(:get, request, http_opts, opts, :bumblebee) + download_loop(%{request_id: request_id, file: file, total_size: nil, size: nil}) + after + File.close(file) + end + + {:error, error} -> + {:error, "failed to open file for download, reason: #{:file.format_error(error)}"} + end + end + + defp download_loop(state) do + receive do + {:http, reply_info} when elem(reply_info, 0) == state.request_id -> + download_receive(state, reply_info) + end + end + + defp download_receive(_state, {_, {:error, error}}) do + {:error, "download failed, reason: #{inspect(error)}"} + end + + defp download_receive(state, {_, {{_, 200, _}, _headers, body}}) do + safe_binwrite(state.file, body) + end + + defp download_receive(_state, {_, {{_, status, _}, _headers, _body}}) do + {:error, "download failed, got HTTP status: #{status}"} + end + + defp download_receive(state, {_, :stream_start, headers}) do + total_size = total_size(headers) + download_loop(%{state | total_size: total_size, size: 0}) + end + + defp download_receive(state, {_, :stream, body_part}) do + case safe_binwrite(state.file, body_part) do + :ok -> + part_size = byte_size(body_part) + state = update_in(state.size, &(&1 + part_size)) + + if Bumblebee.Utils.progress_bar_enabled?() && + state.total_size && part_size != state.total_size do + ProgressBar.render(state.size, state.total_size, suffix: :bytes) + end + + download_loop(state) + + {:error, error} -> + :httpc.cancel_request(state.request_id, :bumblebee) + {:error, error} + end + end + + defp download_receive(_state, {_, :stream_end, _headers}) do + :ok + end + + defp total_size(headers) do + case List.keyfind(headers, ~c"content-length", 0) do + {_, content_length} -> + content_length |> List.to_string() |> String.to_integer() + + _ -> + nil + end + end + + defp safe_binwrite(file, iodata) do + try do + IO.binwrite(file, iodata) + catch + :error, error -> + {:error, "failed to write to file, reason: #{inspect(error)}"} + end + end + + @doc """ + Makes an HTTP request. + + ## Options + + * `:headers` - request headers + + * `:body` - request body given as `{content_type, body}` + + * `:timeout` - request timeout in milliseconds. Defaults to `10_000` + + * `:follow_redirects` - whether to automatically repeat the request + to the redirect location. Defaults to `true` + + """ + @spec request(atom(), String.t(), keyword()) :: {:ok, response()} | {:error, String.t()} + def request(method, url, opts \\ []) do + headers = build_headers(opts[:headers] || []) + follow_redirects = Keyword.get(opts, :follow_redirects, true) + + request = + case opts[:body] do + nil -> {url, headers} + {content_type, body} -> {url, headers, to_charlist(content_type), body} + end + + http_opts = [ + ssl: http_ssl_opts(), + timeout: opts[:timeout] || 10_000, + autoredirect: follow_redirects + ] + + opts = [ + body_format: :binary + ] + + case :httpc.request(method, request, http_opts, opts, :bumblebee) do + {:ok, {{_, status, _}, headers, body}} -> + {:ok, %{status: status, headers: parse_headers(headers), body: body}} + + {:error, error} -> + {:error, "HTTP request failed, reason: #{inspect(error)}"} + end + end + + defp build_headers(entries) do + headers = + Enum.map(entries, fn {key, value} -> + {to_charlist(key), to_charlist(value)} + end) + + [{~c"user-agent", ~c"bumblebee"} | headers] + end + + defp parse_headers(headers) do + Enum.map(headers, fn {key, val} -> + {String.downcase(to_string(key)), to_string(val)} + end) + end + + defp http_ssl_opts() do + # Allow a user-specified CA certs to support, for example, HTTPS proxies + cacert_opt = + case System.get_env("BUMBLEBEE_CACERTS_PATH") do + nil -> {:cacerts, :public_key.cacerts_get()} + file -> {:cacertfile, file} + end + + # Use secure options, see https://gist.github.com/jonatanklosko/5e20ca84127f6b31bbe3906498e1a1d7 + [ + cacert_opt, + verify: :verify_peer, + customize_hostname_check: [ + match_fun: :public_key.pkix_verify_hostname_match_fun(:https) + ] + ] + end + + @doc false + def start_inets_profile() do + # Starting an HTTP client profile allows us to scope the httpc + # configuration options, such as proxy options + {:ok, _pid} = :inets.start(:httpc, profile: :bumblebee) + set_proxy_options() + end + + @doc false + def stop_inets_profile() do + :inets.stop(:httpc, :bumblebee) + end + + defp set_proxy_options() do + http_proxy = System.get_env("HTTP_PROXY") || System.get_env("http_proxy") + https_proxy = System.get_env("HTTPS_PROXY") || System.get_env("https_proxy") + + no_proxy = + if no_proxy = System.get_env("NO_PROXY") || System.get_env("no_proxy") do + no_proxy + |> String.split(",") + |> Enum.map(&String.to_charlist/1) + else + [] + end + + set_proxy_option(:proxy, http_proxy, no_proxy) + set_proxy_option(:https_proxy, https_proxy, no_proxy) + end + + defp set_proxy_option(proxy_scheme, proxy, no_proxy) do + uri = URI.parse(proxy || "") + + if uri.host && uri.port do + host = String.to_charlist(uri.host) + :httpc.set_options([{proxy_scheme, {{host, uri.port}, no_proxy}}], :bumblebee) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/utils/image.ex b/deps/bumblebee/lib/bumblebee/utils/image.ex new file mode 100644 index 0000000000000000000000000000000000000000..c211a9e61d0c309cf75ee2c3643c2a5d0d9fbf43 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/utils/image.ex @@ -0,0 +1,57 @@ +defmodule Bumblebee.Utils.Image do + @moduledoc false + + import Nx.Defn + + @doc """ + Converts the given term to a batch of image. + """ + defn to_batched_tensor(image) do + case Nx.rank(image) do + 3 -> + Nx.new_axis(image, 0, :batch) + + 4 -> + image + + rank -> + raise ArgumentError, + "expected image to be a rank-3 image or a rank-4 batch, got rank: #{rank}" + end + end + + @doc """ + Normalizes an image size to a `{height, width}` tuple. + + Accepts either an existing tuple or a single number used for both + dimensions. + """ + def normalize_size(size) + + def normalize_size({height, width}), do: {height, width} + def normalize_size(size) when is_integer(size), do: {size, size} + + @doc """ + Matches image against the desired number of channels and applies + automatic conversions if applicable. + """ + def normalize_channels(input, channels) do + channel_axis = Nx.axis_index(input, -1) + + case {Nx.axis_size(input, channel_axis), channels} do + {channels, channels} -> + input + + {4, 3} -> + Nx.slice_along_axis(input, 0, 3, axis: channel_axis) + + {1, 3} -> + shape = input |> Nx.shape() |> put_elem(channel_axis, 3) + Nx.broadcast(input, shape) + + {actual, expected} -> + raise ArgumentError, + "expected image with #{expected} channels, but got #{actual} and no automatic conversion applies" + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/utils/model.ex b/deps/bumblebee/lib/bumblebee/utils/model.ex new file mode 100644 index 0000000000000000000000000000000000000000..c268eca2f1b61e80698cf7be333fcb1e478d934c --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/utils/model.ex @@ -0,0 +1,23 @@ +defmodule Bumblebee.Utils.Model do + @moduledoc false + + @doc """ + Adds another word to a hierarchical name. + """ + @spec join(String.t() | nil, String.Chars.t()) :: String.t() + def join(name, suffix) + + def join(nil, suffix), do: to_string(suffix) + def join(name, suffix), do: name <> "." <> to_string(suffix) + + @doc """ + Converts a list of inputs to a map with input names as keys. + """ + @spec inputs_to_map(list(Axon.t())) :: %{String.t() => Axon.t()} + def inputs_to_map(inputs) when is_list(inputs) do + for %Axon{output: id, nodes: nodes} = axon <- inputs, into: %{} do + input = nodes[id] + {input.name.(:input, %{}), axon} + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/utils/nx.ex b/deps/bumblebee/lib/bumblebee/utils/nx.ex new file mode 100644 index 0000000000000000000000000000000000000000..c3bf368c9de5fba2e76204c70e5e6a13a9730209 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/utils/nx.ex @@ -0,0 +1,494 @@ +defmodule Bumblebee.Utils.Nx do + @moduledoc false + + import Nx.Defn + + @doc """ + Recursively maps the given container with a function. + + When a tensor is given, the function is applied to this tensor. + """ + @spec map(Nx.Tensor.t() | Nx.Container.t(), (Nx.Tensor.t() -> term())) :: term() + def map(container_or_tensor, fun) + + def map(%Nx.Tensor{} = tensor, fun) do + fun.(tensor) + end + + def map(container, fun) do + container + |> Nx.Container.traverse(nil, fn item, acc -> + {map(item, fun), acc} + end) + |> elem(0) + end + + @doc """ + Recursively zips the given containers with the given function. + """ + @spec zip_with( + tensor_or_container, + tensor_or_container, + (Nx.Tensor.t(), Nx.Tensor.t() -> term()) + ) :: tensor_or_container + when tensor_or_container: Nx.Tensor.t() | Nx.Container.t() + def zip_with(left, right, fun) + + def zip_with(%Nx.Tensor{} = left, %Nx.Tensor{} = right, fun) do + fun.(left, right) + end + + def zip_with(left, right, fun) do + right_items = + right + |> Nx.Container.reduce([], fn item, acc -> [item | acc] end) + |> Enum.reverse() + + case Nx.Container.traverse(left, right_items, &recur_zip_with(&1, &2, fun)) do + {result, []} -> + result + + {_result, _leftover} -> + raise ArgumentError, "unable to merge arguments with incompatible structure" + end + end + + defp recur_zip_with(left, [right | right_items], fun) do + case {left, right} do + {%Nx.Tensor{} = left, %Nx.Tensor{} = right} -> + {fun.(left, right), right_items} + + {left, right} -> + {recur_zip_with(left, right, fun), right_items} + end + end + + @doc """ + Splits tensor or container along the first axis. + + Note: this function traverses the container N times, where N is the + batch size. Don't use it for containers with a lot of tensors. + + ## Examples + + iex> outputs = %{x: Nx.tensor([[0, 0], [1, 1]]), y: Nx.tensor([0, 1])} + iex> [first, second] = Bumblebee.Utils.Nx.batch_to_list(outputs) + iex> first.x + #Nx.Tensor< + s32[2] + [0, 0] + > + iex> second.x + #Nx.Tensor< + s32[2] + [1, 1] + > + iex> first.y + #Nx.Tensor< + s32 + 0 + > + iex> second.y + #Nx.Tensor< + s32 + 1 + > + + """ + @spec batch_to_list(Nx.Tensor.t() | Nx.Container.t()) :: list(Nx.Tensor.t() | Nx.Container.t()) + def batch_to_list(tensor_or_container) do + batch_size = + Nx.Defn.Composite.reduce(tensor_or_container, nil, fn + tensor, nil -> Nx.axis_size(tensor, 0) + tensor, size -> ^size = Nx.axis_size(tensor, 0) + end) + + for idx <- 0..(batch_size - 1)//1 do + Nx.Defn.Composite.traverse(tensor_or_container, fn tensor -> tensor[idx] end) + end + end + + @doc """ + Concatenates corresponding tensors in matching containers. + + ## Options + + * `:axis` - the axis to concatenate along. Defaults to `0` + + ## Examples + + iex> left = %{x: Nx.tensor([[0, 0], [1, 1]]), y: Nx.tensor([0, 1])} + iex> right = %{x: Nx.tensor([[2, 2], [3, 3]]), y: Nx.tensor([2, 3])} + iex> result = Bumblebee.Utils.Nx.composite_concatenate(left, right) + iex> result.x + #Nx.Tensor< + s32[4][2] + [ + [0, 0], + [1, 1], + [2, 2], + [3, 3] + ] + > + iex> result.y + #Nx.Tensor< + s32[4] + [0, 1, 2, 3] + > + + """ + deftransform composite_concatenate(left, right, opts \\ []) do + opts = Keyword.validate!(opts, axis: 0) + + axis = opts[:axis] + + right_tensors = + right + |> Nx.Defn.Composite.reduce([], &[&1 | &2]) + |> Enum.reverse() + + {result, []} = + Nx.Defn.Composite.traverse(left, right_tensors, fn left, [right | right_tensors] -> + {Nx.concatenate([left, right], axis: axis), right_tensors} + end) + + result + end + + @doc """ + Reshapes the tensor to have a new leading axis of the given size. + + ## Examples + + iex> output = %{x: Nx.tensor([[0, 0], [1, 1]]), y: Nx.tensor([0, 1])} + iex> result = Bumblebee.Utils.Nx.composite_unflatten_batch(output, 2) + iex> result.x + #Nx.Tensor< + s32[2][1][2] + [ + [ + [0, 0] + ], + [ + [1, 1] + ] + ] + > + iex> result.y + #Nx.Tensor< + s32[2][1] + [ + [0], + [1] + ] + > + + """ + deftransform composite_unflatten_batch(container, batch_size) do + map(container, fn tensor -> + shape = + tensor + |> Nx.shape() + |> Tuple.insert_at(0, batch_size) + |> put_elem(1, :auto) + + Nx.reshape(tensor, shape) + end) + end + + @doc """ + Flattens two leading tensor axes into a single axis. + + ## Examples + + iex> output = %{x: Nx.tensor([[0, 0], [1, 1]]), y: Nx.tensor([[0], [1]])} + iex> result = Bumblebee.Utils.Nx.composite_flatten_batch(output) + iex> result.x + #Nx.Tensor< + s32[4] + [0, 0, 1, 1] + > + iex> result.y + #Nx.Tensor< + s32[2] + [0, 1] + > + + """ + deftransform composite_flatten_batch(container) do + map(container, fn tensor -> + shape = + tensor + |> Nx.shape() + |> Tuple.delete_at(0) + |> put_elem(0, :auto) + + Nx.reshape(tensor, shape) + end) + end + + @doc """ + A version of `Nx.take/3` with a leading batch dimension. + + Conceptually, this function zips `tensor` with `indices` and then + applies `Nx.take/3` along the first axis for every pair. + + ## Examples + + iex> t = + ...> Nx.tensor([ + ...> [ + ...> [1, 1], + ...> [2, 2] + ...> ], + ...> [ + ...> [3, 3], + ...> [4, 4] + ...> ] + ...> ]) + iex> idx = Nx.tensor([[1, 0], [1, 1]]) + iex> Bumblebee.Utils.Nx.batched_take(t, idx) + #Nx.Tensor< + s32[2][2][2] + [ + [ + [2, 2], + [1, 1] + ], + [ + [4, 4], + [4, 4] + ] + ] + > + + ## Error cases + + iex> Bumblebee.Utils.Nx.batched_take(Nx.tensor([[1, 2], [3, 4]]), Nx.tensor([1])) + ** (ArgumentError) expected tensor and indices with the same leading axis size, got: {2, 2} and {1} + + """ + defn batched_take(tensor, idx) do + {batch_size, axis_size, flat_shape, final_shape} = get_batched_take_shapes(tensor, idx) + + flat_idx = + idx + |> Nx.reshape({batch_size, :auto}) + |> Nx.add(Nx.iota({batch_size, 1}) * axis_size) + |> Nx.flatten() + + tensor + |> Nx.reshape(flat_shape) + |> Nx.take(flat_idx) + |> Nx.reshape(final_shape) + end + + deftransformp get_batched_take_shapes(tensor, idx) do + tensor_shape = Nx.shape(tensor) + idx_shape = Nx.shape(idx) + + unless Elixir.Kernel.==(elem(tensor_shape, 0), elem(idx_shape, 0)) do + raise ArgumentError, + "expected tensor and indices with the same leading axis size, got: #{inspect(tensor_shape)} and #{inspect(idx_shape)}" + end + + [batch_size, axis_size | inner_sizes] = Tuple.to_list(tensor_shape) + + flat_shape = List.to_tuple([batch_size * axis_size | inner_sizes]) + final_shape = List.to_tuple(Tuple.to_list(idx_shape) ++ inner_sizes) + {batch_size, axis_size, flat_shape, final_shape} + end + + @doc """ + Computes cosine similarity between the given tensors. + + ## Options + + * `:batched?` - if `true`, treats inputs as batches along the first + axis and computes individual similarities. Defaults to `false` + + """ + deftransform cosine_similarity(x, y, opts \\ []) do + opts = Keyword.validate!(opts, batched?: false) + batched? = opts[:batched?] + + x = normalize(x) + y = normalize(y) + + batch_axes = if batched?, do: [0], else: [] + + Nx.dot(x, [-1], batch_axes, y, [-1], batch_axes) + end + + @doc """ + Applies L2 normalization to the last dimension of the given tensor. + """ + defn normalize(tensor) do + norm = + tensor + |> Nx.pow(2) + |> Nx.sum(axes: [-1], keep_axes: true) + |> Nx.sqrt() + + norm = Nx.select(norm == 0.0, 1.0, norm) + + tensor / norm + end + + @doc """ + Repeats tensor along the given axis, such that repeated chunks are + adjacent to each other. + + ## Options + + * `:axis` - the axis to repeat along. Defaults to `0` + + ## Examples + + iex> x = Nx.tensor([[1, 2], [3, 4]]) + iex> Bumblebee.Utils.Nx.repeat_interleave(x, 2) + #Nx.Tensor< + s32[4][2] + [ + [1, 2], + [1, 2], + [3, 4], + [3, 4] + ] + > + + """ + deftransform repeat_interleave(tensor, times, opts \\ []) do + opts = Keyword.validate!(opts, axis: 0) + + axis = opts[:axis] + + repetitions = + 1 + |> List.duplicate(Nx.rank(tensor)) + |> List.insert_at(axis + 1, times) + + tensor + |> Nx.new_axis(axis + 1) + |> Nx.tile(repetitions) + |> Nx.flatten(axes: [axis, axis + 1]) + end + + @doc """ + A version of `Nx.take/3` with each index applying to a corresponding + chunk. + + ## Options + + * `:axis` - the axis to take along. Defaults to `0` + + ## Examples + + iex> x = Nx.tensor([[1, 1], [2, 2], [3, 3], [4, 4]]) + iex> Bumblebee.Utils.Nx.chunked_take(x, 2, Nx.tensor([1, 0])) + #Nx.Tensor< + s32[2][2] + [ + [2, 2], + [3, 3] + ] + > + + """ + deftransform chunked_take(tensor, chunk_size, idx, opts \\ []) do + opts = Keyword.validate!(opts, axis: 0) + + flat_idx = + idx + |> Nx.shape() + |> Nx.iota() + |> Nx.multiply(chunk_size) + |> Nx.add(idx) + + Nx.take(tensor, flat_idx, axis: opts[:axis]) + end + + @doc """ + Shifts elements along the specified axes. + + When an shift is positive, the elements are shifted clockwise. + Negative shifts result in counter-clockwise shift. + + ## Options + + * `:shifts` - the shift size to apply to the corresponding axis + from `:axes` + + * `:axes` - the axes to apply shift to, must have the same length + as `:shifts` + + ## Examples + + iex> x = Nx.iota({3, 3}) + iex> Bumblebee.Utils.Nx.roll(x, shifts: [1], axes: [0]) + #Nx.Tensor< + s32[3][3] + [ + [6, 7, 8], + [0, 1, 2], + [3, 4, 5] + ] + > + + iex> x = Nx.iota({3, 3}) + iex> Bumblebee.Utils.Nx.roll(x, shifts: [-1], axes: [0]) + #Nx.Tensor< + s32[3][3] + [ + [3, 4, 5], + [6, 7, 8], + [0, 1, 2] + ] + > + + iex> x = Nx.iota({3, 3}) + iex> Bumblebee.Utils.Nx.roll(x, shifts: [1, 2], axes: [0, 1]) + #Nx.Tensor< + s32[3][3] + [ + [7, 8, 6], + [1, 2, 0], + [4, 5, 3] + ] + > + + """ + deftransform roll(tensor, opts) do + opts = Keyword.validate!(opts, shifts: [], axes: []) + + shifts = opts[:shifts] + axes = opts[:axes] + + if length(shifts) != length(axes) do + raise ArgumentError, + "expected shifts and axes to have the same number of elements," <> + " got shifts: #{inspect(shifts)}, axes: #{inspect(axes)}" + end + + shifts + |> Enum.zip(axes) + |> Enum.reduce(tensor, fn {shift, axis}, tensor -> + shift = rem(shift, Nx.axis_size(tensor, axis)) + + if shift == 0 do + tensor + else + {left, right} = Nx.split(tensor, -shift, axis: axis) + Nx.concatenate([right, left], axis: axis) + end + end) + end + + @doc """ + Returns size of the given `Nx.Batch`, including padding. + """ + @spec batch_size(Nx.Batch.t()) :: non_neg_integer() + def batch_size(batch) do + batch.size + batch.pad + end +end diff --git a/deps/bumblebee/lib/bumblebee/vision.ex b/deps/bumblebee/lib/bumblebee/vision.ex new file mode 100644 index 0000000000000000000000000000000000000000..e1b540521c9dc90ef45bf87d510eab66d2be1e8e --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision.ex @@ -0,0 +1,214 @@ +defmodule Bumblebee.Vision do + @moduledoc """ + High-level tasks related to vision. + """ + + @typedoc """ + A term representing an image. + + Either `Nx.Tensor` or a struct implementing `Nx.Container` and + resolving to a tensor, with the following properties: + + * HWC order + * RGB color channels + * alpha channel may be present, but it's usually stripped out + * integer type (`:s` or `:u`) + + """ + @type image :: Nx.Container.t() + + @type image_classification_input :: image() + @type image_classification_output :: %{predictions: list(image_classification_prediction())} + @type image_classification_prediction :: %{score: number(), label: String.t()} + + @doc """ + Builds serving for image classification. + + The serving accepts `t:image_classification_input/0` and returns + `t:image_classification_output/0`. A list of inputs is also supported. + + ## Options + + * `:top_k` - the number of top predictions to include in the output. If + the configured value is higher than the number of labels, all + labels are returned. Defaults to `5` + + * `:compile` - compiles all computations for predefined input shapes + during serving initialization. Should be a keyword list with the + following keys: + + * `:batch_size` - the maximum batch size of the input. Inputs + are optionally padded to always match this batch size + + It is advised to set this option in production and also configure + a defn compiler using `:defn_options` to maximally reduce inference + time. + + * `:scores_function` - the function to use for converting logits to + scores. Should be one of `:softmax`, `:sigmoid`, or `:none`. + Defaults to `:softmax` + + * `:defn_options` - the options for JIT compilation. Defaults to `[]` + + * `:preallocate_params` - when `true`, explicitly allocates params + on the device configured by `:defn_options`. You may want to set + this option when using partitioned serving, to allocate params + on each of the devices. When using this option, you should first + load the parameters into the host. This can be done by passing + `backend: {EXLA.Backend, client: :host}` to `load_model/1` and friends. + Defaults to `false` + + ## Examples + + {:ok, resnet} = Bumblebee.load_model({:hf, "microsoft/resnet-50"}) + {:ok, featurizer} = Bumblebee.load_featurizer({:hf, "microsoft/resnet-50"}) + + serving = Bumblebee.Vision.image_classification(resnet, featurizer) + + image = StbImage.read_file!(path) + Nx.Serving.run(serving, image) + #=> %{ + #=> predictions: [ + #=> %{label: "Egyptian cat", score: 0.979233980178833}, + #=> %{label: "tabby, tabby cat", score: 0.00679466687142849}, + #=> %{label: "tiger cat", score: 0.005290505941957235}, + #=> %{label: "lynx, catamount", score: 0.004550771787762642}, + #=> %{label: "Siamese cat, Siamese", score: 1.1611092486418784e-4} + #=> ] + #=> } + + """ + @spec image_classification( + Bumblebee.model_info(), + Bumblebee.Featurizer.t(), + keyword() + ) :: Nx.Serving.t() + defdelegate image_classification(model_info, featurizer, opts \\ []), + to: Bumblebee.Vision.ImageClassification + + @type image_to_text_input :: image() | %{:image => image(), optional(:seed) => integer() | nil} + @type image_to_text_output :: %{results: list(image_to_text_result())} + @type image_to_text_result :: %{text: String.t()} + + @doc """ + Builds serving for image-to-text generation. + + The serving accepts `t:image_to_text_input/0` and returns + `t:image_to_text_output/0`. A list of inputs is also supported. + + ## Options + + * `:compile` - compiles all computations for predefined input shapes + during serving initialization. Should be a keyword list with the + following keys: + + * `:batch_size` - the maximum batch size of the input. Inputs + are optionally padded to always match this batch size + + It is advised to set this option in production and also configure + a defn compiler using `:defn_options` to maximally reduce inference + time. + + * `:defn_options` - the options for JIT compilation. Defaults to `[]` + + * `:preallocate_params` - when `true`, explicitly allocates params + on the device configured by `:defn_options`. You may want to set + this option when using partitioned serving, to allocate params + on each of the devices. When using this option, you should first + load the parameters into the host. This can be done by passing + `backend: {EXLA.Backend, client: :host}` to `load_model/1` and friends. + Defaults to `false` + + ## Examples + + {:ok, blip} = Bumblebee.load_model({:hf, "Salesforce/blip-image-captioning-base"}) + {:ok, featurizer} = Bumblebee.load_featurizer({:hf, "Salesforce/blip-image-captioning-base"}) + {:ok, tokenizer} = Bumblebee.load_tokenizer({:hf, "Salesforce/blip-image-captioning-base"}) + + {:ok, generation_config} = + Bumblebee.load_generation_config({:hf, "Salesforce/blip-image-captioning-base"}) + + serving = + Bumblebee.Vision.image_to_text(blip, featurizer, tokenizer, generation_config, + defn_options: [compiler: EXLA] + ) + + image = StbImage.read_file!(path) + Nx.Serving.run(serving, image) + #=> %{results: [%{text: "a cat sitting on a chair"}]} + + """ + @spec image_to_text( + Bumblebee.model_info(), + Bumblebee.Featurizer.t(), + Bumblebee.Tokenizer.t(), + Bumblebee.Text.GenerationConfig.t(), + keyword() + ) :: Nx.Serving.t() + defdelegate image_to_text(model_info, featurizer, tokenizer, generation_config, opts \\ []), + to: Bumblebee.Vision.ImageToText + + @type image_embedding_input :: image() + @type image_embedding_output :: %{embedding: Nx.Tensor.t()} + @doc """ + Builds serving for image embeddings. + + The serving accepts `t:image_embedding_input/0` and returns + `t:image_embedding_output/0`. A list of inputs is also supported. + + ## Options + + * `:output_attribute` - the attribute of the model output map to + retrieve. When the output is a single tensor (rather than a map), + this option is ignored. Defaults to `:pooled_state` + + * `:embedding_processor` - a post-processing step to apply to the + embedding. Supported values: `:l2_norm`. By default the output is + returned as is + + * `:compile` - compiles all computations for predefined input shapes + during serving initialization. Should be a keyword list with the + following keys: + + * `:batch_size` - the maximum batch size of the input. Inputs + are optionally padded to always match this batch size + + It is advised to set this option in production and also configure + a defn compiler using `:defn_options` to maximally reduce inference + time. + + * `:defn_options` - the options for JIT compilation. Defaults to `[]` + + * `:preallocate_params` - when `true`, explicitly allocates params + on the device configured by `:defn_options`. You may want to set + this option when using partitioned serving, to allocate params + on each of the devices. When using this option, you should first + load the parameters into the host. This can be done by passing + `backend: {EXLA.Backend, client: :host}` to `load_model/1` and friends. + Defaults to `false` + + ## Examples + + {:ok, clip} = + Bumblebee.load_model({:hf, "openai/clip-vit-base-patch32"}, + module: Bumblebee.Vision.ClipVision + ) + {:ok, featurizer} = Bumblebee.load_featurizer({:hf, "openai/clip-vit-base-patch32"}) + serving = Bumblebee.Vision.image_embedding(clip, featurizer) + image = StbImage.read_file!(path) + Nx.Serving.run(serving, image) + #=> %{ + #=> embedding: #Nx.Tensor< + #=> f32[768] + #=> [-0.43403682112693787, 0.09786412119865417, -0.7233262062072754, -0.7707743644714355, 0.5550824403762817, -0.8923342227935791, 0.2687447965145111, 0.9633643627166748, 0.3520320951938629, 0.43195801973342896, 2.1438512802124023, -0.6542983651161194, -1.9736307859420776, 0.1611439287662506, 0.24555791914463043, 0.16985465586185455, 0.9012499451637268, 1.0657984018325806, 1.087411642074585, -0.5864712595939636, 0.3314521908760071, 0.8396108150482178, 0.3906593322753906, 0.13463366031646729, 0.2605385184288025, -0.07457947731018066, 0.4735124707221985, -0.41367805004119873, 0.18244807422161102, 1.4741417169570923, -5.807061195373535, 0.38920706510543823, 0.057687126100063324, 0.060301072895526886, 0.9680367708206177, 0.9670255184173584, 1.3876476287841797, -0.15498873591423035, -0.969764232635498, -0.38127464056015015, 0.05450016260147095, 2.2317700386047363, -0.07926210761070251, -0.11876475065946579, -1.5408644676208496, 0.7505669593811035, 0.9280041456222534, -0.3571934103965759, -1.1390857696533203, ...] + #=> > + #=> } + """ + @spec image_embedding( + Bumblebee.model_info(), + Bumblebee.Featurizer.t(), + keyword() + ) :: Nx.Serving.t() + defdelegate image_embedding(model_info, featurizer, opts \\ []), + to: Bumblebee.Vision.ImageEmbedding +end diff --git a/deps/bumblebee/lib/bumblebee/vision/bit_featurizer.ex b/deps/bumblebee/lib/bumblebee/vision/bit_featurizer.ex new file mode 100644 index 0000000000000000000000000000000000000000..71ee5545322a677a9ab135433e2018b8857c169e --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/bit_featurizer.ex @@ -0,0 +1,179 @@ +defmodule Bumblebee.Vision.BitFeaturizer do + alias Bumblebee.Shared + + options = [ + resize: [ + default: true, + doc: "whether to resize the input to the given `:size`" + ], + size: [ + default: %{shortest_edge: 448}, + doc: """ + the size to resize the input to, either `%{height: ..., width: ...}` or `%{shortest_edge: ...}`. + Only has an effect if `:resize` is `true` + """ + ], + resize_method: [ + default: :bicubic, + doc: + "the resizing method, either of `:nearest`, `:bilinear`, `:bicubic`, `:lanczos3`, `:lanczos5`" + ], + center_crop: [ + default: true, + doc: """ + whether to crop the input at the center. If the input size is smaller than `:crop_size` along + any edge, the image is padded with zeros and then center cropped + """ + ], + crop_size: [ + default: %{height: 448, width: 448}, + doc: """ + the size to center crop the image to, given as `%{height: ..., width: ...}`. Only has an effect + if `:center_crop` is `true` + """ + ], + rescale: [ + default: true, + doc: "whether to rescale the input by the given `:rescale_factor`" + ], + rescale_factor: [ + default: 0.00392156862745098, + doc: """ + the factor by which to rescale the input. A single number + Only has an effect if `:rescale` is `true` + """ + ], + normalize: [ + default: true, + doc: "whether or not to normalize the input with mean and standard deviation" + ], + image_mean: [ + default: [0.5, 0.5, 0.5], + doc: "the sequence of mean values for each channel, to be used when normalizing images" + ], + image_std: [ + default: [0.5, 0.5, 0.5], + doc: + "the sequence of standard deviations for each channel, to be used when normalizing images" + ] + ] + + @moduledoc """ + BiT featurizer for image data. + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct Shared.option_defaults(options) + + @behaviour Bumblebee.Featurizer + @behaviour Bumblebee.Configurable + + alias Bumblebee.Utils.Image + + @impl true + def config(featurizer, opts) do + featurizer = Shared.put_config_attrs(featurizer, opts) + + if featurizer.resize and Shared.featurizer_size_fixed?(featurizer.size) and + not featurizer.center_crop do + raise ArgumentError, + "the resize shape depends on the input shape and cropping is disabled." <> + "You must either configure a fixed size or enable cropping" + end + + featurizer + end + + @impl true + def process_input(featurizer, images) do + images = List.wrap(images) + + for image <- images do + images = + image + |> Image.to_batched_tensor() + |> Nx.as_type(:f32) + |> Image.normalize_channels(length(featurizer.image_mean)) + + images = + if featurizer.resize do + size = Shared.featurizer_resize_size(images, featurizer.size) + NxImage.resize(images, size, method: featurizer.resize_method) + else + images + end + + if featurizer.center_crop do + %{height: height, width: width} = featurizer.crop_size + NxImage.center_crop(images, {height, width}) + else + images + end + end + |> Nx.concatenate() + end + + @impl true + def batch_template(featurizer, batch_size) do + num_channels = length(featurizer.image_mean) + + {height, width} = + case featurizer do + %{center_crop: true, crop_size: %{height: height, width: width}} -> + {height, width} + + %{resize: true, size: %{height: height, width: width}} -> + {height, width} + end + + Nx.template({batch_size, height, width, num_channels}, :f32) + end + + @impl true + def process_batch(featurizer, images) do + images = + if featurizer.rescale do + Nx.multiply(images, featurizer.rescale_factor) + else + images + end + + images = + if featurizer.normalize do + NxImage.normalize( + images, + Nx.tensor(featurizer.image_mean), + Nx.tensor(featurizer.image_std) + ) + else + images + end + + %{"pixel_values" => images} + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(featurizer, data) do + import Shared.Converters + + opts = + convert!(data, + resize: {"do_resize", boolean()}, + size: {"size", image_size(single_as: :shortest_edge)}, + resize_method: {"resample", resize_method()}, + center_crop: {"do_center_crop", boolean()}, + crop_size: {"crop_size", image_size()}, + rescale: {"do_rescale", boolean()}, + rescale_factor: {"rescale_factor", number()}, + normalize: {"do_normalize", boolean()}, + image_mean: {"image_mean", list(number())}, + image_std: {"image_std", list(number())} + ) + + @for.config(featurizer, opts) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/vision/blip_featurizer.ex b/deps/bumblebee/lib/bumblebee/vision/blip_featurizer.ex new file mode 100644 index 0000000000000000000000000000000000000000..f623ef2f3b501d877ed2f946c5c04932bff321e4 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/blip_featurizer.ex @@ -0,0 +1,119 @@ +defmodule Bumblebee.Vision.BlipFeaturizer do + alias Bumblebee.Shared + + options = [ + resize: [ + default: true, + doc: "whether to resize the input to the given `:size`" + ], + size: [ + default: %{height: 384, width: 384}, + doc: """ + the size to resize the input to, given as `%{height: ..., width: ...}`. Only has + an effect if `:resize` is `true` + """ + ], + resize_method: [ + default: :bicubic, + doc: + "the resizing method, either of `:nearest`, `:bilinear`, `:bicubic`, `:lanczos3`, `:lanczos5`" + ], + normalize: [ + default: true, + doc: "whether or not to normalize the input with mean and standard deviation" + ], + image_mean: [ + default: [0.48145466, 0.4578275, 0.40821073], + doc: "the sequence of mean values for each channel, to be used when normalizing images" + ], + image_std: [ + default: [0.26862954, 0.26130258, 0.27577711], + doc: + "the sequence of standard deviations for each channel, to be used when normalizing images" + ] + ] + + @moduledoc """ + BLIP featurizer for image data. + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct Shared.option_defaults(options) + + @behaviour Bumblebee.Featurizer + @behaviour Bumblebee.Configurable + + alias Bumblebee.Utils.Image + + @impl true + def config(featurizer, opts) do + Shared.put_config_attrs(featurizer, opts) + end + + @impl true + def process_input(featurizer, images) do + images = List.wrap(images) + + for image <- images do + image = + image + |> Image.to_batched_tensor() + |> Nx.as_type(:f32) + |> Image.normalize_channels(length(featurizer.image_mean)) + + if featurizer.resize do + %{height: height, width: width} = featurizer.size + NxImage.resize(image, {height, width}, method: featurizer.resize_method) + else + image + end + end + |> Nx.concatenate() + end + + @impl true + def batch_template(featurizer, batch_size) do + %{height: height, width: width} = featurizer.size + num_channels = length(featurizer.image_mean) + Nx.template({batch_size, height, width, num_channels}, :f32) + end + + @impl true + def process_batch(featurizer, images) do + images = NxImage.to_continuous(images, 0, 1) + + images = + if featurizer.normalize do + NxImage.normalize( + images, + Nx.tensor(featurizer.image_mean), + Nx.tensor(featurizer.image_std) + ) + else + images + end + + %{"pixel_values" => images} + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(featurizer, data) do + import Shared.Converters + + opts = + convert!(data, + resize: {"do_resize", boolean()}, + size: {"size", image_size()}, + resize_method: {"resample", resize_method()}, + normalize: {"do_normalize", boolean()}, + image_mean: {"image_mean", list(number())}, + image_std: {"image_std", list(number())} + ) + + @for.config(featurizer, opts) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/vision/blip_vision.ex b/deps/bumblebee/lib/bumblebee/vision/blip_vision.ex new file mode 100644 index 0000000000000000000000000000000000000000..741f3298dfba419a049604cb91a7d95160a95edd --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/blip_vision.ex @@ -0,0 +1,278 @@ +defmodule Bumblebee.Vision.BlipVision do + alias Bumblebee.Shared + + options = + [ + image_size: [ + default: 384, + doc: "the size of the input spatial dimensions" + ], + num_channels: [ + default: 3, + doc: "the number of channels in the input" + ], + patch_size: [ + default: 16, + doc: "the size of the patch spatial dimensions" + ], + hidden_size: [ + default: 768, + doc: "the dimensionality of hidden layers" + ], + num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the encoder" + ], + num_attention_heads: [ + default: 12, + doc: "the number of attention heads for each attention layer in the encoder" + ], + intermediate_size: [ + default: 3072, + docs: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder" + ], + activation: [ + default: :gelu, + doc: "the activation function" + ], + attention_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for attention weights" + ], + layer_norm_epsilon: [ + default: 1.0e-5, + doc: "the epsilon used by the layer normalization layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] + + @moduledoc """ + The BLIP model for image encoding. + + ## Architectures + + * `:base` - the base image model + + ## Inputs + + * `"pixel_values"` - `{batch_size, image_size, image_size, num_channels}` + + Featurized image pixel values. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), do: [:base] + + @impl true + def config(spec, opts) do + Shared.put_config_attrs(spec, opts) + end + + @impl true + def input_template(spec) do + %{ + "pixel_values" => + Nx.template({1, spec.image_size, spec.image_size, spec.num_channels}, :f32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + defp inputs(spec) do + shape = {nil, spec.image_size, spec.image_size, spec.num_channels} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("pixel_values", shape: shape) + ]) + end + + defp core(inputs, spec) do + embeddings = embedder(inputs["pixel_values"], spec, name: "embedder") + + encoder_outputs = encoder(embeddings, spec, name: "encoder") + + hidden_state = + Axon.layer_norm( + encoder_outputs.hidden_state, + epsilon: spec.layer_norm_epsilon, + name: "norm" + ) + + pooled_state = + hidden_state + |> Layers.take_token(index: 0, axis: 1) + |> Axon.layer_norm(epsilon: spec.layer_norm_epsilon, name: "norm") + + %{ + hidden_state: hidden_state, + pooled_state: pooled_state, + hidden_states: encoder_outputs.hidden_states, + attentions: encoder_outputs.attentions + } + end + + defp embedder(pixel_values, spec, opts) do + name = opts[:name] + + patch_embeddings = patch_embedding(pixel_values, spec, name: join(name, "patch_embedding")) + + class_embedding = + Layers.learned_embeddings(1, spec.hidden_size, + name: join(name, "class_embedding"), + initializer: Axon.Initializers.normal() + ) + + input_embeddings = Layers.concatenate_embeddings([class_embedding, patch_embeddings]) + + num_patches = div(spec.image_size, spec.patch_size) ** 2 + num_positions = num_patches + 1 + + position_embeddings = + Layers.learned_embeddings(num_positions, spec.hidden_size, + initializer: Axon.Initializers.normal(), + name: join(name, "position_embedding") + ) + + Axon.add(input_embeddings, position_embeddings) + end + + defp patch_embedding(pixel_values, spec, opts) do + name = opts[:name] + + pixel_values + |> Axon.conv(spec.hidden_size, + kernel_size: spec.patch_size, + strides: spec.patch_size, + padding: :valid, + kernel_initializer: kernel_initializer(spec), + name: name + ) + |> Axon.reshape({:batch, :auto, spec.hidden_size}, name: join(name, "reshape")) + end + + defp encoder(embeddings, spec, opts) do + name = opts[:name] + + Layers.Transformer.blocks(embeddings, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: 0.0, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: spec.layer_norm_epsilon + ], + ffn: [ + intermediate_size: spec.intermediate_size, + activation: spec.activation + ], + block_type: :norm_first, + name: join(name, "blocks") + ) + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + # Support loading from the entire Blip configuration + def load(spec, %{"model_type" => "blip", "vision_config" => data}) do + load(spec, data) + end + + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + image_size: {"image_size", number()}, + patch_size: {"patch_size", number()}, + hidden_size: {"hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_attention_heads: {"num_attention_heads", number()}, + intermediate_size: {"intermediate_size", number()}, + activation: {"hidden_act", activation()}, + attention_dropout_rate: {"attention_dropout", number()}, + layer_norm_epsilon: {"layer_norm_eps", number()}, + initializer_scale: {"initializer_range", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.patch_embedding" => "vision_model.embeddings.patch_embedding", + "embedder.class_embedding" => %{ + "embeddings" => { + [{"vision_model.embeddings", "class_embedding"}], + fn [value] -> Nx.squeeze(value, axes: [0]) end + } + }, + "embedder.position_embedding" => %{ + "embeddings" => + {[{"vision_model.embeddings", "position_embedding"}], + fn [value] -> Nx.squeeze(value, axes: [0]) end} + }, + "encoder.blocks.{n}.self_attention_norm" => "vision_model.encoder.layers.{n}.layer_norm1", + "encoder.blocks.{n}.self_attention.query" => + Shared.sliced_dense_params_source( + "vision_model.encoder.layers.{n}.self_attn.qkv", + {[1, 1, 1], :auto}, + 0 + ), + "encoder.blocks.{n}.self_attention.key" => + Shared.sliced_dense_params_source( + "vision_model.encoder.layers.{n}.self_attn.qkv", + {[1, 1, 1], :auto}, + 1 + ), + "encoder.blocks.{n}.self_attention.value" => + Shared.sliced_dense_params_source( + "vision_model.encoder.layers.{n}.self_attn.qkv", + {[1, 1, 1], :auto}, + 2 + ), + "encoder.blocks.{n}.self_attention.output" => + "vision_model.encoder.layers.{n}.self_attn.projection", + "encoder.blocks.{n}.ffn.intermediate" => "vision_model.encoder.layers.{n}.mlp.fc1", + "encoder.blocks.{n}.ffn.output" => "vision_model.encoder.layers.{n}.mlp.fc2", + "encoder.blocks.{n}.output_norm" => "vision_model.encoder.layers.{n}.layer_norm2", + "norm" => "vision_model.post_layernorm" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/vision/clip_featurizer.ex b/deps/bumblebee/lib/bumblebee/vision/clip_featurizer.ex new file mode 100644 index 0000000000000000000000000000000000000000..4df314c9dc84ec80d1f2434be35e3a66343b786e --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/clip_featurizer.ex @@ -0,0 +1,161 @@ +defmodule Bumblebee.Vision.ClipFeaturizer do + alias Bumblebee.Shared + + options = [ + resize: [ + default: true, + doc: "whether to resize the input to the given `:size`" + ], + size: [ + default: %{shortest_edge: 224}, + doc: """ + the size to resize the input to, either `%{height: ..., width: ...}` or `%{shortest_edge: ...}`. + Only has an effect if `:resize` is `true` + """ + ], + resize_method: [ + default: :bicubic, + doc: + "the resizing method, either of `:nearest`, `:bilinear`, `:bicubic`, `:lanczos3`, `:lanczos5`" + ], + center_crop: [ + default: true, + doc: """ + whether to crop the input at the center. If the input size is smaller than `:crop_size` along + any edge, the image is padded with zeros and then center cropped + """ + ], + crop_size: [ + default: %{height: 224, width: 224}, + doc: """ + the size to center crop the image to, given as `%{height: ..., width: ...}`. Only has an effect + if `:center_crop` is `true` + """ + ], + normalize: [ + default: true, + doc: "whether or not to normalize the input with mean and standard deviation" + ], + image_mean: [ + default: [0.485, 0.456, 0.406], + doc: "the sequence of mean values for each channel, to be used when normalizing images" + ], + image_std: [ + default: [0.229, 0.224, 0.225], + doc: + "the sequence of standard deviations for each channel, to be used when normalizing images" + ] + ] + + @moduledoc """ + CLIP featurizer for image data. + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct Shared.option_defaults(options) + + @behaviour Bumblebee.Featurizer + @behaviour Bumblebee.Configurable + + alias Bumblebee.Utils.Image + + @impl true + def config(featurizer, opts) do + featurizer = Shared.put_config_attrs(featurizer, opts) + + if featurizer.resize and Shared.featurizer_size_fixed?(featurizer.size) and + not featurizer.center_crop do + raise ArgumentError, + "the resize shape depends on the input shape and cropping is disabled." <> + "You must either configure a fixed size or enable cropping" + end + + featurizer + end + + @impl true + def process_input(featurizer, images) do + images = List.wrap(images) + + for image <- images do + images = + image + |> Image.to_batched_tensor() + |> Nx.as_type(:f32) + |> Image.normalize_channels(length(featurizer.image_mean)) + + images = + if featurizer.resize do + size = Shared.featurizer_resize_size(images, featurizer.size) + NxImage.resize(images, size, method: featurizer.resize_method) + else + images + end + + if featurizer.center_crop do + %{height: height, width: width} = featurizer.crop_size + NxImage.center_crop(images, {height, width}) + else + images + end + end + |> Nx.concatenate() + end + + @impl true + def batch_template(featurizer, batch_size) do + num_channels = length(featurizer.image_mean) + + {height, width} = + case featurizer do + %{center_crop: true, crop_size: %{height: height, width: width}} -> + {height, width} + + %{resize: true, size: %{height: height, width: width}} -> + {height, width} + end + + Nx.template({batch_size, height, width, num_channels}, :f32) + end + + @impl true + def process_batch(featurizer, images) do + images = NxImage.to_continuous(images, 0, 1) + + images = + if featurizer.normalize do + NxImage.normalize( + images, + Nx.tensor(featurizer.image_mean), + Nx.tensor(featurizer.image_std) + ) + else + images + end + + %{"pixel_values" => images} + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(featurizer, data) do + import Shared.Converters + + opts = + convert!(data, + resize: {"do_resize", boolean()}, + size: {"size", image_size(single_as: :shortest_edge)}, + resize_method: {"resample", resize_method()}, + center_crop: {"do_center_crop", boolean()}, + crop_size: {"crop_size", image_size()}, + normalize: {"do_normalize", boolean()}, + image_mean: {"image_mean", list(number())}, + image_std: {"image_std", list(number())} + ) + + @for.config(featurizer, opts) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/vision/clip_vision.ex b/deps/bumblebee/lib/bumblebee/vision/clip_vision.ex new file mode 100644 index 0000000000000000000000000000000000000000..c77c66e3b21ecde1235f61994262fe5db710a18d --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/clip_vision.ex @@ -0,0 +1,284 @@ +defmodule Bumblebee.Vision.ClipVision do + alias Bumblebee.Shared + + options = + [ + image_size: [ + default: 224, + doc: "the size of the input spatial dimensions" + ], + num_channels: [ + default: 3, + doc: "the number of channels in the input" + ], + patch_size: [ + default: 32, + doc: "the size of the patch spatial dimensions" + ], + hidden_size: [ + default: 768, + doc: "the dimensionality of hidden layers" + ], + num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the encoder" + ], + num_attention_heads: [ + default: 12, + doc: "the number of attention heads for each attention layer in the encoder" + ], + intermediate_size: [ + default: 3072, + docs: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder" + ], + projection_size: [ + default: 512, + doc: "the dimensionality of the projection layer" + ], + activation: [ + default: :gelu_approx_sigmoid, + doc: "the activation function" + ], + attention_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for attention weights" + ], + layer_norm_epsilon: [ + default: 1.0e-5, + doc: "the epsilon used by the layer normalization layers" + ] + ] + + @moduledoc """ + The CLIP model for image encoding. + + ## Architectures + + * `:base` - the base image model + + * `:for_embedding` - the base model with a single projection layer + on top. The head returns a vector embedded in the joint text-image + CLIP space + + ## Inputs + + * `"pixel_values"` - `{batch_size, image_size, image_size, num_channels}` + + Featurized image pixel values. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), do: [:base, :for_embedding] + + @impl true + def config(spec, opts) do + Shared.put_config_attrs(spec, opts) + end + + @impl true + def input_template(spec) do + %{ + "pixel_values" => + Nx.template({1, spec.image_size, spec.image_size, spec.num_channels}, :f32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_embedding} = spec) do + inputs = inputs(spec) + + outputs = core(inputs, spec) + + embedding = + outputs.pooled_state + |> Axon.dense(spec.projection_size, use_bias: false, name: "projection_head.output") + + Layers.output(%{ + embedding: embedding, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + defp inputs(spec) do + shape = {nil, spec.image_size, spec.image_size, spec.num_channels} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("pixel_values", shape: shape) + ]) + end + + defp core(inputs, spec) do + embeddings = embedder(inputs["pixel_values"], spec, name: "embedder") + + encoder_outputs = + embeddings + |> Axon.layer_norm(epsilon: spec.layer_norm_epsilon, name: "pre_norm") + |> encoder(spec, name: "encoder") + + pooled_state = + encoder_outputs.hidden_state + |> Axon.layer_norm(epsilon: spec.layer_norm_epsilon, name: "post_norm") + |> Layers.take_token(index: 0, axis: 1) + + %{ + hidden_state: encoder_outputs.hidden_state, + pooled_state: pooled_state, + hidden_states: encoder_outputs.hidden_states, + attentions: encoder_outputs.attentions + } + end + + defp embedder(pixel_values, spec, opts) do + name = opts[:name] + + patch_embeddings = patch_embedding(pixel_values, spec, name: join(name, "patch_embedding")) + + class_embedding = + Layers.learned_embeddings(1, spec.hidden_size, + name: join(name, "class_embedding"), + initializer: Axon.Initializers.normal() + ) + + input_embeddings = Layers.concatenate_embeddings([class_embedding, patch_embeddings]) + + num_patches = div(spec.image_size, spec.patch_size) ** 2 + num_positions = num_patches + 1 + position_ids = position_ids(num_positions) + + position_embeddings = + Axon.embedding(position_ids, num_patches + 1, spec.hidden_size, + name: join(name, "position_embedding") + ) + + Axon.add(input_embeddings, position_embeddings) + end + + defp patch_embedding(pixel_values, spec, opts) do + name = opts[:name] + + pixel_values + |> Axon.conv(spec.hidden_size, + kernel_size: spec.patch_size, + strides: spec.patch_size, + padding: :valid, + kernel_initializer: Axon.Initializers.normal(), + use_bias: false, + name: name + ) + |> Axon.reshape({:batch, :auto, spec.hidden_size}, name: join(name, "reshape")) + end + + defp position_ids(num_position_ids) do + Axon.layer( + fn _opts -> Nx.iota({1, num_position_ids}) end, + [], + op_name: :position_ids + ) + end + + defp encoder(embeddings, spec, opts) do + name = opts[:name] + + Layers.Transformer.blocks(embeddings, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: Axon.Initializers.normal(scale: 0.01), + dropout_rate: 0.0, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm: [ + epsilon: spec.layer_norm_epsilon + ], + ffn: [ + intermediate_size: spec.intermediate_size, + activation: spec.activation + ], + block_type: :norm_first, + name: join(name, "blocks") + ) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + # Support loading from the entire Clip configuration + def load(spec, %{"model_type" => "clip", "vision_config" => data}) do + load(spec, data) + end + + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + image_size: {"image_size", number()}, + patch_size: {"patch_size", number()}, + hidden_size: {"hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_attention_heads: {"num_attention_heads", number()}, + intermediate_size: {"intermediate_size", number()}, + projection_size: {"projection_dim", number()}, + activation: {"hidden_act", activation()}, + attention_dropout_rate: {"attention_dropout", number()}, + layer_norm_epsilon: {"layer_norm_eps", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.patch_embedding" => "vision_model.embeddings.patch_embedding", + "embedder.class_embedding" => %{ + "embeddings" => { + [{"vision_model.embeddings", "class_embedding"}], + fn [value] -> Nx.new_axis(value, 0) end + } + }, + "embedder.position_embedding" => "vision_model.embeddings.position_embedding", + "encoder.blocks.{n}.self_attention_norm" => "vision_model.encoder.layers.{n}.layer_norm1", + "encoder.blocks.{n}.self_attention.query" => + "vision_model.encoder.layers.{n}.self_attn.q_proj", + "encoder.blocks.{n}.self_attention.key" => + "vision_model.encoder.layers.{n}.self_attn.k_proj", + "encoder.blocks.{n}.self_attention.value" => + "vision_model.encoder.layers.{n}.self_attn.v_proj", + "encoder.blocks.{n}.self_attention.output" => + "vision_model.encoder.layers.{n}.self_attn.out_proj", + "encoder.blocks.{n}.ffn.intermediate" => "vision_model.encoder.layers.{n}.mlp.fc1", + "encoder.blocks.{n}.ffn.output" => "vision_model.encoder.layers.{n}.mlp.fc2", + "encoder.blocks.{n}.output_norm" => "vision_model.encoder.layers.{n}.layer_norm2", + "pre_norm" => "vision_model.pre_layrnorm", + "post_norm" => "vision_model.post_layernorm", + "projection_head.output" => "visual_projection" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/vision/convnext.ex b/deps/bumblebee/lib/bumblebee/vision/convnext.ex new file mode 100644 index 0000000000000000000000000000000000000000..54a70c255fe793ebe9b5e352fd3dcf0b516af6d1 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/convnext.ex @@ -0,0 +1,358 @@ +defmodule Bumblebee.Vision.ConvNext do + alias Bumblebee.Shared + + options = + [ + num_channels: [ + default: 3, + doc: "the number of channels in the input" + ], + patch_size: [ + default: 4, + doc: "the size of the patch spatial dimensions" + ], + hidden_sizes: [ + default: [96, 192, 384, 768], + doc: "the dimensionality of hidden layers at each stage" + ], + depths: [ + default: [3, 3, 9, 3], + doc: "the depth (number of residual blocks) at each stage" + ], + activation: [ + default: :gelu, + doc: "the activation function" + ], + scale_initial_value: [ + default: 1.0e-6, + doc: "the initial value for scaling layers" + ], + drop_path_rate: [ + default: 0.0, + doc: "the drop path rate used to for stochastic depth" + ], + layer_norm_epsilon: [ + default: 1.0e-12, + doc: "the epsilon used by the layer normalization layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] ++ Shared.common_options([:num_labels, :id_to_label]) + + @moduledoc """ + ConvNeXT model family. + + ## Architectures + + * `:base` - plain ConvNeXT without any head on top + + * `:for_image_classification` - ConvNeXT with a classification head. + The head consists of a single dense layer on top of the pooled + features + + ## Inputs + + * `"pixel_values"` - {batch_size, height, width, num_channels} + + Featurized image pixel values (224x224). + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states])} + + ## Configuration + + #{Shared.options_doc(options)} + + ## References + + * [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) + + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), do: [:base, :for_image_classification] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(spec) do + %{ + "pixel_values" => Nx.template({1, 224, 224, spec.num_channels}, :f32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + spec + |> core() + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_image_classification} = spec) do + outputs = core(spec) + + logits = + Axon.dense(outputs.pooled_state, spec.num_labels, + name: "image_classification_head.output", + kernel_initializer: kernel_initializer(spec) + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states + }) + end + + defp core(spec, opts \\ []) do + name = opts[:name] + + pixel_values = Axon.input("pixel_values", shape: {nil, 224, 224, spec.num_channels}) + + encoder_outputs = + pixel_values + |> embedder(spec, name: join(name, "embedder")) + |> encoder(spec, name: join(name, "encoder")) + + pooled_output = + encoder_outputs.hidden_state + |> Axon.global_avg_pool() + |> Axon.layer_norm( + name: join(name, "norm"), + beta_initializer: :zeros, + gamma_initializer: :ones + ) + + %{ + hidden_state: encoder_outputs.hidden_state, + pooled_state: pooled_output, + hidden_states: encoder_outputs.hidden_states + } + end + + defp embedder(pixel_values, spec, opts) do + name = opts[:name] + embedding_size = hd(spec.hidden_sizes) + + pixel_values + |> Axon.conv(embedding_size, + kernel_size: spec.patch_size, + strides: spec.patch_size, + name: join(name, "patch_embedding"), + kernel_initializer: kernel_initializer(spec) + ) + |> Axon.layer_norm( + epsilon: 1.0e-6, + name: join(name, "norm"), + beta_initializer: :zeros, + gamma_initializer: :ones + ) + end + + defp encoder(hidden_state, spec, opts) do + name = opts[:name] + + drop_path_rates = get_drop_path_rates(spec.depths, spec.drop_path_rate) + + stages = Enum.zip([spec.depths, drop_path_rates, spec.hidden_sizes]) |> Enum.with_index() + + state = %{ + hidden_state: hidden_state, + hidden_states: Axon.container({hidden_state}), + in_channels: hd(spec.hidden_sizes) + } + + for {{depth, drop_path_rates, out_channels}, idx} <- stages, reduce: state do + state -> + strides = if idx > 0, do: 2, else: 1 + + hidden_state = + stage( + state.hidden_state, + state.in_channels, + out_channels, + spec, + strides: strides, + depth: depth, + drop_path_rates: drop_path_rates, + name: name |> join("stages") |> join(idx) + ) + + %{ + hidden_state: hidden_state, + hidden_states: Layers.append(state.hidden_states, hidden_state), + in_channels: out_channels + } + end + end + + defp stage(hidden_state, in_channels, out_channels, spec, opts) do + name = opts[:name] + + strides = opts[:strides] + depth = opts[:depth] + drop_path_rates = opts[:drop_path_rates] + + downsampled = + if in_channels != out_channels or strides > 1 do + hidden_state + |> Axon.layer_norm( + epsilon: 1.0e-6, + name: join(name, "downsample_norm"), + beta_initializer: :zeros, + gamma_initializer: :ones + ) + |> Axon.conv(out_channels, + kernel_size: 2, + strides: strides, + name: join(name, "downsample"), + kernel_initializer: kernel_initializer(spec) + ) + else + hidden_state + end + + # Ensure the rates have been computed properly + ^depth = length(drop_path_rates) + + for {drop_path_rate, idx} <- Enum.with_index(drop_path_rates), reduce: downsampled do + x -> + block(x, out_channels, spec, + name: name |> join("blocks") |> join(idx), + drop_path_rate: drop_path_rate + ) + end + end + + defp block(hidden_state, out_channels, spec, opts) do + name = opts[:name] + drop_path_rate = opts[:drop_path_rate] + + input = hidden_state + + hidden_state = + hidden_state + |> Axon.depthwise_conv(1, + kernel_size: 7, + padding: [{3, 3}, {3, 3}], + name: join(name, "depthwise_conv"), + kernel_initializer: kernel_initializer(spec) + ) + |> Axon.layer_norm( + epsilon: 1.0e-6, + channel_index: 3, + name: join(name, "norm"), + beta_initializer: :zeros, + gamma_initializer: :ones + ) + |> Axon.dense(4 * out_channels, + name: join(name, "pointwise_conv_1"), + kernel_initializer: kernel_initializer(spec) + ) + |> Axon.activation(spec.activation, name: join(name, "activation")) + |> Axon.dense(out_channels, + name: join(name, "pointwise_conv_2"), + kernel_initializer: kernel_initializer(spec) + ) + + hidden_state = + if spec.scale_initial_value > 0 do + Layers.scale(hidden_state, + scale_initializer: Axon.Initializers.full(spec.scale_initial_value), + name: join(name, "scale") + ) + else + hidden_state + end + + hidden_state + |> Layers.drop_path(rate: drop_path_rate, name: join(name, "drop_path")) + |> Axon.add(input) + end + + defp get_drop_path_rates(depths, rate) do + sum_of_depths = Enum.sum(depths) + + rates = + Nx.iota({sum_of_depths}) + |> Nx.multiply(rate / sum_of_depths - 1) + |> Nx.to_flat_list() + + {final_rates, _} = + Enum.map_reduce(depths, rates, fn depth, rates -> + Enum.split(rates, depth) + end) + + final_rates + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + num_channels: {"num_channels", number()}, + patch_size: {"patch_size", number()}, + hidden_sizes: {"hidden_sizes", list(number())}, + depths: {"depths", list(number())}, + activation: {"hidden_act", activation()}, + scale_initial_value: {"layer_scale_init_value", number()}, + drop_path_rate: {"drop_path_rate", number()}, + layer_norm_epsilon: {"layer_norm_eps", number()}, + initializer_scale: {"initializer_range", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.patch_embedding" => "convnext.embeddings.patch_embeddings", + "embedder.norm" => "convnext.embeddings.layernorm", + "encoder.stages.{n}.downsample_norm" => + "convnext.encoder.stages.{n}.downsampling_layer.0", + "encoder.stages.{n}.downsample" => "convnext.encoder.stages.{n}.downsampling_layer.1", + "encoder.stages.{n}.blocks.{m}.depthwise_conv" => + "convnext.encoder.stages.{n}.layers.{m}.dwconv", + "encoder.stages.{n}.blocks.{m}.norm" => + "convnext.encoder.stages.{n}.layers.{m}.layernorm", + "encoder.stages.{n}.blocks.{m}.pointwise_conv_1" => + "convnext.encoder.stages.{n}.layers.{m}.pwconv1", + "encoder.stages.{n}.blocks.{m}.pointwise_conv_2" => + "convnext.encoder.stages.{n}.layers.{m}.pwconv2", + "encoder.stages.{n}.blocks.{m}.scale" => %{ + "scale" => { + [{"convnext.encoder.stages.{n}.layers.{m}", "layer_scale_parameter"}], + fn [scale] -> scale end + } + }, + "norm" => "convnext.layernorm", + "image_classification_head.output" => "classifier" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/vision/convnext_featurizer.ex b/deps/bumblebee/lib/bumblebee/vision/convnext_featurizer.ex new file mode 100644 index 0000000000000000000000000000000000000000..6eabf1a028c5b00020ca70d673f8004f35c28940 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/convnext_featurizer.ex @@ -0,0 +1,155 @@ +defmodule Bumblebee.Vision.ConvNextFeaturizer do + alias Bumblebee.Shared + + options = [ + resize: [ + default: true, + doc: "whether to resize (and optionally center crop) the input to the given `:size`" + ], + size: [ + default: 224, + doc: """ + the size to resize the input to. If 384 or larger, the image is resized to (`:size`, `:size`). + Otherwise, the shorter edge of the image is matched to `:size` / `:crop_percentage`, then image + is cropped to `:size`. Only has an effect if `:resize` is `true` + """ + ], + resize_method: [ + default: :bicubic, + doc: + "the resizing method, either of `:nearest`, `:bilinear`, `:bicubic`, `:lanczos3`, `:lanczos5`" + ], + crop_percentage: [ + default: 224 / 256, + doc: + "the percentage of the image to crop. Only has an effect if `:resize` is `true` and `:size` < 384" + ], + normalize: [ + default: true, + doc: "whether or not to normalize the input with mean and standard deviation" + ], + image_mean: [ + default: [0.485, 0.456, 0.406], + doc: "the sequence of mean values for each channel, to be used when normalizing images" + ], + image_std: [ + default: [0.229, 0.224, 0.225], + doc: + "the sequence of standard deviations for each channel, to be used when normalizing images" + ] + ] + + @moduledoc """ + ConvNeXT featurizer for image data. + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct Shared.option_defaults(options) + + @behaviour Bumblebee.Featurizer + @behaviour Bumblebee.Configurable + + alias Bumblebee.Utils.Image + + @impl true + def config(featurizer, opts) do + Shared.put_config_attrs(featurizer, opts) + end + + @impl true + def process_input(featurizer, images) do + images = List.wrap(images) + + for image <- images do + images = + image + |> Image.to_batched_tensor() + |> Nx.as_type(:f32) + |> Image.normalize_channels(length(featurizer.image_mean)) + + cond do + not featurizer.resize -> + images + + featurizer.size >= 384 -> + NxImage.resize(images, {featurizer.size, featurizer.size}, + method: featurizer.resize_method + ) + + true -> + scale_size = floor(featurizer.size / featurizer.crop_percentage) + + images + |> NxImage.resize_short(scale_size, method: featurizer.resize_method) + |> NxImage.center_crop({featurizer.size, featurizer.size}) + end + end + |> Nx.concatenate() + end + + @impl true + def batch_template(featurizer, batch_size) do + num_channels = length(featurizer.image_mean) + Nx.template({batch_size, featurizer.size, featurizer.size, num_channels}, :f32) + end + + @impl true + def process_batch(featurizer, images) do + images = NxImage.to_continuous(images, 0, 1) + + images = + if featurizer.normalize do + NxImage.normalize( + images, + Nx.tensor(featurizer.image_mean), + Nx.tensor(featurizer.image_std) + ) + else + images + end + + %{"pixel_values" => images} + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(featurizer, data) do + import Shared.Converters + + opts = + convert!(data, + resize: {"do_resize", boolean()}, + size: {"size", size()}, + resize_method: {"resample", resize_method()}, + crop_percentage: {"crop_pct", number()}, + normalize: {"do_normalize", boolean()}, + image_mean: {"image_mean", list(number())}, + image_std: {"image_std", list(number())} + ) + + @for.config(featurizer, opts) + end + + defp size() do + # Note that in contrast to other featurizers, in this case size + # is always a single number and its meaning depends on the input + # size. huggingface/transformers put it under the "shortest_edge" + # key, but we keep it as a single number as it is more clear. + fn name, value -> + case value do + %{"shortest_edge" => size} -> + {:ok, size} + + size when is_number(size) -> + {:ok, size} + + _ -> + {:error, + "expected #{inspect(name)} to be a number or a map with shortest_edge, got: #{inspect(value)}"} + end + end + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/vision/deit.ex b/deps/bumblebee/lib/bumblebee/vision/deit.ex new file mode 100644 index 0000000000000000000000000000000000000000..9eaf7ce334d9a69b09caca5c088e2e0324c426e4 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/deit.ex @@ -0,0 +1,412 @@ +defmodule Bumblebee.Vision.Deit do + alias Bumblebee.Shared + + options = + [ + image_size: [ + default: 224, + doc: "the size of the input spatial dimensions" + ], + num_channels: [ + default: 3, + doc: "the number of channels in the input" + ], + patch_size: [ + default: 16, + doc: "the size of the patch spatial dimensions" + ], + hidden_size: [ + default: 768, + doc: "the dimensionality of hidden layers" + ], + num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the encoder" + ], + num_attention_heads: [ + default: 12, + doc: "the number of attention heads for each attention layer in the encoder" + ], + intermediate_size: [ + default: 3072, + docs: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder" + ], + use_attention_bias: [ + default: true, + doc: "whether to use bias in query, key, and value projections" + ], + activation: [ + default: :gelu, + doc: "the activation function" + ], + dropout_rate: [ + default: 0.0, + doc: "the dropout rate for encoder and decoder" + ], + attention_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for attention weights" + ], + layer_norm_epsilon: [ + default: 1.0e-12, + doc: "the epsilon used by the layer normalization layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] ++ Shared.common_options([:num_labels, :id_to_label]) + + @moduledoc """ + DeiT model family. + + ## Architectures + + * `:base` - plain DeiT without any head on top + + * `:for_image_classification` - DeiT with a classification head. + The head consists of two dense layers on top of the final + hidden state of the CLS token + + * `:for_image_classification_with teacher` - DeiT with a + classification head. The head consists of two dense layers + on top of the final hidden state of the CLS token and the + final hidden state of the distillation token + + * `:for_masked_image_modeling` - DEiT with a language modeling + head on top for predicting visual tokens + + ## Inputs + + * `"pixel_values"` - `{batch_size, image_size, image_size, num_channels}` + + Featurized image pixel values. + + * `"patch_mask"` - `{batch_size, num_patches}` + + Mask to nullify selected embedded patches. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + + ## References + + * [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929) + + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), + do: [ + :base, + :for_image_classification, + :for_image_classification_with_teacher, + :for_masked_image_modeling + ] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(spec) do + %{ + "pixel_values" => + Nx.template({1, spec.image_size, spec.image_size, spec.num_channels}, :f32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + + inputs + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_image_classification} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + outputs.hidden_state + |> Layers.take_token(index: 0, axis: 1) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "image_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_image_classification_with_teacher} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + class_logits = + outputs.hidden_state + |> Layers.take_token(index: 0, axis: 1) + |> Axon.dense(spec.num_labels, + name: "image_classification_with_teacher_head.class_output" + ) + + distillation_logits = + outputs.hidden_state + |> Layers.take_token(index: 1, axis: 1) + |> Axon.dense(spec.num_labels, + name: "image_classification_with_teacher_head.distillation_output" + ) + + # TODO: Replace with mean layer in Axon + + logits = + class_logits + |> Axon.add(distillation_logits) + |> Axon.nx(&Nx.divide(&1, 2)) + + Layers.output(%{ + logits: logits, + class_logits: class_logits, + distillation_logits: distillation_logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_masked_image_modeling} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + pixel_values = + outputs.hidden_state + |> Axon.nx(fn x -> + x = x[[.., 1..-2//1]] + {batch_size, sequence_length, channels} = Nx.shape(x) + height = width = sequence_length |> :math.sqrt() |> floor() + Nx.reshape(x, {batch_size, height, width, channels}) + end) + # Upsample to the original spatial resolution + |> Axon.conv(spec.patch_size ** 2 * 3, + kernel_size: 1, + kernel_initializer: kernel_initializer(spec), + name: "masked_image_modeling_head.output" + ) + |> Layers.pixel_shuffle(spec.patch_size) + + Layers.output(%{ + pixel_values: pixel_values, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + defp inputs(spec) do + shape = {nil, spec.image_size, spec.image_size, spec.num_channels} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("pixel_values", shape: shape), + Axon.input("patch_mask", shape: {nil, nil}, optional: true) + ]) + end + + defp core(inputs, spec, opts \\ []) do + name = opts[:name] + + embeddings = + embedder(inputs["pixel_values"], inputs["patch_mask"], spec, name: join(name, "embedder")) + + encoder_outputs = encoder(embeddings, spec, name: join(name, "encoder")) + + hidden_state = + Axon.layer_norm(encoder_outputs.hidden_state, + epsilon: spec.layer_norm_epsilon, + name: join(name, "norm") + ) + + pooled_state = pooler(hidden_state, spec, name: join(name, "pooler")) + + %{ + hidden_state: hidden_state, + pooled_state: pooled_state, + hidden_states: encoder_outputs.hidden_states, + attentions: encoder_outputs.attentions + } + end + + defp embedder(pixel_values, patch_mask, spec, opts) do + name = opts[:name] + + patch_embeddings = + pixel_values + |> patch_embedding(spec, name: join(name, "patch_embedding")) + |> Layers.apply_vision_patch_mask(patch_mask, name: join(name, "mask_tokens")) + + class_embedding = + Layers.learned_embeddings(1, spec.hidden_size, name: join(name, "class_embedding")) + + distillation_embedding = + Layers.learned_embeddings(1, spec.hidden_size, name: join(name, "distillation_embedding")) + + input_embeddings = + Layers.concatenate_embeddings([class_embedding, distillation_embedding, patch_embeddings]) + + num_patches = div(spec.image_size, spec.patch_size) ** 2 + + position_embeddings = + Layers.learned_embeddings(num_patches + 2, spec.hidden_size, + initializer: :zeros, + name: join(name, "position_embedding") + ) + + Axon.add(input_embeddings, position_embeddings) + |> Axon.dropout(rate: spec.dropout_rate, name: join(name, "dropout")) + end + + defp patch_embedding(pixel_values, spec, opts) do + name = opts[:name] + + pixel_values + |> Axon.conv(spec.hidden_size, + kernel_size: spec.patch_size, + strides: spec.patch_size, + padding: :valid, + kernel_initializer: kernel_initializer(spec), + name: join(name, "projection") + ) + |> Axon.reshape({:batch, :auto, spec.hidden_size}, name: join(name, "reshape")) + end + + defp encoder(hidden_state, spec, opts) do + name = opts[:name] + + Layers.Transformer.blocks(hidden_state, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + query_use_bias: spec.use_attention_bias, + key_use_bias: spec.use_attention_bias, + value_use_bias: spec.use_attention_bias, + layer_norm: [ + epsilon: spec.layer_norm_epsilon + ], + ffn: [ + intermediate_size: spec.intermediate_size, + activation: spec.activation + ], + block_type: :norm_first, + name: join(name, "blocks") + ) + end + + defp pooler(hidden_state, spec, opts) do + name = opts[:name] + + hidden_state + |> Layers.take_token(index: 0, axis: 1) + |> Axon.dense(spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + |> Axon.tanh() + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + image_size: {"image_size", number()}, + num_channels: {"num_channels", number()}, + patch_size: {"patch_size", number()}, + hidden_size: {"hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_attention_heads: {"num_attention_heads", number()}, + intermediate_size: {"intermediate_size", number()}, + use_attention_bias: {"qkv_bias", boolean()}, + activation: {"hidden_act", activation()}, + dropout_rate: {"hidden_dropout_prob", number()}, + attention_dropout_rate: {"attention_probs_dropout_prob", number()}, + layer_norm_epsilon: {"layer_norm_eps", number()}, + initializer_scale: {"initializer_range", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.patch_embedding.projection" => "deit.embeddings.patch_embeddings.projection", + "embedder.distillation_embedding" => %{ + "embeddings" => { + [{"deit.embeddings", "distillation_token"}], + fn [value] -> Nx.squeeze(value, axes: [0]) end + } + }, + "embedder.class_embedding" => %{ + "embeddings" => { + [{"deit.embeddings", "cls_token"}], + fn [value] -> Nx.squeeze(value, axes: [0]) end + } + }, + "embedder.position_embedding" => %{ + "embeddings" => { + [{"deit.embeddings", "position_embeddings"}], + fn [value] -> Nx.squeeze(value, axes: [0]) end + } + }, + "encoder.blocks.{n}.self_attention_norm" => "deit.encoder.layer.{n}.layernorm_before", + "encoder.blocks.{n}.self_attention.key" => + "deit.encoder.layer.{n}.attention.attention.key", + "encoder.blocks.{n}.self_attention.query" => + "deit.encoder.layer.{n}.attention.attention.query", + "encoder.blocks.{n}.self_attention.value" => + "deit.encoder.layer.{n}.attention.attention.value", + "encoder.blocks.{n}.self_attention.output" => + "deit.encoder.layer.{n}.attention.output.dense", + "encoder.blocks.{n}.ffn.intermediate" => "deit.encoder.layer.{n}.intermediate.dense", + "encoder.blocks.{n}.ffn.output" => "deit.encoder.layer.{n}.output.dense", + "encoder.blocks.{n}.output_norm" => "deit.encoder.layer.{n}.layernorm_after", + "norm" => "deit.layernorm", + "pooler.output" => "deit.pooler.dense", + "image_classification_head.output" => "classifier", + "image_classification_with_teacher_head.class_output" => "cls_classifier", + "image_classification_with_teacher_head.distillation_output" => "distillation_classifier", + "masked_image_modeling_head.output" => "decoder.0" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/vision/deit_featurizer.ex b/deps/bumblebee/lib/bumblebee/vision/deit_featurizer.ex new file mode 100644 index 0000000000000000000000000000000000000000..976479cf03ee353b7b559111b6c259304e82b20d --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/deit_featurizer.ex @@ -0,0 +1,143 @@ +defmodule Bumblebee.Vision.DeitFeaturizer do + alias Bumblebee.Shared + + options = [ + resize: [ + default: true, + doc: "whether to resize the input to the given `:size`" + ], + size: [ + default: %{height: 256, width: 256}, + doc: """ + the size to resize the input to, given as `%{height: ..., width: ...}`. Only has + an effect if `:resize` is `true` + """ + ], + resize_method: [ + default: :bicubic, + doc: + "the resizing method, either of `:nearest`, `:bilinear`, `:bicubic`, `:lanczos3`, `:lanczos5`" + ], + center_crop: [ + default: true, + doc: """ + whether to crop the input at the center. If the input size is smaller than `:crop_size` along + any edge, the image is padded with zeros and then center cropped + """ + ], + crop_size: [ + default: %{height: 224, width: 224}, + doc: """ + the size to center crop the image to, given as `%{height: ..., width: ...}`. Only has an effect + if `:center_crop` is `true` + """ + ], + normalize: [ + default: true, + doc: "whether or not to normalize the input with mean and standard deviation" + ], + image_mean: [ + default: [0.485, 0.456, 0.406], + doc: "the sequence of mean values for each channel, to be used when normalizing images" + ], + image_std: [ + default: [0.229, 0.224, 0.225], + doc: + "the sequence of standard deviations for each channel, to be used when normalizing images" + ] + ] + + @moduledoc """ + DeiT featurizer for image data. + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct Shared.option_defaults(options) + + @behaviour Bumblebee.Featurizer + @behaviour Bumblebee.Configurable + + alias Bumblebee.Utils.Image + + @impl true + def config(featurizer, opts) do + Shared.put_config_attrs(featurizer, opts) + end + + @impl true + def process_input(featurizer, images) do + images = List.wrap(images) + + for image <- images do + images = + image + |> Image.to_batched_tensor() + |> Nx.as_type(:f32) + |> Image.normalize_channels(length(featurizer.image_mean)) + + if featurizer.resize do + %{height: height, width: width} = featurizer.size + NxImage.resize(images, {height, width}, method: featurizer.resize_method) + else + images + end + end + |> Nx.concatenate() + end + + @impl true + def batch_template(featurizer, batch_size) do + %{height: height, width: width} = featurizer.size + num_channels = length(featurizer.image_mean) + Nx.template({batch_size, height, width, num_channels}, :f32) + end + + @impl true + def process_batch(featurizer, images) do + images = + if featurizer.center_crop do + %{height: height, width: width} = featurizer.crop_size + NxImage.center_crop(images, {height, width}) + else + images + end + + images = NxImage.to_continuous(images, 0, 1) + + images = + if featurizer.normalize do + NxImage.normalize( + images, + Nx.tensor(featurizer.image_mean), + Nx.tensor(featurizer.image_std) + ) + else + images + end + + %{"pixel_values" => images} + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(featurizer, data) do + import Shared.Converters + + opts = + convert!(data, + resize: {"do_resize", boolean()}, + size: {"size", image_size()}, + resize_method: {"resample", resize_method()}, + center_crop: {"do_center_crop", boolean()}, + crop_size: {"crop_size", image_size()}, + normalize: {"do_normalize", boolean()}, + image_mean: {"image_mean", list(number())}, + image_std: {"image_std", list(number())} + ) + + @for.config(featurizer, opts) + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/vision/dino_v2.ex b/deps/bumblebee/lib/bumblebee/vision/dino_v2.ex new file mode 100644 index 0000000000000000000000000000000000000000..07c945f0840ca2797d20399fec70e04e104e0fe4 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/dino_v2.ex @@ -0,0 +1,516 @@ +defmodule Bumblebee.Vision.DinoV2 do + alias Bumblebee.Shared + + options = + [ + image_size: [ + default: 518, + doc: """ + the size of the input spatial dimensions. The model is trained for this size, however + the model supports any other input size by interpolating position embeddings + """ + ], + num_channels: [ + default: 3, + doc: "the number of channels in the input" + ], + patch_size: [ + default: 14, + doc: "the size of the patch spatial dimensions" + ], + hidden_size: [ + default: 384, + doc: "the dimensionality of hidden layers" + ], + num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the encoder" + ], + num_attention_heads: [ + default: 12, + doc: "the number of attention heads for each attention layer in the encoder" + ], + intermediate_size_ratio: [ + default: 4, + doc: """ + the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder, + expressed as a multiplier of `:hidden_size` + """ + ], + use_attention_bias: [ + default: true, + doc: "whether to use bias in query, key, and value projections" + ], + activation: [ + default: :gelu, + doc: "the activation function" + ], + ffn_swiglu_activation: [ + default: false, + doc: + "whether to use the gated SwiGLU activation function in the feed-forward network (FFN)" + ], + scale_initial_value: [ + default: 1.0, + doc: "the initial value for scaling layers" + ], + dropout_rate: [ + default: 0.0, + doc: "the dropout rate for encoder and decoder" + ], + attention_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for attention weights" + ], + layer_norm_epsilon: [ + default: 1.0e-6, + doc: "the epsilon used by the layer normalization layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ], + backbone_output_indices: [ + default: nil, + doc: """ + list of indices indicating which feature maps to include in the output. If not specified, only + the last feature map is included + """ + ], + backbone_use_norm: [ + default: true, + doc: + "whether to add layer normalization layer to each of the feature maps returned by the backbone" + ] + ] ++ Shared.common_options([:num_labels, :id_to_label]) + + @moduledoc """ + DINOv2 model family. + + ## Architectures + + * `:base` - plain DINOv2 without any head on top + + * `:for_image_classification` - DINOv2 with head for image classification + + * `:backbone` - DINOv2 with feature maps output + + ## Inputs + + * `"pixel_values"` - `{batch_size, image_size, image_size, num_channels}` + + Featurized image pixel values. + + * `"patch_mask"` - `{batch_size, num_patches}` + + Mask to nullify selected embedded patches. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + + ## References + + * [DINOv2: Learning Robust Visual Features without Supervision](https://arxiv.org/abs/2304.07193) + + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), do: [:base, :backbone, :for_image_classification] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(spec) do + %{ + "pixel_values" => + Nx.template({1, spec.image_size, spec.image_size, spec.num_channels}, :f32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + hidden_state = + Axon.layer_norm(outputs.hidden_state, epsilon: spec.layer_norm_epsilon, name: "norm") + + pooled_state = Layers.take_token(hidden_state, index: 0, axis: 1) + + Layers.output(%{ + hidden_state: hidden_state, + pooled_state: pooled_state, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_image_classification} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + hidden_state = + Axon.layer_norm(outputs.hidden_state, epsilon: spec.layer_norm_epsilon, name: "norm") + + class_token = Layers.take_token(hidden_state, index: 0, axis: 1) + + patch_embeddings_mean = + Axon.nx(hidden_state, fn hidden_state -> + patch_embeddings = hidden_state[[.., 1..-1//1, ..]] + Nx.mean(patch_embeddings, axes: [1]) + end) + + logits = + Axon.concatenate(class_token, patch_embeddings_mean) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "image_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :backbone} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + feature_maps = feature_maps(outputs.hidden_states, inputs["pixel_values"], spec) + + Layers.output(%{ + feature_maps: feature_maps, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + defp inputs(spec) do + shape = {nil, nil, nil, spec.num_channels} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("pixel_values", shape: shape), + Axon.input("patch_mask", shape: {nil, nil}, optional: true) + ]) + end + + defp core(inputs, spec, opts \\ []) do + name = opts[:name] + + embeddings = + embedder(inputs["pixel_values"], inputs["patch_mask"], spec, name: join(name, "embedder")) + + encoder_outputs = encoder(embeddings, spec, name: join(name, "encoder")) + + %{ + hidden_state: encoder_outputs.hidden_state, + hidden_states: encoder_outputs.hidden_states, + attentions: encoder_outputs.attentions + } + end + + defp feature_maps(hidden_states, pixel_values, spec, opts \\ []) do + name = opts[:name] + + num_feature_maps = spec.num_blocks + 1 + output_indices = spec.backbone_output_indices || [num_feature_maps - 1] + + for index <- output_indices do + hidden_state = Axon.nx(hidden_states, &elem(&1, index)) + + hidden_state = + if spec.backbone_use_norm do + Axon.layer_norm(hidden_state, + epsilon: spec.layer_norm_epsilon, + name: join(name, "norm") + ) + else + hidden_state + end + + Axon.layer( + fn hidden_state, pixel_values, _opts -> + {batch_size, height, width, _channels} = Nx.shape(pixel_values) + + hidden_state = hidden_state[[.., 1..-1//1, ..]] + + Nx.reshape( + hidden_state, + {batch_size, div(height, spec.patch_size), div(width, spec.patch_size), :auto} + ) + end, + [hidden_state, pixel_values] + ) + end + |> List.to_tuple() + |> Axon.container() + end + + defp embedder(pixel_values, patch_mask, spec, opts) do + name = opts[:name] + + patch_embeddings = + pixel_values + |> patch_embedding(spec, name: join(name, "patch_embedding")) + |> Layers.apply_vision_patch_mask(patch_mask, name: join(name, "mask_tokens")) + + class_embedding = + Layers.learned_embeddings(1, spec.hidden_size, name: join(name, "class_embedding")) + + input_embeddings = Layers.concatenate_embeddings([class_embedding, patch_embeddings]) + + num_patches = div(spec.image_size, spec.patch_size) ** 2 + + position_embeddings = + Layers.learned_embeddings(num_patches + 1, spec.hidden_size, + initializer: :zeros, + name: join(name, "position_embedding") + ) + |> interpolate_position_embeddings(pixel_values, spec) + + Axon.add(input_embeddings, position_embeddings) + |> Axon.dropout(rate: spec.dropout_rate, name: join(name, "dropout")) + end + + defp patch_embedding(pixel_values, spec, opts) do + name = opts[:name] + + pixel_values + |> Axon.conv(spec.hidden_size, + kernel_size: spec.patch_size, + strides: spec.patch_size, + padding: :valid, + kernel_initializer: kernel_initializer(spec), + name: join(name, "projection") + ) + |> Axon.reshape({:batch, :auto, spec.hidden_size}, name: join(name, "reshape")) + end + + defp interpolate_position_embeddings(position_embeddings, pixel_values, spec) do + Axon.layer( + fn position_embeddings, pixel_values, _opts -> + original_positions = div(spec.image_size, spec.patch_size) + {batch_size, height, width, _channels} = Nx.shape(pixel_values) + resized_height = div(height, spec.patch_size) + resized_width = div(width, spec.patch_size) + + class_position_embedding = position_embeddings[[.., 0..0//1, ..]] + input_position_embeddings = position_embeddings[[.., 1..-1//1, ..]] + + interpolated_position_embeddings = + input_position_embeddings + |> Nx.reshape({batch_size, original_positions, original_positions, spec.hidden_size}) + |> Axon.Layers.resize( + size: {resized_height, resized_width}, + method: :bicubic, + antialias: false + ) + |> Nx.reshape({batch_size, :auto, spec.hidden_size}) + + Nx.concatenate([class_position_embedding, interpolated_position_embeddings], axis: 1) + end, + [position_embeddings, pixel_values], + op_name: :interpolate_position_embeddings + ) + end + + defp encoder(hidden_state, spec, opts) do + name = opts[:name] + + ffn = + if spec.ffn_swiglu_activation do + intermediate_size = + div(floor(floor(spec.hidden_size * spec.intermediate_size_ratio) * 2 / 3 + 7), 8) * 8 + + &ffn_swiglu(&1, intermediate_size, spec.hidden_size, name: &2) + else + intermediate_size = floor(spec.hidden_size * spec.intermediate_size_ratio) + + [ + intermediate_size: intermediate_size, + activation: spec.activation + ] + end + + Layers.Transformer.blocks(hidden_state, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + query_use_bias: spec.use_attention_bias, + key_use_bias: spec.use_attention_bias, + value_use_bias: spec.use_attention_bias, + layer_norm: [ + epsilon: spec.layer_norm_epsilon + ], + ffn: ffn, + block_type: &block_impl(&1, &2, &3, spec), + name: join(name, "blocks") + ) + end + + # A feed-forward network with SwiGLU nonlinearity as in https://arxiv.org/abs/2002.05202 + defp ffn_swiglu(x, intermediate_size, output_size, opts) do + name = opts[:name] + dropout = opts[:dropout] || 0.0 + + {gate, x} = + x + |> Axon.dense(intermediate_size * 2, name: join(name, "intermediate")) + |> Axon.split(2, axis: -1) + + x = Axon.multiply(x, Axon.silu(gate)) + + x + |> Axon.dropout(rate: dropout, name: join(name, "dropout")) + |> Axon.dense(output_size, name: join(name, "output")) + end + + # :norm_first block with additional scaling layers + defp block_impl(hidden_state, steps, name, spec) do + shortcut = hidden_state + + {hidden_state, attention_info} = + hidden_state + |> steps.self_attention_norm.() + |> steps.self_attention.() + + hidden_state = + hidden_state + |> Bumblebee.Layers.scale( + scale_initializer: Axon.Initializers.full(spec.scale_initial_value), + name: join(name, "self_attention_scale") + ) + |> Axon.add(shortcut) + + {_hidden_state, cross_attention_info} = + steps.cross_attention_maybe.(hidden_state, fn _hidden_state -> + raise "cross attention not supported" + end) + + shortcut = hidden_state + + hidden_state = + hidden_state + |> steps.output_norm.() + |> steps.ffn.() + |> Bumblebee.Layers.scale( + scale_initializer: Axon.Initializers.full(spec.scale_initial_value), + name: join(name, "output_scale") + ) + |> Axon.add(shortcut) + + {hidden_state, attention_info, cross_attention_info} + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + image_size: {"image_size", number()}, + num_channels: {"num_channels", number()}, + patch_size: {"patch_size", number()}, + hidden_size: {"hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_attention_heads: {"num_attention_heads", number()}, + intermediate_size_ratio: {"mlp_ratio", number()}, + activation: {"hidden_act", activation()}, + use_attention_bias: {"qkv_bias", boolean()}, + dropout_rate: {"hidden_dropout_prob", number()}, + attention_dropout_rate: {"attention_probs_dropout_prob", number()}, + layer_norm_epsilon: {"layer_norm_eps", number()}, + initializer_scale: {"initializer_range", number()}, + scale_initial_value: {"layerscale_value", number()}, + ffn_swiglu_activation: {"use_swiglu_ffn", boolean()}, + backbone_output_indices: {"out_indices", list(number())}, + backbone_use_norm: {"use_backbone_norm", boolean()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(spec) do + %{ + "embedder.patch_embedding.projection" => "dinov2.embeddings.patch_embeddings.projection", + "embedder.class_embedding" => %{ + "embeddings" => { + [{"dinov2.embeddings", "cls_token"}], + fn [value] -> Nx.squeeze(value, axes: [0]) end + } + }, + "embedder.position_embedding" => %{ + "embeddings" => { + [{"dinov2.embeddings", "position_embeddings"}], + fn [value] -> Nx.squeeze(value, axes: [0]) end + } + }, + "encoder.blocks.{n}.self_attention_norm" => "dinov2.encoder.layer.{n}.norm1", + "encoder.blocks.{n}.self_attention.key" => + "dinov2.encoder.layer.{n}.attention.attention.key", + "encoder.blocks.{n}.self_attention.query" => + "dinov2.encoder.layer.{n}.attention.attention.query", + "encoder.blocks.{n}.self_attention.value" => + "dinov2.encoder.layer.{n}.attention.attention.value", + "encoder.blocks.{n}.self_attention.output" => + "dinov2.encoder.layer.{n}.attention.output.dense", + "encoder.blocks.{n}.self_attention_scale" => %{ + "scale" => { + [{"dinov2.encoder.layer.{n}.layer_scale1", "lambda1"}], + fn [lambda1] -> lambda1 end + } + }, + "encoder.blocks.{n}.ffn.intermediate" => + if(spec.ffn_swiglu_activation, + do: "dinov2.encoder.layer.{n}.mlp.weights_in", + else: "dinov2.encoder.layer.{n}.mlp.fc1" + ), + "encoder.blocks.{n}.ffn.output" => + if(spec.ffn_swiglu_activation, + do: "dinov2.encoder.layer.{n}.mlp.weights_out", + else: "dinov2.encoder.layer.{n}.mlp.fc2" + ), + "encoder.blocks.{n}.output_norm" => "dinov2.encoder.layer.{n}.norm2", + "encoder.blocks.{n}.output_scale" => %{ + "scale" => { + [{"dinov2.encoder.layer.{n}.layer_scale2", "lambda1"}], + fn [lambda1] -> lambda1 end + } + }, + "norm" => "dinov2.layernorm", + "image_classification_head.output" => "classifier" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/vision/image_classification.ex b/deps/bumblebee/lib/bumblebee/vision/image_classification.ex new file mode 100644 index 0000000000000000000000000000000000000000..79fa936c0e2f7510d728469005571e02d06d50dc --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/image_classification.ex @@ -0,0 +1,88 @@ +defmodule Bumblebee.Vision.ImageClassification do + @moduledoc false + + alias Bumblebee.Shared + + def image_classification(model_info, featurizer, opts \\ []) do + %{model: model, params: params, spec: spec} = model_info + + Shared.validate_architecture!(spec, [ + :for_image_classification, + :for_image_classification_with_teacher + ]) + + opts = + Keyword.validate!(opts, [ + :compile, + top_k: 5, + scores_function: :softmax, + defn_options: [], + preallocate_params: false + ]) + + top_k = opts[:top_k] + scores_function = opts[:scores_function] + preallocate_params = opts[:preallocate_params] + defn_options = opts[:defn_options] + + compile = + if compile = opts[:compile] do + compile + |> Keyword.validate!([:batch_size]) + |> Shared.require_options!([:batch_size]) + end + + batch_size = compile[:batch_size] + + {_init_fun, predict_fun} = Axon.build(model) + + scores_fun = fn params, input -> + input = Bumblebee.Featurizer.process_batch(featurizer, input) + outputs = predict_fun.(params, input) + scores = Shared.logits_to_scores(outputs.logits, scores_function) + k = min(top_k, Nx.axis_size(scores, 1)) + {top_scores, top_indices} = Nx.top_k(scores, k: k) + {top_scores, top_indices} + end + + Nx.Serving.new( + fn defn_options -> + params = Shared.maybe_preallocate(params, preallocate_params, defn_options) + + scores_fun = + Shared.compile_or_jit(scores_fun, :scores, defn_options, compile != nil, fn -> + inputs = Bumblebee.Featurizer.batch_template(featurizer, batch_size) + [params, inputs] + end) + + fn inputs -> + inputs = Shared.maybe_pad(inputs, batch_size) + scores_fun.(params, inputs) |> Shared.serving_post_computation() + end + end, + defn_options + ) + |> Nx.Serving.batch_size(batch_size) + |> Nx.Serving.client_preprocessing(fn input -> + {images, multi?} = Shared.validate_serving_input!(input, &Shared.validate_image/1) + inputs = Bumblebee.Featurizer.process_input(featurizer, images) + {Nx.Batch.concatenate([inputs]), multi?} + end) + |> Nx.Serving.client_postprocessing(fn {{top_scores, top_indices}, _metadata}, multi? -> + Enum.zip_with( + Nx.to_list(top_scores), + Nx.to_list(top_indices), + fn top_scores, top_indices -> + predictions = + Enum.zip_with(top_scores, top_indices, fn score, idx -> + label = spec.id_to_label[idx] || "LABEL_#{idx}" + %{score: score, label: label} + end) + + %{predictions: predictions} + end + ) + |> Shared.normalize_output(multi?) + end) + end +end diff --git a/deps/bumblebee/lib/bumblebee/vision/image_embedding.ex b/deps/bumblebee/lib/bumblebee/vision/image_embedding.ex new file mode 100644 index 0000000000000000000000000000000000000000..345ac14e7db03af42e2d877cefa8e2a8109f1e89 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/image_embedding.ex @@ -0,0 +1,103 @@ +defmodule Bumblebee.Vision.ImageEmbedding do + @moduledoc false + + alias Bumblebee.Shared + + def image_embedding(model_info, featurizer, opts \\ []) do + %{model: model, params: params} = model_info + + opts = + Keyword.validate!(opts, [ + :compile, + output_attribute: :pooled_state, + embedding_processor: nil, + defn_options: [], + preallocate_params: false + ]) + + output_attribute = opts[:output_attribute] + embedding_processor = opts[:embedding_processor] + preallocate_params = opts[:preallocate_params] + defn_options = opts[:defn_options] + + compile = + if compile = opts[:compile] do + compile + |> Keyword.validate!([:batch_size]) + |> Shared.require_options!([:batch_size]) + end + + batch_size = compile[:batch_size] + + {_init_fun, encoder} = Axon.build(model) + + embedding_fun = fn params, inputs -> + inputs = Bumblebee.Featurizer.process_batch(featurizer, inputs) + + output = encoder.(params, inputs) + + output = + case output do + %{^output_attribute => output} -> + output + + %{} -> + keys = output |> Map.keys() |> Enum.sort() + + raise ArgumentError, + "key #{inspect(output_attribute)} not found in the output map," <> + " you may want to set :output_attribute to one of the map keys: #{inspect(keys)}" + + _ -> + output + end + + output = + case embedding_processor do + nil -> + output + + :l2_norm -> + Bumblebee.Utils.Nx.normalize(output) + + other -> + raise ArgumentError, + "expected :embedding_processor to be one of nil or :l2_norm, got: #{inspect(other)}" + end + + output + end + + Nx.Serving.new( + fn defn_options -> + params = Shared.maybe_preallocate(params, preallocate_params, defn_options) + + embedding_fun = + Shared.compile_or_jit(embedding_fun, :embedding, defn_options, compile != nil, fn -> + inputs = Bumblebee.Featurizer.batch_template(featurizer, batch_size) + [params, inputs] + end) + + fn inputs -> + inputs = Shared.maybe_pad(inputs, batch_size) + embedding_fun.(params, inputs) |> Shared.serving_post_computation() + end + end, + defn_options + ) + |> Nx.Serving.batch_size(batch_size) + |> Nx.Serving.client_preprocessing(fn input -> + {images, multi?} = Shared.validate_serving_input!(input, &Shared.validate_image/1) + + inputs = Bumblebee.Featurizer.process_input(featurizer, images) + + {Nx.Batch.concatenate([inputs]), multi?} + end) + |> Nx.Serving.client_postprocessing(fn {embeddings, _metadata}, multi? -> + for embedding <- Bumblebee.Utils.Nx.batch_to_list(embeddings) do + %{embedding: embedding} + end + |> Shared.normalize_output(multi?) + end) + end +end diff --git a/deps/bumblebee/lib/bumblebee/vision/image_to_text.ex b/deps/bumblebee/lib/bumblebee/vision/image_to_text.ex new file mode 100644 index 0000000000000000000000000000000000000000..055e13a350a2061a8e6db3b315eb008c9d2543ae --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/image_to_text.ex @@ -0,0 +1,87 @@ +defmodule Bumblebee.Vision.ImageToText do + @moduledoc false + + alias Bumblebee.Shared + alias Bumblebee.Text + + def image_to_text( + model_info, + featurizer, + tokenizer, + %Text.GenerationConfig{} = generation_config, + opts \\ [] + ) do + opts = Keyword.validate!(opts, [:compile, defn_options: [], preallocate_params: false]) + + %{model: model, params: params, spec: spec} = model_info + + Shared.validate_architecture!(spec, [:for_conditional_generation]) + + preallocate_params = opts[:preallocate_params] + defn_options = opts[:defn_options] + + compile = + if compile = opts[:compile] do + compile + |> Keyword.validate!([:batch_size]) + |> Shared.require_options!([:batch_size]) + end + + batch_size = compile[:batch_size] + + generate_fun = Text.Generation.build_generate(model, spec, generation_config) + + generate_fun = fn params, {inputs, seed} -> + inputs = Bumblebee.Featurizer.process_batch(featurizer, inputs) + inputs = Map.put(inputs, "seed", seed) + %{token_ids: token_ids} = generate_fun.(params, inputs) + token_ids + end + + Nx.Serving.new( + fn defn_options -> + params = Shared.maybe_preallocate(params, preallocate_params, defn_options) + + generate_fun = + Shared.compile_or_jit(generate_fun, :generate, defn_options, compile != nil, fn -> + inputs = Bumblebee.Featurizer.batch_template(featurizer, batch_size) + seed = Nx.template({batch_size}, :s64) + [params, {inputs, seed}] + end) + + fn inputs -> + inputs = Shared.maybe_pad(inputs, batch_size) + generate_fun.(params, inputs) |> Shared.serving_post_computation() + end + end, + defn_options + ) + |> Nx.Serving.batch_size(batch_size) + |> Nx.Serving.client_preprocessing(fn input -> + {inputs, multi?} = Shared.validate_serving_input!(input, &validate_input/1) + + images = Enum.map(inputs, & &1.image) + seed = Enum.map(inputs, & &1.seed) |> Nx.tensor(type: :s64, backend: Nx.BinaryBackend) + + inputs = Bumblebee.Featurizer.process_input(featurizer, images) + {Nx.Batch.concatenate([{inputs, seed}]), multi?} + end) + |> Nx.Serving.client_postprocessing(fn {token_ids, _metadata}, multi? -> + decoded = Bumblebee.Tokenizer.decode(tokenizer, token_ids) + + decoded + |> Enum.map(&%{results: [%{text: &1}]}) + |> Shared.normalize_output(multi?) + end) + end + + defp validate_input(%{image: image} = input) do + if Shared.image?(image) do + {:ok, %{image: image, seed: input[:seed] || :erlang.system_time()}} + else + {:error, "expected an image, got: #{inspect(image)}"} + end + end + + defp validate_input(input), do: validate_input(%{image: input}) +end diff --git a/deps/bumblebee/lib/bumblebee/vision/resnet.ex b/deps/bumblebee/lib/bumblebee/vision/resnet.ex new file mode 100644 index 0000000000000000000000000000000000000000..674e30512b916b88e6a9f74bfbc847f3e9380132 --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/resnet.ex @@ -0,0 +1,345 @@ +defmodule Bumblebee.Vision.ResNet do + alias Bumblebee.Shared + + options = + [ + num_channels: [ + default: 3, + doc: "the number of channels in the input" + ], + embedding_size: [ + default: 64, + doc: "the dimensionality of the embedding layer" + ], + hidden_sizes: [ + default: [256, 512, 1024, 2048], + doc: "the dimensionality of hidden layers at each stage" + ], + depths: [ + default: [3, 4, 6, 3], + doc: "the depth (number of residual blocks) at each stage" + ], + residual_block_type: [ + default: :bottleneck, + doc: """ + the residual block to use, either `:basic` (used for smaller models, like ResNet-18 or ResNet-34) + or `:bottleneck` (used for larger models like ResNet-50 and above) + """ + ], + activation: [ + default: :relu, + doc: "the activation function" + ], + downsample_in_first_stage: [ + default: false, + doc: "whether the first stage should downsample the inputs using a stride of 2" + ] + ] ++ Shared.common_options([:num_labels, :id_to_label]) + + @moduledoc """ + ResNet model family. + + ## Architectures + + * `:base` - plain ResNet without any head on top + + * `:for_image_classification` - ResNet with a classification head. + The head consists of a single dense layer on top of the pooled + features and it returns logits corresponding to possible classes + + ## Inputs + + * `"pixel_values"` - {batch_size, height, width, num_channels} + + Featurized image pixel values (224x224). + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states])} + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), do: [:base, :for_image_classification] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(spec) do + %{ + "pixel_values" => Nx.template({1, 224, 224, spec.num_channels}, :f32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + spec + |> core() + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_image_classification} = spec) do + outputs = core(spec) + + logits = + Axon.dense(outputs.pooled_state, spec.num_labels, name: "image_classification_head.output") + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states + }) + end + + defp core(spec, opts \\ []) do + name = opts[:name] + + input = Axon.input("pixel_values", shape: {nil, 224, 224, spec.num_channels}) + + encoder_outputs = + input + |> embedder(spec, name: join(name, "embedder")) + |> encoder(spec, name: join(name, "encoder")) + + pooled_output = + encoder_outputs.hidden_state + |> Axon.adaptive_avg_pool( + output_size: {1, 1}, + name: join(name, "pooler") + ) + |> Axon.flatten() + + %{ + hidden_state: encoder_outputs.hidden_state, + pooled_state: pooled_output, + hidden_states: encoder_outputs.hidden_states + } + end + + defp embedder(pixel_values, spec, opts) do + name = opts[:name] + + pixel_values + |> conv_block(spec.embedding_size, + kernel_size: 7, + strides: 2, + activation: spec.activation, + name: join(name, "conv_block") + ) + |> Axon.max_pool( + kernel_size: 3, + strides: 2, + padding: [{1, 1}, {1, 1}], + name: join(name, "pooler") + ) + end + + defp encoder(hidden_state, spec, opts) do + name = opts[:name] + + stages = spec.hidden_sizes |> Enum.zip(spec.depths) |> Enum.with_index() + + state = %{ + hidden_state: hidden_state, + hidden_states: Axon.container({hidden_state}), + in_channels: spec.embedding_size + } + + for {{size, depth}, idx} <- stages, reduce: state do + state -> + strides = if idx == 0 and not spec.downsample_in_first_stage, do: 1, else: 2 + + hidden_state = + stage(state.hidden_state, state.in_channels, size, spec, + depth: depth, + strides: strides, + name: join(name, "stages.#{idx}") + ) + + %{ + hidden_state: hidden_state, + hidden_states: Layers.append(state.hidden_states, hidden_state), + in_channels: size + } + end + end + + defp stage(hidden_state, in_channels, out_channels, spec, opts) do + opts = Keyword.validate!(opts, [:name, strides: 2, depth: 2]) + name = opts[:name] + strides = opts[:strides] + depth = opts[:depth] + + residual_block = + case spec.residual_block_type do + :basic -> &basic_residual_block/4 + :bottleneck -> &bottleneck_residual_block/4 + end + + # Downsampling is done in the first block with stride of 2 + hidden_state = + residual_block.(hidden_state, in_channels, out_channels, + strides: strides, + activation: spec.activation, + name: join(name, "blocks.0") + ) + + for idx <- 1..(depth - 1)//1, reduce: hidden_state do + hidden_state -> + residual_block.(hidden_state, out_channels, out_channels, + activation: spec.activation, + name: join(name, "blocks.#{idx}") + ) + end + end + + defp basic_residual_block(hidden_state, in_channels, out_channels, opts) do + opts = Keyword.validate!(opts, [:name, strides: 1, activation: :relu]) + name = opts[:name] + strides = opts[:strides] + activation = opts[:activation] + + shortcut = + shortcut(hidden_state, in_channels, out_channels, + strides: strides, + name: join(name, "shortcut") + ) + + hidden_state + |> conv_block(out_channels, strides: strides, name: join(name, "conv_blocks.0")) + |> conv_block(out_channels, activation: :linear, name: join(name, "conv_blocks.1")) + |> Axon.add(shortcut) + |> Axon.activation(activation, name: join(name, "activation")) + end + + defp bottleneck_residual_block(hidden_state, in_channels, out_channels, opts) do + opts = Keyword.validate!(opts, [:name, strides: 1, activation: :relu, reduction: 4]) + name = opts[:name] + strides = opts[:strides] + activation = opts[:activation] + reduction = opts[:reduction] + + shortcut = + shortcut(hidden_state, in_channels, out_channels, + strides: strides, + name: join(name, "shortcut") + ) + + reduced_channels = div(out_channels, reduction) + + hidden_state + |> conv_block(reduced_channels, kernel_size: 1, name: join(name, "conv_blocks.0")) + |> conv_block(reduced_channels, strides: strides, name: join(name, "conv_blocks.1")) + |> conv_block(out_channels, + kernel_size: 1, + activation: :linear, + name: join(name, "conv_blocks.2") + ) + |> Axon.add(shortcut) + |> Axon.activation(activation, name: join(name, "activation")) + end + + defp shortcut(hidden_state, in_channels, out_channels, opts) do + opts = Keyword.validate!(opts, [:name, strides: 2]) + name = opts[:name] + strides = opts[:strides] + + # If the output shape doesn't match input shape, we need to project + # the shortcut connection + project_shortcut? = in_channels != out_channels or strides != 1 + + if project_shortcut? do + hidden_state + |> Axon.conv(out_channels, + kernel_size: 1, + strides: strides, + use_bias: false, + kernel_initializer: conv_kernel_initializer(), + name: join(name, "projection") + ) + |> Axon.batch_norm(gamma_initializer: :ones, name: join(name, "norm")) + else + hidden_state + end + end + + defp conv_block(hidden_state, out_channels, opts) do + opts = Keyword.validate!(opts, [:name, kernel_size: 3, strides: 1, activation: :relu]) + name = opts[:name] + kernel_size = opts[:kernel_size] + strides = opts[:strides] + activation = opts[:activation] + + edge_padding = div(kernel_size, 2) + padding_spec = [{edge_padding, edge_padding}, {edge_padding, edge_padding}] + + hidden_state + |> Axon.conv(out_channels, + kernel_size: kernel_size, + strides: strides, + padding: padding_spec, + use_bias: false, + kernel_initializer: conv_kernel_initializer(), + name: join(name, "conv") + ) + |> Axon.batch_norm(gamma_initializer: :ones, name: join(name, "norm")) + |> Axon.activation(activation, name: join(name, "activation")) + end + + defp conv_kernel_initializer() do + Axon.Initializers.variance_scaling(scale: 2.0, mode: :fan_out, distribution: :normal) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + num_channels: {"num_channels", number()}, + embedding_size: {"embedding_size", number()}, + hidden_sizes: {"hidden_sizes", list(number())}, + depths: {"depths", list(number())}, + residual_block_type: {"layer_type", atom()}, + activation: {"hidden_act", activation()}, + downsample_in_first_stage: {"downsample_in_first_stage", boolean()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.conv_block.conv" => "resnet.embedder.embedder.convolution", + "embedder.conv_block.norm" => "resnet.embedder.embedder.normalization", + "encoder.stages.{n}.blocks.{m}.conv_blocks.{l}.conv" => + "resnet.encoder.stages.{n}.layers.{m}.layer.{l}.convolution", + "encoder.stages.{n}.blocks.{m}.conv_blocks.{l}.norm" => + "resnet.encoder.stages.{n}.layers.{m}.layer.{l}.normalization", + "encoder.stages.{n}.blocks.{m}.shortcut.projection" => + "resnet.encoder.stages.{n}.layers.{m}.shortcut.convolution", + "encoder.stages.{n}.blocks.{m}.shortcut.norm" => + "resnet.encoder.stages.{n}.layers.{m}.shortcut.normalization", + "image_classification_head.output" => "classifier.1" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/vision/swin.ex b/deps/bumblebee/lib/bumblebee/vision/swin.ex new file mode 100644 index 0000000000000000000000000000000000000000..42da43ca4681d63f19777ea6d647c027bd1c5d6c --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/swin.ex @@ -0,0 +1,660 @@ +defmodule Bumblebee.Vision.Swin do + alias Bumblebee.Shared + + options = + [ + image_size: [ + default: 224, + doc: "the size of the input spatial dimensions" + ], + num_channels: [ + default: 3, + doc: "the number of channels in the input" + ], + patch_size: [ + default: 4, + doc: "the size of the patch spatial dimensions" + ], + embedding_size: [ + default: 96, + doc: "the dimensionality of patch embedding layer" + ], + use_absolute_position_embeddings: [ + default: false, + doc: "whether to add absolute position embeddings to the patch embeddings" + ], + num_blocks: [ + default: [2, 2, 6, 2], + doc: "the number of Transformer blocks in the encoder at each stage" + ], + num_attention_heads: [ + default: [3, 6, 12, 24], + doc: "the number of attention heads for each attention layer in the encoder at each stage" + ], + window_size: [ + default: 7, + doc: + "the window size, used to limit self-attention computation to non-overlapping windows" + ], + intermediate_size_ratio: [ + default: 4, + doc: """ + the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder, + expressed as a multiplier of hidden size (at the given stage) + """ + ], + use_attention_bias: [ + default: true, + doc: "whether to use bias in query, key, and value projections" + ], + activation: [ + default: :gelu, + doc: "the activation function" + ], + dropout_rate: [ + default: 0.0, + doc: "the dropout rate for encoder and decoder" + ], + attention_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for attention weights" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ], + drop_path_rate: [ + default: 0.1, + doc: "the drop path rate used to for stochastic depth" + ], + layer_norm_epsilon: [ + default: 1.0e-5, + doc: "the epsilon used by the layer normalization layers" + ] + ] ++ Shared.common_options([:num_labels, :id_to_label]) + + @moduledoc """ + Swin Transformer model. + + ## Architectures + + * `:base` - plain Swin without any head on top + + * `:for_image_classification` - Swin tranformer model with a + classification head + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + + ## References + + * [Swin Transformer: Hierarchical Vision Transformer using Shifted Windows](https://arxiv.org/abs/2103.14030) + + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + import Bumblebee.Utils.Model, only: [join: 2] + import Nx.Defn + + alias Bumblebee.Layers + + @impl true + def architectures(), do: [:base, :for_image_classification] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(spec) do + %{ + "pixel_values" => + Nx.template({1, spec.image_size, spec.image_size, spec.num_channels}, :f32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + spec + |> inputs() + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_image_classification} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + Axon.dense(outputs.pooled_state, spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "image_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + defp inputs(spec) do + shape = {nil, spec.image_size, spec.image_size, spec.num_channels} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("pixel_values", shape: shape), + Axon.input("patch_mask", shape: {nil, nil}, optional: true) + ]) + end + + defp core(inputs, spec, opts \\ []) do + name = opts[:name] + + embeddings = + embedder(inputs["pixel_values"], inputs["patch_mask"], spec, name: join(name, "embedder")) + + encoder_outputs = + encoder(embeddings, spec, name: join(name, "encoder")) + + hidden_state = + Axon.layer_norm(encoder_outputs.hidden_state, + epsilon: spec.layer_norm_epsilon, + name: join(name, "norm") + ) + + pooled_state = + hidden_state + |> Axon.adaptive_avg_pool(output_size: {1}, name: join(name, "pooler")) + |> Axon.flatten() + + %{ + hidden_state: hidden_state, + pooled_state: pooled_state, + hidden_states: encoder_outputs.hidden_states, + attentions: encoder_outputs.attentions + } + end + + defp embedder(pixel_values, patch_mask, spec, opts) do + name = opts[:name] + + embeddings = + pixel_values + |> patch_embedding(spec, name: join(name, "patch_embedding")) + |> Layers.apply_vision_patch_mask(patch_mask, name: join(name, "mask_tokens")) + |> Axon.layer_norm(epsilon: spec.layer_norm_epsilon, name: join(name, "norm")) + + embeddings = + if spec.use_absolute_position_embeddings do + num_patches = div(spec.image_size, spec.patch_size) ** 2 + + position_embeddings = + Layers.learned_embeddings(num_patches, spec.embedding_size, + initializer: :zeros, + name: join(name, "position_embedding") + ) + + Axon.add(embeddings, position_embeddings) + else + embeddings + end + + embeddings + |> Axon.dropout(rate: spec.dropout_rate, name: join(name, "dropout")) + end + + defp patch_embedding(pixel_values, spec, opts) do + name = opts[:name] + hidden_size = spec.embedding_size + + pixel_values + |> Axon.conv(hidden_size, + kernel_size: spec.patch_size, + strides: spec.patch_size, + padding: :valid, + kernel_initializer: kernel_initializer(spec), + name: join(name, "projection") + ) + |> Axon.reshape({:batch, :auto, spec.embedding_size}, name: join(name, "reshape")) + end + + defp encoder(hidden_state, spec, opts) do + name = opts[:name] + + state = %{ + hidden_state: hidden_state, + hidden_states: Axon.container({hidden_state}), + attentions: Axon.container({}) + } + + for stage_idx <- 0..(length(spec.num_blocks) - 1), reduce: state do + state -> + name = name |> join("stages") |> join(stage_idx) + + grid_size = div(spec.image_size, spec.patch_size) + input_resolution = div(grid_size, 2 ** stage_idx) + + {hidden_state, attention, hidden_state_before_downsample} = + stage(state.hidden_state, spec, + hidden_size: spec.embedding_size * 2 ** stage_idx, + num_blocks: Enum.at(spec.num_blocks, stage_idx), + num_attention_heads: Enum.at(spec.num_attention_heads, stage_idx), + downsample: stage_idx < length(spec.num_blocks) - 1, + input_resolution: input_resolution, + name: name + ) + + %{ + hidden_state: hidden_state, + hidden_states: Layers.append(state.hidden_states, hidden_state_before_downsample), + attentions: Layers.append(state.attentions, attention) + } + end + end + + defp stage(hidden_state, spec, opts) do + name = opts[:name] + downsample = opts[:downsample] + hidden_size = opts[:hidden_size] + num_blocks = opts[:num_blocks] + num_attention_heads = opts[:num_attention_heads] + input_resolution = opts[:input_resolution] + + # Note that we include only record hidden_state and attention + # from the last block in each stage + + {hidden_state, attention} = + for block_idx <- 0..(num_blocks - 1), reduce: {hidden_state, nil} do + {hidden_state, _attention} -> + name = name |> join("blocks") |> join(block_idx) + + shift_size = + if rem(block_idx, 2) == 0 do + 0 + else + div(spec.window_size, 2) + end + + {hidden_state, attention} = + transformer_block(hidden_state, + num_attention_heads: num_attention_heads, + hidden_size: hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + layer_norm_epsilon: spec.layer_norm_epsilon, + intermediate_size: floor(spec.intermediate_size_ratio * hidden_size), + activation: spec.activation, + name: name, + window_size: spec.window_size, + shift_size: shift_size, + input_resolution: input_resolution + ) + + {hidden_state, attention} + end + + hidden_state_before_downsample = hidden_state + + hidden_state = + if downsample do + patch_merging(hidden_state, + input_resolution: input_resolution, + hidden_size: hidden_size, + layer_norm_epsilon: spec.layer_norm_epsilon, + kernel_initializer: kernel_initializer(spec), + name: join(name, "downsample") + ) + else + hidden_state + end + + {hidden_state, attention, hidden_state_before_downsample} + end + + defp transformer_block(hidden_state, opts) do + num_attention_heads = opts[:num_attention_heads] + hidden_size = opts[:hidden_size] + kernel_initializer = opts[:kernel_initializer] + dropout_rate = opts[:dropout_rate] + attention_dropout_rate = opts[:attention_dropout_rate] + layer_norm_epsilon = opts[:layer_norm_epsilon] + intermediate_size = opts[:intermediate_size] + activation = opts[:activation] + name = opts[:name] + window_size = opts[:window_size] + shift_size = opts[:shift_size] + input_resolution = opts[:input_resolution] + + {shift_size, window_size} = + if input_resolution <= window_size do + {0, input_resolution} + else + {shift_size, window_size} + end + + shortcut = hidden_state + + attention_mask = + window_attention_mask(hidden_state, shift_size, window_size, input_resolution) + + relative_attention_bias = + relative_attention_bias(window_size, num_attention_heads, + name: join(name, "self_attention.relative_attention_bias") + ) + + hidden_state = + hidden_state + |> Axon.layer_norm(epsilon: layer_norm_epsilon, name: join(name, "self_attention_norm")) + |> hidden_state_windows(shift_size, window_size, input_resolution) + + {hidden_state, attention, _self_attention_cache, _attention_relative_bias} = + Layers.Transformer.multi_head_attention(hidden_state, hidden_state, hidden_state, + attention_mask: attention_mask, + attention_relative_bias: relative_attention_bias, + num_heads: num_attention_heads, + hidden_size: hidden_size, + kernel_initializer: kernel_initializer, + dropout_rate: attention_dropout_rate, + name: join(name, "self_attention") + ) + + hidden_state = + Axon.dropout(hidden_state, rate: dropout_rate, name: join(name, "self_attention_dropout")) + + hidden_state = + hidden_state + |> reverse_hidden_state_windows(shift_size, window_size, input_resolution) + |> Axon.dropout(rate: dropout_rate) + + hidden_state = Axon.add(hidden_state, shortcut) + + shortcut = hidden_state + + hidden_state = + hidden_state + |> Axon.layer_norm(epsilon: layer_norm_epsilon, name: join(name, "output_norm")) + |> Axon.dense(intermediate_size, name: join(name, "ffn.intermediate")) + |> Layers.activation(activation) + |> Axon.dense(hidden_size, name: join(name, "ffn.output")) + |> Axon.dropout(rate: dropout_rate) + + hidden_state = Axon.add(hidden_state, shortcut) + + {hidden_state, attention} + end + + defp window_attention_mask(hidden_state, shift_size, window_size, input_resolution) do + if shift_size > 0 do + # Computes attention mask for shifted window multi-head self-attention (SW-MSA) + + Axon.nx(hidden_state, fn hidden_state -> + {batch_size, _dimension, _hidden_size} = Nx.shape(hidden_state) + height = width = input_resolution + + # See Figure 4. in the paper. We color the 2D patches (tokens) + # into 4 groups. Then, we compute a mask such that each token + # attends only to tokens within the same group. + + grid_0 = Nx.broadcast(0, {height - shift_size, width - shift_size}) + grid_b = Nx.broadcast(1, {height - shift_size, shift_size}) + grid_c = Nx.broadcast(2, {shift_size, width - shift_size}) + grid_a = Nx.broadcast(3, {shift_size, shift_size}) + + grid = + Nx.concatenate([ + Nx.concatenate([grid_0, grid_b], axis: 1), + Nx.concatenate([grid_c, grid_a], axis: 1) + ]) + + windowed_patch_groups = + grid + |> Nx.reshape({1, height, width, 1}) + |> window_partition(window_size) + |> Nx.reshape({:auto, window_size * window_size}) + + windows_attention_mask = + Nx.equal( + Nx.new_axis(windowed_patch_groups, 1), + Nx.new_axis(windowed_patch_groups, 2) + ) + |> Nx.new_axis(1) + + # Note that we repeat the mask for each batched input, so that + # the batch dimension has size batch_size * num_windows, which + # matches the input. This way we can apply the mask as usual, + # without reshaping back and forth. + Nx.tile(windows_attention_mask, [batch_size, 1, 1, 1]) + end) + else + Layers.none() + end + end + + defp relative_attention_bias(window_size, num_attention_heads, opts) do + name = opts[:name] + + kernel = + Axon.param("kernel", {(2 * window_size - 1) * (2 * window_size - 1), num_attention_heads}) + + Axon.layer( + fn kernel, opts -> + window_size = opts[:window_size] + + idx = relative_position_index(window_size) |> Nx.reshape({:auto}) + + kernel + |> Nx.take(idx) + |> Nx.reshape({window_size * window_size, window_size * window_size, :auto}) + |> Nx.transpose(axes: [2, 0, 1]) + |> Nx.new_axis(0) + end, + [kernel], + window_size: window_size, + name: name + ) + end + + defp relative_position_index(window_size) do + coords_h = Nx.iota({window_size, window_size}, axis: 0) |> Nx.flatten() + coords_w = Nx.iota({window_size, window_size}, axis: 1) |> Nx.flatten() + coord_pairs = Nx.stack([coords_h, coords_w]) + + relative_coords = Nx.subtract(Nx.new_axis(coord_pairs, 2), Nx.new_axis(coord_pairs, 1)) + + relative_coords + |> Nx.add(Nx.reshape(Nx.tensor([window_size - 1, window_size - 1]), {2, 1, 1})) + |> Nx.multiply(Nx.reshape(Nx.tensor([2 * window_size - 1, 1]), {2, 1, 1})) + |> Nx.sum(axes: [0]) + end + + defp hidden_state_windows(hidden_state, shift_size, window_size, input_resolution) do + Axon.nx(hidden_state, fn hidden_state -> + {batch_size, _dimension, hidden_size} = Nx.shape(hidden_state) + + height = width = input_resolution + hidden_state = Nx.reshape(hidden_state, {batch_size, height, width, hidden_size}) + + # Apply cyclic shift + hidden_state = + if shift_size > 0 do + Bumblebee.Utils.Nx.roll(hidden_state, shifts: [-shift_size, -shift_size], axes: [1, 2]) + else + hidden_state + end + + # Partition windows + hidden_state + |> window_partition(window_size) + |> Nx.reshape({:auto, window_size * window_size, hidden_size}) + end) + end + + defp reverse_hidden_state_windows(hidden_state, shift_size, window_size, input_resolution) do + Axon.nx(hidden_state, fn hidden_state -> + {_batch_size, _dimension, hidden_size} = Nx.shape(hidden_state) + height = width = input_resolution + + # Reverse window partitioning + hidden_state = + hidden_state + |> Nx.reshape({:auto, window_size, window_size, hidden_size}) + |> window_unpartition(window_size, height, width) + + # Reverse cyclic shift + hidden_state = + if shift_size > 0 do + Bumblebee.Utils.Nx.roll(hidden_state, shifts: [shift_size, shift_size], axes: [1, 2]) + else + hidden_state + end + + Nx.reshape(hidden_state, {:auto, height * width, hidden_size}) + end) + end + + defnp window_partition(tensor, window_size) do + {batch_size, height, width, hidden_size} = Nx.shape(tensor) + windowed_height = div(height, window_size) + windowed_width = div(width, window_size) + + Nx.reshape( + tensor, + {batch_size, windowed_height, window_size, windowed_width, window_size, hidden_size} + ) + |> Nx.transpose(axes: [0, 1, 3, 2, 4, 5]) + |> Nx.reshape({:auto, window_size, window_size, hidden_size}) + end + + defnp window_unpartition(tensor, window_size, height, width) do + {_batch_size, _height, _width, hidden_size} = Nx.shape(tensor) + windowed_height = div(height, window_size) + windowed_width = div(width, window_size) + + Nx.reshape( + tensor, + {:auto, windowed_height, windowed_width, window_size, window_size, hidden_size} + ) + |> Nx.transpose(axes: [0, 1, 3, 2, 4, 5]) + |> Nx.reshape({:auto, height, width, hidden_size}) + end + + defp patch_merging(hidden_state, opts) do + input_resolution = opts[:input_resolution] + hidden_size = opts[:hidden_size] + layer_norm_epsilon = opts[:layer_norm_epsilon] + kernel_initializer = opts[:kernel_initializer] + name = opts[:name] + + # We group patches from each 2x2 square and apply a dense layer + # against each group + + hidden_state + |> Axon.nx(fn hidden_state -> + {batch_size, _sequence_length, _hidden_size} = Nx.shape(hidden_state) + + hidden_state = + Nx.reshape(hidden_state, {batch_size, input_resolution, input_resolution, :auto}) + + input_feature_0 = hidden_state[[.., 0..-1//2, 0..-1//2, ..]] + input_feature_1 = hidden_state[[.., 1..-1//2, 0..-1//2, ..]] + input_feature_2 = hidden_state[[.., 0..-1//2, 1..-1//2, ..]] + input_feature_3 = hidden_state[[.., 1..-1//2, 1..-1//2, ..]] + + Nx.concatenate([input_feature_0, input_feature_1, input_feature_2, input_feature_3], + axis: -1 + ) + |> Nx.reshape({batch_size, :auto, 4 * hidden_size}) + end) + |> Axon.layer_norm(epsilon: layer_norm_epsilon, name: join(name, "norm")) + |> Axon.dense(2 * hidden_size, + kernel_initializer: kernel_initializer, + name: join(name, "reduction"), + use_bias: false + ) + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + attention_dropout_rate: {"attention_probs_dropout_prob", number()}, + num_blocks: {"depths", list(number())}, + drop_path_rate: {"drop_path_rate", number()}, + embedding_size: {"embed_dim", number()}, + activation: {"hidden_act", activation()}, + dropout_rate: {"hidden_dropout_prob", number()}, + image_size: {"image_size", number()}, + initializer_scale: {"initializer_range", number()}, + layer_norm_epsilon: {"layer_norm_eps", number()}, + intermediate_size_ratio: {"mlp_ratio", number()}, + num_channels: {"num_channels", number()}, + num_attention_heads: {"num_heads", list(number())}, + patch_size: {"patch_size", number()}, + use_attention_bias: {"qkv_bias", boolean()}, + use_absolute_position_embeddings: {"use_absolute_embeddings", boolean()}, + window_size: {"window_size", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.patch_embedding.projection" => "swin.embeddings.patch_embeddings.projection", + "embedder.norm" => "swin.embeddings.norm", + "encoder.stages.{n}.blocks.{m}.output_norm" => + "swin.encoder.layers.{n}.blocks.{m}.layernorm_after", + "encoder.stages.{n}.blocks.{m}.self_attention_norm" => + "swin.encoder.layers.{n}.blocks.{m}.layernorm_before", + "encoder.stages.{n}.blocks.{m}.self_attention.key" => + "swin.encoder.layers.{n}.blocks.{m}.attention.self.key", + "encoder.stages.{n}.blocks.{m}.self_attention.output" => + "swin.encoder.layers.{n}.blocks.{m}.attention.output.dense", + "encoder.stages.{n}.blocks.{m}.self_attention.query" => + "swin.encoder.layers.{n}.blocks.{m}.attention.self.query", + "encoder.stages.{n}.blocks.{m}.self_attention.value" => + "swin.encoder.layers.{n}.blocks.{m}.attention.self.value", + "encoder.stages.{n}.blocks.{m}.self_attention.relative_attention_bias" => %{ + "kernel" => { + [ + {"swin.encoder.layers.{n}.blocks.{m}.attention.self", + "relative_position_bias_table"} + ], + fn [kernel] -> kernel end + } + }, + "encoder.stages.{n}.blocks.{m}.ffn.intermediate" => + "swin.encoder.layers.{n}.blocks.{m}.intermediate.dense", + "encoder.stages.{n}.blocks.{m}.ffn.output" => + "swin.encoder.layers.{n}.blocks.{m}.output.dense", + "encoder.stages.{n}.downsample.norm" => "swin.encoder.layers.{n}.downsample.norm", + "encoder.stages.{n}.downsample.reduction" => + "swin.encoder.layers.{n}.downsample.reduction", + "norm" => "swin.layernorm", + "image_classification_head.output" => "classifier" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/vision/vit.ex b/deps/bumblebee/lib/bumblebee/vision/vit.ex new file mode 100644 index 0000000000000000000000000000000000000000..3f2d3b7201d3c85b752472f39b297aa6422bd6ea --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/vit.ex @@ -0,0 +1,354 @@ +defmodule Bumblebee.Vision.Vit do + alias Bumblebee.Shared + + options = + [ + image_size: [ + default: 224, + doc: "the size of the input spatial dimensions" + ], + num_channels: [ + default: 3, + doc: "the number of channels in the input" + ], + patch_size: [ + default: 16, + doc: "the size of the patch spatial dimensions" + ], + hidden_size: [ + default: 768, + doc: "the dimensionality of hidden layers" + ], + num_blocks: [ + default: 12, + doc: "the number of Transformer blocks in the encoder" + ], + num_attention_heads: [ + default: 12, + doc: "the number of attention heads for each attention layer in the encoder" + ], + intermediate_size: [ + default: 3072, + docs: + "the dimensionality of the intermediate layer in the transformer feed-forward network (FFN) in the encoder" + ], + use_attention_bias: [ + default: true, + doc: "whether to use bias in query, key, and value projections" + ], + activation: [ + default: :gelu, + doc: "the activation function" + ], + dropout_rate: [ + default: 0.0, + doc: "the dropout rate for encoder and decoder" + ], + attention_dropout_rate: [ + default: 0.0, + doc: "the dropout rate for attention weights" + ], + layer_norm_epsilon: [ + default: 1.0e-12, + doc: "the epsilon used by the layer normalization layers" + ], + initializer_scale: [ + default: 0.02, + doc: + "the standard deviation of the normal initializer used for initializing kernel parameters" + ] + ] ++ Shared.common_options([:num_labels, :id_to_label]) + + @moduledoc """ + ViT model family. + + ## Architectures + + * `:base` - plain ViT without any head on top + + * `:for_image_classification` - ViT with a classification head. + The head consists of a single dense layer on top of the pooled + features + + * `:for_masked_image_modeling` - ViT with a language modeling + head on top for predicting visual tokens + + ## Inputs + + * `"pixel_values"` - `{batch_size, image_size, image_size, num_channels}` + + Featurized image pixel values. + + * `"patch_mask"` - `{batch_size, num_patches}` + + Mask to nullify selected embedded patches. + + ## Global layer options + + #{Shared.global_layer_options_doc([:output_hidden_states, :output_attentions])} + + ## Configuration + + #{Shared.options_doc(options)} + + ## References + + * [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://arxiv.org/abs/2010.11929) + + """ + + defstruct [architecture: :base] ++ Shared.option_defaults(options) + + @behaviour Bumblebee.ModelSpec + @behaviour Bumblebee.Configurable + + import Bumblebee.Utils.Model, only: [join: 2] + + alias Bumblebee.Layers + + @impl true + def architectures(), do: [:base, :for_image_classification, :for_masked_image_modeling] + + @impl true + def config(spec, opts) do + spec + |> Shared.put_config_attrs(opts) + |> Shared.validate_label_options() + end + + @impl true + def input_template(spec) do + %{ + "pixel_values" => + Nx.template({1, spec.image_size, spec.image_size, spec.num_channels}, :f32) + } + end + + @impl true + def model(%__MODULE__{architecture: :base} = spec) do + spec + |> inputs() + |> core(spec) + |> Layers.output() + end + + def model(%__MODULE__{architecture: :for_image_classification} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + logits = + outputs.hidden_state + |> Layers.take_token(index: 0, axis: 1) + |> Axon.dense(spec.num_labels, + kernel_initializer: kernel_initializer(spec), + name: "image_classification_head.output" + ) + + Layers.output(%{ + logits: logits, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + def model(%__MODULE__{architecture: :for_masked_image_modeling} = spec) do + inputs = inputs(spec) + outputs = core(inputs, spec) + + pixel_values = + outputs.hidden_state + |> Axon.nx(fn x -> + x = x[[.., 1..-1//1]] + {batch_size, sequence_length, channels} = Nx.shape(x) + height = width = sequence_length |> :math.sqrt() |> floor() + Nx.reshape(x, {batch_size, height, width, channels}) + end) + # Upsample to the original spatial resolution + |> Axon.conv(spec.patch_size ** 2 * 3, + kernel_size: 1, + kernel_initializer: kernel_initializer(spec), + name: "masked_image_modeling_head.output" + ) + |> Layers.pixel_shuffle(spec.patch_size) + + Layers.output(%{ + pixel_values: pixel_values, + hidden_states: outputs.hidden_states, + attentions: outputs.attentions + }) + end + + defp inputs(spec) do + shape = {nil, spec.image_size, spec.image_size, spec.num_channels} + + Bumblebee.Utils.Model.inputs_to_map([ + Axon.input("pixel_values", shape: shape), + Axon.input("patch_mask", shape: {nil, nil}, optional: true) + ]) + end + + defp core(inputs, spec, opts \\ []) do + name = opts[:name] + + embeddings = + embedder(inputs["pixel_values"], inputs["patch_mask"], spec, name: join(name, "embedder")) + + encoder_outputs = encoder(embeddings, spec, name: join(name, "encoder")) + + hidden_state = + Axon.layer_norm(encoder_outputs.hidden_state, + epsilon: spec.layer_norm_epsilon, + name: join(name, "norm") + ) + + pooled_state = pooler(hidden_state, spec, name: join(name, "pooler")) + + %{ + hidden_state: hidden_state, + pooled_state: pooled_state, + hidden_states: encoder_outputs.hidden_states, + attentions: encoder_outputs.attentions + } + end + + defp embedder(pixel_values, patch_mask, spec, opts) do + name = opts[:name] + + patch_embeddings = + pixel_values + |> patch_embedding(spec, name: join(name, "patch_embedding")) + |> Layers.apply_vision_patch_mask(patch_mask, name: join(name, "mask_tokens")) + + class_embedding = + Layers.learned_embeddings(1, spec.hidden_size, name: join(name, "class_embedding")) + + input_embeddings = Layers.concatenate_embeddings([class_embedding, patch_embeddings]) + + num_patches = div(spec.image_size, spec.patch_size) ** 2 + + position_embeddings = + Layers.learned_embeddings(num_patches + 1, spec.hidden_size, + initializer: :zeros, + name: join(name, "position_embedding") + ) + + Axon.add(input_embeddings, position_embeddings) + |> Axon.dropout(rate: spec.dropout_rate, name: join(name, "dropout")) + end + + defp patch_embedding(pixel_values, spec, opts) do + name = opts[:name] + + pixel_values + |> Axon.conv(spec.hidden_size, + kernel_size: spec.patch_size, + strides: spec.patch_size, + padding: :valid, + kernel_initializer: kernel_initializer(spec), + name: join(name, "projection") + ) + |> Axon.reshape({:batch, :auto, spec.hidden_size}, name: join(name, "reshape")) + end + + defp encoder(hidden_state, spec, opts) do + name = opts[:name] + + Layers.Transformer.blocks(hidden_state, + num_blocks: spec.num_blocks, + num_attention_heads: spec.num_attention_heads, + hidden_size: spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + dropout_rate: spec.dropout_rate, + attention_dropout_rate: spec.attention_dropout_rate, + query_use_bias: spec.use_attention_bias, + key_use_bias: spec.use_attention_bias, + value_use_bias: spec.use_attention_bias, + layer_norm: [ + epsilon: spec.layer_norm_epsilon + ], + ffn: [ + intermediate_size: spec.intermediate_size, + activation: spec.activation + ], + block_type: :norm_first, + name: join(name, "blocks") + ) + end + + defp pooler(hidden_state, spec, opts) do + name = opts[:name] + + hidden_state + |> Layers.take_token(index: 0, axis: 1) + |> Axon.dense(spec.hidden_size, + kernel_initializer: kernel_initializer(spec), + name: join(name, "output") + ) + |> Axon.tanh() + end + + defp kernel_initializer(spec) do + Axon.Initializers.normal(scale: spec.initializer_scale) + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(spec, data) do + import Shared.Converters + + opts = + convert!(data, + image_size: {"image_size", number()}, + num_channels: {"num_channels", number()}, + patch_size: {"patch_size", number()}, + hidden_size: {"hidden_size", number()}, + num_blocks: {"num_hidden_layers", number()}, + num_attention_heads: {"num_attention_heads", number()}, + intermediate_size: {"intermediate_size", number()}, + activation: {"hidden_act", activation()}, + use_attention_bias: {"qkv_bias", boolean()}, + dropout_rate: {"hidden_dropout_prob", number()}, + attention_dropout_rate: {"attention_probs_dropout_prob", number()}, + layer_norm_epsilon: {"layer_norm_eps", number()}, + initializer_scale: {"initializer_range", number()} + ) ++ Shared.common_options_from_transformers(data, spec) + + @for.config(spec, opts) + end + end + + defimpl Bumblebee.HuggingFace.Transformers.Model do + def params_mapping(_spec) do + %{ + "embedder.patch_embedding.projection" => "vit.embeddings.patch_embeddings.projection", + "embedder.class_embedding" => %{ + "embeddings" => { + [{"vit.embeddings", "cls_token"}], + fn [value] -> Nx.squeeze(value, axes: [0]) end + } + }, + "embedder.position_embedding" => %{ + "embeddings" => { + [{"vit.embeddings", "position_embeddings"}], + fn [value] -> Nx.squeeze(value, axes: [0]) end + } + }, + "encoder.blocks.{n}.self_attention_norm" => "vit.encoder.layer.{n}.layernorm_before", + "encoder.blocks.{n}.self_attention.key" => + "vit.encoder.layer.{n}.attention.attention.key", + "encoder.blocks.{n}.self_attention.query" => + "vit.encoder.layer.{n}.attention.attention.query", + "encoder.blocks.{n}.self_attention.value" => + "vit.encoder.layer.{n}.attention.attention.value", + "encoder.blocks.{n}.self_attention.output" => + "vit.encoder.layer.{n}.attention.output.dense", + "encoder.blocks.{n}.ffn.intermediate" => "vit.encoder.layer.{n}.intermediate.dense", + "encoder.blocks.{n}.ffn.output" => "vit.encoder.layer.{n}.output.dense", + "encoder.blocks.{n}.output_norm" => "vit.encoder.layer.{n}.layernorm_after", + "norm" => "vit.layernorm", + "pooler.output" => "vit.pooler.dense", + "image_classification_head.output" => "classifier", + "masked_image_modeling_head.output" => "decoder.0" + } + end + end +end diff --git a/deps/bumblebee/lib/bumblebee/vision/vit_featurizer.ex b/deps/bumblebee/lib/bumblebee/vision/vit_featurizer.ex new file mode 100644 index 0000000000000000000000000000000000000000..f9522cba907445c82ec42e6a8fecb4caa689addc --- /dev/null +++ b/deps/bumblebee/lib/bumblebee/vision/vit_featurizer.ex @@ -0,0 +1,119 @@ +defmodule Bumblebee.Vision.VitFeaturizer do + alias Bumblebee.Shared + + options = [ + resize: [ + default: true, + doc: "whether to resize the input to the given `:size`" + ], + size: [ + default: %{height: 224, width: 224}, + doc: """ + the size to resize the input to, given as `%{height: ..., width: ...}`. Only has + an effect if `:resize` is `true` + """ + ], + resize_method: [ + default: :bilinear, + doc: + "the resizing method, either of `:nearest`, `:bilinear`, `:bicubic`, `:lanczos3`, `:lanczos5`" + ], + normalize: [ + default: true, + doc: "whether or not to normalize the input with mean and standard deviation" + ], + image_mean: [ + default: [0.5, 0.5, 0.5], + doc: "the sequence of mean values for each channel, to be used when normalizing images" + ], + image_std: [ + default: [0.5, 0.5, 0.5], + doc: + "the sequence of standard deviations for each channel, to be used when normalizing images" + ] + ] + + @moduledoc """ + ViT featurizer for image data. + + ## Configuration + + #{Shared.options_doc(options)} + """ + + defstruct Shared.option_defaults(options) + + @behaviour Bumblebee.Featurizer + @behaviour Bumblebee.Configurable + + alias Bumblebee.Utils.Image + + @impl true + def config(featurizer, opts) do + Shared.put_config_attrs(featurizer, opts) + end + + @impl true + def process_input(featurizer, images) do + images = List.wrap(images) + + for image <- images do + image = + image + |> Image.to_batched_tensor() + |> Nx.as_type(:f32) + |> Image.normalize_channels(length(featurizer.image_mean)) + + if featurizer.resize do + %{height: height, width: width} = featurizer.size + NxImage.resize(image, {height, width}, method: featurizer.resize_method) + else + image + end + end + |> Nx.concatenate() + end + + @impl true + def batch_template(featurizer, batch_size) do + %{height: height, width: width} = featurizer.size + num_channels = length(featurizer.image_mean) + Nx.template({batch_size, height, width, num_channels}, :f32) + end + + @impl true + def process_batch(featurizer, images) do + images = NxImage.to_continuous(images, 0, 1) + + images = + if featurizer.normalize do + NxImage.normalize( + images, + Nx.tensor(featurizer.image_mean), + Nx.tensor(featurizer.image_std) + ) + else + images + end + + %{"pixel_values" => images} + end + + defimpl Bumblebee.HuggingFace.Transformers.Config do + def load(featurizer, data) do + import Shared.Converters + + opts = + convert!(data, + resize: {"do_resize", boolean()}, + size: {"size", image_size()}, + resize_method: {"resample", resize_method()}, + normalize: {"do_normalize", boolean()}, + image_mean: {"image_mean", list(number())}, + image_std: {"image_std", list(number())} + ) + + @for.config(featurizer, opts) + end + end +end diff --git a/deps/bumblebee/mix.exs b/deps/bumblebee/mix.exs new file mode 100644 index 0000000000000000000000000000000000000000..23e8f8e8dd5dd906934ecdd86300f37c9efd1e8f --- /dev/null +++ b/deps/bumblebee/mix.exs @@ -0,0 +1,183 @@ +defmodule Bumblebee.MixProject do + use Mix.Project + + @version "0.6.3" + @description "Pre-trained and transformer Neural Network models in Axon" + + def project do + [ + app: :bumblebee, + version: @version, + description: @description, + name: "Bumblebee", + elixir: "~> 1.14", + elixirc_paths: elixirc_paths(Mix.env()), + start_permanent: Mix.env() == :prod, + deps: deps(), + docs: docs(), + package: package() + ] + end + + def application do + [ + mod: {Bumblebee.Application, []}, + extra_applications: [:logger, :inets, :ssl] + ] + end + + defp elixirc_paths(:test), do: ["lib", "test/support"] + defp elixirc_paths(_), do: ["lib"] + + defp deps do + [ + {:axon, "~> 0.7.0"}, + # {:axon, github: "elixir-nx/axon", override: true}, + {:tokenizers, "~> 0.4"}, + {:nx, "~> 0.9.0 or ~> 0.10.0"}, + {:exla, ">= 0.0.0", only: [:dev, :test]}, + {:torchx, ">= 0.0.0", only: [:dev, :test]}, + # {:nx, github: "elixir-nx/nx", sparse: "nx", override: true}, + # {:exla, github: "elixir-nx/nx", sparse: "exla", override: true, only: [:dev, :test]}, + # {:torchx, github: "elixir-nx/nx", sparse: "torchx", override: true, only: [:dev, :test]}, + {:nx_image, "~> 0.1.0"}, + {:unpickler, "~> 0.1.0"}, + {:safetensors, "~> 0.1.3"}, + {:jason, "~> 1.4.0"}, + {:unzip, "~> 0.12.0"}, + {:progress_bar, "~> 3.0"}, + {:stb_image, "~> 0.6.0", only: :test}, + {:bypass, "~> 2.1", only: :test}, + {:ex_doc, "~> 0.28", only: :dev, runtime: false}, + {:nx_signal, "~> 0.2.0"} + ] + end + + defp docs do + [ + main: "Bumblebee", + source_url: "https://github.com/elixir-nx/bumblebee", + source_ref: "v#{@version}", + extras: [ + "notebooks/examples.livemd", + "notebooks/stable_diffusion.livemd", + "notebooks/llms.livemd", + "notebooks/llms_rag.livemd", + "notebooks/fine_tuning.livemd", + "examples/phoenix/README.md" + ], + extra_section: "GUIDES", + groups_for_modules: [ + Tasks: [ + Bumblebee.Audio, + Bumblebee.Text, + Bumblebee.Vision, + Bumblebee.Diffusion.StableDiffusion, + Bumblebee.Diffusion.StableDiffusionControlNet + ], + Models: [ + Bumblebee.Audio.Whisper, + Bumblebee.Diffusion.ControlNet, + Bumblebee.Diffusion.StableDiffusion.SafetyChecker, + Bumblebee.Diffusion.UNet2DConditional, + Bumblebee.Diffusion.VaeKl, + Bumblebee.Multimodal.Blip, + Bumblebee.Multimodal.Clip, + Bumblebee.Multimodal.LayoutLm, + Bumblebee.Text.Albert, + Bumblebee.Text.Bart, + Bumblebee.Text.Bert, + Bumblebee.Text.Blenderbot, + Bumblebee.Text.BlipText, + Bumblebee.Text.ClipText, + Bumblebee.Text.Distilbert, + Bumblebee.Text.Gemma, + Bumblebee.Text.Gpt2, + Bumblebee.Text.GptBigCode, + Bumblebee.Text.GptNeoX, + Bumblebee.Text.Llama, + Bumblebee.Text.M2m100, + Bumblebee.Text.Mbart, + Bumblebee.Text.Mistral, + Bumblebee.Text.Phi, + Bumblebee.Text.Phi3, + Bumblebee.Text.Roberta, + Bumblebee.Text.T5, + Bumblebee.Vision.BlipVision, + Bumblebee.Vision.ClipVision, + Bumblebee.Vision.ConvNext, + Bumblebee.Vision.Deit, + Bumblebee.Vision.DinoV2, + Bumblebee.Vision.ResNet, + Bumblebee.Vision.Swin, + Bumblebee.Vision.Vit + ], + Preprocessors: [ + Bumblebee.Audio.WhisperFeaturizer, + Bumblebee.Text.PreTrainedTokenizer, + Bumblebee.Vision.BitFeaturizer, + Bumblebee.Vision.BlipFeaturizer, + Bumblebee.Vision.ClipFeaturizer, + Bumblebee.Vision.ConvNextFeaturizer, + Bumblebee.Vision.DeitFeaturizer, + Bumblebee.Vision.VitFeaturizer + ], + Schedulers: [ + Bumblebee.Diffusion.DdimScheduler, + Bumblebee.Diffusion.LcmScheduler, + Bumblebee.Diffusion.PndmScheduler + ], + Interfaces: [ + Bumblebee.Configurable, + Bumblebee.ModelSpec, + Bumblebee.Featurizer, + Bumblebee.Tokenizer, + Bumblebee.Scheduler, + Bumblebee.Text.Generation + ], + Other: [ + Bumblebee.Text.GenerationConfig, + Bumblebee.Text.WhisperGenerationConfig + ] + ], + groups_for_docs: [ + # Bumblebee + Models: &(&1[:type] == :model), + Featurizers: &(&1[:type] == :featurizer), + Tokenizers: &(&1[:type] == :tokenizer), + Schedulers: &(&1[:type] == :scheduler) + ], + before_closing_body_tag: &before_closing_body_tag/1 + ] + end + + def package do + [ + licenses: ["Apache-2.0"], + links: %{ + "GitHub" => "https://github.com/elixir-nx/bumblebee" + } + ] + end + + # Add KaTeX integration for rendering math + defp before_closing_body_tag(:html) do + """ + + + + + """ + end + + defp before_closing_body_tag(_), do: "" +end diff --git a/deps/elixir_make/.fetch b/deps/elixir_make/.fetch new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/deps/elixir_make/.formatter.exs b/deps/elixir_make/.formatter.exs new file mode 100644 index 0000000000000000000000000000000000000000..682fc6c6bcd0ed29a60ba268c8afe920fb712351 --- /dev/null +++ b/deps/elixir_make/.formatter.exs @@ -0,0 +1,3 @@ +[ + inputs: ["{mix,.formatter}.exs", "{lib,test}/**/*.{ex,exs}"] +] diff --git a/deps/elixir_make/.hex b/deps/elixir_make/.hex new file mode 100644 index 0000000000000000000000000000000000000000..28e3e64946b4f5155a8ba6292dfe2cdc7c232d97 Binary files /dev/null and b/deps/elixir_make/.hex differ diff --git a/deps/elixir_make/CHANGELOG.md b/deps/elixir_make/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..21944a78f467c260bc0194e14ba5f28718da2d0e --- /dev/null +++ b/deps/elixir_make/CHANGELOG.md @@ -0,0 +1,88 @@ +# Changelog + +## v0.9.0 (2024-11-12) + + * Rely on certificate stores provided by Erlang/OTP 25+ + * Support setting `:force_build` opts in config: + + ```elixir + config :elixir_make, :force_build, app1: true, app2: false + ``` + +## v0.8.4 (2024-06-04) + + * Support configuring `make_precompiler_downloader` + * Support DragonFlyBSD + * Support non-UTF8 encoding from compilation (may happen on Windows) + +## v0.8.3 (2024-03-24) + + * Support storing checksum of individial precompilation artefacts + +## v0.8.2 (2024-03-10) + + * Fix checksum error when checksuming NIF version + +## v0.8.1 (2024-03-10) + + * Fix checksum error when falling back to a previous NIF version + +## v0.8.0 (2024-03-10) + + * Fallback to the previous compatible NIF version by default + * Deprecate availability in favor of passing a function to `:versions` + +## v0.7.8 (2024-01-17) + + * List certifi as an optional dependency + +## v0.7.7 (2023-06-01) + + * Fix compiler in umbrella apps + +## v0.7.6 (2023-03-17) + + * Do not display error message when a target is unavailable + * Allow usage of castore 1.0 + +## v0.7.5 (2023-02-18) + + * Support precompiling for multiple NIF versions + +## v0.7.4 (2023-02-17) + + * Preload Erlang/OTP applications for Elixir v1.15+ + +## v0.7.3 (2022-12-27) + + * Add `post_precompile_target` to `ElixirMake.Precompiler` behaviour + +## v0.7.2 (2022-12-14) + + * Allow precompiler to configure behaviour for unavailable targets + +## v0.7.1 (2022-12-07) + + * Use CACerts from Erlang/OTP 25 if available + +## v0.7.0 (2022-12-02) + + * Support precompilation with custom precompilers + * Don't pass default Erlang environment variables into make + +## v0.6.3 (2021-10-19) + + * Fallback to `make` if `nmake` is not available on Windows. + +## v0.6.2 (2020-12-03) + + * Fix permissions for some files in the repository. + +## v0.6.1 (2020-09-07) + + * Warn on paths that contain spaces. + * Use `gmake` on NetBSD. + +## v0.6.0 (2019-06-10) + + * Start tracking CHANGELOG. diff --git a/deps/elixir_make/README.md b/deps/elixir_make/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8c75561229e07dca8451f4512c1314225830791b --- /dev/null +++ b/deps/elixir_make/README.md @@ -0,0 +1,50 @@ +# A Make compiler for Mix + +[![Build Status](https://github.com/elixir-lang/elixir_make/workflows/CI/badge.svg)](https://github.com/elixir-lang/elixir_make/actions) +[![Hex version](https://img.shields.io/hexpm/v/elixir_make.svg "Hex version")](https://hex.pm/packages/elixir_make) + +This project provides a Mix compiler that makes it straight-forward to use makefiles in your Mix projects. + +## Documentation + +API documentation is available at [https://hexdocs.pm/elixir_make](https://hexdocs.pm/elixir_make) + +## Usage + +The package can be installed by adding `elixir_make` to your list of dependencies in `mix.exs`: + +```elixir +def deps do + [{:elixir_make, "~> 0.4", runtime: false}] +end +``` + +Still in your `mix.exs` file, you will need to add `:elixir_make` to your list of compilers in `project/0`: + +```elixir +compilers: [:elixir_make] ++ Mix.compilers, +``` + +And that's it. The command above will invoke `make` for Unix, `nmake` for Windows and `gmake` for FreeBSD and OpenBSD. A "Makefile" file is expected at your project root for Unix systems and "Makefile.win" for Windows systems. Run `mix help compile.elixir_make` for more information and options. + +## Publishing a package to Hex.pm + +When publishing a package to Hex.pm using `elixir_make` requires you to add +any file (such as the Makefile and any source files) to the `files` option. +See [the hex docs](https://hex.pm/docs/publish#adding-metadata-to-code-classinlinemixexscode) + +```elixir + defp package do + [ + # ... + files: [ + "lib", "LICENSE", "mix.exs", "README.md", # These are the default files + "src/*.[ch]", "Makefile"], # You will need to add something like this. + # ... + ] + end +``` + +## License + +Same as Elixir. diff --git a/deps/elixir_make/hex_metadata.config b/deps/elixir_make/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..a3a63e724166dadd9f15d2f23aa4f5a8eb6d5e57 --- /dev/null +++ b/deps/elixir_make/hex_metadata.config @@ -0,0 +1,20 @@ +{<<"links">>, + [{<<"GitHub">>,<<"https://github.com/elixir-lang/elixir_make">>}]}. +{<<"name">>,<<"elixir_make">>}. +{<<"version">>,<<"0.9.0">>}. +{<<"description">>,<<"A Make compiler for Mix">>}. +{<<"elixir">>,<<"~> 1.9">>}. +{<<"app">>,<<"elixir_make">>}. +{<<"licenses">>,[<<"Apache-2.0">>]}. +{<<"requirements">>,[]}. +{<<"files">>, + [<<"lib">>,<<"lib/elixir_make">>,<<"lib/elixir_make/artefact.ex">>, + <<"lib/elixir_make/compiler.ex">>,<<"lib/elixir_make/downloader">>, + <<"lib/elixir_make/downloader/httpc.ex">>, + <<"lib/elixir_make/downloader.ex">>,<<"lib/elixir_make/precompiler.ex">>, + <<"lib/mix">>,<<"lib/mix/tasks">>, + <<"lib/mix/tasks/elixir_make.checksum.ex">>, + <<"lib/mix/tasks/elixir_make.precompile.ex">>, + <<"lib/mix/tasks/compile.elixir_make.ex">>,<<".formatter.exs">>, + <<"mix.exs">>,<<"README.md">>,<<"CHANGELOG.md">>]}. +{<<"build_tools">>,[<<"mix">>]}. diff --git a/deps/elixir_make/lib/elixir_make/artefact.ex b/deps/elixir_make/lib/elixir_make/artefact.ex new file mode 100644 index 0000000000000000000000000000000000000000..efcdba51804a2466c3aa0adb395bfb6c0c7365cb --- /dev/null +++ b/deps/elixir_make/lib/elixir_make/artefact.ex @@ -0,0 +1,293 @@ +defmodule ElixirMake.Artefact do + @moduledoc false + + require Logger + alias ElixirMake.Artefact + + @checksum_algo :sha256 + defstruct [:basename, :checksum, :checksum_algo] + + @doc """ + Returns user cache directory. + """ + def cache_dir() do + cache_opts = if System.get_env("MIX_XDG"), do: %{os: :linux}, else: %{} + + cache_dir = + Path.expand( + System.get_env("ELIXIR_MAKE_CACHE_DIR") || + :filename.basedir(:user_cache, "elixir_make", cache_opts) + ) + + File.mkdir_p!(cache_dir) + cache_dir + end + + @doc """ + Returns the checksum algorithm + """ + def checksum_algo do + @checksum_algo + end + + @doc """ + Computes the checksum and artefact for the given contents. + """ + def checksum(basename, contents) do + hash = :crypto.hash(checksum_algo(), contents) + checksum = Base.encode16(hash, case: :lower) + %Artefact{basename: basename, checksum: checksum, checksum_algo: checksum_algo()} + end + + @doc """ + Writes checksum for the target to disk. + """ + def write_checksum_for_target!(%Artefact{ + basename: basename, + checksum: checksum, + checksum_algo: checksum_algo + }) do + cache_dir = Artefact.cache_dir() + file = Path.join(cache_dir, "#{basename}.#{Atom.to_string(checksum_algo)}") + File.write!(file, [checksum, " ", basename, "\n"]) + end + + @doc """ + Writes checksums to disk. + """ + def write_checksums!(checksums) do + file = checksum_file() + + pairs = + Enum.map(checksums, fn + %Artefact{basename: basename, checksum: checksum, checksum_algo: algo} -> + {basename, "#{algo}:#{checksum}"} + end) + + lines = + for {filename, checksum} <- Enum.sort(pairs) do + ~s( "#{filename}" => "#{checksum}",\n) + end + + File.write!(file, ["%{\n", lines, "}\n"]) + end + + defp checksum_file() do + Path.join(File.cwd!(), "checksum.exs") + end + + ## Archive handling + + @doc """ + Returns the full path to the precompiled archive. + """ + def archive_path(config, target, nif_version) do + Path.join(cache_dir(), archive_filename(config, target, nif_version)) + end + + defp archive_filename(config, target, nif_version) do + case config[:make_precompiler] do + {:nif, _} -> + "#{config[:app]}-nif-#{nif_version}-#{target}-#{config[:version]}.tar.gz" + + {type, _} -> + "#{config[:app]}-#{type}-#{target}-#{config[:version]}.tar.gz" + end + end + + @doc """ + Compresses the given files and computes its checksum and artefact. + """ + def compress(archive_path, paths) do + :ok = :erl_tar.create(archive_path, paths, [:compressed]) + checksum(Path.basename(archive_path), File.read!(archive_path)) + end + + @doc """ + Verifies and decompresses the given `archive_path` at `app_priv`. + """ + def verify_and_decompress(archive_path, app_priv) do + basename = Path.basename(archive_path) + + case File.read(archive_path) do + {:ok, contents} -> + verify_and_decompress(basename, archive_path, contents, app_priv) + + {:error, reason} -> + {:error, + "precompiled #{inspect(basename)} does not exist or cannot download: #{inspect(reason)}"} + end + end + + defp verify_and_decompress(basename, archive_path, contents, app_priv) do + checksum_file() + |> read_map_from_file() + |> case do + %{^basename => algo_with_checksum} -> + [algo, checksum] = String.split(algo_with_checksum, ":") + algo = String.to_existing_atom(algo) + + case checksum(basename, contents) do + %Artefact{checksum: ^checksum, checksum_algo: ^algo} -> + case :erl_tar.extract({:binary, contents}, [:compressed, {:cwd, app_priv}]) do + :ok -> + :ok + + {:error, term} -> + {:error, + "cannot decompress precompiled #{inspect(archive_path)}: #{inspect(term)}"} + end + + _ -> + {:error, "precompiled #{inspect(basename)} does not match its checksum"} + end + + checksum when checksum == %{} -> + {:error, "missing checksum.exs file"} + + _checksum -> + {:error, "precompiled #{inspect(basename)} does not exist in checksum.exs"} + end + end + + defp read_map_from_file(file) do + with {:ok, contents} <- File.read(file), + {%{} = contents, _} <- Code.eval_string(contents) do + contents + else + _ -> %{} + end + end + + ## Archive/NIF urls + + defp nif_version_to_tuple(nif_version) do + [major, minor | _] = String.split(nif_version, ".") + {String.to_integer(major), String.to_integer(minor)} + end + + defp fallback_version(opts) do + current_nif_version = "#{:erlang.system_info(:nif_version)}" + {major, minor} = nif_version_to_tuple(current_nif_version) + + # Get all matching major versions, earlier than the current version + # and their distance. We want the closest (smallest distance). + candidates = + for version <- opts.versions, + {^major, candidate_minor} <- [nif_version_to_tuple(version)], + candidate_minor <= minor, + do: {minor - candidate_minor, version} + + case Enum.sort(candidates) do + [{_, version} | _] -> version + _ -> current_nif_version + end + end + + defp get_versions_for_target(versions, current_target) do + case versions do + version_list when is_list(version_list) -> + version_list + + version_func when is_function(version_func, 1) -> + version_func.(%{target: current_target}) + end + end + + @doc """ + Returns all available {{target, nif_version}, url} pairs available. + """ + def available_target_urls(config, precompiler) do + targets = precompiler.all_supported_targets(:fetch) + + url_template = + config[:make_precompiler_url] || + Mix.raise("`make_precompiler_url` is not specified in `project`") + + current_nif_version = "#{:erlang.system_info(:nif_version)}" + + nif_versions = + config[:make_precompiler_nif_versions] || + [versions: [current_nif_version]] + + Enum.reduce(targets, [], fn target, archives -> + versions = get_versions_for_target(nif_versions[:versions], target) + + archive_filenames = + Enum.reduce(versions, [], fn nif_version_for_target, acc -> + availability = nif_versions[:availability] + + available? = + if is_function(availability, 2) do + IO.warn( + ":availability key in elixir_make is deprecated, pass a function as :versions instead" + ) + + availability.(target, nif_version_for_target) + else + true + end + + if available? do + archive_filename = archive_filename(config, target, nif_version_for_target) + + [ + {{target, nif_version_for_target}, + String.replace(url_template, "@{artefact_filename}", archive_filename)} + | acc + ] + else + acc + end + end) + + archive_filenames ++ archives + end) + end + + @doc """ + Returns the url for the current target. + """ + def current_target_url(config, precompiler, current_nif_version) do + case precompiler.current_target() do + {:ok, current_target} -> + nif_versions = + config[:make_precompiler_nif_versions] || + [versions: []] + + versions = get_versions_for_target(nif_versions[:versions], current_target) + + nif_version_to_use = + if current_nif_version in versions do + current_nif_version + else + fallback_version = nif_versions[:fallback_version] || (&fallback_version/1) + opts = %{target: current_target, versions: versions} + fallback_version.(opts) + end + + available_urls = available_target_urls(config, precompiler) + target_at_nif_version = {current_target, nif_version_to_use} + + case List.keyfind(available_urls, target_at_nif_version, 0) do + {^target_at_nif_version, download_url} -> + {:ok, current_target, nif_version_to_use, download_url} + + nil -> + available_targets = Enum.map(available_urls, fn {target, _url} -> target end) + + {:error, + {:unavailable_target, current_target, + "cannot find download url for current target `#{inspect(current_target)}`. Available targets are: #{inspect(available_targets)}"}} + end + + {:error, msg} -> + {:error, msg} + end + end + + def download(config, url) do + downloader = config[:make_precompiler_downloader] || ElixirMake.Downloader.Httpc + downloader.download(url) + end +end diff --git a/deps/elixir_make/lib/elixir_make/compiler.ex b/deps/elixir_make/lib/elixir_make/compiler.ex new file mode 100644 index 0000000000000000000000000000000000000000..8cc5fcfa8732970bc7683e942aee7c938beb30d2 --- /dev/null +++ b/deps/elixir_make/lib/elixir_make/compiler.ex @@ -0,0 +1,227 @@ +defmodule ElixirMake.Compiler do + @moduledoc false + + @mac_error_msg """ + You need to have gcc and make installed. Try running the + commands "gcc --version" and / or "make --version". If these programs + are not installed, you will be prompted to install them. + """ + + @unix_error_msg """ + You need to have gcc and make installed. If you are using + Ubuntu or any other Debian-based system, install the packages + "build-essential". Also install "erlang-dev" package if not + included in your Erlang/OTP version. If you're on Fedora, run + "dnf group install 'Development Tools'". + """ + + @windows_error_msg ~S""" + One option is to install a recent version of + [Visual C++ Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) + either manually or using [Chocolatey](https://chocolatey.org/) - + `choco install VisualCppBuildTools`. + + After installing Visual C++ Build Tools, look in the "Program Files (x86)" + directory and search for "Microsoft Visual Studio". Note down the full path + of the folder with the highest version number. Open the "run" command and + type in the following command (make sure that the path and version number + are correct): + + cmd /K "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" amd64 + + This should open up a command prompt with the necessary environment variables + set, and from which you will be able to run the "mix compile", "mix deps.compile", + and "mix test" commands. + + Another option is to install the Linux compatiblity tools from [MSYS2](https://www.msys2.org/). + + After installation start the msys64 bit terminal from the start menu and install the + C/C++ compiler toolchain. E.g.: + + pacman -S --noconfirm pacman-mirrors pkg-config + pacman -S --noconfirm --needed base-devel autoconf automake make libtool git \ + mingw-w64-x86_64-toolchain mingw-w64-x86_64-openssl mingw-w64-x86_64-libtool + + This will give you a compilation suite nearly compatible with Unix' standard tools. + """ + + def compile(args) do + config = Mix.Project.config() + Mix.shell().print_app() + priv? = File.dir?("priv") + Mix.Project.ensure_structure() + make(config, args) + + # IF there was no priv before and now there is one, we assume + # the user wants to copy it. If priv already existed and was + # written to it, then it won't be copied if build_embedded is + # set to true. + if not priv? and File.dir?("priv") do + Mix.Project.build_structure() + end + + {:ok, []} + end + + def make(config, task_args) do + exec = + System.get_env("MAKE") || + os_specific_executable(Keyword.get(config, :make_executable, :default)) + + makefile = Keyword.get(config, :make_makefile, :default) + targets = Keyword.get(config, :make_targets, []) + env = Keyword.get(config, :make_env, %{}) + env = if is_function(env), do: env.(), else: env + env = default_env(config, env) + + cwd = Keyword.get(config, :make_cwd, ".") |> Path.expand(File.cwd!()) + error_msg = Keyword.get(config, :make_error_message, :default) |> os_specific_error_msg() + custom_args = Keyword.get(config, :make_args, []) + + if String.contains?(cwd, " ") do + IO.warn(""" + the absolute path to the Makefile for this project contains spaces. \ + Make might not work properly if spaces are present in the path. \ + The absolute path is: #{inspect(cwd)} + """) + end + + base = exec |> Path.basename() |> Path.rootname() + args = args_for_makefile(base, makefile) ++ targets ++ custom_args + + case cmd(exec, args, cwd, env, "--verbose" in task_args) do + 0 -> + :ok + + exit_status -> + raise_build_error(exec, exit_status, error_msg) + end + end + + # Runs `exec [args]` in `cwd` and prints the stdout and stderr in real time, + # as soon as `exec` prints them (using `IO.Stream`). + defp cmd(exec, args, cwd, env, verbose?) do + opts = [ + # There is no guarantee the command will return valid UTF-8, + # especially on Windows, so don't try to interpret the stream + into: IO.binstream(:stdio, :line), + stderr_to_stdout: true, + cd: cwd, + env: env + ] + + if verbose? do + print_verbose_info(exec, args) + end + + {%IO.Stream{}, status} = System.cmd(find_executable(exec), args, opts) + status + end + + defp find_executable(exec) do + System.find_executable(exec) || + Mix.raise(""" + "#{exec}" not found in the path. If you have set the MAKE environment variable, \ + please make sure it is correct. + """) + end + + defp raise_build_error(exec, exit_status, error_msg) do + Mix.raise(~s{Could not compile with "#{exec}" (exit status: #{exit_status}).\n} <> error_msg) + end + + defp os_specific_executable(exec) when is_binary(exec) do + exec + end + + defp os_specific_executable(:default) do + case :os.type() do + {:win32, _} -> + cond do + System.find_executable("nmake") -> "nmake" + System.find_executable("make") -> "make" + true -> "nmake" + end + + {:unix, type} when type in [:freebsd, :openbsd, :netbsd, :dragonfly] -> + "gmake" + + _ -> + "make" + end + end + + defp os_specific_error_msg(msg) when is_binary(msg) do + msg + end + + defp os_specific_error_msg(:default) do + case :os.type() do + {:unix, :darwin} -> @mac_error_msg + {:unix, _} -> @unix_error_msg + {:win32, _} -> @windows_error_msg + _ -> "" + end + end + + # Returns a list of command-line args to pass to make (or nmake/gmake) in + # order to specify the makefile to use. + defp args_for_makefile("nmake", :default), do: ["/F", "Makefile.win"] + defp args_for_makefile("nmake", makefile), do: ["/F", makefile] + defp args_for_makefile(_, :default), do: [] + defp args_for_makefile(_, makefile), do: ["-f", makefile] + + defp print_verbose_info(exec, args) do + args = + Enum.map_join(args, " ", fn arg -> + if String.contains?(arg, " "), do: inspect(arg), else: arg + end) + + Mix.shell().info("Compiling with make: #{exec} #{args}") + end + + # Returns a map of default environment variables + # Defaults may be overwritten. + defp default_env(config, default_env) do + root_dir = :code.root_dir() + erl_interface_dir = Path.join(root_dir, "usr") + erts_dir = Path.join(root_dir, "erts-#{:erlang.system_info(:version)}") + erts_include_dir = Path.join(erts_dir, "include") + erl_ei_lib_dir = Path.join(erl_interface_dir, "lib") + erl_ei_include_dir = Path.join(erl_interface_dir, "include") + + Map.merge( + %{ + # Don't use Mix.target/0 here for backwards compatibility + "MIX_TARGET" => env("MIX_TARGET", "host"), + "MIX_ENV" => to_string(Mix.env()), + "MIX_BUILD_PATH" => Mix.Project.build_path(config), + "MIX_APP_PATH" => Mix.Project.app_path(config), + "MIX_COMPILE_PATH" => Mix.Project.compile_path(config), + "MIX_CONSOLIDATION_PATH" => Mix.Project.consolidation_path(config), + "MIX_DEPS_PATH" => Mix.Project.deps_path(config), + "MIX_MANIFEST_PATH" => Mix.Project.manifest_path(config), + + # Rebar naming + "ERL_EI_LIBDIR" => env("ERL_EI_LIBDIR", erl_ei_lib_dir), + "ERL_EI_INCLUDE_DIR" => env("ERL_EI_INCLUDE_DIR", erl_ei_include_dir), + + # erlang.mk naming + "ERTS_INCLUDE_DIR" => env("ERTS_INCLUDE_DIR", erts_include_dir), + "ERL_INTERFACE_LIB_DIR" => env("ERL_INTERFACE_LIB_DIR", erl_ei_lib_dir), + "ERL_INTERFACE_INCLUDE_DIR" => env("ERL_INTERFACE_INCLUDE_DIR", erl_ei_include_dir), + + # Disable default erlang values + "BINDIR" => nil, + "ROOTDIR" => nil, + "PROGNAME" => nil, + "EMU" => nil + }, + default_env + ) + end + + defp env(var, default) do + System.get_env(var) || default + end +end diff --git a/deps/elixir_make/lib/elixir_make/downloader.ex b/deps/elixir_make/lib/elixir_make/downloader.ex new file mode 100644 index 0000000000000000000000000000000000000000..e0aa5548e2073722eececf9dbd8883a47ce56bb9 --- /dev/null +++ b/deps/elixir_make/lib/elixir_make/downloader.ex @@ -0,0 +1,10 @@ +defmodule ElixirMake.Downloader do + @moduledoc """ + The behaviour for downloader modules. + """ + + @doc """ + This callback should download the artefact from the given URL. + """ + @callback download(url :: String.t()) :: {:ok, iolist() | binary()} | {:error, String.t()} +end diff --git a/deps/elixir_make/lib/elixir_make/downloader/httpc.ex b/deps/elixir_make/lib/elixir_make/downloader/httpc.ex new file mode 100644 index 0000000000000000000000000000000000000000..ab42fb5676a2ca67f77839bdc38578d02159af1a --- /dev/null +++ b/deps/elixir_make/lib/elixir_make/downloader/httpc.ex @@ -0,0 +1,99 @@ +defmodule ElixirMake.Downloader.Httpc do + @moduledoc false + + @behaviour ElixirMake.Downloader + + @impl ElixirMake.Downloader + def download(url) do + url_charlist = String.to_charlist(url) + + # TODO: Remove me when we require Elixir v1.15 + {:ok, _} = Application.ensure_all_started(:inets) + {:ok, _} = Application.ensure_all_started(:ssl) + {:ok, _} = Application.ensure_all_started(:public_key) + + if proxy = System.get_env("HTTP_PROXY") || System.get_env("http_proxy") do + Mix.shell().info("Using HTTP_PROXY: #{proxy}") + %{host: host, port: port} = URI.parse(proxy) + + :httpc.set_options([{:proxy, {{String.to_charlist(host), port}, []}}]) + end + + if proxy = System.get_env("HTTPS_PROXY") || System.get_env("https_proxy") do + Mix.shell().info("Using HTTPS_PROXY: #{proxy}") + %{host: host, port: port} = URI.parse(proxy) + :httpc.set_options([{:https_proxy, {{String.to_charlist(host), port}, []}}]) + end + + # https://erlef.github.io/security-wg/secure_coding_and_deployment_hardening/inets + # TODO: This may no longer be necessary from Erlang/OTP 25.0 or later. + https_options = [ + ssl: + [ + verify: :verify_peer, + customize_hostname_check: [ + match_fun: :public_key.pkix_verify_hostname_match_fun(:https) + ] + ] ++ cacerts_options() + ] + + options = [body_format: :binary] + + case :httpc.request(:get, {url_charlist, []}, https_options, options) do + {:ok, {{_, 200, _}, _headers, body}} -> + {:ok, body} + + other -> + {:error, "couldn't fetch NIF from #{url}: #{inspect(other)}"} + end + end + + defp cacerts_options do + cond do + path = System.get_env("HEX_CACERTS_PATH") -> + [cacertfile: path] + + path = System.get_env("ELIXIR_MAKE_CACERT") -> + IO.warn("Setting ELIXIR_MAKE_CACERT is deprecated, please set HEX_CACERTS_PATH instead") + [cacertfile: path] + + certs = otp_cacerts() -> + [cacerts: certs] + + true -> + warn_no_cacerts() + [] + end + end + + defp otp_cacerts do + if System.otp_release() >= "25" do + # cacerts_get/0 raises if no certs found + try do + :public_key.cacerts_get() + rescue + _ -> nil + end + end + end + + defp warn_no_cacerts do + Mix.shell().error(""" + No certificate trust store was found. + + A certificate trust store is required in + order to download locales for your configuration. + Since elixir_make could not detect a system + installed certificate trust store one of the + following actions may be taken: + + 1. Specify the location of a certificate trust store + by configuring it in environment variable: + + export HEX_CACERTS_PATH="/path/to/cacerts.pem" + + 2. Use OTP 25+ on an OS that has built-in certificate + trust store. + """) + end +end diff --git a/deps/elixir_make/lib/elixir_make/precompiler.ex b/deps/elixir_make/lib/elixir_make/precompiler.ex new file mode 100644 index 0000000000000000000000000000000000000000..dd278883cb231bbafee30751d06604f0d00bad9c --- /dev/null +++ b/deps/elixir_make/lib/elixir_make/precompiler.ex @@ -0,0 +1,110 @@ +defmodule ElixirMake.Precompiler do + @moduledoc """ + The behaviour for precompiler modules. + """ + + require Logger + + @typedoc """ + Target triplet. + """ + @type target :: String.t() + + @doc """ + This callback should return a list of triplets ("arch-os-abi") for all supported targets + of the given operation. + + For the `:compile` operation, `all_supported_targets` should return a list of targets that + the current host is capable of (cross-)compiling to. + + For the `:fetch` operation, `all_supported_targets` should return the full list of targets. + + For example, GitHub Actions provides Linux, macOS and Windows CI hosts, when `operation` is + `:compile`, the precompiler might return `["x86_64-linux-gnu"]` if it is running in the Linux + CI environment, while returning `["x86_64-apple-darwin", "aarch64-apple-darwin"]` on macOS, + or `["amd64-windows", "x86-windows"]` on Windows platform. + + When `operation` is `:fetch`, the precompiler should return the full list. The full list for + the above example should be: + + [ + "x86_64-linux-gnu", + "x86_64-apple-darwin", + "aarch64-apple-darwin", + "amd64-windows", + "x86-windows" + ] + + This allows the precompiler to do the compilation work in multilple hosts and gather all the + artefacts later with `mix elixir_make.checksum --all`. + """ + @callback all_supported_targets(operation :: :compile | :fetch) :: [target] + + @doc """ + This callback should return the target triplet for current node. + """ + @callback current_target() :: {:ok, target} | {:error, String.t()} + + @doc """ + This callback will be invoked when the user executes the `mix compile` + (or `mix compile.elixir_make`) command. + + The precompiler should then compile the NIF library "natively". Note that + it is possible for the precompiler module to pick up other environment variables + like `TARGET_ARCH=aarch64` and adjust compile arguments correspondingly. + """ + @callback build_native(OptionParser.argv()) :: + {Mix.Task.Compiler.status(), [Mix.Task.Compiler.Diagnostic.t()]} + + @doc """ + This callback should precompile the library to the given target(s). + + Returns `:ok` if the requested target has successfully compiled. + """ + @callback precompile(OptionParser.argv(), target) :: :ok | {:error, String.t()} + + @doc """ + Optional post actions to run after each precompilation target is archived. + + It will be called when a target is precompiled and archived successfully. + For example, actions can be deleting all target-specific files. + """ + @callback post_precompile_target(target) :: :ok + + @doc """ + Optional post actions to run after all precompilation tasks are done. + + It will only be called at the end of the `mix elixir_make.precompile` command. + For example, actions can be archiving all precompiled artefacts and uploading + the archive file to an object storage server. + """ + @callback post_precompile() :: :ok + + @doc """ + Optional recover actions when the current target is unavailable. + + There are two reasons that the current target might be unavailable: + when the library only has precompiled binaries for some platforms, + and it either + + - needs to be compiled on other platforms. + + The callback should return `:compile` for this case. + + - is intended to function as `noop` on other platforms. + + The callback should return `:ignore` for this case. + + Defaults to `:compile` if this callback is not implemented. + """ + @callback unavailable_target(String.t()) :: :compile | :ignore + + @optional_callbacks post_precompile: 0, unavailable_target: 1, post_precompile_target: 1 + + @doc """ + Invoke the regular Mix toolchain compilation. + """ + def mix_compile(args) do + ElixirMake.Compiler.compile(args) + end +end diff --git a/deps/elixir_make/lib/mix/tasks/compile.elixir_make.ex b/deps/elixir_make/lib/mix/tasks/compile.elixir_make.ex new file mode 100644 index 0000000000000000000000000000000000000000..56d6c2d98277efe17b90cb760c0b9878e098a43f --- /dev/null +++ b/deps/elixir_make/lib/mix/tasks/compile.elixir_make.ex @@ -0,0 +1,243 @@ +defmodule Mix.Tasks.Compile.ElixirMake do + @moduledoc """ + Runs `make` in the current project. + + This task runs `make` in the current project; any output coming from `make` is + printed in real-time on stdout. + + ## Configuration + + This compiler can be configured through the return value of the `project/0` + function in `mix.exs`; for example: + + def project() do + [app: :myapp, + make_executable: "make", + make_makefile: "Othermakefile", + compilers: [:elixir_make] ++ Mix.compilers, + deps: deps()] + end + + The following options are available: + + * `:make_executable` - (binary or `:default`) it's the executable to use as the + `make` program. If not provided or if `:default`, it defaults to `"nmake"` + on Windows, `"gmake"` on FreeBSD, OpenBSD and NetBSD, and `"make"` on everything + else. You can, for example, customize which executable to use on a + specific OS and use `:default` for every other OS. If the `MAKE` + environment variable is present, that is used as the value of this option. + + * `:make_makefile` - (binary or `:default`) it's the Makefile to + use. Defaults to `"Makefile"` for Unix systems and `"Makefile.win"` for + Windows systems if not provided or if `:default`. + + * `:make_targets` - (list of binaries) it's the list of Make targets that + should be run. Defaults to `[]`, meaning `make` will run the first target. + + * `:make_clean` - (list of binaries) it's a list of Make targets to be run + when `mix clean` is run. It's only run if a non-`nil` value for + `:make_clean` is provided. Defaults to `nil`. + + * `:make_cwd` - (binary) it's the directory where `make` will be run, + relative to the root of the project. + + * `:make_env` - (map of binary to binary) it's a map of extra environment + variables to be passed to `make`. You can also pass a function in here in + case `make_env` needs access to things that are not available during project + setup; the function should return a map of binary to binary. Many default + environment variables are set, see section below + + * `:make_error_message` - (binary or `:default`) it's a custom error message + that can be used to give instructions as of how to fix the error (e.g., it + can be used to suggest installing `gcc` if you're compiling a C + dependency). + + * `:make_args` - (list of binaries) it's a list of extra arguments to be passed. + + The following options configure precompilation: + + * `:make_precompiler` - a two-element tuple with the precompiled type + and module to use. The precompile type is either `:nif` or `:port` + and then the precompilation module. If the type is a `:nif`, it looks + for a DDL or a shared object as precompilation target given by + `:make_precompiler_filename` and the current NIF version is part of + the precompiled archive. If `:port`, it looks for an executable with + `:make_precompiler_filename`. + + * `:make_precompiler_url` - the download URL template. Defaults to none. + Required when `make_precompiler` is set. + + * `:make_precompiler_filename` - the filename of the compiled artefact + without its extension. Defaults to the app name. + + * `:make_precompiler_downloader` - a module implementing the `ElixirMake.Downloader` + behaviour. You can use this to customize how the precompiled artefacts + are downloaded, for example, to add HTTP authentication or to download + from an SFTP server. The default implementation uses `:httpc`. + + * `:make_force_build` - if build should be forced even if precompiled artefacts + are available. Defaults to true if the app has a `-dev` version flag. + + See [the Precompilation guide](PRECOMPILATION_GUIDE.md) for more information. + + ## Default environment variables + + There are also several default environment variables set: + + * `MIX_TARGET` + * `MIX_ENV` + * `MIX_BUILD_PATH` - same as `Mix.Project.build_path/0` + * `MIX_APP_PATH` - same as `Mix.Project.app_path/0` + * `MIX_COMPILE_PATH` - same as `Mix.Project.compile_path/0` + * `MIX_CONSOLIDATION_PATH` - same as `Mix.Project.consolidation_path/0` + * `MIX_DEPS_PATH` - same as `Mix.Project.deps_path/0` + * `MIX_MANIFEST_PATH` - same as `Mix.Project.manifest_path/0` + * `ERL_EI_LIBDIR` + * `ERL_EI_INCLUDE_DIR` + * `ERTS_INCLUDE_DIR` + * `ERL_INTERFACE_LIB_DIR` + * `ERL_INTERFACE_INCLUDE_DIR` + + These may also be overwritten with the `make_env` option. + + ## Compilation artifacts and working with priv directories + + Generally speaking, compilation artifacts are written to the `priv` + directory, as that the only directory, besides `ebin`, which are + available to Erlang/OTP applications. + + However, note that Mix projects supports the `:build_embedded` + configuration, which controls if assets in the `_build` directory + are symlinked (when `false`, the default) or copied (`true`). + In order to support both options for `:build_embedded`, it is + important to follow the given guidelines: + + * The "priv" directory must not exist in the source code + * The Makefile should copy any artifact to `$MIX_APP_PATH/priv` + or, even better, to `$MIX_APP_PATH/priv/$MIX_TARGET` + * If there are static assets, the Makefile should copy them over + from a directory at the project root (not named "priv") + + """ + + use Mix.Task + alias ElixirMake.Artefact + + @recursive true + + @doc false + def run(args) do + if function_exported?(Mix, :ensure_application!, 1) do + Mix.ensure_application!(:inets) + Mix.ensure_application!(:ssl) + Mix.ensure_application!(:crypto) + end + + config = Mix.Project.config() + app = config[:app] + version = config[:version] + + force_build = + pre_release?(version) or Keyword.get(config, :make_force_build, false) or + Keyword.get(Application.get_env(:elixir_make, :force_build, []), app, false) + + {precompiler_type, precompiler} = config[:make_precompiler] || {nil, nil} + + cond do + precompiler == nil -> + ElixirMake.Compiler.compile(args) + + force_build == true -> + precompiler.build_native(args) + + true -> + rootname = config[:make_precompiler_filename] || "#{app}" + + extname = + case {precompiler_type, :os.type()} do + {:nif, {:win32, _}} -> ".dll" + {:nif, _} -> ".so" + {:port, {:win32, _}} -> ".exe" + {:port, _} -> "" + {_, _} -> raise_unknown_precompiler_type(precompiler_type) + end + + app_priv = Path.join(Mix.Project.app_path(config), "priv") + load_path = Path.join(app_priv, rootname <> extname) + + with false <- File.exists?(load_path), + {:error, message} <- download_or_reuse_nif(config, precompiler, app_priv) do + recover = + case message do + {:unavailable_target, current_target, _description} -> + if function_exported?(precompiler, :unavailable_target, 1) do + precompiler.unavailable_target(current_target) + else + :compile + end + + _ -> + Mix.shell().error(""" + Error happened while installing #{app} from precompiled binary: #{inspect(message)}. + + Attempting to compile #{app} from source...\ + """) + + :compile + end + + case recover do + :compile -> precompiler.build_native(args) + :ignore -> {:ok, []} + end + else + _ -> {:ok, []} + end + end + end + + defp raise_unknown_precompiler_type(precompiler_type) do + Mix.raise("Unknown precompiler type: #{inspect(precompiler_type)} (expected :nif or :port)") + end + + # This is called by Elixir when `mix clean` runs + # and `:elixir_make` is in the list of compilers. + @doc false + def clean() do + config = Mix.Project.config() + {clean_targets, config} = Keyword.pop(config, :make_clean) + + if clean_targets do + config + |> Keyword.put(:make_targets, clean_targets) + |> ElixirMake.Compiler.make([]) + end + end + + defp pre_release?(version) do + "dev" in Version.parse!(version).pre + end + + defp download_or_reuse_nif(config, precompiler, app_priv) do + nif_version = "#{:erlang.system_info(:nif_version)}" + + case Artefact.current_target_url(config, precompiler, nif_version) do + {:ok, target, nif_version_to_use, url} -> + archived_fullpath = Artefact.archive_path(config, target, nif_version_to_use) + + unless File.exists?(archived_fullpath) do + Mix.shell().info("Downloading precompiled NIF to #{archived_fullpath}") + + with {:ok, archived_data} <- Artefact.download(config, url) do + File.mkdir_p(Path.dirname(archived_fullpath)) + File.write(archived_fullpath, archived_data) + end + end + + Artefact.verify_and_decompress(archived_fullpath, app_priv) + + {:error, msg} -> + {:error, msg} + end + end +end diff --git a/deps/elixir_make/lib/mix/tasks/elixir_make.checksum.ex b/deps/elixir_make/lib/mix/tasks/elixir_make.checksum.ex new file mode 100644 index 0000000000000000000000000000000000000000..9280d8c41fa079bfd73f8c7c3cf7cfe4f1a48ff0 --- /dev/null +++ b/deps/elixir_make/lib/mix/tasks/elixir_make.checksum.ex @@ -0,0 +1,172 @@ +defmodule Mix.Tasks.ElixirMake.Checksum do + @shortdoc "Fetch precompiled NIFs and build the checksums" + + @moduledoc """ + A task responsible for downloading the precompiled NIFs for a given module. + + This task must only be used by package creators who want to ship the + precompiled NIFs. The goal is to download the precompiled packages and + generate a checksum to check-in alongside the project in the the Hex repository. + This is done by passing the `--all` flag. + + You can also use the `--only-local` flag to download only the precompiled + package for use during development. + + You can use the `--ignore-unavailable` flag to ignore any NIFs that are not available. + This is useful when you are developing a new NIF that does not support all platforms. + + This task also accept the `--print` flag to print the checksums. + """ + + use Mix.Task + alias ElixirMake.Artefact + + @recursive true + + @switches [ + all: :boolean, + only_local: :boolean, + print: :boolean, + ignore_unavailable: :boolean + ] + + @impl true + def run(flags) when is_list(flags) do + if function_exported?(Mix, :ensure_application!, 1) do + Mix.ensure_application!(:inets) + Mix.ensure_application!(:ssl) + Mix.ensure_application!(:crypto) + end + + config = Mix.Project.config() + + {_, precompiler} = + config[:make_precompiler] || + Mix.raise( + ":make_precompiler project configuration is required when using elixir_make.checksum" + ) + + {options, _args} = OptionParser.parse!(flags, strict: @switches) + + urls = + cond do + Keyword.get(options, :all) -> + Artefact.available_target_urls(config, precompiler) + + Keyword.get(options, :only_local) -> + current_nif_version = "#{:erlang.system_info(:nif_version)}" + + case Artefact.current_target_url(config, precompiler, current_nif_version) do + {:ok, target, nif_version_to_use, url} -> + [{{target, nif_version_to_use}, url}] + + {:error, {:unavailable_target, current_target, error}} -> + recover = + if function_exported?(precompiler, :unavailable_target, 1) do + precompiler.unavailable_target(current_target) + else + :compile + end + + case recover do + :compile -> + Mix.raise(error) + + :ignore -> + [] + end + + {:error, error} -> + Mix.raise(error) + end + + true -> + Mix.raise("you need to specify either \"--all\" or \"--only-local\" flags") + end + + artefacts = download_and_checksum_all(config, urls, options) + + if Keyword.get(options, :print, false) do + artefacts + |> Enum.map(fn %Artefact{basename: basename, checksum: checksum} -> {basename, checksum} end) + |> Enum.sort() + |> Enum.map_join("\n", fn {file, checksum} -> "#{checksum} #{file}" end) + |> IO.puts() + end + + Artefact.write_checksums!(artefacts) + end + + defp download_and_checksum_all(config, urls, options) do + ignore_unavailable? = Keyword.get(options, :ignore_unavailable, false) + + tasks = + Task.async_stream( + urls, + fn {{_target, _nif_version}, url} -> + checksum_algo = Artefact.checksum_algo() + checksum_file_url = "#{url}.#{Atom.to_string(checksum_algo)}" + artifact_checksum = Artefact.download(config, checksum_file_url) + + with {:ok, body} <- artifact_checksum, + [checksum, basename] <- String.split(body, " ", trim: true) do + {:checksum, url, + %Artefact{ + basename: String.trim(basename), + checksum: checksum, + checksum_algo: checksum_algo + }} + else + _ -> {:download, url, Artefact.download(config, url)} + end + end, + timeout: :infinity, + ordered: false + ) + + cache_dir = Artefact.cache_dir() + + Enum.flat_map(tasks, fn + {:ok, {:checksum, _url, artefact}} -> + Mix.shell().info( + "NIF checksum file with checksum #{artefact.checksum} (#{artefact.checksum_algo})" + ) + + [artefact] + + {:ok, {:download, url, download}} -> + case download do + {:ok, body} -> + basename = basename_from_url(url) + path = Path.join(cache_dir, basename) + File.write!(path, body) + artefact = Artefact.checksum(basename, body) + + Mix.shell().info( + "NIF cached at #{path} with checksum #{artefact.checksum} (#{artefact.checksum_algo})" + ) + + [artefact] + + result -> + if ignore_unavailable? do + msg = "Skipped unavailable NIF artifact. Reason: #{inspect(result)}" + Mix.shell().info(msg) + else + msg = "Could not finish the download of NIF artifacts. Reason: #{inspect(result)}" + Mix.shell().error(msg) + end + + [] + end + end) + end + + defp basename_from_url(url) do + uri = URI.parse(url) + + uri.path + |> String.split("/") + |> List.last() + end +end diff --git a/deps/elixir_make/lib/mix/tasks/elixir_make.precompile.ex b/deps/elixir_make/lib/mix/tasks/elixir_make.precompile.ex new file mode 100644 index 0000000000000000000000000000000000000000..79bb2f3fd85b0c83d04b3e9c14f768edbe51be65 --- /dev/null +++ b/deps/elixir_make/lib/mix/tasks/elixir_make.precompile.ex @@ -0,0 +1,103 @@ +defmodule Mix.Tasks.ElixirMake.Precompile do + @shortdoc "Precompiles the given project for all targets" + + @moduledoc """ + Precompiles the given project for all targets. + + This task must only be used by package creators who want to ship the + precompiled NIFs. This task is often used on CI to precompile + for different targets. + + This is only supported if `:make_precompiler` is specified + in your project configuration. + """ + + alias ElixirMake.Artefact + require Logger + use Mix.Task + + @recursive true + + @impl true + def run(args) do + if function_exported?(Mix, :ensure_application!, 1) do + Mix.ensure_application!(:inets) + Mix.ensure_application!(:ssl) + Mix.ensure_application!(:crypto) + end + + config = Mix.Project.config() + paths = config[:make_precompiler_priv_paths] || ["."] + + {_, precompiler} = + config[:make_precompiler] || + Mix.raise( + ":make_precompiler project configuration is required when using elixir_make.precompile" + ) + + targets = precompiler.all_supported_targets(:compile) + + try do + precompiled_artefacts = + Enum.map(targets, fn target -> + case precompiler.precompile(args, target) do + :ok -> + precompiled_artefacts = create_precompiled_archive(config, target, paths) + + if function_exported?(precompiler, :post_precompile_target, 1) do + precompiler.post_precompile_target(target) + end + + Artefact.write_checksum_for_target!(precompiled_artefacts) + + precompiled_artefacts + + {:error, msg} -> + Mix.raise(msg) + end + end) + + Artefact.write_checksums!(precompiled_artefacts) + + if function_exported?(precompiler, :post_precompile, 0) do + precompiler.post_precompile() + else + :ok + end + after + app_priv = Path.join(Mix.Project.app_path(config), "priv") + + for include <- paths, + file <- Path.wildcard(Path.join(app_priv, include)) do + File.rm_rf(file) + end + end + end + + defp create_precompiled_archive(config, target, paths) do + archive_path = Artefact.archive_path(config, target, :erlang.system_info(:nif_version)) + + Mix.shell().info("Creating precompiled archive: #{archive_path}") + Mix.shell().info("Paths to archive from priv directory: #{inspect(paths)}") + + app_priv = Path.join(Mix.Project.app_path(config), "priv") + File.mkdir_p!(app_priv) + File.mkdir_p!(Path.dirname(archive_path)) + + artefact = + File.cd!(app_priv, fn -> + filepaths = + for path <- paths, + entry <- Path.wildcard(path), + do: String.to_charlist(entry) + + Artefact.compress(archive_path, filepaths) + end) + + Mix.shell().info( + "NIF cached at #{archive_path} with checksum #{artefact.checksum} (#{artefact.checksum_algo})" + ) + + artefact + end +end diff --git a/deps/elixir_make/mix.exs b/deps/elixir_make/mix.exs new file mode 100644 index 0000000000000000000000000000000000000000..599fcb3c48af19265fe7e0e6cd6a8a930ab9de61 --- /dev/null +++ b/deps/elixir_make/mix.exs @@ -0,0 +1,44 @@ +defmodule ElixirMake.Mixfile do + use Mix.Project + + @version "0.9.0" + def project do + [ + app: :elixir_make, + version: @version, + elixir: "~> 1.9", + description: "A Make compiler for Mix", + package: package(), + docs: docs(), + deps: deps(), + xref: [exclude: [Mix, :crypto, :ssl, :public_key, :httpc]] + ] + end + + def application do + [extra_applications: [:logger]] + end + + defp deps do + [ + {:ex_doc, "~> 0.20", only: :docs} + ] + end + + defp package do + %{ + licenses: ["Apache-2.0"], + links: %{"GitHub" => "https://github.com/elixir-lang/elixir_make"}, + maintainers: ["Andrea Leopardi", "José Valim"] + } + end + + defp docs do + [ + main: "Mix.Tasks.Compile.ElixirMake", + extras: ["PRECOMPILATION_GUIDE.md", "CHANGELOG.md"], + source_ref: "v#{@version}", + source_url: "https://github.com/elixir-lang/elixir_make" + ] + end +end diff --git a/deps/exla/.formatter.exs b/deps/exla/.formatter.exs new file mode 100644 index 0000000000000000000000000000000000000000..2fc6d249b7e4469c3daf5106b6058e30aa4864fe --- /dev/null +++ b/deps/exla/.formatter.exs @@ -0,0 +1,6 @@ +# Used by "mix format" + +[ + import_deps: [:nx], + inputs: ["{mix,.formatter}.exs", "{bench,examples,config,lib,test}/**/*.{ex,exs}"] +] diff --git a/deps/exla/.hex b/deps/exla/.hex new file mode 100644 index 0000000000000000000000000000000000000000..6dca6ad9e5a850b24faf4e53cca3d5f3b93deb0a Binary files /dev/null and b/deps/exla/.hex differ diff --git a/deps/exla/CHANGELOG.md b/deps/exla/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..f12d065c507bfe20a0d059fa423d35297f9531c7 --- /dev/null +++ b/deps/exla/CHANGELOG.md @@ -0,0 +1,188 @@ +# Changelog + +## v0.10.0 (2025-06-17) + +### Enhancements + + * NIFs now use Fine for wrapping the C++ code + * Nx.to_pointer/2 and Nx.from_pointer/5 now raise on errors + * LU decomposition is now supported in all devices + * New EXLA_CPU_ONLY compilation flag for disabling the CUDA-specific EXLA files + * Update XLA to latest version + +### Bug fixes + + * Device id is now respected when automatic transfers are disabled + * Improve vectorized gather implementation + * Fix hook order inside while loop + +## v0.9.2 (2024-11-16) + +### Enhancements + + * Support cross-compilation for use with Nerves + * Optimize LU with a custom call + +## v0.9.1 (2024-10-08) + +### Enhancements + + * Improve compilation times of native code + +### Bug fixes + + * Fix encoding of binary floats + +## v0.9.0 (2024-09-26) + +### Enhancements + + * Overall improvements to the Nx.Defn compiler + * Compiled functions now work across BEAM nodes + * Add `cache: "path/to/file"` for disk caching JIT/compiled functions + +### Bug fixes + + * Use a single thread pool for MLIR contexts + +## v0.8.0 (2024-08-19) + + * Add `EXLA.to_mlir_module/2` + * The precompiled XLA CUDA binaries now require CUDA 12.1+ and cuDNN 9.1+ + * Renamed `XLA_TARGET` value "cuda120" to "cuda12" + * `XLA_TARGET` automatically defaults to "cuda12" when CUDA installation is detected + * Allow NIF modules to be upgradable + +## v0.7.1 (2024-02-27) + + * Add CustomCallOp for QR decomposition + * Minor improvements to the MLIR modules generated + * MLIR Context pooling for better concurrency + +## v0.7.0 (2024-02-22) + + * Update to latest Nx + * Introduce a `:mlir` based compiler and use it by default. The previous `:xla` based compiler is deprecatead. You can temporarily revert to the previous compiler by setting `config :exla, :compiler_mode, :xla` + +## v0.6.4 (2023-11-13) + + * Update to latest Nx + * Allow `:automatic_transfers` configuration on client + * Do not discard client/device in `EXLA.Backend` when it is host + * Always sort NaN last + * Improve the `:axes` option in `gather`, `indexed_add`, and `indexed_put` + +## v0.6.3 (2023-11-09) + + * Update to latest Nx + * Fix mixed device usage on EXLA.Backend + +## v0.6.1 (2023-09-12) + + * Update to latest Nx + +## v0.6.0 (2023-08-15) + + * Allow cross-device transfers on host + * Update dependencies to OpenXLA + * Update to latest Nx + +## v0.5.3 (2023-04-14) + + * Fix compilation issue on certain macOS caused by O3 + * Fix optimization which would cause EXLA to return a complete tuple instead of a subset + +## v0.5.2 (2023-03-21) + + * Automatically transfer tensors between nodes + +## v0.5.1 (2023-02-18) + + * Support `top_k` + +## v0.5.0 (2023-02-10) + + * Optimize backend_transfer/backend_copy within EXLA backends + * Use relative symlinks on compilation whenever possible + +## v0.4.2 (2023-01-13) + +### Enhancements + + * Automatically transfer from `:host` to other devices + * Support `lazy_transfers: :always` on `EXLA.jit/3` and `EXLA.compile/2` + * Run hooks concurrently once they have received the data + +### Bug fixes + + * Respect default `EXLA.Backend` client when jitting argumentless operations + * Do not pick client without devices when loading initial client + * Consider the first conditional of a `cond` part of the current scope + +## v0.4.1 (2022-12-07) + +### Enhancements + + * [EXLA] Require Nx ~> 0.4.1 + * [EXLA] Update `XLA` to TF2.11 + * [EXLA.Defn] Send telemetry event after XLA compilation + * [EXLA.Op] Add optimization barriers as operations + +### Bug fixes + + * [EXLA] Validate backend options + * [EXLA.Backend] Fix `Nx.{any,all}` with `:keep_axes` + * [EXLA.Backend] Make SVD return `V` instead of `transpose(V)` + * [EXLA.Backend] Preserve NaNs in `window` and `reduce` operations + +## v0.4.0 (2022-10-25) + +### Enhancements + + * Support zero copy binaries + * Redirect group leader for EXLA hooks + +### Bug fixes + + * Always hoist `cond` expressions + * Fix conditional inside `Nx.map` + +## v0.3.0 (2022-08-13) + +### Enhancements + + * Support `debug: true` option on `defn` compiler + * Allow specifying preferred clients via the application environment + * Support new callbacks added in Nx v0.3.0 + +### Deprecations + + * Deprecate `set_as_nx_default` + +## v0.2.3 (2022-07-05) + +### Bug fixes + + * Fix predicate handling inside `cond`/`while` + * Set Nx backend globally + +## v0.2.2 (2022-06-15) + +### Bug fixes + + * Fix invalid cache expiration when defn received functions as arguments + +## v0.2.1 (2022-06-04) + +### Enhancements + + * Implement `EXLA.Backend.to_batched_list/3` + +### Bug fixes + + * Improve support for non-finite values in `EXLA` compiler + * Fix segmentation fault while deallocating tensors + +## v0.2.0 (2022-04-28) + +First release. diff --git a/deps/exla/LICENSE b/deps/exla/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d9a10c0d8e868ebf8da0b3dc95bb0be634c34bfe --- /dev/null +++ b/deps/exla/LICENSE @@ -0,0 +1,176 @@ + 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 diff --git a/deps/exla/Makefile b/deps/exla/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..43e79e3907b3eaadeda42c817714262a1f88381a --- /dev/null +++ b/deps/exla/Makefile @@ -0,0 +1,104 @@ +# Environment variables passed via elixir_make +# ERTS_INCLUDE_DIR +# MIX_APP_PATH + +# XLA extension installation location +XLA_EXTENSION_DIR = cache/xla_extension +XLA_EXTENSION_LIB = $(XLA_EXTENSION_DIR)/lib +XLA_INCLUDE_PATH = $(XLA_EXTENSION_DIR)/include + +# Cache configuration +EXLA_CACHE_SO = cache/libexla.so +EXLA_CACHE_OBJ_DIR = cache/$(EXLA_VERSION)/objs + +# Private configuration +EXLA_DIR = c_src/exla +PRIV_DIR = $(MIX_APP_PATH)/priv +EXLA_SO = $(PRIV_DIR)/libexla.so +EXLA_LIB_DIR = $(PRIV_DIR)/xla_extension/lib + +# Link paths +XLA_EXTENSION_LIB_LINK_PATH = ../$(CWD_RELATIVE_TO_PRIV_PATH)/$(XLA_EXTENSION_LIB) +EXLA_CACHE_SO_LINK_PATH = $(CWD_RELATIVE_TO_PRIV_PATH)/$(EXLA_CACHE_SO) + +# Build flags +# Note that XLA requires c++17, Fine as well +CFLAGS += -fPIC -I$(ERTS_INCLUDE_DIR) -I$(FINE_INCLUDE_DIR) -I$(XLA_INCLUDE_PATH) -Wall -Wno-sign-compare \ + -Wno-unused-parameter -Wno-missing-field-initializers -Wno-comment \ + -std=c++17 -w + +ifdef DEBUG + CFLAGS += -g +else + CFLAGS += -O3 +endif + +NVCC = $(CXX) +NVCCFLAGS = $(CFLAGS) +LDFLAGS += -L$(XLA_EXTENSION_LIB) -lxla_extension -shared -fvisibility=hidden + +ifeq ($(CROSSCOMPILE),) + # Interrogate the system for local compilation + UNAME_S = $(shell uname -s) + +ifndef EXLA_CPU_ONLY +$(info EXLA_CPU_ONLY is not set, checking for nvcc availability) + NVCC_RESULT := $(shell which nvcc 2> /dev/null) + NVCC_TEST := $(notdir $(NVCC_RESULT)) + + ifeq ($(NVCC_TEST),nvcc) +$(info CUDA is available.) + NVCC = nvcc + NVCCFLAGS = -Xcompiler "$(CFLAGS)" -DCUDA_ENABLED + else +$(info CUDA is not available.) + endif +else +$(info EXLA_CPU_ONLY is set, skipping nvcc step) +endif +else + # Determine settings for cross-compiled builds like for Nerves + UNAME_S = Linux +endif + +ifeq ($(UNAME_S), Darwin) + LDFLAGS += -flat_namespace -undefined dynamic_lookup -rpath @loader_path/xla_extension/lib +else + # Use a relative RPATH, so at runtime libexla.so looks for libxla_extension.so + # in ./lib regardless of the absolute location. This way priv can be safely + # packed into an Elixir release. Also, we use $$ to escape Makefile variable + # and single quotes to escape shell variable + LDFLAGS += -Wl,-rpath,'$$ORIGIN/xla_extension/lib' +endif + +$(EXLA_SO): $(EXLA_CACHE_SO) + @ mkdir -p $(PRIV_DIR) + @ mkdir -p $(PRIV_DIR)/xla_extension + @ if [ "${MIX_BUILD_EMBEDDED}" = "true" ]; then \ + cp -a $(abspath $(XLA_EXTENSION_LIB)) $(EXLA_LIB_DIR) ; \ + cp -a $(abspath $(EXLA_CACHE_SO)) $(EXLA_SO) ; \ + else \ + ln -sf $(XLA_EXTENSION_LIB_LINK_PATH) $(EXLA_LIB_DIR) ; \ + ln -sf $(EXLA_CACHE_SO_LINK_PATH) $(EXLA_SO) ; \ + fi + +SOURCES = $(EXLA_DIR)/exla.cc $(EXLA_DIR)/exla_client.cc $(EXLA_DIR)/exla_mlir.cc $(EXLA_DIR)/ipc.cc +SOURCES += $(wildcard $(EXLA_DIR)/custom_calls/*.cc) +HEADERS = $(EXLA_DIR)/exla_mlir.h $(EXLA_DIR)/custom_calls/qr.h $(EXLA_DIR)/custom_calls/eigh.h $(EXLA_DIR)/exla_client.h $(EXLA_DIR)/exla_nif_util.h $(EXLA_DIR)/exla_log_sink.h $(EXLA_DIR)/ipc.h +OBJECTS = $(patsubst $(EXLA_DIR)/%.cc,$(EXLA_CACHE_OBJ_DIR)/%.o,$(SOURCES)) $(EXLA_CACHE_OBJ_DIR)/exla_cuda.o + + +$(EXLA_CACHE_OBJ_DIR)/exla_cuda.o: $(EXLA_DIR)/exla_cuda.cc $(EXLA_DIR)/exla_cuda.h + @ mkdir -p $(EXLA_CACHE_OBJ_DIR) + $(NVCC) $(NVCCFLAGS) -c $< -o $@ + +$(EXLA_CACHE_OBJ_DIR)/%.o: $(EXLA_DIR)/%.cc $(HEADERS) + @ mkdir -p $(EXLA_CACHE_OBJ_DIR) + @ mkdir -p $(EXLA_CACHE_OBJ_DIR)/custom_calls + $(CXX) $(CFLAGS) -c $< -o $@ + +$(EXLA_CACHE_SO): $(XLA_EXTENSION_DIR) $(OBJECTS) + $(CXX) $(OBJECTS) -o $(EXLA_CACHE_SO) $(LDFLAGS) + +clean: + rm -rf cache diff --git a/deps/exla/README.md b/deps/exla/README.md new file mode 100644 index 0000000000000000000000000000000000000000..aa05d44f6356c63fc9d9fd26db474381e0b95ed7 --- /dev/null +++ b/deps/exla/README.md @@ -0,0 +1,173 @@ +

EXLA

+ +[Google's XLA](https://www.tensorflow.org/xla/) (Accelerated Linear Algebra) compiler/backend for Nx. It supports just-in-time (JIT) compilation to GPU (both CUDA and ROCm) and TPUs. + +[See the documentation](https://hexdocs.pm/exla). + +## Installation + +In order to use `EXLA`, you will need Elixir installed. Then create an Elixir project via the `mix` build tool: + +``` +$ mix new my_app +``` + +Then you can add `EXLA` as dependency in your `mix.exs`: + +```elixir +def deps do + [ + {:exla, "~> 0.9"} + ] +end +``` + +If you are using Livebook or IEx, you can instead run: + +```elixir +Mix.install([ + {:exla, "~> 0.9"} +]) +``` + +Once installed, you must configure Nx to use EXLA by default. [Check out the "Configuration" section in the docs](https://hexdocs.pm/exla/EXLA.html#module-configuration) to learn how to do so. + +### XLA binaries + +EXLA relies on the [XLA](https://github.com/elixir-nx/xla) package to provide the necessary XLA binaries. Whenever possible it tries to download precompiled builds, but you may need to build from source if there is no version matching your target environment. For more details, including GPU/TPU support see [the usage section](https://github.com/elixir-nx/xla#usage). + +### Common installation issues + + * Missing Dependencies + * Some Erlang installs do not include some of the dependencies needed to compile the EXLA NIF. You may need to install `erlang-dev` separately. + * Incompatible protocol buffer versions + * Error message: "this file was generated by an older version of protoc which is incompatible with your Protocol Buffer headers". + * If you have `protoc` installed on your machine, it may conflict with the `protoc` precompiled inside XLA. Uninstall, unlink, or remove `protoc` from your path to continue. + * Missing CUDA symbols + * In some cases, you might be compiling a CPU-only version of `:xla` in an environment that has CUDA available. For these cases, you can set the `EXLA_CPU_ONLY` environment variable to any value to disable custom CUDA functionality in EXLA. + +### Usage with Nerves + +For cross-compilation, you need to [set your `XLA_TARGET_PLATFORM` variable](https://github.com/elixir-nx/xla#xla_target_platform) to the correct target platform value (i.e. `aarch64-linux-gnu` for the Raspberry Pi 4). + +## Troubleshooting + +EXLA uses NIFs (C-interface code called from Elixir) for part of its functionality. +If for any reason these fail to compile or load, troubleshooting can be tricky. + +We recommend following the steps below: + + 1. If the error appeared after upgrading EXLA, ensure that you have the proper dependency versions given by [XLA](https://github.com/elixir-nx/xla). Afterwards, compile with `mix compile` after setting `EXLA_FORCE_REBUILD` to clean up cached files: + * `EXLA_FORCE_REBUILD=partial`: Removes the only the libexla.so caches (both local and global ones). + * `EXLA_FORCE_REBUILD=true`: Removes the libexla.so caches but also removes the intermediate `.o` compilation artifacts retained from previous builds. + + Additional notes on compilation: + * Besides the XLA dependency versions, ensuring `gcc` (or your compiler of choice), `libc` and `make` are compatible is also important. + * Remember to save the compilation logs from this step for further debugging. + * It is a good idea to save the `cache//libexla.so` file so that the team can inspect its contents if needed. + 2. If the error persists, look for the `** (RuntimeError) Failed to load NIF library.` exception on application start-up. + This exception should provide more information on what's the issue when loading the NIF. Share these logs in an issue on GitHub + so that the Nx team can investigate further. + + +## Contributing + +### Building locally + +EXLA is a regular Elixir project, therefore, to run it locally: + +```shell +mix deps.get +mix test +``` + +By default, EXLA passes `["-jN"]` as a Make argument, where `N` is `System.schedulers_online() - 2`, capped at `1`. `config :exla, :make_args, ...` can be used to override this default setting. + +In order to run tests on a specific device, use the `EXLA_TARGET` environment variable, which is a dev-only variable for this project (it has no effect when using EXLA as a dependency). For example, `EXLA_TARGET=cuda` or `EXLA_TARGET=rocm`. Make sure to also specify `XLA_TARGET` to fetch or compile a proper version of the XLA binary. + +### Building with Docker + +The easiest way to build is with [Docker](https://docs.docker.com/get-docker/). For GPU support, you'll also need to set up the [NVIDIA Container Toolkit](https://github.com/NVIDIA/nvidia-docker). + +To build, clone this repo, select your preferred Dockerfile, and run: + +```shell +docker build --rm -t exla:host . # Host Docker image +docker build --rm -t exla:cuda10.2 . # CUDA 10.2 Docker image +docker build --rm -t exla:rocm . # ROCm Docker image +``` + +Then to run (without Cuda): + +```shell +docker run -it \ + -v $PWD:$PWD \ + -e TEST_TMPDIR=$PWD/tmp/bazel_cache \ + -e BUILD_CACHE=$PWD/tmp/xla_extension_cache \ + -w $PWD \ + --rm exla:host bash +``` + +With CUDA enabled: + +*Note: XLA_TARGET should match your CUDA version. See: https://github.com/elixir-nx/xla#xla_target* + +```shell +docker run -it \ + -v $PWD:$PWD \ + -e TEST_TMPDIR=$PWD/tmp/bazel_cache \ + -e BUILD_CACHE=$PWD/tmp/xla_extension_cache \ + -e XLA_TARGET=cuda102 \ + -e EXLA_TARGET=cuda \ + -w $PWD \ + --gpus=all \ + --rm exla:cuda10.2 bash +``` + +With ROCm enabled: + +```shell +docker run -it \ + -v $PWD:$PWD \ + -e TEST_TMPDIR=$PWD/tmp/bazel_cache \ + -e BUILD_CACHE=$PWD/tmp/xla_extension_cache \ + -e XLA_TARGET=rocm \ + -e EXLA_TARGET=rocm \ + -w $PWD \ + --device=/dev/kfd \ + --device=/dev/dri \ + --group-add video \ + --rm exla:rocm bash +``` + +Inside the container you can interact with the API from IEx using: + +```shell +iex -S mix +``` + +Or you can run an example: + +```shell +mix run examples/regression.exs +``` + +To run tests: + +```shell +mix test +``` + +## License + +Copyright (c) 2020 Sean Moriarity + +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](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/deps/exla/c_src/exla/exla_client.cc b/deps/exla/c_src/exla/exla_client.cc new file mode 100644 index 0000000000000000000000000000000000000000..9d58239401b46ed89a037c04a07a8ba2b1c4af38 --- /dev/null +++ b/deps/exla/c_src/exla/exla_client.cc @@ -0,0 +1,443 @@ +#include "exla_client.h" + +#include +#include +#include "exla_nif_util.h" +#include "xla/layout_util.h" +#include "xla/pjrt/cpu/cpu_client.h" +#include "xla/pjrt/gpu/gpu_helpers.h" +#include "xla/pjrt/gpu/se_gpu_pjrt_client.h" +#include "xla/pjrt/pjrt_api.h" +#include "xla/pjrt/pjrt_c_api_client.h" +#include "xla/pjrt/pjrt_compiler.h" +#include "xla/pjrt/tfrt_cpu_pjrt_client.h" +#include "xla/shape_util.h" +#include + +namespace exla { + +ExlaBuffer::ExlaBuffer(std::unique_ptr buffer) : buffer_(std::move(buffer)) {} + +void CopyLiteralToBinary(xla::Literal* literal, ErlNifBinary* binary, exla::int64 size) { + exla::int64 actual_size = literal->size_bytes(); + if (size < 0 or size > actual_size) size = actual_size; + enif_alloc_binary(size, binary); + std::memcpy(binary->data, literal->untyped_data(), size); +} + +tsl::StatusOr ExlaBuffer::ToBinary(ErlNifEnv* env, exla::int64 size) { + EXLA_ASSIGN_OR_RETURN(std::shared_ptr literal, buffer_->ToLiteralSync()); + + exla::int64 actual_size = literal->size_bytes(); + if (size < 0 or size > actual_size) size = actual_size; + + ERL_NIF_TERM binary_term; + auto data = enif_make_new_binary(env, size, &binary_term); + memcpy(data, literal->untyped_data(), size); + + return binary_term; +} + +tsl::Status ExlaBuffer::Deallocate() { + if (buffer_->IsDeleted()) { + return xla::FailedPrecondition("Attempt to deallocate already deallocated buffer."); + } else { + buffer_->Delete(); + return tsl::OkStatus(); + } +} + +tsl::StatusOr> ExlaBuffer::CopyToDevice(xla::PjRtDevice* dst_device) { + EXLA_ASSIGN_OR_RETURN(auto memory_space, + dst_device->default_memory_space()); + EXLA_ASSIGN_OR_RETURN(std::unique_ptr buf, + buffer_->CopyToMemorySpace(memory_space)); + return fine::make_resource(std::move(buf)); +} + +ExlaExecutable::ExlaExecutable(std::unique_ptr executable, + absl::optional fingerprint, + ExlaClient* client) : executable_(std::move(executable)), + fingerprint_(std::move(fingerprint)), + client_(client) {} + +tsl::StatusOr> PjRtBufferFromBinary(xla::PjRtClient* client, + ERL_NIF_TERM source_term, + const xla::Shape& shape, + int device_id) { + // We copy the binary term into a new env and point the buffer to + // the binary content. Since larger binaries are shared and refcounted + // this should be zero-copy. + + ErlNifEnv* copy_env = enif_alloc_env(); + ERL_NIF_TERM dest_term = enif_make_copy(copy_env, source_term); + + auto binary = fine::decode(copy_env, dest_term); + + xla::PjRtClient::HostBufferSemantics semantics = xla::PjRtClient::HostBufferSemantics::kImmutableZeroCopy; + std::function on_done_with_host_buffer = [copy_env]() { enif_free_env(copy_env); }; + + EXLA_ASSIGN_OR_RETURN(xla::PjRtDevice * device, client->LookupDevice(xla::PjRtGlobalDeviceId(device_id))); + EXLA_ASSIGN_OR_RETURN(auto memory_space, device->default_memory_space()); + // Passing std::nullopt should work, but it fails for subbyte types, + // so we build the default strides. See https://github.com/openxla/xla/issues/16795 + auto byte_strides = xla::ShapeUtil::ByteStrides(shape); + EXLA_ASSIGN_OR_RETURN(auto buffer, client->BufferFromHostBuffer( + binary.data, shape.element_type(), shape.dimensions(), byte_strides, semantics, on_done_with_host_buffer, memory_space, /*device_layout=*/nullptr)); + + return std::move(buffer); +} + +tsl::StatusOr>> +UnpackRunArguments(ErlNifEnv* env, + ExlaExecutable::RunArguments arguments, + std::vector> &transient_buffers, + ExlaClient* client, + xla::DeviceAssignment device_assignment, + int device_id) { + std::vector> arg_buffers; + arg_buffers.reserve(arguments.size()); + + int replica = 0; + + for (const auto & replica_arguments : arguments) { + auto device = device_id >= 0 ? device_id : device_assignment(replica, 0); + + auto replica_buffers = std::vector(); + replica_buffers.reserve(replica_arguments.size()); + + // For a single replica, the argument is a flat list of buffers where + // each buffer can either be an erlang binary or a reference to another + // EXLA buffer, it is not possible for any of the arguments to be nested + // tuples because we handle normalization/flattening of tuples on the + // Elixir side + for (const auto & argument : replica_arguments) { + if (auto value = std::get_if>(&argument)) { + auto [term, shape] = *value; + // We convert the binary into a buffer and transfer it to the + // correct device, this buffer is not managed by the erlang vm + // so it must be deallocated explicitly after use by the execution + EXLA_ASSIGN_OR_RETURN(std::unique_ptr buf, + PjRtBufferFromBinary(client->client(), term, shape, device)); + replica_buffers.push_back(buf.get()); + // Keep track of the buffer pointer, for automatic deallocation later + transient_buffers.push_back(std::move(buf)); + } else if (auto value = std::get_if>(&argument)) { + auto buffer = *value; + // if the buffer is not a tuple it must be a reference to an exla buffer + // which means the resource is already managed by the vm, and should already + // be on the correct device, if it is not, we will not do any implicit transfers + // and instead raise an error + if (buffer->device_id() != device) { + return xla::InvalidArgument("Expected buffer to be placed on device %d", device); + } + replica_buffers.push_back(buffer->buffer()); + } + } + + arg_buffers.push_back(std::move(replica_buffers)); + + replica++; + } + + return arg_buffers; +} + +ExlaExecutable::RunResult UnpackResult(ErlNifEnv* env, + std::vector>> result, + xla::DeviceAssignment device_assignment, + int device_id) { + auto per_replica_results = std::vector>, int64_t>>(); + + for (int i = 0; i < result.size(); i++) { + auto replica_results = std::vector>(); + int64_t device = device_id >= 0 ? device_id : device_assignment(i, 0); + + for (auto& pjrt_buf : result.at(i)) { + pjrt_buf->GetReadyFuture().Await(); + auto result = fine::make_resource(std::move(pjrt_buf)); + replica_results.push_back(result); + } + + per_replica_results.push_back(std::make_tuple(std::move(replica_results), device)); + } + + return per_replica_results; +} + +tsl::StatusOr ExlaExecutable::Run(ErlNifEnv* env, + ExlaExecutable::RunArguments arguments, + int device_id) { + xla::ExecuteOptions options; + // arguments are not passed as a single PjRt tuple buffer, but instead + // as multiple pjrt buffers + options.arguments_are_tupled = false; + // result is a tuple, which pjrt decomposes into a vector of buffers for + // us to handle ourselves + options.untuple_result = true; + // we do not handle multi-device launches at this time, so this must always + // be set to 0 + options.launch_id = 0; + // disable strict shape checking which ensures shapes of buffers match exact + // shape (with layout) expected be compiled executable, we have mismatches + // on gpu + options.strict_shape_checking = false; + // execution mode determines whether or not to launch the executable in the + // calling thread or in a separate thread, default mode is either-or, here + // we specify synchronous because the Elixir side ensures execution is always + // synchronous + options.execution_mode = xla::ExecuteOptions::ExecutionMode::kSynchronous; + + // the number of replicas will equal the number of devices involved in + // a pmap, but in all other cases it will be equal to 1 + int num_replicas = executable_->num_replicas(); + + // input buffers are a list of lists, where each list maps to the args + // to pass to one of the replicas in a computation, e.g. [replica_args1, replica_args2, ...] + std::vector> input_buffers; + + // the device assignment is a 2d array which maps coordinates (replica, partition) + // to a device; or in this case just maps a replica to a device + xla::DeviceAssignment device_assignment; + if (client_->client()->platform_name() == "METAL") { + device_assignment = xla::DeviceAssignment(1, 1); + } else { + EXLA_ASSIGN_OR_RETURN(device_assignment, + client_->client()->GetDefaultDeviceAssignment(num_replicas, 1)); + } + + // Buffers allocated from binaries for this specific run need to be + // freed at the end. We store the corresponding pointers in this + // vector, so they are all freed automatically when this function + // finishes + auto transient_buffers = std::vector>(); + + if (device_id >= 0 && num_replicas > 1) { + // if the device id is greater than or equal to 1, that means we've specified + // a portable executable which cannot be pmapped, this code path should never + // be reached as it should be controlled from Elixir + return xla::InvalidArgument("Cannot specify a device for replicated executable."); + } else { + // else we handle unpacking/validating the run arguments to the correct devices + // according to the device id and the device assignment + EXLA_ASSIGN_OR_RETURN(input_buffers, UnpackRunArguments(env, arguments, transient_buffers, client_, device_assignment, device_id)); + } + + // at this point input buffers is a vector of arguments per replica + // and the size of that vector should equal the number of replicas in the + // executable, otherwise it is invalid + if (num_replicas != input_buffers.size()) { + return xla::InvalidArgument("Got %d replica arguments for %d replicas", input_buffers.size(), num_replicas); + } + + std::vector>> per_replica_results; + + if (device_id >= 0) { + // if we specified a device id, then we need to execute the executable as a portable + // executable, meaning we need to find the device corresponding to the specific device + // id and execute on that device, we've already guaranteed this executable only has 1 + // replica + EXLA_ASSIGN_OR_RETURN(xla::PjRtDevice * device, client_->client()->LookupDevice(xla::PjRtGlobalDeviceId(device_id))); + // because this is a portable executable, it only has 1 replica and so we only need + // to get the arguments at the first position of the input buffers + std::vector portable_args = input_buffers.at(0); + EXLA_ASSIGN_OR_RETURN(auto portable_result, + executable_->ExecutePortable(portable_args, device, options)); + // the logic for handling unpacking of results is shared between portable code path + // and the replicated code-path, so we take ownership of the result buffers to unpack + per_replica_results.push_back(std::move(portable_result)); + } else { + // no device ID is present, so it may be a replicated executable which means we need + // to use the replica execution path + // TODO: This now exposes a `returned_futures` API, does this make sense for us? + EXLA_ASSIGN_OR_RETURN(per_replica_results, executable_->Execute(input_buffers, options)); + } + + // EXLA_ASSIGN_OR_RETURN(per_replica_results, executable_->Execute(input_buffers, options)); + + // sanity check + if (per_replica_results.size() != num_replicas) { + return xla::FailedPrecondition("Invalid execution."); + } + + // we need to unpack the results into Erlang terms, the result is a vector + // of vectors of unique ptrs to pjrt buffers, where the size of the output equals + // the number of replicas and each individual replica is a vector of buffers, the + // inner buffer represents a flattened output because we told PjRt we would always + // return a tuple from the computation + auto ret = UnpackResult(env, std::move(per_replica_results), device_assignment, device_id); + + return ret; +} + +ExlaClient::ExlaClient(std::shared_ptr client) : client_(std::move(client)) {} + +tsl::StatusOr> ExlaClient::BufferFromBinary(ERL_NIF_TERM source_term, + xla::Shape& shape, + int device_id) { + EXLA_ASSIGN_OR_RETURN(auto buffer, PjRtBufferFromBinary(client(), source_term, shape, device_id)); + return fine::make_resource(std::move(buffer)); +} + +tsl::StatusOr> ExecutableFingerprint(std::unique_ptr& executable) { + auto fingerprint = executable->FingerprintExecutable(); + + if (fingerprint.ok()) { + return {fingerprint.value()}; + } else if (fingerprint.status().code() == absl::StatusCode::kUnimplemented) { + // Return nullopt in case of unimplemented error. + return std::nullopt; + } else { + return fingerprint.status(); + } +} + +tsl::StatusOr> ExlaClient::DeserializeExecutable(std::string deserialized_executable) { + EXLA_ASSIGN_OR_RETURN(std::unique_ptr executable, + client_->LoadSerializedExecutable(deserialized_executable, std::nullopt, xla::LoadOptions())); + + EXLA_ASSIGN_OR_RETURN(absl::optional fingerprint, + ExecutableFingerprint(executable)); + + return fine::make_resource(std::move(executable), std::move(fingerprint), this); +} + +tsl::StatusOr> ExlaClient::Compile(mlir::ModuleOp module, + std::vector argument_layouts, + xla::ExecutableBuildOptions& options, + bool compile_portable_executable) { + std::vector layouts; + layouts.reserve(argument_layouts.size()); + for (auto shape : argument_layouts) { + xla::Shape cpy_shape = xla::ShapeUtil::MakeShape(shape.element_type(), shape.dimensions()); + xla::LayoutUtil::ClearLayout(&cpy_shape); + layouts.push_back(cpy_shape); + } + + xla::CompileOptions compile_opts; + compile_opts.argument_layouts = layouts; + compile_opts.parameter_is_tupled_arguments = false; + compile_opts.executable_build_options = options; + compile_opts.compile_portable_executable = compile_portable_executable; + + EXLA_ASSIGN_OR_RETURN(std::unique_ptr executable, + client_->CompileAndLoad(module, std::move(compile_opts))); + EXLA_ASSIGN_OR_RETURN(absl::optional fingerprint, + ExecutableFingerprint(executable)); + + return fine::make_resource(std::move(executable), std::move(fingerprint), this); +} + +tsl::Status ExlaClient::TransferToInfeed(ErlNifEnv* env, + std::vector buffer_bins, + std::vector shapes, + int device_id) { + std::vector buf_ptrs; + buf_ptrs.reserve(buffer_bins.size()); + + for (const auto& buffer_bin : buffer_bins) { + const char* data_ptr = const_cast(reinterpret_cast(buffer_bin.data)); + buf_ptrs.push_back(data_ptr); + } + + auto shape = xla::ShapeUtil::MakeTupleShape(shapes); + + // Instead of pushing each buffer separately, we create a flat tuple + // literal and push the whole group of buffers. + // + // On the CPU, XLA infeed reads buffers from a queue one at a time [1][2] + // (or rather, the infeed operation is lowered to multiple queue reads), + // hence pushing one at a time works fine. Pushing a flat tuple works + // effectively the same, since it basically adds each element to the + // queue [3]. + // + // On the GPU, XLA infeed reads only a single "literal" from a queue [4] + // and expects it to carry all buffers for the given infeed operation. + // Consequently, we need to push all buffers as a single literal. + // + // Given that a flat tuple works in both cases, we just do that. + // + // [1]: https://github.com/openxla/xla/blob/fd58925adee147d38c25a085354e15427a12d00a/xla/service/cpu/ir_emitter.cc#L449-L450 + // [2]: https://github.com/openxla/xla/blob/fd58925adee147d38c25a085354e15427a12d00a/xla/service/cpu/cpu_runtime.cc#L222 + // [3]: https://github.com/openxla/xla/blob/fd58925adee147d38c25a085354e15427a12d00a/xla/service/cpu/cpu_xfeed.cc#L178 + // [4]: https://github.com/openxla/xla/blob/fd58925adee147d38c25a085354e15427a12d00a/xla/service/gpu/runtime/infeed_thunk.cc#L40-L41 + xla::BorrowingLiteral literal(buf_ptrs, shape); + + EXLA_ASSIGN_OR_RETURN(xla::PjRtDevice * device, client_->LookupDevice(xla::PjRtGlobalDeviceId(device_id))); + + tsl::Status status = device->TransferToInfeed(literal); + + return status; +} + +tsl::StatusOr ExlaClient::TransferFromOutfeed(ErlNifEnv* env, int device_id, xla::Shape& shape) { + EXLA_ASSIGN_OR_RETURN(xla::PjRtDevice * device, client_->LookupDevice(xla::PjRtGlobalDeviceId(device_id))); + + auto literal = std::make_shared(shape); + + auto transfer_status = device->TransferFromOutfeed(literal.get()); + + if (!transfer_status.ok()) { + return transfer_status; + } + + auto size = literal->size_bytes(); + + ERL_NIF_TERM binary_term; + auto data = enif_make_new_binary(env, size, &binary_term); + memcpy(data, literal->untyped_data(), size); + + return binary_term; +} + +tsl::StatusOr> GetHostClient() { + xla::CpuClientOptions options; + options.asynchronous = false; + EXLA_ASSIGN_OR_RETURN(std::unique_ptr client, + xla::GetXlaPjrtCpuClient(options)); + + return fine::make_resource(std::move(client)); +} + +tsl::StatusOr> GetGpuClient(double memory_fraction, + bool preallocate, + xla::GpuAllocatorConfig::Kind kind) { + xla::GpuAllocatorConfig allocator_config = { + .kind = kind, + .memory_fraction = memory_fraction, + .preallocate = preallocate}; + + xla::GpuClientOptions client_options = { + .allocator_config = allocator_config}; + + EXLA_ASSIGN_OR_RETURN(std::unique_ptr client, + xla::GetStreamExecutorGpuClient(client_options)); + + return fine::make_resource(std::move(client)); +} + +tsl::StatusOr> GetTpuClient() { + auto statusor = pjrt::LoadPjrtPlugin("tpu", "libtpu.so"); + if (!statusor.ok()) { + return statusor.status(); + } + + tsl::Status status = pjrt::InitializePjrtPlugin("tpu"); + + if (!status.ok()) { + return status; + } + + EXLA_ASSIGN_OR_RETURN(std::unique_ptr client, + xla::GetCApiClient("TPU")); + + return fine::make_resource(std::move(client)); +} + +tsl::StatusOr> GetCApiClient(std::string device_type) { + EXLA_ASSIGN_OR_RETURN(std::unique_ptr client, + xla::GetCApiClient(device_type)); + + return fine::make_resource(std::move(client)); +} +} // namespace exla diff --git a/deps/exla/c_src/exla/exla_cuda.cc b/deps/exla/c_src/exla/exla_cuda.cc new file mode 100644 index 0000000000000000000000000000000000000000..f3851de5d5971d9d198dee7e324318a41b4b8ec8 --- /dev/null +++ b/deps/exla/c_src/exla/exla_cuda.cc @@ -0,0 +1,64 @@ +#include "exla_cuda.h" + +#ifdef CUDA_ENABLED +#include + +#include +#include +#include +#include + +std::optional get_cuda_ipc_handle(std::uintptr_t ptr) { + cudaIpcMemHandle_t ipc_handle; + cudaError_t status = cudaIpcGetMemHandle(&ipc_handle, reinterpret_cast(ptr)); + + if (status != cudaSuccess) { + return std::nullopt; + } + + // Assuming sizeof(cudaIpcMemHandle_t) is constant + const size_t size = sizeof(cudaIpcMemHandle_t); + + // Copy the memory handle to a buffer + auto buffer = std::string(reinterpret_cast(&ipc_handle), size); + + return buffer; +} + +std::optional get_pointer_for_ipc_handle(uint8_t* handle_bin, size_t handle_size, int device_id) { + if (handle_size != sizeof(cudaIpcMemHandle_t)) { + return std::nullopt; + } + + unsigned char ipc_handle_data[sizeof(cudaIpcMemHandle_t)]; + for (int i = 0; i < sizeof(cudaIpcMemHandle_t); i++) { + ipc_handle_data[i] = handle_bin[i]; + } + + cudaIpcMemHandle_t ipc_handle; + memcpy(&ipc_handle, ipc_handle_data, sizeof(cudaIpcMemHandle_t)); + + int* ptr; + cudaError_t cuda_status = cudaSetDevice(device_id); // Assuming device 0, change as needed + if (cuda_status != cudaSuccess) { + printf("Error setting CUDA device: %s\n", cudaGetErrorString(cuda_status)); + return std::nullopt; + } + + cuda_status = cudaIpcOpenMemHandle((void**)&ptr, ipc_handle, cudaIpcMemLazyEnablePeerAccess); + if (cuda_status != cudaSuccess) { + printf("Error opening CUDA IPC memory handle: %s\n", cudaGetErrorString(cuda_status)); + return std::nullopt; + } + + return ptr; +} +#else +std::optional get_cuda_ipc_handle(std::uintptr_t ptr) { + return std::nullopt; +} + +std::optional get_pointer_for_ipc_handle(uint8_t* handle_bin, size_t handle_size, int device_id) { + return std::nullopt; +} +#endif diff --git a/deps/exla/c_src/exla/exla_cuda.h b/deps/exla/c_src/exla/exla_cuda.h new file mode 100644 index 0000000000000000000000000000000000000000..10c258fb1228c90d90d9e6711fe97c4b6d0d2fa3 --- /dev/null +++ b/deps/exla/c_src/exla/exla_cuda.h @@ -0,0 +1,10 @@ +#pragma once + +#include +#include +#include +#include +#include + +std::optional get_cuda_ipc_handle(std::uintptr_t); +std::optional get_pointer_for_ipc_handle(uint8_t *, size_t, int); diff --git a/deps/exla/c_src/exla/exla_mlir.cc b/deps/exla/c_src/exla/exla_mlir.cc new file mode 100644 index 0000000000000000000000000000000000000000..c4aabdcd9e8566c8701f5564bb823af0192db029 --- /dev/null +++ b/deps/exla/c_src/exla/exla_mlir.cc @@ -0,0 +1,155 @@ +#include "exla_mlir.h" + +#include +#include "mlir/IR/Builders.h" +#include "mlir/IR/BuiltinTypes.h" +#include "mlir/AsmParser/AsmParser.h" +#include "mlir/IR/Region.h" + +namespace exla { +MLIRFunction::MLIRFunction(fine::ResourcePtr module, std::unique_ptr func) + : func_(std::move(func)), + module_(module) {} + +std::vector> MLIRFunction::Op( + std::string op_name, std::vector> operands, + std::vector result_types, + std::vector> attributes, + std::vector> regions) { + auto builder = module_->builder(); + auto context = builder->getContext(); + + auto types_range = mlir::TypeRange{llvm::ArrayRef{result_types}}; + + auto named_attributes = std::vector{}; + for (auto const &[key, value] : attributes) { + auto attribute = builder->getNamedAttr(key, value); + named_attributes.push_back(attribute); + } + + + auto operand_values = std::vector(); + operand_values.reserve(operands.size()); + for (const auto &operand : operands) { + operand_values.push_back(*operand); + } + + auto operands_range = mlir::ValueRange{llvm::ArrayRef{operand_values}}; + auto attributes_array = llvm::ArrayRef{named_attributes}; + + setInsertionPoint(); + + auto op_state = mlir::OperationState{mlir::UnknownLoc::get(context), + builder->getStringAttr(op_name), + operands_range, + types_range, + attributes_array, + {}, + {}}; + + for (auto region : regions) { + auto new_region = op_state.addRegion(); + new_region->getBlocks().splice(new_region->end(), region->getBlocks()); + } + + auto op = builder->create(op_state); + + auto result_values = op->getResults(); + + auto results = std::vector>(); + results.reserve(result_values.size()); + for (const auto &result : result_values) { + results.push_back(fine::make_resource(result)); + } + + return results; +} + +std::tuple, std::vector>> +MLIRFunction::PushRegion(std::vector types) { + auto context = module_->builder()->getContext(); + + auto region = fine::make_resource(); + auto & block = region->emplaceBlock(); + + for (mlir::Type type : types) { + block.addArgument(type, mlir::UnknownLoc::get(context)); + } + + auto args = std::vector>(); + for (auto &arg : block.getArguments()) { + args.push_back(fine::make_resource(arg)); + } + + region_stack.push(region); + setInsertionPoint(); + + return std::make_tuple(region, args); +} + +void MLIRFunction::PopRegion() { + region_stack.pop(); + setInsertionPoint(); +} + +void MLIRFunction::setInsertionPoint() { + if (region_stack.size() == 0) { + module_->builder()->setInsertionPointToEnd(&func_->getBody().back()); + } else { + module_->builder()->setInsertionPointToEnd(®ion_stack.top()->back()); + } +} + +MLIRModule::MLIRModule(fine::ResourcePtr context) { + context_ = context; + module_ = mlir::OwningOpRef(mlir::ModuleOp::create(mlir::UnknownLoc::get(context_.get()))); + builder_ = std::make_unique(context_.get()); + builder_->setInsertionPointToStart(module_->getBody()); +} + +std::unique_ptr MLIRModule::CreateFunction( + std::string name, + std::vector arg_types, + std::vector ret_types, + bool is_public) { + auto visibility = is_public ? "public" : "nested"; + + auto funcType = builder_->getFunctionType(arg_types, ret_types); + auto loc = builder_->getUnknownLoc(); + auto funcOp = std::make_unique(mlir::func::FuncOp::create(loc, name, funcType)); + funcOp->setSymVisibility(visibility); + module_->push_back(*funcOp); + funcOp->addEntryBlock(); + builder_->setInsertionPointToStart(&funcOp->getBody().front()); + + return funcOp; +} + +std::string MLIRModule::ToString() { + auto output_string = std::string{}; + auto output_stream = llvm::raw_string_ostream{output_string}; + module_->print(output_stream); + return output_string; +} + +mlir::Type MLIRModule::ParseType(std::string string) { + auto type = mlir::parseType(string, context_.get()); + + if (type == nullptr) { + throw std::runtime_error("unable to parse MLIR type: " + string); + } + + return type; +} + +mlir::Attribute MLIRModule::ParseAttribute(std::string string) { + auto attribute = mlir::parseAttribute(string, context_.get()); + + if (attribute == nullptr) { + throw std::runtime_error("unable to parse MLIR type: " + string); + } + + return attribute; +} + +} // namespace exla diff --git a/deps/exla/c_src/exla/exla_types.h b/deps/exla/c_src/exla/exla_types.h new file mode 100644 index 0000000000000000000000000000000000000000..dd73c924225180815590f3f36d0b72473e7efdd4 --- /dev/null +++ b/deps/exla/c_src/exla/exla_types.h @@ -0,0 +1,31 @@ +#pragma once + +#include + +#include "tsl/platform/types.h" +#include "Eigen/Core" // from @eigen_archive + +namespace exla { +// We standardize numeric types with tensorflow to ensure we are always +// getting an input with the correct width and to ensure that tensorflow +// is happy with what we're giving it. +// +// Most of these types will only ever be used when creating scalar constants; +// however, some methods require a 64-bit integer. You should prefer standard +// types over these unless you are (1) working with computations, or +// (2) require a non-standard width numeric type (like 64-bit integer). +using int8 = tsl::int8; +using int16 = tsl::int16; +using int32 = tsl::int32; +using int64 = tsl::int64; +using uint8 = tsl::uint8; +using uint16 = tsl::uint16; +using uint32 = tsl::uint32; +using uint64 = tsl::uint64; +using float16 = Eigen::half; +using bfloat16 = tsl::bfloat16; +using float32 = float; +using float64 = double; +using complex64 = std::complex; +using complex128 = std::complex; +} // namespace exla diff --git a/deps/exla/c_src/exla/ipc.cc b/deps/exla/c_src/exla/ipc.cc new file mode 100644 index 0000000000000000000000000000000000000000..afcbb0985923f3f38379e0052ff73f48a1e2f5af --- /dev/null +++ b/deps/exla/c_src/exla/ipc.cc @@ -0,0 +1,46 @@ +#include "ipc.h" + +#include +#include +#include +#include +#include + +// Function to create or open a shared memory object and set its size +int get_ipc_handle(const char* memname, size_t memsize) { + int fd = shm_open(memname, O_CREAT | O_RDWR, 0666); + if (fd == -1) { + return -1; + } + + if (ftruncate(fd, memsize) == -1) { + close(fd); + return -1; + } + + return fd; +} + +// Function to map the shared memory in this process +void* open_ipc_handle(int fd, size_t memsize) { + void* ptr = mmap(NULL, memsize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (ptr == MAP_FAILED) { + perror("mmap"); + return nullptr; + } + return ptr; +} + +int close_ipc_handle(int fd, void* ptr, const char* memname, size_t memsize) { + if (munmap(ptr, memsize) == -1) { + return -1; + } + + if (close(fd) == -1) { + return -1; + } + + shm_unlink(memname); + + return 0; +} diff --git a/deps/exla/c_src/exla/ipc.h b/deps/exla/c_src/exla/ipc.h new file mode 100644 index 0000000000000000000000000000000000000000..f11a13d582b974e95c24b7b8f65da2e275896424 --- /dev/null +++ b/deps/exla/c_src/exla/ipc.h @@ -0,0 +1,7 @@ +#pragma once + +#include + +int get_ipc_handle(const char* memname, size_t memsize); +void* open_ipc_handle(int fd, size_t memsize); +int close_ipc_handle(int fd, void* ptr, const char* memname, size_t memsize); diff --git a/deps/exla/hex_metadata.config b/deps/exla/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..4d4660a719e5d9521c3b8247e4778151071d4071 --- /dev/null +++ b/deps/exla/hex_metadata.config @@ -0,0 +1,74 @@ +{<<"links">>,[{<<"GitHub">>,<<"https://github.com/elixir-nx/nx">>}]}. +{<<"name">>,<<"exla">>}. +{<<"version">>,<<"0.10.0">>}. +{<<"description">>, + <<"Google's XLA (Accelerated Linear Algebra) compiler/backend for Nx">>}. +{<<"elixir">>,<<"~> 1.15">>}. +{<<"app">>,<<"exla">>}. +{<<"licenses">>,[<<"Apache-2.0">>]}. +{<<"files">>, + [<<"lib">>,<<"lib/exla.ex">>,<<"lib/exla">>,<<"lib/exla/client.ex">>, + <<"lib/exla/logger.ex">>,<<"lib/exla/binary_buffer.ex">>, + <<"lib/exla/backend.ex">>,<<"lib/exla/defn.ex">>,<<"lib/exla/lib.ex">>, + <<"lib/exla/mlir">>,<<"lib/exla/mlir/region.ex">>, + <<"lib/exla/mlir/context_pool.ex">>,<<"lib/exla/mlir/module.ex">>, + <<"lib/exla/mlir/value.ex">>,<<"lib/exla/mlir/function.ex">>, + <<"lib/exla/typespec.ex">>,<<"lib/exla/device_buffer.ex">>, + <<"lib/exla/nif.ex">>,<<"lib/exla/application.ex">>, + <<"lib/exla/executable.ex">>,<<"lib/exla/defn">>, + <<"lib/exla/defn/runner.ex">>,<<"lib/exla/defn/disk.ex">>, + <<"lib/exla/defn/locked_cache.ex">>,<<"lib/exla/defn/buffers.ex">>, + <<"lib/exla/defn/lock.ex">>,<<"lib/exla/defn/outfeed.ex">>, + <<".formatter.exs">>,<<"mix.exs">>,<<"README.md">>,<<"LICENSE">>, + <<"CHANGELOG.md">>,<<"c_src">>,<<"c_src/exla">>, + <<"c_src/exla/exla_cuda.h">>,<<"c_src/exla/ipc.h">>, + <<"c_src/exla/exla_log_sink.h">>,<<"c_src/exla/custom_calls">>, + <<"c_src/exla/custom_calls/lu.h">>,<<"c_src/exla/custom_calls/qr.h">>, + <<"c_src/exla/custom_calls/lu_f64.cc">>, + <<"c_src/exla/custom_calls/eigh_f32.cc">>, + <<"c_src/exla/custom_calls/qr_f32.cc">>, + <<"c_src/exla/custom_calls/qr_f16.cc">>, + <<"c_src/exla/custom_calls/qr_f64.cc">>, + <<"c_src/exla/custom_calls/eigh.h">>, + <<"c_src/exla/custom_calls/qr_bf16.cc">>, + <<"c_src/exla/custom_calls/lu_f32.cc">>, + <<"c_src/exla/custom_calls/lu_bf16.cc">>, + <<"c_src/exla/custom_calls/eigh_f64.cc">>, + <<"c_src/exla/custom_calls/lu_f16.cc">>,<<"c_src/exla/exla_mlir.h">>, + <<"c_src/exla/exla.cc">>,<<"c_src/exla/exla_mlir.cc">>, + <<"c_src/exla/ipc.cc">>,<<"c_src/exla/exla_types.h">>, + <<"c_src/exla/exla_client.h">>,<<"c_src/exla/exla_client.cc">>, + <<"c_src/exla/exla_cuda.cc">>,<<"c_src/exla/exla_nif_util.h">>, + <<"Makefile">>]}. +{<<"requirements">>, + [[{<<"name">>,<<"nx">>}, + {<<"app">>,<<"nx">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.10.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"telemetry">>}, + {<<"app">>,<<"telemetry">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.4.0 or ~> 1.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"xla">>}, + {<<"app">>,<<"xla">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.9.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"fine">>}, + {<<"app">>,<<"fine">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.1.0">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"elixir_make">>}, + {<<"app">>,<<"elixir_make">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 0.6">>}, + {<<"repository">>,<<"hexpm">>}], + [{<<"name">>,<<"nimble_pool">>}, + {<<"app">>,<<"nimble_pool">>}, + {<<"optional">>,false}, + {<<"requirement">>,<<"~> 1.0">>}, + {<<"repository">>,<<"hexpm">>}]]}. +{<<"build_tools">>,[<<"mix">>,<<"make">>]}. diff --git a/deps/exla/mix.exs b/deps/exla/mix.exs new file mode 100644 index 0000000000000000000000000000000000000000..864419a3353076e8b7c9db706b05dca5fccd1c0b --- /dev/null +++ b/deps/exla/mix.exs @@ -0,0 +1,227 @@ +defmodule EXLA.MixProject do + use Mix.Project + + @source_url "https://github.com/elixir-nx/nx" + @version "0.10.0" + + def project do + make_args = + Application.get_env(:exla, :make_args) || ["-j#{max(System.schedulers_online() - 2, 1)}"] + + [ + app: :exla, + version: @version, + elixir: "~> 1.15", + elixirc_paths: elixirc_paths(Mix.env()), + deps: deps(), + docs: docs(), + + # Package + name: "EXLA", + description: "Google's XLA (Accelerated Linear Algebra) compiler/backend for Nx", + package: package(), + preferred_cli_env: [ + docs: :docs, + "hex.publish": :docs + ], + compilers: [:extract_xla, :cached_make] ++ Mix.compilers(), + aliases: [ + "compile.extract_xla": &extract_xla/1, + "compile.cached_make": &cached_make/1 + ], + make_env: fn -> + priv_path = Path.join(Mix.Project.app_path(), "priv") + cwd_relative_to_priv = relative_to(File.cwd!(), priv_path) + + %{ + "FINE_INCLUDE_DIR" => Fine.include_dir(), + "MIX_BUILD_EMBEDDED" => "#{Mix.Project.config()[:build_embedded]}", + "CWD_RELATIVE_TO_PRIV_PATH" => cwd_relative_to_priv, + "EXLA_VERSION" => "#{@version}" + } + end, + make_args: make_args + ] + end + + def application do + [ + extra_applications: [:logger], + mod: {EXLA.Application, []}, + env: [ + clients: [ + cuda: [platform: :cuda], + rocm: [platform: :rocm], + tpu: [platform: :tpu], + host: [platform: :host] + ], + preferred_clients: [:cuda, :rocm, :tpu, :host] + ] + ] + end + + defp elixirc_paths(:test), do: ~w(lib test/support) + defp elixirc_paths(_), do: ~w(lib) + + defp deps do + [ + {:nx, "~> 0.10.0"}, + # {:nx, path: "../nx"}, + {:telemetry, "~> 0.4.0 or ~> 1.0"}, + {:xla, "~> 0.9.0", runtime: false}, + {:fine, "~> 0.1.0", runtime: false}, + {:elixir_make, "~> 0.6", runtime: false}, + {:benchee, "~> 1.0", only: :dev}, + {:ex_doc, "~> 0.29", only: :docs}, + {:nimble_pool, "~> 1.0"} + ] + end + + defp docs do + [ + main: "EXLA", + source_url_pattern: "#{@source_url}/blob/v#{@version}/exla/%{path}#L%{line}", + extras: [ + "guides/rotating-image.livemd", + "CHANGELOG.md" + ], + skip_undefined_reference_warnings_on: ["CHANGELOG.md"], + groups_for_modules: [ + # EXLA, + # EXLA.Backend, + + Bindings: [ + EXLA.BinaryBuffer, + EXLA.Client, + EXLA.DeviceBuffer, + EXLA.Executable, + EXLA.Typespec + ] + ] + ] + end + + defp package do + [ + maintainers: ["Sean Moriarity", "José Valim", "Paulo Valente", "Jonatan KÅ‚osko"], + licenses: ["Apache-2.0"], + links: %{"GitHub" => @source_url} + ] + end + + # We keep track of the current XLA archive path in xla_snapshot.txt. + # Whenever the path changes, we extract it again and Makefile picks + # up this change + defp extract_xla(_) do + xla_archive_path = XLA.archive_path!() + + cache_dir = Path.join(__DIR__, "cache") + xla_snapshot_path = Path.join(cache_dir, "xla_snapshot.txt") + xla_extension_path = Path.join(cache_dir, "xla_extension") + + case File.read(xla_snapshot_path) do + {:ok, ^xla_archive_path} -> + :ok + + _ -> + File.rm_rf!(xla_extension_path) + Mix.shell().info("Unpacking #{xla_archive_path} into #{cache_dir}") + + case :erl_tar.extract(xla_archive_path, [:compressed, cwd: cache_dir]) do + :ok -> File.write!(xla_snapshot_path, xla_archive_path) + {:error, term} -> Mix.raise("failed to extract xla archive, reason: #{inspect(term)}") + end + end + + {:ok, []} + end + + defp cached_make(args) do + force_rebuild_env_var = System.get_env("EXLA_FORCE_REBUILD", "") + + force_rebuild_mode = + cond do + force_rebuild_env_var in ["", "false", "0"] -> + :none + + force_rebuild_env_var == "partial" -> + :partial + + force_rebuild_env_var in ["true", "1"] -> + :full + + true -> + Mix.raise( + "invalid value for EXLA_FORCE_REBUILD: '#{force_rebuild_env_var}'. Expected one of: partial, true, false" + ) + end + + File.mkdir_p!("cache/#{@version}") + + # remove only in full mode + if force_rebuild_mode in [:partial, :full] do + Mix.shell().info("Removing cached .o files in cache/#{@version}/objs") + File.rm_rf!("cache/#{@version}/objs") + end + + contents = + for path <- Path.wildcard("c_src/**/*"), + {:ok, contents} <- [File.read(path)], + do: contents + + md5 = + [XLA.archive_path!() | contents] + |> :erlang.md5() + |> Base.encode32(padding: false, case: :lower) + + cache_key = + "elixir-#{System.version()}-erts-#{:erlang.system_info(:version)}-xla-#{Application.spec(:xla, :vsn)}-exla-#{@version}-#{md5}" + + cached_so = Path.join([xla_cache_dir(), "exla", cache_key, "libexla.so"]) + cached? = File.exists?(cached_so) and force_rebuild_mode == :none + + if force_rebuild_mode in [:partial, :full] do + Mix.shell().info("Removing cached libexla.so file in cache/libexla.so") + File.rm_rf!("cache/libexla.so") + + Mix.shell().info("Removing libexla.so cache at #{cached_so}") + File.rm_rf!(cached_so) + end + + if cached? do + Mix.shell().info("Using libexla.so from #{cached_so}") + File.cp!(cached_so, "cache/libexla.so") + end + + result = Mix.Tasks.Compile.ElixirMake.run(args) + + if not cached? and match?({:ok, _}, result) do + Mix.shell().info("Caching libexla.so at #{cached_so}") + File.mkdir_p!(Path.dirname(cached_so)) + File.cp!("cache/libexla.so", cached_so) + end + + result + end + + defp xla_cache_dir() do + # The directory where we store all the archives + if dir = System.get_env("XLA_CACHE_DIR") do + Path.expand(dir) + else + :filename.basedir(:user_cache, "xla") + end + end + + # Returns `path` relative to the `from` directory. + defp relative_to(path, from) do + path_parts = path |> Path.expand() |> Path.split() + from_parts = from |> Path.expand() |> Path.split() + {path_parts, from_parts} = drop_common_prefix(path_parts, from_parts) + root_relative = for _ <- from_parts, do: ".." + Path.join(root_relative ++ path_parts) + end + + defp drop_common_prefix([h | left], [h | right]), do: drop_common_prefix(left, right) + defp drop_common_prefix(left, right), do: {left, right} +end diff --git a/deps/fss/.hex b/deps/fss/.hex new file mode 100644 index 0000000000000000000000000000000000000000..f5b105dbcd246054c389b3f011682ab6ff511777 Binary files /dev/null and b/deps/fss/.hex differ diff --git a/deps/fss/LICENSE b/deps/fss/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/deps/fss/LICENSE @@ -0,0 +1,202 @@ + + 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 [yyyy] [name of copyright owner] + + 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/deps/fss/README.md b/deps/fss/README.md new file mode 100644 index 0000000000000000000000000000000000000000..87008dc27c56269922a67c66e79dd28a821470be --- /dev/null +++ b/deps/fss/README.md @@ -0,0 +1,43 @@ +# FSS - File system specifications + +[![Docs](https://img.shields.io/badge/hex.pm-docs-8e7ce6.svg)](https://hexdocs.pm/fss) +[![Actions Status](https://github.com/elixir-explorer/fss/actions/workflows/ci.yml/badge.svg)](https://github.com/elixir-explorer/fss/actions) + +`FSS` is a small abstraction to describe how to access files in different filesystems. + +The docs can be found at . + +## Installation + +The package can be installed by adding `fss` to your list of dependencies +in `mix.exs`: + +```elixir +def deps do + [ + {:fss, "~> 0.1.0"} + ] +end +``` + +Or by using `Mix.install/2`: + +```elixir +Mix.install([{:fss, "~> 0.1.0"}]) +``` + +## License + +Copyright 2023 Philip Sampaio, José Valim + +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/deps/fss/hex_metadata.config b/deps/fss/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..41006a4c9b8827429ae994f7b304699b743eedd8 --- /dev/null +++ b/deps/fss/hex_metadata.config @@ -0,0 +1,14 @@ +{<<"links">>,[{<<"GitHub">>,<<"https://github.com/elixir-explorer/fss">>}]}. +{<<"name">>,<<"fss">>}. +{<<"version">>,<<"0.1.1">>}. +{<<"description">>, + <<"An abstraction to describe files on local or remote file systems">>}. +{<<"elixir">>,<<"~> 1.14">>}. +{<<"app">>,<<"fss">>}. +{<<"files">>, + [<<"README.md">>,<<"LICENSE">>,<<"mix.exs">>,<<"lib">>,<<"lib/fss.ex">>, + <<"lib/fss">>,<<"lib/fss/local.ex">>,<<"lib/fss/s3.ex">>, + <<"lib/fss/http.ex">>]}. +{<<"licenses">>,[<<"Apache-2.0">>]}. +{<<"requirements">>,[]}. +{<<"build_tools">>,[<<"mix">>]}. diff --git a/deps/fss/lib/fss.ex b/deps/fss/lib/fss.ex new file mode 100644 index 0000000000000000000000000000000000000000..99334264ca9a81fd9c01447c1aca59890ae58b90 --- /dev/null +++ b/deps/fss/lib/fss.ex @@ -0,0 +1,27 @@ +defmodule FSS do + # The initial work is from Explorer's code base. + # + # See https://github.com/elixir-explorer/explorer/pull/645 + # and the PRs that followed that one. + + @moduledoc """ + A small abstraction to describe how to access files. + + It works with different file systems, for local files + and remote ones. + + It's a library to parse and validate URIs, with the necessary + attributes. + + See the supported specifications for more details: + + * `FSS.Local` + * `FSS.HTTP` + * `FSS.S3` + """ + + @typedoc """ + Can be used to refer to any entry that FSS supports. + """ + @type entry() :: FSS.Local.Entry.t() | FSS.S3.Entry.t() | FSS.HTTP.Entry.t() +end diff --git a/deps/fss/lib/fss/http.ex b/deps/fss/lib/fss/http.ex new file mode 100644 index 0000000000000000000000000000000000000000..2b21321e8640b8fbc0da92495602ccc11d7f5fe2 --- /dev/null +++ b/deps/fss/lib/fss/http.ex @@ -0,0 +1,84 @@ +defmodule FSS.HTTP do + @moduledoc """ + Specification for accessing HTTP(s) resources. + """ + + defmodule Config do + @moduledoc """ + Represents the configuration for an HTTP resource. + """ + defstruct [:headers] + + @typedoc """ + Only `:headers` are configurable now. + + They are a list of `{String.t(), String.t()}` + """ + @type t :: %__MODULE__{headers: [{String.t(), String.t()}]} + end + + defmodule Entry do + @moduledoc """ + Represents the actual HTTP resource. + """ + defstruct [:url, :config] + + @typedoc """ + The entry type of an HTTP resource. + + The `:url` is expected to be a valid HTTP or HTTPS URL, + and `:config` is expected to be a `Config.t()`. + """ + @type t :: %__MODULE__{url: String.t(), config: Config.t()} + end + + @doc """ + Parses an HTTP or HTTPs url. + + ## Options + + * `:config` - A `Config.t()`. This is optional and by default it's `nil`. + """ + @spec parse(String.t(), Keyword.t()) :: {:ok, Entry.t()} | {:error, Exception.t()} + def parse(url, opts \\ []) do + opts = Keyword.validate!(opts, config: nil) + + with {:ok, config} <- build_config(opts[:config]) do + {:ok, %Entry{url: url, config: config}} + end + end + + defp build_config(nil), do: {:ok, %Config{headers: []}} + defp build_config(%Config{} = config), do: {:ok, config} + + defp build_config(config) when is_list(config) do + case Keyword.validate(config, headers: []) do + {:ok, opts} -> + callback = fn pair -> + match?({key, value} when is_binary(key) and is_binary(value), pair) + end + + if Enum.all?(opts[:headers], callback) do + {:ok, %Config{headers: opts[:headers]}} + else + {:error, + ArgumentError.exception( + "one of the headers is invalid. Expecting a list of `{\"key\", \"value\"}`, but got: #{inspect(opts[:headers])}" + )} + end + + {:error, key} -> + {:error, + ArgumentError.exception( + "the keys #{inspect(key)} are not valid keys for the HTTP configuration" + )} + end + end + + defp build_config(other) do + {:error, + ArgumentError.exception( + "config for HTTP entry is invalid. Expecting `:headers`, but got #{inspect(other)}" + )} + end +end diff --git a/deps/fss/lib/fss/local.ex b/deps/fss/lib/fss/local.ex new file mode 100644 index 0000000000000000000000000000000000000000..9292397178c7d55e36b99bcf9b899eac9c8cd6da --- /dev/null +++ b/deps/fss/lib/fss/local.ex @@ -0,0 +1,37 @@ +defmodule FSS.Local do + @moduledoc """ + Specification for local files. + + The `FSS.Local.Entry` represents a local file with its path. + """ + + defmodule Entry do + defstruct [:path] + + @moduledoc """ + Represents a local file. + """ + + @typedoc """ + The only attribute is the `:path` to a local file. + """ + @type t :: %__MODULE__{path: String.t()} + end + + @doc """ + Builds a `FSS.Local.Entry` struct from a path. + + ## Examples + + iex> FSS.Local.from_path("/home/joe/file.txt") + %FSS.Local.Entry{path: "/home/joe/file.txt"} + + iex> FSS.Local.from_path("C:/joe/file.txt") + %FSS.Local.Entry{path: "C:/joe/file.txt"} + + """ + @spec from_path(String.t()) :: Entry.t() + def from_path(path) when is_binary(path) do + %Entry{path: path} + end +end diff --git a/deps/fss/lib/fss/s3.ex b/deps/fss/lib/fss/s3.ex new file mode 100644 index 0000000000000000000000000000000000000000..e0e894a30f5a6935dca7363f8732679f089ceec1 --- /dev/null +++ b/deps/fss/lib/fss/s3.ex @@ -0,0 +1,199 @@ +defmodule FSS.S3 do + @moduledoc """ + Specification for accessing AWS S3 resources. + """ + + defmodule Config do + @moduledoc """ + Represents the configuration needed for accessing an S3 resource. + """ + + @derive {Inspect, only: [:bucket, :region, :endpoint]} + defstruct [ + :access_key_id, + :bucket, + :region, + :secret_access_key, + :endpoint, + :token + ] + + @typedoc """ + The configuration struct for S3. + + The attributes are: + + * `:access_key_id` - This attribute is required. + + * `:secret_access_key` - This attribute is required. + + * `:bucket` - A valid bucket name. This attribute is optional, + but if is not provided, then the `:endpoint` must include the bucket name + either in the host, as a virtual host, or in the path. In other words: + if the bucket is not given, then `:endpoint` must be configured. + + This attribute is going to be set to `nil` if the endpoint was + not provided, unless the bucket name contain dots in it. + + * `:region` - This attribute is optional. It's normally required when working + with the official AWS S3 API. + + * `:endpoint` - If specified, then `:region` is ignored. + This attribute is required to be configured if you are using a service that + is compatible with the AWS S3 API. + + In case only a "bucket URL" - without discrimination of the bucket name - is provided + then the `:bucket` attribute can be nil just like the `:region`. + + In case the endpoint is not provided, we compute a valid one for the AWS S3 API. + This endpoint is going to follow the virtual-host style most of the time, with + the only exception being when the bucket name has dots. In that case we build + the AWS S3 endpoint without the bucket name in it. + + * `:token` - This attribute is optional. + """ + @type t :: %__MODULE__{ + access_key_id: String.t(), + secret_access_key: String.t(), + endpoint: String.t(), + bucket: String.t() | nil, + region: String.t() | nil, + token: String.t() | nil + } + end + + defmodule Entry do + @moduledoc """ + Represents the S3 resource itself. + """ + + defstruct [:key, :config] + + @typedoc """ + The entry struct for S3. + + The attributes are: + + * `:key` - A valid key for the resource. This attribute is required. + * `:config` - A valid S3 config from the type `Config.t()`. This attribute is required. + """ + @type t :: %__MODULE__{ + key: String.t(), + config: Config.t() + } + end + + @doc """ + Parses a URL in the format `s3://bucket/resource-key`. + + ## Options + + * `:config` - It expects a `Config.t()` or a `Keyword.t()` with the keys + representing the attributes of the `Config.t()`. By default it is `nil`, + which means that we are going to try to fetch the credentials and configuration + from the system's environment variables. + + The following env vars are read: + + - `AWS_ACCESS_KEY_ID` + - `AWS_SECRET_ACCESS_KEY` + - `AWS_REGION` or `AWS_DEFAULT_REGION` + - `AWS_SESSION_TOKEN` + + In case the endpoint is not provided, we compute a valid one for the AWS S3 API, + That is going to follow the path style. The endpoint is not going to include the + `:bucket` in it, being necessary to do that when using this FSS entry. + + See https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html + for more details. + """ + @spec parse(String.t(), Keyword.t()) :: {:ok, Entry.t()} | {:error, Exception.t()} + def parse(url, opts \\ []) do + opts = Keyword.validate!(opts, config: nil) + + uri = URI.parse(url) + + case uri do + %{scheme: "s3", host: bucket, path: "/" <> key} when is_binary(bucket) -> + bucket = if bucket != "", do: bucket + + config = + opts + |> Keyword.fetch!(:config) + |> normalize_config!() + |> validate_config!() + |> then(fn %Config{} = config -> + config = %Config{config | bucket: bucket} + + if is_nil(config.endpoint) and not is_nil(bucket) do + s3_host_suffix = "s3." <> config.region <> ".amazonaws.com" + + # We consume the bucket name in the endpoint if there is no dots in it. + {endpoint, bucket} = + if String.contains?(bucket, ".") do + {"https://" <> s3_host_suffix, bucket} + else + {"https://" <> bucket <> "." <> s3_host_suffix, nil} + end + + %Config{config | endpoint: endpoint, bucket: bucket} + else + config + end + end) + + if is_nil(config.endpoint) do + {:error, ArgumentError.exception("endpoint is required when bucket is nil")} + else + {:ok, %Entry{key: key, config: config}} + end + + _ -> + {:error, + ArgumentError.exception( + "expected s3:/// URL, got: " <> + URI.to_string(uri) + )} + end + end + + defp validate_config!(%Config{} = config) do + check!(config, :access_key_id, "AWS_ACCESS_KEY_ID") + check!(config, :secret_access_key, "AWS_SECRET_ACCESS_KEY") + check!(config, :region, "AWS_REGION") + + config + end + + defp normalize_config!(nil), do: config_from_system_env() + defp normalize_config!(%Config{} = config), do: config + + defp normalize_config!(config) when is_list(config) or is_map(config) do + struct!(config_from_system_env(), config) + end + + defp normalize_config!(other) do + raise ArgumentError, + "expect configuration to be a %FSS.S3.Config{} struct, a keyword list or a map. Instead got #{inspect(other)}" + end + + defp check!(config, key, env) do + if Map.fetch!(config, key) in ["", nil] do + raise ArgumentError, + "missing #{inspect(key)} for FSS.S3 (set the key or the #{env} env var)" + end + end + + @doc """ + Builds a `Config.t()` reading from the system env. + """ + @spec config_from_system_env :: Config.t() + def config_from_system_env() do + %Config{ + access_key_id: System.get_env("AWS_ACCESS_KEY_ID"), + secret_access_key: System.get_env("AWS_SECRET_ACCESS_KEY"), + region: System.get_env("AWS_REGION", System.get_env("AWS_DEFAULT_REGION")), + token: System.get_env("AWS_SESSION_TOKEN") + } + end +end diff --git a/deps/fss/mix.exs b/deps/fss/mix.exs new file mode 100644 index 0000000000000000000000000000000000000000..02522c57922f087befbcf7420abdebbabbeecea3 --- /dev/null +++ b/deps/fss/mix.exs @@ -0,0 +1,45 @@ +defmodule Fss.MixProject do + use Mix.Project + + @version "0.1.1" + @github_url "https://github.com/elixir-explorer/fss" + + def project do + [ + app: :fss, + version: @version, + elixir: "~> 1.14", + start_permanent: Mix.env() == :prod, + package: package(), + docs: docs(), + deps: deps() + ] + end + + def application do + [ + extra_applications: [:logger] + ] + end + + defp deps do + [ + # docs + {:ex_doc, "~> 0.30", only: :docs, runtime: false} + ] + end + + defp docs do + [main: "FSS", source_ref: "v#{@version}", source_url: @github_url] + end + + defp package do + [ + name: "fss", + description: "An abstraction to describe files on local or remote file systems", + files: ~w(README* LICENSE* mix.exs lib), + licenses: ["Apache-2.0"], + links: %{"GitHub" => @github_url} + ] + end +end diff --git a/deps/hpax/.formatter.exs b/deps/hpax/.formatter.exs new file mode 100644 index 0000000000000000000000000000000000000000..8c80937603cd811bfcdbed2addd70967f3387dee --- /dev/null +++ b/deps/hpax/.formatter.exs @@ -0,0 +1,5 @@ +# Used by "mix format" +[ + inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"], + import_deps: [:stream_data] +] diff --git a/deps/hpax/.hex b/deps/hpax/.hex new file mode 100644 index 0000000000000000000000000000000000000000..b5f2b34552132388fd9a8478253ec4b273581f1e Binary files /dev/null and b/deps/hpax/.hex differ diff --git a/deps/hpax/CHANGELOG.md b/deps/hpax/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..73d4032d9736b7c63e2a6dbef7aee52a8a8a97e9 --- /dev/null +++ b/deps/hpax/CHANGELOG.md @@ -0,0 +1,34 @@ +# Changelog + +## v1.0.3 + + * Silence warnings on (upcoming, at this time) Elixir 1.19+. + +## v1.0.2 + + * The changes in v1.0.1 introduced some subtle compression errors with HPACK encoding. This has been fixed in this version. See [this issue](https://github.com/elixir-mint/hpax/issues/20) for more details. + +## v1.0.1 + + * Fix some issues with dynamic table resizing. You should not need to do anything to your code, it should Just Workâ„¢. If you want to read more, [this issue](https://github.com/elixir-mint/hpax/issues/18) has all the context. + +## v1.0.0 + + * Silence warnings on Elixir 1.17+. + * Require Elixir 1.12+. + +## v0.2.0 + + * Add `HPAX.new/2`, which supports a list of options. For now, the only option + is `:huffman_encoding`, to choose whether to use Huffman encoding or not. + * Add `HPAX.encode/3`, which supports encoding all headers with the same + action. + * Add the `HPAX.table/0` opaque type. + +## v0.1.2 + + * Fix `use Bitwise` deprecation warning. + +## v0.1.1 + + * Improve checking of dynamic resize updates. diff --git a/deps/hpax/LICENSE.txt b/deps/hpax/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..d9a10c0d8e868ebf8da0b3dc95bb0be634c34bfe --- /dev/null +++ b/deps/hpax/LICENSE.txt @@ -0,0 +1,176 @@ + 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 diff --git a/deps/hpax/README.md b/deps/hpax/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4cc27f70f202a9fee7e59c9f4764571c2d8699ff --- /dev/null +++ b/deps/hpax/README.md @@ -0,0 +1,74 @@ +# HPAX + +![CI](https://github.com/elixir-mint/hpax/actions/workflows/main.yml/badge.svg) +[![Docs](https://img.shields.io/badge/api-docs-green.svg?style=flat)](https://hexdocs.pm/hpax) +[![Hex.pm Version](http://img.shields.io/hexpm/v/hpax.svg?style=flat)](https://hex.pm/packages/hpax) +[![Coverage Status](https://coveralls.io/repos/github/elixir-mint/hpax/badge.svg?branch=main)](https://coveralls.io/github/elixir-mint/hpax?branch=main) + +HPAX is an Elixir implementation of the HPACK header compression algorithm as used in HTTP/2 and +defined in RFC 7541. HPAX is used by several Elixir projects, including the +[Mint](https://github.com/elixir-mint/mint) HTTP client and +[bandit](https://github.com/mtrudel/bandit) HTTP server projects. + +## Installation + +To install HPAX, add it to your `mix.exs` file. + +```elixir +defp deps do + [ + {:hpax, "~> 0.1.0"} + ] +end +``` + +Then, run `$ mix deps.get`. + +## Usage + +HPAX is designed to be used in both encoding and decoding scenarios. In both cases, a context is +used to maintain state internal to the HPACK algorithm. In the common use case of using HPAX +within HTTP/2, this context is called a **table** and must be shared between any +subsequent encoding/decoding calls within +an endpoint. Note that the contexts used for encoding and decoding within HTTP/2 are completely +distinct from one another, even though they are structurally identical. + +To encode a set of headers into a binary with HPAX: + +```elixir +context = HPAX.new(4096) +headers = [{:store, ":status", "201"}, {:store, "location", "http://example.com"}] +{encoded_headers, context} = HPAX.encode(headers, context) +#=> {iodata, updated_context} +``` + +To decode a binary into a set of headers with HPAX: + +```elixir +context = HPAX.new(4096) +encoded_headers = <<...>> +{:ok, headers, context} = HPAX.decode(encoded_headers, context) +#=> {:ok, [{:store, ":status", "201"}, {:store, "location", "http://example.com"}], updated_context} +``` + +For complete usage information, please see the HPAX [documentation](https://hex.pm/packages/hpax). + +## Contributing + +If you wish to contribute check out the [issue list](https://github.com/elixir-mint/hpax/issues) and let us know what you want to work on so we can discuss it and reduce duplicate work. + +## License + +Copyright 2021 Eric Meadows-Jönsson and Andrea Leopardi + + 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/deps/hpax/hex_metadata.config b/deps/hpax/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..b8f08242812d96a01d5c738c3bbf76a5854263f5 --- /dev/null +++ b/deps/hpax/hex_metadata.config @@ -0,0 +1,15 @@ +{<<"links">>,[{<<"GitHub">>,<<"https://github.com/elixir-mint/hpax">>}]}. +{<<"name">>,<<"hpax">>}. +{<<"version">>,<<"1.0.3">>}. +{<<"description">>, + <<"Implementation of the HPACK protocol (RFC 7541) for Elixir">>}. +{<<"elixir">>,<<"~> 1.12">>}. +{<<"app">>,<<"hpax">>}. +{<<"licenses">>,[<<"Apache-2.0">>]}. +{<<"requirements">>,[]}. +{<<"files">>, + [<<"lib">>,<<"lib/hpax">>,<<"lib/hpax/huffman_table">>, + <<"lib/hpax/types.ex">>,<<"lib/hpax/huffman.ex">>,<<"lib/hpax/table.ex">>, + <<"lib/hpax.ex">>,<<".formatter.exs">>,<<"mix.exs">>,<<"README.md">>, + <<"LICENSE.txt">>,<<"CHANGELOG.md">>]}. +{<<"build_tools">>,[<<"mix">>]}. diff --git a/deps/hpax/lib/hpax.ex b/deps/hpax/lib/hpax.ex new file mode 100644 index 0000000000000000000000000000000000000000..91c94016bd93907c978cbd2bb06e6d3c6411e73e --- /dev/null +++ b/deps/hpax/lib/hpax.ex @@ -0,0 +1,360 @@ +defmodule HPAX do + @moduledoc """ + Support for the HPACK header compression algorithm. + + This module provides support for the HPACK header compression algorithm used mainly in HTTP/2. + + ## Encoding and decoding contexts + + The HPACK algorithm requires both + + * an encoding context on the encoder side + * a decoding context on the decoder side + + These contexts are semantically different but structurally the same. In HPACK they are + implemented as **HPACK tables**. This library uses the name "tables" everywhere internally + + HPACK tables can be created through the `new/1` function. + """ + + alias HPAX.{Table, Types} + + @typedoc """ + An HPACK table. + + This can be used for encoding or decoding. + """ + @typedoc since: "0.2.0" + @opaque table() :: Table.t() + + @typedoc """ + An HPACK header name. + """ + @type header_name() :: binary() + + @typedoc """ + An HPACK header value. + """ + @type header_value() :: binary() + + @valid_header_actions [:store, :store_name, :no_store, :never_store] + + @doc """ + Creates a new HPACK table. + + Same as `new/2` with default options. + """ + @spec new(non_neg_integer()) :: table() + def new(max_table_size), do: new(max_table_size, []) + + @doc """ + Create a new HPACK table that can be used as encoding or decoding context. + + See the "Encoding and decoding contexts" section in the module documentation. + + `max_table_size` is the maximum table size (in bytes) for the newly created table. + + ## Options + + This function accepts the following `options`: + + * `:huffman_encoding` - (since 0.2.0) `:always` or `:never`. If `:always`, + then HPAX will always encode headers using Huffman encoding. If `:never`, + HPAX will not use any Huffman encoding. Defaults to `:never`. + + ## Examples + + encoding_context = HPAX.new(4096) + + """ + @doc since: "0.2.0" + @spec new(non_neg_integer(), [keyword()]) :: table() + def new(max_table_size, options) + when is_integer(max_table_size) and max_table_size >= 0 and is_list(options) do + options = Keyword.put_new(options, :huffman_encoding, :never) + + Enum.each(options, fn + {:huffman_encoding, _huffman_encoding} -> :ok + {key, _value} -> raise ArgumentError, "unknown option: #{inspect(key)}" + end) + + Table.new(max_table_size, Keyword.fetch!(options, :huffman_encoding)) + end + + @doc """ + Resizes the given table to the given maximum size. + + This is intended for use where the overlying protocol has signaled a change to the table's + maximum size, such as when an HTTP/2 `SETTINGS` frame is received. + + If the indicated size is less than the table's current size, entries + will be evicted as needed to fit within the specified size, and the table's + maximum size will be decreased to the specified value. A flag will also be + set which will enqueue a "dynamic table size update" command to be prefixed + to the next block encoded with this table, per + [RFC9113§4.3.1](https://www.rfc-editor.org/rfc/rfc9113.html#section-4.3.1). + + If the indicated size is greater than or equal to the table's current max size, no entries are evicted + and the table's maximum size changes to the specified value. + + ## Examples + + decoding_context = HPAX.new(4096) + HPAX.resize(decoding_context, 8192) + + """ + @spec resize(table(), non_neg_integer()) :: table() + defdelegate resize(table, new_max_size), to: Table + + @doc """ + Decodes a header block fragment (HBF) through a given table. + + If decoding is successful, this function returns a `{:ok, headers, updated_table}` tuple where + `headers` is a list of decoded headers, and `updated_table` is the updated table. If there's + an error in decoding, this function returns `{:error, reason}`. + + ## Examples + + decoding_context = HPAX.new(1000) + hbf = get_hbf_from_somewhere() + HPAX.decode(hbf, decoding_context) + #=> {:ok, [{":method", "GET"}], decoding_context} + + """ + @spec decode(binary(), table()) :: + {:ok, [{header_name(), header_value()}], table()} | {:error, term()} + + # Dynamic resizes must occur only at the start of a block + # https://datatracker.ietf.org/doc/html/rfc7541#section-4.2 + def decode(<<0b001::3, rest::bitstring>>, %Table{} = table) do + {new_max_size, rest} = decode_integer(rest, 5) + + # Dynamic resizes must be less than protocol max table size + # https://datatracker.ietf.org/doc/html/rfc7541#section-6.3 + if new_max_size <= table.protocol_max_table_size do + decode(rest, Table.dynamic_resize(table, new_max_size)) + else + {:error, :protocol_error} + end + end + + def decode(block, %Table{} = table) when is_binary(block) do + decode_headers(block, table, _acc = []) + catch + :throw, {:hpax, error} -> {:error, error} + end + + @doc """ + Encodes a list of headers through the given table. + + Returns a two-element tuple where the first element is a binary representing the encoded headers + and the second element is an updated table. + + ## Examples + + headers = [{:store, ":authority", "https://example.com"}] + encoding_context = HPAX.new(1000) + HPAX.encode(headers, encoding_context) + #=> {iodata, updated_encoding_context} + + """ + @spec encode([header], table()) :: {iodata(), table()} + when header: {action, header_name(), header_value()}, + action: :store | :store_name | :no_store | :never_store + def encode(headers, %Table{} = table) when is_list(headers) do + {table, pending_resizes} = Table.pop_pending_resizes(table) + acc = Enum.map(pending_resizes, &[<<0b001::3, Types.encode_integer(&1, 5)::bitstring>>]) + encode_headers(headers, table, acc) + end + + @doc """ + Encodes a list of headers through the given table, applying the same `action` to all of them. + + This function is the similar to `encode/2`, but `headers` are `{name, value}` tuples instead, + and the same `action` is applied to all headers. + + ## Examples + + headers = [{":authority", "https://example.com"}] + encoding_context = HPAX.new(1000) + HPAX.encode(:store, headers, encoding_context) + #=> {iodata, updated_encoding_context} + + """ + @doc since: "0.2.0" + @spec encode(action, [header], table()) :: {iodata(), table()} + when action: :store | :store_name | :no_store | :never_store, + header: {header_name(), header_value()} + def encode(action, headers, %Table{} = table) + when is_list(headers) and action in [:store, :store_name, :no_store, :never_store] do + headers + |> Enum.map(fn {name, value} -> {action, name, value} end) + |> encode(table) + end + + ## Helpers + + defp decode_headers(<<>>, table, acc) do + {:ok, Enum.reverse(acc), table} + end + + # Indexed header field + # http://httpwg.org/specs/rfc7541.html#rfc.section.6.1 + defp decode_headers(<<0b1::1, rest::bitstring>>, table, acc) do + {index, rest} = decode_integer(rest, 7) + decode_headers(rest, table, [lookup_by_index!(table, index) | acc]) + end + + # Literal header field with incremental indexing + # http://httpwg.org/specs/rfc7541.html#rfc.section.6.2.1 + defp decode_headers(<<0b01::2, rest::bitstring>>, table, acc) do + {name, value, rest} = + case rest do + # The header name is a string. + <<0::6, rest::binary>> -> + {name, rest} = decode_binary(rest) + {value, rest} = decode_binary(rest) + {name, value, rest} + + # The header name is an index to be looked up in the table. + _other -> + {index, rest} = decode_integer(rest, 6) + {value, rest} = decode_binary(rest) + {name, _value} = lookup_by_index!(table, index) + {name, value, rest} + end + + decode_headers(rest, Table.add(table, name, value), [{name, value} | acc]) + end + + # Literal header field without indexing + # http://httpwg.org/specs/rfc7541.html#rfc.section.6.2.2 + defp decode_headers(<<0b0000::4, rest::bitstring>>, table, acc) do + {name, value, rest} = + case rest do + <<0::4, rest::binary>> -> + {name, rest} = decode_binary(rest) + {value, rest} = decode_binary(rest) + {name, value, rest} + + _other -> + {index, rest} = decode_integer(rest, 4) + {value, rest} = decode_binary(rest) + {name, _value} = lookup_by_index!(table, index) + {name, value, rest} + end + + decode_headers(rest, table, [{name, value} | acc]) + end + + # Literal header field never indexed + # http://httpwg.org/specs/rfc7541.html#rfc.section.6.2.3 + defp decode_headers(<<0b0001::4, rest::bitstring>>, table, acc) do + {name, value, rest} = + case rest do + <<0::4, rest::binary>> -> + {name, rest} = decode_binary(rest) + {value, rest} = decode_binary(rest) + {name, value, rest} + + _other -> + {index, rest} = decode_integer(rest, 4) + {value, rest} = decode_binary(rest) + {name, _value} = lookup_by_index!(table, index) + {name, value, rest} + end + + # TODO: enforce the "never indexed" part somehow. + decode_headers(rest, table, [{name, value} | acc]) + end + + defp decode_headers(_other, _table, _acc) do + throw({:hpax, :protocol_error}) + end + + defp lookup_by_index!(table, index) do + case Table.lookup_by_index(table, index) do + {:ok, header} -> header + :error -> throw({:hpax, {:index_not_found, index}}) + end + end + + defp decode_integer(bitstring, prefix) do + case Types.decode_integer(bitstring, prefix) do + {:ok, int, rest} -> {int, rest} + :error -> throw({:hpax, :bad_integer_encoding}) + end + end + + defp decode_binary(binary) do + case Types.decode_binary(binary) do + {:ok, binary, rest} -> {binary, rest} + :error -> throw({:hpax, :bad_binary_encoding}) + end + end + + defp encode_headers([], table, acc) do + {acc, table} + end + + defp encode_headers([{action, name, value} | rest], table, acc) + when action in @valid_header_actions and is_binary(name) and is_binary(value) do + huffman? = table.huffman_encoding == :always + + {encoded, table} = + case Table.lookup_by_header(table, name, value) do + {:full, index} -> + {encode_indexed_header(index), table} + + {:name, index} when action == :store -> + {encode_literal_header_with_indexing(index, value, huffman?), + Table.add(table, name, value)} + + {:name, index} when action in [:store_name, :no_store] -> + {encode_literal_header_without_indexing(index, value, huffman?), table} + + {:name, index} when action == :never_store -> + {encode_literal_header_never_indexed(index, value, huffman?), table} + + :not_found when action in [:store, :store_name] -> + {encode_literal_header_with_indexing(name, value, huffman?), + Table.add(table, name, value)} + + :not_found when action == :no_store -> + {encode_literal_header_without_indexing(name, value, huffman?), table} + + :not_found when action == :never_store -> + {encode_literal_header_never_indexed(name, value, huffman?), table} + end + + encode_headers(rest, table, [acc, encoded]) + end + + defp encode_indexed_header(index) do + <<1::1, Types.encode_integer(index, 7)::bitstring>> + end + + defp encode_literal_header_with_indexing(index, value, huffman?) when is_integer(index) do + [<<1::2, Types.encode_integer(index, 6)::bitstring>>, Types.encode_binary(value, huffman?)] + end + + defp encode_literal_header_with_indexing(name, value, huffman?) when is_binary(name) do + [<<1::2, 0::6>>, Types.encode_binary(name, huffman?), Types.encode_binary(value, huffman?)] + end + + defp encode_literal_header_without_indexing(index, value, huffman?) when is_integer(index) do + [<<0::4, Types.encode_integer(index, 4)::bitstring>>, Types.encode_binary(value, huffman?)] + end + + defp encode_literal_header_without_indexing(name, value, huffman?) when is_binary(name) do + [<<0::4, 0::4>>, Types.encode_binary(name, huffman?), Types.encode_binary(value, huffman?)] + end + + defp encode_literal_header_never_indexed(index, value, huffman?) when is_integer(index) do + [<<1::4, Types.encode_integer(index, 4)::bitstring>>, Types.encode_binary(value, huffman?)] + end + + defp encode_literal_header_never_indexed(name, value, huffman?) when is_binary(name) do + [<<1::4, 0::4>>, Types.encode_binary(name, huffman?), Types.encode_binary(value, huffman?)] + end +end diff --git a/deps/hpax/lib/hpax/huffman.ex b/deps/hpax/lib/hpax/huffman.ex new file mode 100644 index 0000000000000000000000000000000000000000..e337fab1f9a3653804ebed30f43804d5bd2e5226 --- /dev/null +++ b/deps/hpax/lib/hpax/huffman.ex @@ -0,0 +1,94 @@ +defmodule HPAX.Huffman do + @moduledoc false + + import Bitwise, only: [>>>: 2] + + # This file is downloaded from the spec directly. + # http://httpwg.org/specs/rfc7541.html#huffman.code + table_file = Path.absname("huffman_table", __DIR__) + @external_resource table_file + + entries = + Enum.map(File.stream!(table_file), fn line -> + [byte_value, bits, _hex, bit_count] = + line + |> case do + <> -> rest + "EOS " <> rest -> rest + _other -> line + end + |> String.replace(["|", "(", ")", "[", "]"], "") + |> String.split() + + byte_value = String.to_integer(byte_value) + bits = String.to_integer(bits, 2) + bit_count = String.to_integer(bit_count) + + {byte_value, bits, bit_count} + end) + + {regular_entries, [eos_entry]} = Enum.split(entries, -1) + {_eos_byte_value, eos_bits, eos_bit_count} = eos_entry + + ## Encoding + + @spec encode(binary()) :: binary() + def encode(binary) do + encode(binary, _acc = <<>>) + end + + for {byte_value, bits, bit_count} <- regular_entries do + defp encode(<>, acc) do + encode(rest, <>) + end + end + + defp encode(<<>>, acc) do + overflowing_bits = rem(bit_size(acc), 8) + + if overflowing_bits == 0 do + acc + else + bits_to_add = 8 - overflowing_bits + + value_of_bits_to_add = + take_significant_bits(unquote(eos_bits), unquote(eos_bit_count), bits_to_add) + + <> + end + end + + ## Decoding + + @spec decode(binary()) :: binary() + def decode(binary) + + for {byte_value, bits, bit_count} <- regular_entries do + def decode(<>) do + <> + end + end + + def decode(<<>>) do + <<>> + end + + # Use binary syntax for single match context optimization. + def decode(<>) when bit_size(padding) in 1..7 do + padding_size = bit_size(padding) + <> = padding + + if take_significant_bits(unquote(eos_bits), unquote(eos_bit_count), padding_size) == padding do + <<>> + else + throw({:hpax, {:protocol_error, :invalid_huffman_encoding}}) + end + end + + ## Helpers + + @compile {:inline, take_significant_bits: 3} + defp take_significant_bits(value, bit_count, bits_to_take) do + value >>> (bit_count - bits_to_take) + end +end diff --git a/deps/hpax/lib/hpax/huffman_table b/deps/hpax/lib/hpax/huffman_table new file mode 100644 index 0000000000000000000000000000000000000000..b116ba3aaf45d5123a78388da02198aab340d761 --- /dev/null +++ b/deps/hpax/lib/hpax/huffman_table @@ -0,0 +1,257 @@ +( 0) |11111111|11000 1ff8 [13] +( 1) |11111111|11111111|1011000 7fffd8 [23] +( 2) |11111111|11111111|11111110|0010 fffffe2 [28] +( 3) |11111111|11111111|11111110|0011 fffffe3 [28] +( 4) |11111111|11111111|11111110|0100 fffffe4 [28] +( 5) |11111111|11111111|11111110|0101 fffffe5 [28] +( 6) |11111111|11111111|11111110|0110 fffffe6 [28] +( 7) |11111111|11111111|11111110|0111 fffffe7 [28] +( 8) |11111111|11111111|11111110|1000 fffffe8 [28] +( 9) |11111111|11111111|11101010 ffffea [24] +( 10) |11111111|11111111|11111111|111100 3ffffffc [30] +( 11) |11111111|11111111|11111110|1001 fffffe9 [28] +( 12) |11111111|11111111|11111110|1010 fffffea [28] +( 13) |11111111|11111111|11111111|111101 3ffffffd [30] +( 14) |11111111|11111111|11111110|1011 fffffeb [28] +( 15) |11111111|11111111|11111110|1100 fffffec [28] +( 16) |11111111|11111111|11111110|1101 fffffed [28] +( 17) |11111111|11111111|11111110|1110 fffffee [28] +( 18) |11111111|11111111|11111110|1111 fffffef [28] +( 19) |11111111|11111111|11111111|0000 ffffff0 [28] +( 20) |11111111|11111111|11111111|0001 ffffff1 [28] +( 21) |11111111|11111111|11111111|0010 ffffff2 [28] +( 22) |11111111|11111111|11111111|111110 3ffffffe [30] +( 23) |11111111|11111111|11111111|0011 ffffff3 [28] +( 24) |11111111|11111111|11111111|0100 ffffff4 [28] +( 25) |11111111|11111111|11111111|0101 ffffff5 [28] +( 26) |11111111|11111111|11111111|0110 ffffff6 [28] +( 27) |11111111|11111111|11111111|0111 ffffff7 [28] +( 28) |11111111|11111111|11111111|1000 ffffff8 [28] +( 29) |11111111|11111111|11111111|1001 ffffff9 [28] +( 30) |11111111|11111111|11111111|1010 ffffffa [28] +( 31) |11111111|11111111|11111111|1011 ffffffb [28] +' ' ( 32) |010100 14 [ 6] +'!' ( 33) |11111110|00 3f8 [10] +'"' ( 34) |11111110|01 3f9 [10] +'#' ( 35) |11111111|1010 ffa [12] +'$' ( 36) |11111111|11001 1ff9 [13] +'%' ( 37) |010101 15 [ 6] +'&' ( 38) |11111000 f8 [ 8] +''' ( 39) |11111111|010 7fa [11] +'(' ( 40) |11111110|10 3fa [10] +')' ( 41) |11111110|11 3fb [10] +'*' ( 42) |11111001 f9 [ 8] +'+' ( 43) |11111111|011 7fb [11] +',' ( 44) |11111010 fa [ 8] +'-' ( 45) |010110 16 [ 6] +'.' ( 46) |010111 17 [ 6] +'/' ( 47) |011000 18 [ 6] +'0' ( 48) |00000 0 [ 5] +'1' ( 49) |00001 1 [ 5] +'2' ( 50) |00010 2 [ 5] +'3' ( 51) |011001 19 [ 6] +'4' ( 52) |011010 1a [ 6] +'5' ( 53) |011011 1b [ 6] +'6' ( 54) |011100 1c [ 6] +'7' ( 55) |011101 1d [ 6] +'8' ( 56) |011110 1e [ 6] +'9' ( 57) |011111 1f [ 6] +':' ( 58) |1011100 5c [ 7] +';' ( 59) |11111011 fb [ 8] +'<' ( 60) |11111111|1111100 7ffc [15] +'=' ( 61) |100000 20 [ 6] +'>' ( 62) |11111111|1011 ffb [12] +'?' ( 63) |11111111|00 3fc [10] +'@' ( 64) |11111111|11010 1ffa [13] +'A' ( 65) |100001 21 [ 6] +'B' ( 66) |1011101 5d [ 7] +'C' ( 67) |1011110 5e [ 7] +'D' ( 68) |1011111 5f [ 7] +'E' ( 69) |1100000 60 [ 7] +'F' ( 70) |1100001 61 [ 7] +'G' ( 71) |1100010 62 [ 7] +'H' ( 72) |1100011 63 [ 7] +'I' ( 73) |1100100 64 [ 7] +'J' ( 74) |1100101 65 [ 7] +'K' ( 75) |1100110 66 [ 7] +'L' ( 76) |1100111 67 [ 7] +'M' ( 77) |1101000 68 [ 7] +'N' ( 78) |1101001 69 [ 7] +'O' ( 79) |1101010 6a [ 7] +'P' ( 80) |1101011 6b [ 7] +'Q' ( 81) |1101100 6c [ 7] +'R' ( 82) |1101101 6d [ 7] +'S' ( 83) |1101110 6e [ 7] +'T' ( 84) |1101111 6f [ 7] +'U' ( 85) |1110000 70 [ 7] +'V' ( 86) |1110001 71 [ 7] +'W' ( 87) |1110010 72 [ 7] +'X' ( 88) |11111100 fc [ 8] +'Y' ( 89) |1110011 73 [ 7] +'Z' ( 90) |11111101 fd [ 8] +'[' ( 91) |11111111|11011 1ffb [13] +'\' ( 92) |11111111|11111110|000 7fff0 [19] +']' ( 93) |11111111|11100 1ffc [13] +'^' ( 94) |11111111|111100 3ffc [14] +'_' ( 95) |100010 22 [ 6] +'`' ( 96) |11111111|1111101 7ffd [15] +'a' ( 97) |00011 3 [ 5] +'b' ( 98) |100011 23 [ 6] +'c' ( 99) |00100 4 [ 5] +'d' (100) |100100 24 [ 6] +'e' (101) |00101 5 [ 5] +'f' (102) |100101 25 [ 6] +'g' (103) |100110 26 [ 6] +'h' (104) |100111 27 [ 6] +'i' (105) |00110 6 [ 5] +'j' (106) |1110100 74 [ 7] +'k' (107) |1110101 75 [ 7] +'l' (108) |101000 28 [ 6] +'m' (109) |101001 29 [ 6] +'n' (110) |101010 2a [ 6] +'o' (111) |00111 7 [ 5] +'p' (112) |101011 2b [ 6] +'q' (113) |1110110 76 [ 7] +'r' (114) |101100 2c [ 6] +'s' (115) |01000 8 [ 5] +'t' (116) |01001 9 [ 5] +'u' (117) |101101 2d [ 6] +'v' (118) |1110111 77 [ 7] +'w' (119) |1111000 78 [ 7] +'x' (120) |1111001 79 [ 7] +'y' (121) |1111010 7a [ 7] +'z' (122) |1111011 7b [ 7] +'{' (123) |11111111|1111110 7ffe [15] +'|' (124) |11111111|100 7fc [11] +'}' (125) |11111111|111101 3ffd [14] +'~' (126) |11111111|11101 1ffd [13] +(127) |11111111|11111111|11111111|1100 ffffffc [28] +(128) |11111111|11111110|0110 fffe6 [20] +(129) |11111111|11111111|010010 3fffd2 [22] +(130) |11111111|11111110|0111 fffe7 [20] +(131) |11111111|11111110|1000 fffe8 [20] +(132) |11111111|11111111|010011 3fffd3 [22] +(133) |11111111|11111111|010100 3fffd4 [22] +(134) |11111111|11111111|010101 3fffd5 [22] +(135) |11111111|11111111|1011001 7fffd9 [23] +(136) |11111111|11111111|010110 3fffd6 [22] +(137) |11111111|11111111|1011010 7fffda [23] +(138) |11111111|11111111|1011011 7fffdb [23] +(139) |11111111|11111111|1011100 7fffdc [23] +(140) |11111111|11111111|1011101 7fffdd [23] +(141) |11111111|11111111|1011110 7fffde [23] +(142) |11111111|11111111|11101011 ffffeb [24] +(143) |11111111|11111111|1011111 7fffdf [23] +(144) |11111111|11111111|11101100 ffffec [24] +(145) |11111111|11111111|11101101 ffffed [24] +(146) |11111111|11111111|010111 3fffd7 [22] +(147) |11111111|11111111|1100000 7fffe0 [23] +(148) |11111111|11111111|11101110 ffffee [24] +(149) |11111111|11111111|1100001 7fffe1 [23] +(150) |11111111|11111111|1100010 7fffe2 [23] +(151) |11111111|11111111|1100011 7fffe3 [23] +(152) |11111111|11111111|1100100 7fffe4 [23] +(153) |11111111|11111110|11100 1fffdc [21] +(154) |11111111|11111111|011000 3fffd8 [22] +(155) |11111111|11111111|1100101 7fffe5 [23] +(156) |11111111|11111111|011001 3fffd9 [22] +(157) |11111111|11111111|1100110 7fffe6 [23] +(158) |11111111|11111111|1100111 7fffe7 [23] +(159) |11111111|11111111|11101111 ffffef [24] +(160) |11111111|11111111|011010 3fffda [22] +(161) |11111111|11111110|11101 1fffdd [21] +(162) |11111111|11111110|1001 fffe9 [20] +(163) |11111111|11111111|011011 3fffdb [22] +(164) |11111111|11111111|011100 3fffdc [22] +(165) |11111111|11111111|1101000 7fffe8 [23] +(166) |11111111|11111111|1101001 7fffe9 [23] +(167) |11111111|11111110|11110 1fffde [21] +(168) |11111111|11111111|1101010 7fffea [23] +(169) |11111111|11111111|011101 3fffdd [22] +(170) |11111111|11111111|011110 3fffde [22] +(171) |11111111|11111111|11110000 fffff0 [24] +(172) |11111111|11111110|11111 1fffdf [21] +(173) |11111111|11111111|011111 3fffdf [22] +(174) |11111111|11111111|1101011 7fffeb [23] +(175) |11111111|11111111|1101100 7fffec [23] +(176) |11111111|11111111|00000 1fffe0 [21] +(177) |11111111|11111111|00001 1fffe1 [21] +(178) |11111111|11111111|100000 3fffe0 [22] +(179) |11111111|11111111|00010 1fffe2 [21] +(180) |11111111|11111111|1101101 7fffed [23] +(181) |11111111|11111111|100001 3fffe1 [22] +(182) |11111111|11111111|1101110 7fffee [23] +(183) |11111111|11111111|1101111 7fffef [23] +(184) |11111111|11111110|1010 fffea [20] +(185) |11111111|11111111|100010 3fffe2 [22] +(186) |11111111|11111111|100011 3fffe3 [22] +(187) |11111111|11111111|100100 3fffe4 [22] +(188) |11111111|11111111|1110000 7ffff0 [23] +(189) |11111111|11111111|100101 3fffe5 [22] +(190) |11111111|11111111|100110 3fffe6 [22] +(191) |11111111|11111111|1110001 7ffff1 [23] +(192) |11111111|11111111|11111000|00 3ffffe0 [26] +(193) |11111111|11111111|11111000|01 3ffffe1 [26] +(194) |11111111|11111110|1011 fffeb [20] +(195) |11111111|11111110|001 7fff1 [19] +(196) |11111111|11111111|100111 3fffe7 [22] +(197) |11111111|11111111|1110010 7ffff2 [23] +(198) |11111111|11111111|101000 3fffe8 [22] +(199) |11111111|11111111|11110110|0 1ffffec [25] +(200) |11111111|11111111|11111000|10 3ffffe2 [26] +(201) |11111111|11111111|11111000|11 3ffffe3 [26] +(202) |11111111|11111111|11111001|00 3ffffe4 [26] +(203) |11111111|11111111|11111011|110 7ffffde [27] +(204) |11111111|11111111|11111011|111 7ffffdf [27] +(205) |11111111|11111111|11111001|01 3ffffe5 [26] +(206) |11111111|11111111|11110001 fffff1 [24] +(207) |11111111|11111111|11110110|1 1ffffed [25] +(208) |11111111|11111110|010 7fff2 [19] +(209) |11111111|11111111|00011 1fffe3 [21] +(210) |11111111|11111111|11111001|10 3ffffe6 [26] +(211) |11111111|11111111|11111100|000 7ffffe0 [27] +(212) |11111111|11111111|11111100|001 7ffffe1 [27] +(213) |11111111|11111111|11111001|11 3ffffe7 [26] +(214) |11111111|11111111|11111100|010 7ffffe2 [27] +(215) |11111111|11111111|11110010 fffff2 [24] +(216) |11111111|11111111|00100 1fffe4 [21] +(217) |11111111|11111111|00101 1fffe5 [21] +(218) |11111111|11111111|11111010|00 3ffffe8 [26] +(219) |11111111|11111111|11111010|01 3ffffe9 [26] +(220) |11111111|11111111|11111111|1101 ffffffd [28] +(221) |11111111|11111111|11111100|011 7ffffe3 [27] +(222) |11111111|11111111|11111100|100 7ffffe4 [27] +(223) |11111111|11111111|11111100|101 7ffffe5 [27] +(224) |11111111|11111110|1100 fffec [20] +(225) |11111111|11111111|11110011 fffff3 [24] +(226) |11111111|11111110|1101 fffed [20] +(227) |11111111|11111111|00110 1fffe6 [21] +(228) |11111111|11111111|101001 3fffe9 [22] +(229) |11111111|11111111|00111 1fffe7 [21] +(230) |11111111|11111111|01000 1fffe8 [21] +(231) |11111111|11111111|1110011 7ffff3 [23] +(232) |11111111|11111111|101010 3fffea [22] +(233) |11111111|11111111|101011 3fffeb [22] +(234) |11111111|11111111|11110111|0 1ffffee [25] +(235) |11111111|11111111|11110111|1 1ffffef [25] +(236) |11111111|11111111|11110100 fffff4 [24] +(237) |11111111|11111111|11110101 fffff5 [24] +(238) |11111111|11111111|11111010|10 3ffffea [26] +(239) |11111111|11111111|1110100 7ffff4 [23] +(240) |11111111|11111111|11111010|11 3ffffeb [26] +(241) |11111111|11111111|11111100|110 7ffffe6 [27] +(242) |11111111|11111111|11111011|00 3ffffec [26] +(243) |11111111|11111111|11111011|01 3ffffed [26] +(244) |11111111|11111111|11111100|111 7ffffe7 [27] +(245) |11111111|11111111|11111101|000 7ffffe8 [27] +(246) |11111111|11111111|11111101|001 7ffffe9 [27] +(247) |11111111|11111111|11111101|010 7ffffea [27] +(248) |11111111|11111111|11111101|011 7ffffeb [27] +(249) |11111111|11111111|11111111|1110 ffffffe [28] +(250) |11111111|11111111|11111101|100 7ffffec [27] +(251) |11111111|11111111|11111101|101 7ffffed [27] +(252) |11111111|11111111|11111101|110 7ffffee [27] +(253) |11111111|11111111|11111101|111 7ffffef [27] +(254) |11111111|11111111|11111110|000 7fffff0 [27] +(255) |11111111|11111111|11111011|10 3ffffee [26] +EOS (256) |11111111|11111111|11111111|111111 3fffffff [30] diff --git a/deps/hpax/lib/hpax/table.ex b/deps/hpax/lib/hpax/table.ex new file mode 100644 index 0000000000000000000000000000000000000000..8873b4544fcccb42cbc0fb484b2a6af4587a5f40 --- /dev/null +++ b/deps/hpax/lib/hpax/table.ex @@ -0,0 +1,348 @@ +defmodule HPAX.Table do + @moduledoc false + + @enforce_keys [:max_table_size, :huffman_encoding] + defstruct [ + :protocol_max_table_size, + :max_table_size, + :huffman_encoding, + entries: [], + size: 0, + length: 0, + pending_minimum_resize: nil + ] + + @type huffman_encoding() :: :always | :never + + @type t() :: %__MODULE__{ + protocol_max_table_size: non_neg_integer(), + max_table_size: non_neg_integer(), + huffman_encoding: huffman_encoding(), + entries: [{binary(), binary()}], + size: non_neg_integer(), + length: non_neg_integer(), + pending_minimum_resize: non_neg_integer() | nil + } + + @static_table [ + {":authority", nil}, + {":method", "GET"}, + {":method", "POST"}, + {":path", "/"}, + {":path", "/index.html"}, + {":scheme", "http"}, + {":scheme", "https"}, + {":status", "200"}, + {":status", "204"}, + {":status", "206"}, + {":status", "304"}, + {":status", "400"}, + {":status", "404"}, + {":status", "500"}, + {"accept-charset", nil}, + {"accept-encoding", "gzip, deflate"}, + {"accept-language", nil}, + {"accept-ranges", nil}, + {"accept", nil}, + {"access-control-allow-origin", nil}, + {"age", nil}, + {"allow", nil}, + {"authorization", nil}, + {"cache-control", nil}, + {"content-disposition", nil}, + {"content-encoding", nil}, + {"content-language", nil}, + {"content-length", nil}, + {"content-location", nil}, + {"content-range", nil}, + {"content-type", nil}, + {"cookie", nil}, + {"date", nil}, + {"etag", nil}, + {"expect", nil}, + {"expires", nil}, + {"from", nil}, + {"host", nil}, + {"if-match", nil}, + {"if-modified-since", nil}, + {"if-none-match", nil}, + {"if-range", nil}, + {"if-unmodified-since", nil}, + {"last-modified", nil}, + {"link", nil}, + {"location", nil}, + {"max-forwards", nil}, + {"proxy-authenticate", nil}, + {"proxy-authorization", nil}, + {"range", nil}, + {"referer", nil}, + {"refresh", nil}, + {"retry-after", nil}, + {"server", nil}, + {"set-cookie", nil}, + {"strict-transport-security", nil}, + {"transfer-encoding", nil}, + {"user-agent", nil}, + {"vary", nil}, + {"via", nil}, + {"www-authenticate", nil} + ] + + @static_table_size length(@static_table) + @dynamic_table_start @static_table_size + 1 + + @doc """ + Creates a new HPACK table with the given maximum size. + + The maximum size is not the maximum number of entries but rather the maximum size as defined in + http://httpwg.org/specs/rfc7541.html#maximum.table.size. + """ + @spec new(non_neg_integer(), huffman_encoding()) :: t() + def new(protocol_max_table_size, huffman_encoding) + when is_integer(protocol_max_table_size) and protocol_max_table_size >= 0 and + huffman_encoding in [:always, :never] do + %__MODULE__{ + protocol_max_table_size: protocol_max_table_size, + max_table_size: protocol_max_table_size, + huffman_encoding: huffman_encoding + } + end + + @doc """ + Adds the given header to the given table. + + If the new entry does not fit within the max table size then the oldest entries will be evicted. + + Header names should be lowercase when added to the HPACK table + as per the [HTTP/2 spec](https://http2.github.io/http2-spec/#rfc.section.8.1.2): + + > header field names MUST be converted to lowercase prior to their encoding in HTTP/2 + + """ + @spec add(t(), binary(), binary()) :: t() + def add(%__MODULE__{} = table, name, value) do + %{max_table_size: max_table_size, size: size} = table + entry_size = entry_size(name, value) + + cond do + # An attempt to add an entry larger than the maximum size causes the table to be emptied of + # all existing entries and results in an empty table. + entry_size > max_table_size -> + %{table | entries: [], size: 0, length: 0} + + size + entry_size > max_table_size -> + table + |> evict_to_size(max_table_size - entry_size) + |> add_header(name, value, entry_size) + + true -> + add_header(table, name, value, entry_size) + end + end + + defp add_header(%__MODULE__{} = table, name, value, entry_size) do + %{entries: entries, size: size, length: length} = table + %{table | entries: [{name, value} | entries], size: size + entry_size, length: length + 1} + end + + @doc """ + Looks up a header by index `index` in the given `table`. + + Returns `{:ok, {name, value}}` if a header is found at the given `index`, otherwise returns + `:error`. `value` can be a binary in case both the header name and value are present in the + table, or `nil` if only the name is present (this can only happen in the static table). + """ + @spec lookup_by_index(t(), pos_integer()) :: {:ok, {binary(), binary() | nil}} | :error + def lookup_by_index(table, index) + + # Static table + for {header, index} <- Enum.with_index(@static_table, 1) do + def lookup_by_index(%__MODULE__{}, unquote(index)), do: {:ok, unquote(header)} + end + + def lookup_by_index(%__MODULE__{length: 0}, _index) do + :error + end + + def lookup_by_index(%__MODULE__{entries: entries, length: length}, index) + when index >= @dynamic_table_start and index <= @dynamic_table_start + length - 1 do + {:ok, Enum.at(entries, index - @dynamic_table_start)} + end + + def lookup_by_index(%__MODULE__{}, _index) do + :error + end + + @doc """ + Looks up the index of a header by its name and value. + + It returns: + + * `{:full, index}` if the full header (name and value) are present in the table at `index` + + * `{:name, index}` if `name` is present in the table but with a different value than `value` + + * `:not_found` if the header name is not in the table at all + + Header names should be lowercase when looked up in the HPACK table + as per the [HTTP/2 spec](https://http2.github.io/http2-spec/#rfc.section.8.1.2): + + > header field names MUST be converted to lowercase prior to their encoding in HTTP/2 + + """ + @spec lookup_by_header(t(), binary(), binary() | nil) :: + {:full, pos_integer()} | {:name, pos_integer()} | :not_found + def lookup_by_header(table, name, value) + + def lookup_by_header(%__MODULE__{entries: entries}, name, value) do + case static_lookup_by_header(name, value) do + {:full, _index} = result -> + result + + {:name, index} -> + # Check if we get full match in the dynamic tabble + case dynamic_lookup_by_header(entries, name, value, @dynamic_table_start, nil) do + {:full, _index} = result -> result + _other -> {:name, index} + end + + :not_found -> + dynamic_lookup_by_header(entries, name, value, @dynamic_table_start, nil) + end + end + + for {{name, value}, index} when is_binary(value) <- Enum.with_index(@static_table, 1) do + defp static_lookup_by_header(unquote(name), unquote(value)) do + {:full, unquote(index)} + end + end + + static_table_names = + @static_table + |> Enum.map(&elem(&1, 0)) + |> Enum.with_index(1) + |> Enum.uniq_by(&elem(&1, 0)) + + for {name, index} <- static_table_names do + defp static_lookup_by_header(unquote(name), _value) do + {:name, unquote(index)} + end + end + + defp static_lookup_by_header(_name, _value) do + :not_found + end + + defp dynamic_lookup_by_header([{name, value} | _rest], name, value, index, _name_index) do + {:full, index} + end + + defp dynamic_lookup_by_header([{name, _} | rest], name, value, index, _name_index) do + dynamic_lookup_by_header(rest, name, value, index + 1, index) + end + + defp dynamic_lookup_by_header([_other | rest], name, value, index, name_index) do + dynamic_lookup_by_header(rest, name, value, index + 1, name_index) + end + + defp dynamic_lookup_by_header([], _name, _value, _index, name_index) do + if name_index, do: {:name, name_index}, else: :not_found + end + + @doc """ + Changes the table's protocol negotiated maximum size, possibly evicting entries as needed to satisfy. + + If the indicated size is less than the table's current max size, entries + will be evicted as needed to fit within the specified size, and the table's + maximum size will be decreased to the specified value. An will also be + set which will enqueue a 'dynamic table size update' command to be prefixed + to the next block encoded with this table, per RFC9113§4.3.1. + + If the indicated size is greater than or equal to the table's current max size, no entries are evicted + and the table's maximum size changes to the specified value. + + In all cases, the table's `:protocol_max_table_size` is updated accordingly + """ + @spec resize(t(), non_neg_integer()) :: t() + def resize(%__MODULE__{} = table, new_protocol_max_table_size) do + pending_minimum_resize = + case table.pending_minimum_resize do + nil -> new_protocol_max_table_size + current -> min(current, new_protocol_max_table_size) + end + + %{ + evict_to_size(table, new_protocol_max_table_size) + | protocol_max_table_size: new_protocol_max_table_size, + max_table_size: new_protocol_max_table_size, + pending_minimum_resize: pending_minimum_resize + } + end + + def dynamic_resize(%__MODULE__{} = table, new_max_table_size) do + %{ + evict_to_size(table, new_max_table_size) + | max_table_size: new_max_table_size + } + end + + @doc """ + Returns (and clears) any pending resize events on the table which will need to be signalled to + the decoder via dynamic table size update messages. Intended to be called at the start of any + block encode to prepend such dynamic table size update(s) as needed. The value of + `pending_minimum_resize` indicates the smallest maximum size of this table which has not yet + been signalled to the decoder, and is always included in the list returned if it is set. + Additionally, if the current max table size is larger than this value, it is also included int + the list, per https://www.rfc-editor.org/rfc/rfc7541#section-4.2 + """ + def pop_pending_resizes(%__MODULE__{pending_minimum_resize: nil} = table), do: {table, []} + + def pop_pending_resizes(%__MODULE__{} = table) do + pending_resizes = + if table.max_table_size > table.pending_minimum_resize, + do: [table.pending_minimum_resize, table.max_table_size], + else: [table.pending_minimum_resize] + + {%{table | pending_minimum_resize: nil}, pending_resizes} + end + + # Removes records as necessary to have the total size of entries within the table be less than + # or equal to the specified value. Does not change the table's max size. + defp evict_to_size(%__MODULE__{size: size} = table, new_size) when size <= new_size, do: table + + defp evict_to_size(%__MODULE__{entries: entries, size: size} = table, new_size) do + {new_entries_reversed, new_size} = + evict_towards_size(Enum.reverse(entries), size, new_size) + + %{ + table + | entries: Enum.reverse(new_entries_reversed), + size: new_size, + length: length(new_entries_reversed) + } + end + + defp evict_towards_size([{name, value} | rest], size, max_target_size) do + new_size = size - entry_size(name, value) + + if new_size <= max_target_size do + {rest, new_size} + else + evict_towards_size(rest, new_size, max_target_size) + end + end + + defp evict_towards_size([], 0, _max_target_size) do + {[], 0} + end + + defp entry_size(name, value) do + byte_size(name) + byte_size(value) + 32 + end + + # Made public to be used in tests. + @doc false + def __static_table__() do + @static_table + end +end diff --git a/deps/hpax/lib/hpax/types.ex b/deps/hpax/lib/hpax/types.ex new file mode 100644 index 0000000000000000000000000000000000000000..8106555ec88dc08cef0b60d2eddf77f30ff7fc41 --- /dev/null +++ b/deps/hpax/lib/hpax/types.ex @@ -0,0 +1,89 @@ +defmodule HPAX.Types do + @moduledoc false + + import Bitwise, only: [<<<: 2] + + alias HPAX.Huffman + + # This is used as a macro and not an inlined function because we want to be able to use it in + # guards. + defmacrop power_of_two(n) do + quote do: 1 <<< unquote(n) + end + + ## Encoding + + @spec encode_integer(non_neg_integer(), 1..8) :: bitstring() + def encode_integer(integer, prefix) + + def encode_integer(integer, prefix) when integer < power_of_two(prefix) - 1 do + <> + end + + def encode_integer(integer, prefix) do + initial = power_of_two(prefix) - 1 + remaining = integer - initial + <> + end + + defp encode_remaining_integer(remaining) when remaining >= 128 do + first = rem(remaining, 128) + 128 + <> + end + + defp encode_remaining_integer(remaining) do + <> + end + + @spec encode_binary(binary(), boolean()) :: iodata() + def encode_binary(binary, huffman?) do + binary = if huffman?, do: Huffman.encode(binary), else: binary + huffman_bit = if huffman?, do: 1, else: 0 + binary_size = encode_integer(byte_size(binary), 7) + [<>, binary] + end + + ## Decoding + + @spec decode_integer(bitstring, 1..8) :: {:ok, non_neg_integer(), binary()} | :error + def decode_integer(bitstring, prefix) when is_bitstring(bitstring) and prefix in 1..8 do + with <> <- bitstring do + if value < power_of_two(prefix) - 1 do + {:ok, value, rest} + else + decode_remaining_integer(rest, value, 0) + end + else + _ -> :error + end + end + + defp decode_remaining_integer(<<0::1, value::7, rest::binary>>, int, m) do + {:ok, int + (value <<< m), rest} + end + + defp decode_remaining_integer(<<1::1, value::7, rest::binary>>, int, m) do + decode_remaining_integer(rest, int + (value <<< m), m + 7) + end + + defp decode_remaining_integer(_, _, _) do + :error + end + + @spec decode_binary(binary) :: {:ok, binary(), binary()} | :error + def decode_binary(binary) when is_binary(binary) do + with <> <- binary, + {:ok, length, rest} <- decode_integer(rest, 7), + <> <- rest do + contents = + case huffman_bit do + 0 -> contents + 1 -> Huffman.decode(contents) + end + + {:ok, contents, rest} + else + _ -> :error + end + end +end diff --git a/deps/hpax/mix.exs b/deps/hpax/mix.exs new file mode 100644 index 0000000000000000000000000000000000000000..a7ddaed1b47692f75c5c8ea8bd112206008f0383 --- /dev/null +++ b/deps/hpax/mix.exs @@ -0,0 +1,54 @@ +defmodule HPAX.MixProject do + use Mix.Project + + @version "1.0.3" + @repo_url "https://github.com/elixir-mint/hpax" + + def project do + [ + app: :hpax, + version: @version, + elixir: "~> 1.12", + start_permanent: Mix.env() == :prod, + deps: deps(), + + # Tests + test_coverage: [tool: ExCoveralls], + + # Hex + package: package(), + description: "Implementation of the HPACK protocol (RFC 7541) for Elixir", + + # Docs + name: "HPAX", + docs: [ + source_ref: "v#{@version}", + source_url: @repo_url + ] + ] + end + + def application do + [ + extra_applications: [] + ] + end + + defp deps do + [ + {:ex_doc, "~> 0.34", only: :dev}, + {:hpack, ">= 0.0.0", hex: :hpack_erl, only: :test}, + {:stream_data, "~> 1.0", only: [:dev, :test]}, + {:dialyxir, "~> 1.0", only: [:dev, :test], runtime: false}, + {:excoveralls, "~> 0.18", only: :test}, + {:castore, "~> 1.0", only: :test} + ] + end + + defp package do + [ + licenses: ["Apache-2.0"], + links: %{"GitHub" => @repo_url} + ] + end +end diff --git a/deps/nx_signal/.formatter.exs b/deps/nx_signal/.formatter.exs new file mode 100644 index 0000000000000000000000000000000000000000..d9f22bc671ca3cff0cf57f8d84c2f221822ae296 --- /dev/null +++ b/deps/nx_signal/.formatter.exs @@ -0,0 +1,5 @@ +# Used by "mix format" +[ + import_deps: [:nx], + inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] +] diff --git a/deps/nx_signal/.hex b/deps/nx_signal/.hex new file mode 100644 index 0000000000000000000000000000000000000000..68ebcabf5e20ad86ca0ca9896e3ae139a3c6e303 Binary files /dev/null and b/deps/nx_signal/.hex differ diff --git a/deps/nx_signal/LICENSE b/deps/nx_signal/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..55d90a0c40efa00b7925c69d690617035a117048 --- /dev/null +++ b/deps/nx_signal/LICENSE @@ -0,0 +1,13 @@ +Copyright 2022 Paulo Valente + +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/deps/nx_signal/README.md b/deps/nx_signal/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a53d8bfb683c01c661b95e85c3650cbf7440bc74 --- /dev/null +++ b/deps/nx_signal/README.md @@ -0,0 +1,50 @@ +# NxSignal + +DSP (Digital Signal Processing) with [Nx](https://github.com/elixir-nx/nx) + +## Why NxSignal? + +This library comes from the author's urge to experiment with audio processing in Elixir through Nx. +However, the scope is not limited to audio signals. This library aims to provide the tooling for +a more classical approach to dealing with time series, through Fourier Transforms, FIR filters, +IIR filters and similar mathematical tools. + +## Getting Started + +In order to use `NxSignal`, you need Elixir installed. Then, you can add `NxSignal` as a dependency +to your Mix project: + +```elixir +def deps do + [ + {:nx_signal, "~> 0.1"} + ] +end +``` + +You can also use `Mix.install` for standalone development: + +```elixir +Mix.install([ + {:nx_signal, "~> 0.1"} +]) +``` + +By default, `NxSignal` only depends directly on `Nx` itself. If you wish to use separate backends +such as `Torchx` or `EXLA`, you need to explicitly depend on them. + +All of `NxSignal`'s functionality is provided through `Nx.Defn`, so things should work out of the +box with different backends and compilers. + +## Guides (Livebook) + +Check out the "guides" directory in the repository for examples. + +## Contributing + +Contributions are more than welcome! + +Firstly, please make sure you check the issues tracker and the pull requests list for +a similar feature or bugfix to what you wish to contribute. +If there aren't any mentions to be found, open up an issue so that we can discuss the +feature beforehand. diff --git a/deps/nx_signal/hex_metadata.config b/deps/nx_signal/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..b5d2b3ad6ecb4009afb734dd55bdf148a783bc42 --- /dev/null +++ b/deps/nx_signal/hex_metadata.config @@ -0,0 +1,19 @@ +{<<"app">>,<<"nx_signal">>}. +{<<"build_tools">>,[<<"mix">>]}. +{<<"description">>,<<"Digital Signal Processing extension for Nx">>}. +{<<"elixir">>,<<"~> 1.14">>}. +{<<"files">>, + [<<"lib">>,<<"lib/nx_signal.ex">>,<<"lib/nx_signal">>, + <<"lib/nx_signal/waveforms.ex">>,<<"lib/nx_signal/peak_finding.ex">>, + <<"lib/nx_signal/windows.ex">>,<<"lib/nx_signal/filters.ex">>, + <<".formatter.exs">>,<<"mix.exs">>,<<"README.md">>,<<"LICENSE">>]}. +{<<"licenses">>,[<<"Apache-2.0">>]}. +{<<"links">>,[{<<"GitHub">>,<<"https://github.com/elixir-nx/nx_signal">>}]}. +{<<"name">>,<<"nx_signal">>}. +{<<"requirements">>, + [[{<<"app">>,<<"nx">>}, + {<<"name">>,<<"nx">>}, + {<<"optional">>,false}, + {<<"repository">>,<<"hexpm">>}, + {<<"requirement">>,<<"~> 0.6">>}]]}. +{<<"version">>,<<"0.2.0">>}. diff --git a/deps/nx_signal/lib/nx_signal.ex b/deps/nx_signal/lib/nx_signal.ex new file mode 100644 index 0000000000000000000000000000000000000000..0484dc9d2355e120ee2b8f789f9b54f4b8eee955 --- /dev/null +++ b/deps/nx_signal/lib/nx_signal.ex @@ -0,0 +1,741 @@ +defmodule NxSignal do + @moduledoc """ + Nx library extension for digital signal processing. + """ + + import Nx.Defn + + @doc ~S""" + Computes the Short-Time Fourier Transform of a tensor. + + Returns the complex spectrum Z, the time in seconds for + each frame and the frequency bins in Hz. + + The STFT is parameterized through: + + * $k$: length of the Discrete Fourier Transform (DFT) + * $N$: length of each frame + * $H$: hop (in samples) between frames (calculated as $H = N - \text{overlap\\_length}$) + * $M$: number of frames + * $x[n]$: the input time-domain signal + * $w[n]$: the window function to be applied to each frame + + $$ + DFT(x, w) := \sum_{n=0}^{N - 1} x[n]w[n]e^\frac{-2 \pi i k n}{N} \\\\ + X[m, k] = DFT(x[mH..(mH + N - 1)], w) + $$ + + where $m$ assumes all values in the interval $[0, M - 1]$ + + See also: `NxSignal.Windows`, `istft/3`, `stft_to_mel/3` + + ## Options + + * `:sampling_rate` - the sampling frequency $F_s$ for the input in Hz. Defaults to `1000`. + * `:fft_length` - the DFT length that will be passed to `Nx.fft/2`. Defaults to `:power_of_two`. + * `:overlap_length` - the number of samples for the overlap between frames. + Defaults to half the window size. + * `:window_padding` - `:reflect`, `:zeros` or `nil`. See `as_windowed/3` for more details. + * `:scaling` - `nil`, `:spectrum` or `:psd`. + * `:spectrum` - each frame is divided by $\sum_{i} window[i]$. + * `nil` - No scaling is applied. + * `:psd` - each frame is divided by $\sqrt{F\_s\sum_{i} window[i]^2}$. + + ## Examples + + iex> {z, t, f} = NxSignal.stft(Nx.iota({4}), NxSignal.Windows.rectangular(n: 2), overlap_length: 1, fft_length: 2, sampling_rate: 400) + iex> z + #Nx.Tensor< + c64[frames: 3][frequencies: 2] + [ + [1.0+0.0i, -1.0+0.0i], + [3.0+0.0i, -1.0+0.0i], + [5.0+0.0i, -1.0+0.0i] + ] + > + iex> t + #Nx.Tensor< + f32[frames: 3] + [0.0024999999441206455, 0.004999999888241291, 0.007499999832361937] + > + iex> f + #Nx.Tensor< + f32[frequencies: 2] + [0.0, 200.0] + > + """ + @doc type: :time_frequency + deftransform stft(data, window, opts \\ []) do + {frame_length} = Nx.shape(window) + + opts = + Keyword.validate!(opts, [ + :overlap_length, + :window, + :scaling, + window_padding: :valid, + sampling_rate: 100, + fft_length: :power_of_two + ]) + + sampling_rate = opts[:sampling_rate] || raise ArgumentError, "missing sampling_rate option" + + overlap_length = opts[:overlap_length] || div(frame_length, 2) + + stft_n(data, window, sampling_rate, Keyword.put(opts, :overlap_length, overlap_length)) + end + + defnp stft_n(data, window, sampling_rate, opts) do + {frame_length} = Nx.shape(window) + padding = opts[:window_padding] + fft_length = opts[:fft_length] + overlap_length = opts[:overlap_length] + + spectrum = + data + |> as_windowed( + padding: padding, + window_length: frame_length, + stride: frame_length - overlap_length + ) + |> Nx.multiply(window) + |> Nx.fft(length: fft_length) + + {num_frames, fft_length} = Nx.shape(spectrum) + + frequencies = fft_frequencies(sampling_rate, fft_length: fft_length) + + # assign the middle of the equivalent time window as the time for the given frame + time_step = frame_length / (2 * sampling_rate) + last_frame = time_step * num_frames + times = Nx.linspace(time_step, last_frame, n: num_frames, name: :frames) + + output = + case opts[:scaling] do + :spectrum -> + spectrum / Nx.sum(window) + + :psd -> + spectrum / Nx.sqrt(sampling_rate * Nx.sum(window ** 2)) + + nil -> + spectrum + + scaling -> + raise ArgumentError, + "invalid :scaling, expected one of :spectrum, :psd or nil, got: #{inspect(scaling)}" + end + + {Nx.reshape(output, spectrum.shape, names: [:frames, :frequencies]), times, frequencies} + end + + @doc """ + Computes the frequency bins for a FFT with given options. + + ## Arguments + + * `sampling_rate` - Sampling frequency in Hz. + + ## Options + + * `:fft_length` - Number of FFT frequency bins. + * `:type` - Optional output type. Defaults to `{:f, 32}` + * `:name` - Optional axis name for the tensor. Defaults to `:frequencies` + + ## Examples + + iex> NxSignal.fft_frequencies(1.6e4, fft_length: 10) + #Nx.Tensor< + f32[frequencies: 10] + [0.0, 1.6e3, 3.2e3, 4.8e3, 6.4e3, 8.0e3, 9.6e3, 1.12e4, 1.28e4, 1.44e4] + > + """ + @doc type: :time_frequency + defn fft_frequencies(sampling_rate, opts \\ []) do + opts = keyword!(opts, [:fft_length, type: {:f, 32}, name: :frequencies, endpoint: false]) + fft_length = opts[:fft_length] + + step = sampling_rate / fft_length + + Nx.linspace(0, step * fft_length, + n: fft_length, + type: opts[:type], + name: opts[:name], + endpoint: opts[:endpoint] + ) + end + + @doc """ + Returns a tensor of K windows of length N + + ## Options + + * `:window_length` - the number of samples in a window + * `:stride` - The number of samples to skip between windows. Defaults to `1`. + * `:padding` - Padding mode, can be `:reflect` or a valid padding as per `Nx.pad/3` over the + input tensor's shape. Defaults to `:valid`. If `:reflect` or `:same`, the first window will be centered + at the start of the signal. The padding is applied for the whole input, rather than individual + windows. For `:zeros`, effectively each incomplete window will be zero-padded. + + ## Examples + + iex> NxSignal.as_windowed(Nx.tensor([0, 1, 2, 3, 4, 10, 11, 12]), window_length: 4) + #Nx.Tensor< + s64[5][4] + [ + [0, 1, 2, 3], + [1, 2, 3, 4], + [2, 3, 4, 10], + [3, 4, 10, 11], + [4, 10, 11, 12] + ] + > + + iex> NxSignal.as_windowed(Nx.tensor([0, 1, 2, 3, 4, 10, 11, 12]), window_length: 3) + #Nx.Tensor< + s64[6][3] + [ + [0, 1, 2], + [1, 2, 3], + [2, 3, 4], + [3, 4, 10], + [4, 10, 11], + [10, 11, 12] + ] + > + + iex> NxSignal.as_windowed(Nx.tensor([0, 1, 2, 3, 4, 10, 11]), window_length: 2, stride: 2, padding: [{0, 3}]) + #Nx.Tensor< + s64[5][2] + [ + [0, 1], + [2, 3], + [4, 10], + [11, 0], + [0, 0] + ] + > + + iex> t = Nx.iota({7}); + iex> NxSignal.as_windowed(t, window_length: 6, padding: :reflect, stride: 1) + #Nx.Tensor< + s64[8][6] + [ + [3, 2, 1, 0, 1, 2], + [2, 1, 0, 1, 2, 3], + [1, 0, 1, 2, 3, 4], + [0, 1, 2, 3, 4, 5], + [1, 2, 3, 4, 5, 6], + [2, 3, 4, 5, 6, 5], + [3, 4, 5, 6, 5, 4], + [4, 5, 6, 5, 4, 3] + ] + > + + iex> NxSignal.as_windowed(Nx.iota({10}), window_length: 6, padding: :reflect, stride: 2) + #Nx.Tensor< + s64[6][6] + [ + [3, 2, 1, 0, 1, 2], + [1, 0, 1, 2, 3, 4], + [1, 2, 3, 4, 5, 6], + [3, 4, 5, 6, 7, 8], + [5, 6, 7, 8, 9, 8], + [7, 8, 9, 8, 7, 6] + ] + > + """ + @doc type: :windowing + deftransform as_windowed(tensor, opts \\ []) do + if opts[:padding] == :reflect do + as_windowed_reflect_padding(tensor, opts) + else + as_windowed_non_reflect_padding(tensor, opts) + end + end + + deftransformp as_windowed_parse_reflect_opts(shape, opts) do + window_length = opts[:window_length] + + as_windowed_parse_non_reflect_opts( + shape, + Keyword.put(opts, :padding, [{div(window_length, 2), div(window_length, 2)}]) + ) + end + + deftransformp as_windowed_parse_non_reflect_opts(shape, opts) do + opts = Keyword.validate!(opts, [:window_length, padding: :valid, stride: 1]) + window_length = opts[:window_length] + window_dimensions = {window_length} + + padding = opts[:padding] + + [stride] = + strides = + case opts[:stride] do + stride when is_list(stride) -> + stride + + stride when is_integer(stride) and stride >= 1 -> + [stride] + + stride -> + raise ArgumentError, + "expected an integer >= 1 or a list of integers, got: #{inspect(stride)}" + end + + padding_config = as_windowed_to_padding_config(shape, window_dimensions, padding) + + # trick so that we can get Nx to calculate the pooled shape for us + %{shape: pooled_shape} = + Nx.window_max( + Nx.iota(shape, backend: Nx.Defn.Expr), + window_dimensions, + padding: padding, + strides: strides + ) + + output_shape = {Tuple.product(pooled_shape), window_length} + + {window_length, stride, padding_config, output_shape} + end + + defp as_windowed_to_padding_config(shape, kernel_size, mode) do + case mode do + :valid -> + List.duplicate({0, 0, 0}, tuple_size(shape)) + + :same -> + Enum.zip_with(Tuple.to_list(shape), Tuple.to_list(kernel_size), fn dim, k -> + padding_size = max(dim - 1 + k - dim, 0) + {floor(padding_size / 2), ceil(padding_size / 2), 0} + end) + + config when is_list(config) -> + Enum.map(config, fn + {x, y} when is_integer(x) and is_integer(y) -> + {x, y, 0} + + _other -> + raise ArgumentError, + "padding must be a list of {high, low} tuples, where each element is an integer. " <> + "Got: #{inspect(config)}" + end) + + mode -> + raise ArgumentError, + "invalid padding mode specified, padding must be one" <> + " of :valid, :same, or a padding configuration, got:" <> + " #{inspect(mode)}" + end + end + + defnp as_windowed_non_reflect_padding(tensor, opts \\ []) do + # current implementation only supports windowing 1D tensors + {window_length, stride, padding, output_shape} = + as_windowed_parse_non_reflect_opts(Nx.shape(tensor), opts) + + tensor = Nx.pad(tensor, 0, padding) + + as_windowed_apply(tensor, stride, output_shape, window_length) + end + + defnp as_windowed_reflect_padding(tensor, opts \\ []) do + # current implementation only supports windowing 1D tensors + {window_length, stride, _padding, output_shape} = + as_windowed_parse_reflect_opts(Nx.shape(tensor), opts) + + half_window = div(window_length, 2) + tensor = Nx.reflect(tensor, padding_config: [{half_window, half_window}]) + + as_windowed_apply(tensor, stride, output_shape, window_length) + end + + defnp as_windowed_apply(tensor, stride, output_shape, window_length) do + output = Nx.broadcast(Nx.tensor(0, type: tensor.type), output_shape) + {num_windows, _} = Nx.shape(output) + + [output, tensor] = Nx.broadcast_vectors([output, tensor]) + + {output, _, _, _} = + while {output, i = 0, current_window = 0, t = tensor}, current_window < num_windows do + window = t |> Nx.slice([i], [window_length]) + updated = Nx.put_slice(output, [current_window, 0], Nx.new_axis(window, 0)) + {updated, i + stride, current_window + 1, t} + end + + output + end + + @doc """ + Generates weights for converting an STFT representation into MEL-scale. + + See also: `stft/3`, `istft/3`, `stft_to_mel/3` + + ## Arguments + + * `fft_length` - Number of FFT bins + * `mel_bins` - Number of target MEL bins + * `sampling_rate` - Sampling frequency in Hz + + ## Options + * `:max_mel` - the pitch for the last MEL bin before log scaling. Defaults to 3016 + * `:mel_frequency_spacing` - the distance in Hz between two MEL bins before log scaling. Defaults to 66.6 + * `:type` - Target output type. Defaults to `{:f, 32}` + + ## Examples + + iex> NxSignal.mel_filters(10, 5, 8.0e3) + #Nx.Tensor< + f32[mels: 5][frequencies: 10] + [ + [0.0, 8.129207999445498e-4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 9.972016559913754e-4, 2.1870288765057921e-4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 9.510891977697611e-4, 4.150509194005281e-4, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 4.035891906823963e-4, 5.276656011119485e-4, 2.574124082457274e-4, 0.0, 0.0, 0.0, 0.0], + [0.0, 0.0, 0.0, 0.0, 7.329034269787371e-5, 2.342205698369071e-4, 3.8295105332508683e-4, 2.8712040511891246e-4, 1.9128978601656854e-4, 9.545915963826701e-5] + ] + > + """ + @doc type: :time_frequency + deftransform mel_filters(fft_length, mel_bins, sampling_rate, opts \\ []) do + opts = + Keyword.validate!(opts, + max_mel: 3016, + mel_frequency_spacing: 200 / 3, + type: {:f, 32} + ) + + mel_filters_n(sampling_rate, opts[:max_mel], opts[:mel_frequency_spacing], + type: opts[:type], + fft_length: fft_length, + mel_bins: mel_bins + ) + end + + defnp mel_filters_n(sampling_rate, max_mel, f_sp, opts) do + fft_length = opts[:fft_length] + mel_bins = opts[:mel_bins] + type = opts[:type] + + fftfreqs = fft_frequencies(sampling_rate, type: type, fft_length: fft_length) + + mels = Nx.linspace(0, max_mel / f_sp, type: type, n: mel_bins + 2, name: :mels) + freqs = f_sp * mels + + min_log_hz = 1_000 + min_log_mel = min_log_hz / f_sp + + # numpy uses the f64 value by default + logstep = Nx.log(6.4) / 27 + + log_t = mels >= min_log_mel + + # This is the same as freqs[log_t] = min_log_hz * Nx.exp(logstep * (mels[log_t] - min_log_mel)) + # notice that since freqs and mels are indexed by the same conditional tensor, we don't + # need to slice either of them + mel_f = Nx.select(log_t, min_log_hz * Nx.exp(logstep * (mels - min_log_mel)), freqs) + + fdiff = Nx.new_axis(mel_f[1..-1//1] - mel_f[0..-2//1], 1) + ramps = Nx.new_axis(mel_f, 1) - fftfreqs + + lower = -ramps[0..(mel_bins - 1)] / fdiff[0..(mel_bins - 1)] + upper = ramps[2..(mel_bins + 1)//1] / fdiff[1..mel_bins] + weights = Nx.max(0, Nx.min(lower, upper)) + + enorm = 2.0 / (mel_f[2..(mel_bins + 1)] - mel_f[0..(mel_bins - 1)]) + + weights * Nx.new_axis(enorm, 1) + end + + @doc """ + Converts a given STFT time-frequency spectrum into a MEL-scale time-frequency spectrum. + + See also: `stft/3`, `istft/3`, `mel_filters/4` + + ## Arguments + + * `z` - STFT spectrum + * `sampling_rate` - Sampling frequency in Hz + + ## Options + + * `:fft_length` - Number of FFT bins + * `:mel_bins` - Number of target MEL bins. Defaults to 128 + * `:type` - Target output type. Defaults to `{:f, 32}` + + ## Examples + + iex> fft_length = 16 + iex> sampling_rate = 8.0e3 + iex> {z, _, _} = NxSignal.stft(Nx.iota({10}), NxSignal.Windows.hann(n: 4), overlap_length: 2, fft_length: fft_length, sampling_rate: sampling_rate, window_padding: :reflect) + iex> Nx.axis_size(z, :frequencies) + 16 + iex> Nx.axis_size(z, :frames) + 6 + iex> NxSignal.stft_to_mel(z, sampling_rate, fft_length: fft_length, mel_bins: 4) + #Nx.Tensor< + f32[frames: 6][mel: 4] + [ + [0.2900530695915222, 0.17422175407409668, 0.18422472476959229, 0.09807997941970825], + [0.6093881130218506, 0.5647397041320801, 0.4353824257850647, 0.08635270595550537], + [0.7584103345870972, 0.7085014581680298, 0.5636920928955078, 0.179118812084198], + [0.8461772203445435, 0.7952491044998169, 0.6470762491226196, 0.2520409822463989], + [0.908548891544342, 0.8572604656219482, 0.7078656554222107, 0.3086767792701721], + [0.908548891544342, 0.8572604656219482, 0.7078656554222107, 0.3086767792701721] + ] + > + """ + @doc type: :time_frequency + defn stft_to_mel(z, sampling_rate, opts \\ []) do + opts = + keyword!(opts, [:fft_length, :mel_bins, :max_mel, :mel_frequency_spacing, type: {:f, 32}]) + + magnitudes = Nx.abs(z) ** 2 + + filters = + mel_filters(opts[:fft_length], opts[:mel_bins], sampling_rate, mel_filters_opts(opts)) + + freq_size = div(opts[:fft_length], 2) + + real_freqs_mag = Nx.slice_along_axis(magnitudes, 0, freq_size, axis: :frequencies) + real_freqs_filters = Nx.slice_along_axis(filters, 0, freq_size, axis: :frequencies) + + mel_spec = + Nx.dot( + real_freqs_mag, + [:frequencies], + real_freqs_filters, + [:frequencies] + ) + + mel_spec = Nx.reshape(mel_spec, Nx.shape(mel_spec), names: [:frames, :mel]) + + log_spec = Nx.log(Nx.clip(mel_spec, 1.0e-10, :infinity)) / Nx.log(10) + log_spec = Nx.max(log_spec, Nx.reduce_max(log_spec) - 8) + (log_spec + 4) / 4 + end + + deftransformp mel_filters_opts(opts) do + Keyword.take(opts, [:max_mel, :mel_frequency_spacing, :type]) + end + + @doc ~S""" + Computes the Inverse Short-Time Fourier Transform of a tensor. + + Returns a tensor of M time-domain frames of length `fft_length`. + + See also: `NxSignal.Windows`, `stft/3` + + ## Options + + * `:fft_length` - the DFT length that will be passed to `Nx.fft/2`. Defaults to `:power_of_two`. + * `:overlap_length` - the number of samples for the overlap between frames. + Defaults to half the window size. + * `:sampling_rate` - the sampling rate $F_s$ in Hz. Defaults to `1000`. + * `:scaling` - `nil`, `:spectrum` or `:psd`. + * `:spectrum` - each frame is multiplied by $\sum_{i} window[i]$. + * `nil` - No scaling is applied. + * `:psd` - each frame is multiplied by $\sqrt{F\_s\sum_{i} window[i]^2}$. + + ## Examples + + In general, `istft/3` takes in the same parameters and window as the `stft/3` that generated the spectrum. + In the first example, we can notice that the reconstruction is mostly perfect, aside from the first sample. + + This is because the Hann window only ensures perfect reconstruction in overlapping regions, so the edges + of the signal end up being distorted. + + iex> t = Nx.tensor([10, 10, 1, 0, 10, 10, 2, 20]) + iex> w = NxSignal.Windows.hann(n: 4) + iex> opts = [sampling_rate: 1, fft_length: 4] + iex> {z, _time, _freqs} = NxSignal.stft(t, w, opts) + iex> result = NxSignal.istft(z, w, opts) + iex> Nx.as_type(result, Nx.type(t)) + #Nx.Tensor< + s64[8] + [0, 10, 1, 0, 10, 10, 2, 20] + > + + Different scaling options are available (see `stft/3` for a more detailed explanation). + For perfect reconstruction, you want to use the same scaling as the STFT: + + iex> t = Nx.tensor([10, 10, 1, 0, 10, 10, 2, 20]) + iex> w = NxSignal.Windows.hann(n: 4) + iex> opts = [scaling: :spectrum, sampling_rate: 1, fft_length: 4] + iex> {z, _time, _freqs} = NxSignal.stft(t, w, opts) + iex> result = NxSignal.istft(z, w, opts) + iex> Nx.as_type(result, Nx.type(t)) + #Nx.Tensor< + s64[8] + [0, 10, 1, 0, 10, 10, 2, 20] + > + + iex> t = Nx.tensor([10, 10, 1, 0, 10, 10, 2, 20], type: :f32) + iex> w = NxSignal.Windows.hann(n: 4) + iex> opts = [scaling: :psd, sampling_rate: 1, fft_length: 4] + iex> {z, _time, _freqs} = NxSignal.stft(t, w, opts) + iex> result = NxSignal.istft(z, w, opts) + iex> Nx.as_type(result, Nx.type(t)) + #Nx.Tensor< + f32[8] + [0.0, 10.0, 0.9999999403953552, -2.1900146407460852e-7, 10.0, 10.0, 2.000000238418579, 20.0] + > + """ + @doc type: :time_frequency + defn istft(data, window, opts) do + opts = keyword!(opts, [:fft_length, :overlap_length, :scaling, sampling_rate: 1000]) + + fft_length = + case opts[:fft_length] do + nil -> + :power_of_two + + fft_length -> + fft_length + end + + overlap_length = + case opts[:overlap_length] do + nil -> + div(Nx.size(window), 2) + + overlap_length -> + overlap_length + end + + sampling_rate = + case {opts[:scaling], opts[:sampling_rate]} do + {:psd, nil} -> raise ArgumentError, ":sampling_rate is mandatory if scaling is :psd" + {_, sampling_rate} -> sampling_rate + end + + frames = Nx.ifft(data, length: fft_length) + + frames_rescaled = + case opts[:scaling] do + :spectrum -> + frames * Nx.sum(window) + + :psd -> + frames * Nx.sqrt(sampling_rate * Nx.sum(window ** 2)) + + nil -> + frames + + scaling -> + raise ArgumentError, + "invalid :scaling, expected one of :spectrum, :psd or nil, got: #{inspect(scaling)}" + end + + result_non_normalized = + overlap_and_add(frames_rescaled * window, overlap_length: overlap_length) + + normalization_factor = + overlap_and_add(Nx.broadcast(Nx.abs(window) ** 2, data.shape), + overlap_length: overlap_length + ) + + normalization_factor = Nx.select(normalization_factor > 1.0e-10, normalization_factor, 1.0) + + result_non_normalized / normalization_factor + end + + @doc """ + Performs the overlap-and-add algorithm over + an {..., M, N}-shaped tensor, where M is the number of + windows and N is the window size. + + The tensor is zero-padded on the right so + the last window fully appears in the result. + + ## Options + + * `:overlap_length` - The number of overlapping samples between windows + * `:type` - output type for casting the accumulated result. + If not given, defaults to `Nx.Type.to_complex/1` called on the input type. + + ## Examples + + iex> NxSignal.overlap_and_add(Nx.iota({3, 4}), overlap_length: 0) + #Nx.Tensor< + s64[12] + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + > + + iex> NxSignal.overlap_and_add(Nx.iota({3, 4}), overlap_length: 3) + #Nx.Tensor< + s64[6] + [0, 5, 15, 18, 17, 11] + > + + iex> t = Nx.tensor([[[[0, 1, 2, 3], [4, 5, 6, 7]]], [[[10, 11, 12, 13], [14, 15, 16, 17]]]]) |> Nx.vectorize(x: 2, y: 1) + iex> NxSignal.overlap_and_add(t, overlap_length: 3) + #Nx.Tensor< + vectorized[x: 2][y: 1] + s64[5] + [ + [ + [0, 5, 7, 9, 7] + ], + [ + [10, 25, 27, 29, 17] + ] + ] + > + """ + @doc type: :windowing + defn overlap_and_add(tensor, opts \\ []) do + opts = keyword!(opts, [:overlap_length, type: Nx.type(tensor)]) + overlap_length = opts[:overlap_length] + + %{vectorized_axes: vectorized_axes, shape: input_shape} = tensor + num_windows = Nx.axis_size(tensor, -2) + window_length = Nx.axis_size(tensor, -1) + + if overlap_length >= window_length do + raise ArgumentError, + "overlap_length must be a number less than the window size #{window_length}, got: #{inspect(window_length)}" + end + + tensor = + Nx.revectorize(tensor, [condensed_vectors: :auto, windows: num_windows], + target_shape: {window_length} + ) + + stride = window_length - overlap_length + output_holder_shape = {num_windows * stride + overlap_length} + + out = + Nx.broadcast( + Nx.tensor(0, type: tensor.type), + output_holder_shape + ) + + idx_template = Nx.iota({window_length, 1}, vectorized_axes: [windows: 1]) + i = Nx.iota({num_windows}) |> Nx.vectorize(:windows) + idx = idx_template + i * stride + + [%{vectorized_axes: [condensed_vectors: n, windows: _]} = tensor, idx] = + Nx.broadcast_vectors([tensor, idx]) + + tensor = Nx.revectorize(tensor, [condensed_vectors: n], target_shape: {:auto}) + idx = Nx.revectorize(idx, [condensed_vectors: n], target_shape: {:auto, 1}) + + out_shape = overlap_and_add_output_shape(out.shape, input_shape) + + out + |> Nx.indexed_add(idx, tensor) + |> Nx.as_type(opts[:type]) + |> Nx.revectorize(vectorized_axes, target_shape: out_shape) + end + + deftransformp overlap_and_add_output_shape({out_len}, in_shape) do + idx = tuple_size(in_shape) - 2 + + in_shape + |> Tuple.delete_at(idx) + |> Tuple.delete_at(idx) + |> Tuple.append(out_len) + end +end diff --git a/deps/nx_signal/lib/nx_signal/filters.ex b/deps/nx_signal/lib/nx_signal/filters.ex new file mode 100644 index 0000000000000000000000000000000000000000..ccecf268ca7574023d39870d0f5ae894cdd399bc --- /dev/null +++ b/deps/nx_signal/lib/nx_signal/filters.ex @@ -0,0 +1,28 @@ +defmodule NxSignal.Filters do + @moduledoc """ + Common filter functions. + """ + import Nx.Defn + + @pi :math.pi() + + @doc ~S""" + Calculates the normalized sinc function $sinc(t) = \frac{sin(\pi t)}{\pi t}$ + + ## Examples + + iex> NxSignal.Filters.sinc(Nx.tensor([0, 0.25, 1])) + #Nx.Tensor< + f32[3] + [1.0, 0.9003162980079651, -2.7827534054836178e-8] + > + """ + @doc type: :filters + defn sinc(t) do + t = t * @pi + zero_idx = Nx.equal(t, 0) + + # Define sinc(0) = 1 + Nx.select(zero_idx, 1, Nx.sin(t) / t) + end +end diff --git a/deps/nx_signal/lib/nx_signal/peak_finding.ex b/deps/nx_signal/lib/nx_signal/peak_finding.ex new file mode 100644 index 0000000000000000000000000000000000000000..2de1df8c283d1629221dcfb3f78408293808b919 --- /dev/null +++ b/deps/nx_signal/lib/nx_signal/peak_finding.ex @@ -0,0 +1,392 @@ +defmodule NxSignal.PeakFinding do + @moduledoc """ + Peak finding algorithms. + """ + + import Nx.Defn + import Nx, only: [u8: 1, s64: 1] + + @doc """ + Finds a relative minimum along the selected `:axis`. + + A relative minimum is defined by the element being greater + than its neighbors along the axis `:axis`. + + Returns a map in the following format: + + %{ + indices: #Nx.Tensor<...>, + valid_indices: #Nx.Tensor<...> + } + + * `:indices` - the `{n, rank}` tensor of indices. + Contains `-1` as a placeholder for invalid indices. + + * `:valid_indices` - the number of valid indices that lead the tensor. + + ## Options + + * `:axis` - the axis along which to do comparisons. Defaults to 0. + * `:order` - the number of neighbor samples considered for the + comparison in each direction. Defaults to 1. + + ## Examples + + iex> x = Nx.tensor([2, 1, 2, 3, 2, 0, 1, 0]) + iex> %{indices: indices, valid_indices: valid_indices} = NxSignal.PeakFinding.argrelmin(x) + iex> valid_indices + #Nx.Tensor< + u64 + 2 + > + iex> indices + #Nx.Tensor< + s64[8][1] + [ + [1], + [5], + [-1], + [-1], + [-1], + [-1], + [-1], + [-1] + ] + > + iex> Nx.slice_along_axis(indices, 0, Nx.to_number(valid_indices), axis: 0) + #Nx.Tensor< + s64[2][1] + [ + [1], + [5] + ] + > + + For the same tensor in the previous example, we can use `:order` to check if + the relative maxima are extrema in a wider neighborhood. + + iex> x = Nx.tensor([2, 1, 2, 3, 2, 0, 1, 0]) + iex> %{indices: indices, valid_indices: valid_indices} = NxSignal.PeakFinding.argrelmin(x, order: 3) + iex> valid_indices + #Nx.Tensor< + u64 + 1 + > + iex> indices + #Nx.Tensor< + s64[8][1] + [ + [1], + [-1], + [-1], + [-1], + [-1], + [-1], + [-1], + [-1] + ] + > + iex> Nx.slice_along_axis(indices, 0, Nx.to_number(valid_indices), axis: 0) + #Nx.Tensor< + s64[1][1] + [ + [1] + ] + > + + We can also apply this function to tensors with a larger rank: + + iex> x = Nx.tensor([[1, 2, 1, 2], [6, 2, 0, 0], [5, 3, 4, 4]]) + iex> %{indices: indices, valid_indices: valid_indices} = NxSignal.PeakFinding.argrelmin(x) + iex> valid_indices + #Nx.Tensor< + u64 + 2 + > + iex> indices[0..1] + #Nx.Tensor< + s64[2][2] + [ + [1, 2], + [1, 3] + ] + > + iex> %{indices: indices} = NxSignal.PeakFinding.argrelmin(x, axis: 1) + iex> valid_indices + #Nx.Tensor< + u64 + 2 + > + iex> indices[0..1] + #Nx.Tensor< + s64[2][2] + [ + [0, 2], + [2, 1] + ] + > + + """ + @doc type: :peak_finding + defn argrelmin(data, opts \\ []) do + opts = keyword!(opts, axis: 0, order: 1) + argrelextrema(data, &Nx.less/2, opts) + end + + @doc """ + Finds a relative maximum along the selected `:axis`. + + A relative maximum is defined by the element being greater + than its neighbors along the axis `:axis`. + + Returns a map in the following format: + + %{ + indices: #Nx.Tensor<...>, + valid_indices: #Nx.Tensor<...> + } + + * `:indices` - the `{n, rank}` tensor of indices. + Contains `-1` as a placeholder for invalid indices. + + * `:valid_indices` - the number of valid indices that lead the tensor. + + ## Options + + * `:axis` - the axis along which to do comparisons. Defaults to 0. + * `:order` - the number of neighbor samples considered for the + comparison in each direction. Defaults to 1. + + ## Examples + + iex> x = Nx.tensor([2, 1, 2, 3, 2, 0, 1, 0]) + iex> %{indices: indices, valid_indices: valid_indices} = NxSignal.PeakFinding.argrelmax(x) + iex> valid_indices + #Nx.Tensor< + u64 + 2 + > + iex> indices + #Nx.Tensor< + s64[8][1] + [ + [3], + [6], + [-1], + [-1], + [-1], + [-1], + [-1], + [-1] + ] + > + iex> Nx.slice_along_axis(indices, 0, Nx.to_number(valid_indices), axis: 0) + #Nx.Tensor< + s64[2][1] + [ + [3], + [6] + ] + > + + For the same tensor in the previous example, we can use `:order` to check if + the relative maxima are extrema in a wider neighborhood. + + iex> x = Nx.tensor([2, 1, 2, 3, 2, 0, 1, 0]) + iex> %{indices: indices, valid_indices: valid_indices} = NxSignal.PeakFinding.argrelmax(x, order: 3) + iex> valid_indices + #Nx.Tensor< + u64 + 1 + > + iex> indices + #Nx.Tensor< + s64[8][1] + [ + [3], + [-1], + [-1], + [-1], + [-1], + [-1], + [-1], + [-1] + ] + > + iex> Nx.slice_along_axis(indices, 0, Nx.to_number(valid_indices), axis: 0) + #Nx.Tensor< + s64[1][1] + [ + [3] + ] + > + + We can also apply this function to tensors with a larger rank: + + iex> x = Nx.tensor([[1, 2, 1, 2], [6, 2, 0, 0], [5, 3, 4, 4]]) + iex> %{indices: indices, valid_indices: valid_indices} = NxSignal.PeakFinding.argrelmax(x) + iex> valid_indices + #Nx.Tensor< + u64 + 1 + > + iex> indices[0] + #Nx.Tensor< + s64[2] + [1, 0] + > + iex> %{indices: indices} = NxSignal.PeakFinding.argrelmax(x, axis: 1) + iex> valid_indices + #Nx.Tensor< + u64 + 1 + > + iex> indices[0] + #Nx.Tensor< + s64[2] + [0, 1] + > + + """ + @doc type: :peak_finding + defn argrelmax(data, opts \\ []) do + opts = keyword!(opts, axis: 0, order: 1) + argrelextrema(data, &Nx.greater/2, opts) + end + + @doc """ + Finds a relative extrema along the selected `:axis`. + + A relative extremum is defined by the given `comparator_fn` + function of arity 2 function that returns a boolean tensor. + + This is the function upon which `&argrelmax/2` and `&argrelmin/2` + are implemented. + + Returns a map in the following format: + + %{ + indices: #Nx.Tensor<...>, + valid_indices: #Nx.Tensor<...> + } + + * `:indices` - the `{n, rank}` tensor of indices. + Contains `-1` as a placeholder for invalid indices. + + * `:valid_indices` - the number of valid indices that lead the tensor. + + ## Options + + * `:axis` - the axis along which to do comparisons. Defaults to 0. + * `:order` - the number of neighbor samples considered for the + comparison in each direction. Defaults to 1. + + ## Examples + + First, do read the examples on `argrelmax/2` keeping in mind that + it is equivalent to `argrelextrema(&1, &Nx.greater/2, &2)`, as well + as `argrelmin/2` which is equivalent to `argrelextrema(&1, &Nx.less/2, &2)`. + + Having that in mind, we will expand on those concepts by using a custom function. + For instance, we can change the definition of a relative maximum to one where + a number is a relative maximum if it is greater than or equal to the double of its + neighbors, as follows: + + iex> comparator = fn x, y -> Nx.greater_equal(x, Nx.multiply(y, 2)) end + iex> x = Nx.tensor([0, 1, 3, 2, 0, 1, 0, 0, 0, 2, 1]) + iex> result = NxSignal.PeakFinding.argrelextrema(x, comparator) + iex> result.valid_indices + #Nx.Tensor< + u64 + 3 + > + iex> result.indices[0..2] + #Nx.Tensor< + s64[3][1] + [ + [5], + [7], + [9] + ] + > + + Same applies for finding local minima. In the next example, we + find all local minima (i.e. `&Nx.less/2`) that are + different to the global minimum. + + iex> x = Nx.tensor([0, 1, 0, 2, 1, 3, 0, 1]) + iex> global_minimum = Nx.reduce_min(x) + iex> comparator = fn x, y -> + ...> x_not_global = Nx.not_equal(x, global_minimum) + ...> y_not_global = Nx.not_equal(y, global_minimum) + ...> both_not_global = Nx.logical_and(x_not_global, y_not_global) + ...> Nx.logical_and(Nx.less(x, y), both_not_global) + ...> end + iex> result = NxSignal.PeakFinding.argrelextrema(x, comparator) + iex> result.valid_indices + #Nx.Tensor< + u64 + 1 + > + iex> result.indices[0..0] + #Nx.Tensor< + s64[1][1] + [ + [4] + ] + > + """ + @doc type: :peak_finding + defn argrelextrema(data, comparator_fn, opts \\ []) do + opts = keyword!(opts, axis: 0, order: 1) + + data + |> boolrelextrema(comparator_fn, opts) + |> nonzero() + end + + defnp boolrelextrema(data, comparator_fn, opts \\ []) do + axis = opts[:axis] + order = opts[:order] + locs = Nx.iota({Nx.axis_size(data, axis)}) + + ones = Nx.broadcast(u8(1), data.shape) + [ones, _] = Nx.broadcast_vectors([ones, data]) + + {results, _} = + while {results = ones, {data, locs, halt = u8(0), shift = s64(1)}}, + not halt and shift < order + 1 do + plus = Nx.take(data, Nx.clip(locs + shift, 0, Nx.size(locs) - 1), axis: axis) + minus = Nx.take(data, Nx.clip(locs - shift, 0, Nx.size(locs) - 1), axis: axis) + results = comparator_fn.(data, plus) and results + results = comparator_fn.(data, minus) and results + + {results, {data, locs, not Nx.any(results), shift + 1}} + end + + results + end + + deftransformp nonzero(data) do + flat_data = Nx.reshape(data, {:auto, 1}) + + indices = + for axis <- 0..(Nx.rank(data) - 1), + reduce: Nx.broadcast(0, {Nx.axis_size(flat_data, 0), Nx.rank(data)}) do + %{shape: {n, _}} = indices -> + iota = data.shape |> Nx.iota(axis: axis) |> Nx.reshape({n, 1}) + Nx.put_slice(indices, [0, axis], iota) + end + + indices_with_mask = + Nx.select( + Nx.broadcast(flat_data, indices.shape), + indices, + Nx.broadcast(-1, indices.shape) + ) + + order = Nx.argsort(Nx.squeeze(flat_data, axes: [1]), axis: 0, direction: :desc) + + %{indices: Nx.take(indices_with_mask, order), valid_indices: Nx.sum(flat_data)} + end +end diff --git a/deps/nx_signal/lib/nx_signal/waveforms.ex b/deps/nx_signal/lib/nx_signal/waveforms.ex new file mode 100644 index 0000000000000000000000000000000000000000..0522bb5f077657efcceb5097c4260129d1ab0405 --- /dev/null +++ b/deps/nx_signal/lib/nx_signal/waveforms.ex @@ -0,0 +1,438 @@ +defmodule NxSignal.Waveforms do + @moduledoc """ + Functions that calculate waveforms given a time tensor. + """ + import Nx.Defn + import Nx.Constants, only: [pi: 0] + + @doc ~S""" + Periodic sawtooth or triangular waveform. + + The wave as a period of $2\pi$, rising from -1 to 1 + in the interval $[0, 2\pi\cdot\text{width}]$ and dropping from + 1 to -1 in the interval $[2\pi \cdot \text{width}, 2\pi]$. + + ## Options + + * `:width` - the width of the sawtooth. Must be a number + between 0 and 1 (both inclusive). Defaults to 1. + + ## Examples + + A 5Hz waveform sampled at 500Hz for 1 second can be defined as: + + t = Nx.linspace(0, 1, n: 500) + n = Nx.multiply(2 * :math.pi() * 5, t) + wave = NxSignal.Waveforms.sawtooth(n) + """ + @doc type: :waveforms + defn sawtooth(t, opts \\ []) do + opts = keyword!(opts, width: 1) + + width = opts[:width] + + if width < 0 or width > 1 do + raise ArgumentError, "width must be between 0 and 1, inclusive. Got: #{inspect(width)}" + end + + tmod = Nx.remainder(t, 2 * pi()) + + cond do + width == 1 -> + tmod / (pi() * width) - 1 + + width == 0 -> + (pi() * (width + 1) - tmod) / (pi() * (1 - width)) + + true -> + Nx.select( + tmod < 2 * pi() * width, + tmod / (pi() * width) - 1, + (pi() * (width + 1) - tmod) / (pi() * (1 - width)) + ) + end + end + + @doc """ + A periodic square wave with period $2\\pi$. + + Evaluates to 1 in the interval $[0, 2\\pi\\text{duty}]$ + and -1 in the interval $[2\\pi\\text{duty}, 2\\pi]$. + + ## Options + + * `:duty` - a number or tensor representing the duty cycle. + If a tensor is given, the waveform changes over time, and it + must have the same length as the `t` input. Defaults to `0.5`. + + ## Examples + + iex> t = Nx.iota({10}) |> Nx.multiply(:math.pi() * 2 / 10) + iex> NxSignal.Waveforms.square(t, duty: 0.1) + #Nx.Tensor< + s64[10] + [1, -1, -1, -1, -1, -1, -1, -1, -1, -1] + > + iex> NxSignal.Waveforms.square(t, duty: 0.5) + #Nx.Tensor< + s64[10] + [1, 1, 1, 1, 1, -1, -1, -1, -1, -1] + > + iex> NxSignal.Waveforms.square(t, duty: 1) + #Nx.Tensor< + s64[10] + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] + > + + iex> t = Nx.iota({10}) |> Nx.multiply(:math.pi() * 2 / 10) + iex> duty = Nx.tensor([0.1, 0, 0.3, 0, 0.5, 0, 0.7, 0, 0.9, 0]) + iex> NxSignal.Waveforms.square(t, duty: duty) + #Nx.Tensor< + s64[10] + [1, -1, 1, -1, 1, -1, 1, -1, 1, -1] + > + """ + @doc type: :waveforms + deftransform square(t, opts \\ []) do + opts = Keyword.validate!(opts, duty: 0.5) + square_n(t, opts[:duty]) + end + + defnp square_n(t, duty) do + tmod = Nx.remainder(t, 2 * pi()) + Nx.select(tmod < duty * 2 * pi(), 1, -1) + end + + @doc ~S""" + Gaussian modulated sinusoid. + + The returned value follows the formula: + + $$ + f(t) = e^{-at^2}(cos(2 \pi f_c t) + isin(2 \pi f_c t)) + $$ + + Where the exponential envelope is returned as `envelope`, + and the real and imaginary parts of $f(t)$ are returned as + `in_phase` and `quadrature` in the output map. + + Note that `in_phase` and `quadrature` are are equivalent to + $\operatorname{Re} \lbrace f(t) \rbrace$ and $\operatorname{Im} \lbrace f(t) \rbrace$ respectively. + + ## Examples + + iex> t = Nx.linspace(0, 1, n: 4) + iex> pulse = NxSignal.Waveforms.gaussian_pulse(t, center_frequency: 4) + iex> pulse.envelope + #Nx.Tensor< + f32[4] + [1.0, 0.20443114638328552, 0.001746579073369503, 6.236254534996988e-7] + > + iex> pulse.in_phase + #Nx.Tensor< + f32[4] + [1.0, -0.10221561044454575, -8.732887799851596e-4, 6.236254534996988e-7] + > + iex> pulse.quadrature + #Nx.Tensor< + f32[4] + [0.0, 0.17704254388809204, -0.0015125821810215712, 4.361525517918713e-13] + > + + iex> t = Nx.linspace(0, 1, n: 4) + iex> pulse = NxSignal.Waveforms.gaussian_pulse(t, center_frequency: 4, bandwidth: 0.25) + iex> pulse.envelope + #Nx.Tensor< + f32[4] + [1.0, 0.6724140048027039, 0.20443114638328552, 0.028101593255996704] + > + iex> pulse.in_phase + #Nx.Tensor< + f32[4] + [1.0, -0.3362071216106415, -0.1022154912352562, 0.028101593255996704] + > + iex> pulse.quadrature + #Nx.Tensor< + f32[4] + [0.0, 0.5823275446891785, -0.177042618393898, 1.9653754179671523e-8] + > + """ + @doc type: :waveforms + defn gaussian_pulse(t, opts \\ []) do + opts = + keyword!(opts, + center_frequency: 1000, + bandwidth: 0.5, + bandwidth_reference_level: -6 + ) + + fc = opts[:center_frequency] + bw = opts[:bandwidth] + bwr = opts[:bandwidth_reference_level] + + if fc < 0 do + raise ArgumentError, + "Center frequency must be greater than or equal to 0, got: #{inspect(fc)}" + end + + if bw <= 0 do + raise ArgumentError, + "Bandwidth must be greater than 0, got: #{inspect(bw)}" + end + + if bwr >= 0 do + raise ArgumentError, + "Bandwidth reference level must be less than 0, got: #{inspect(bwr)}" + end + + ref = 10 ** (bwr / 20) + + a = -((pi() * fc * bw) ** 2) / (4.0 * Nx.log(ref)) + + yenv = Nx.exp(-a * t * t) + yarg = 2 * pi() * fc * t + yI = yenv * Nx.cos(yarg) + yQ = yenv * Nx.sin(yarg) + + %{envelope: yenv, in_phase: yI, quadrature: yQ} + end + + @doc """ + Chirp function. + + Starts at `t` with frequency `f0` and ends at `t1` with + frequency `f1`. + + ## Options + + * `:phi` - phase shift for the chirp. + * `:vertex_zero` - determines the position of the parabolic vertex + for when `method: :quadratic`. Defaults to `true`. + * `:method` - One of various frequency interpolation methods: + * `:linear` - linear interpolation. + * `:quadratic` - parabolic interpolation with vertex at `t1` or `t0`, + depending if `vertex_zero: false` or `vertex_zero: true` respectively. + * `:hyperbolic` - hyperbolic interpolation. + * `:logarithmic` - logarithmic (also known as geometric or exponential) + interpolation. `f0` and `f1` must be non-zero and have the same sign. + + ## Examples + + iex> t = Nx.linspace(0, 10, n: 5) + iex> NxSignal.Waveforms.chirp(t, 10, 10, 1, method: :linear) + #Nx.Tensor< + f32[5] + [1.0, 0.38268470764160156, 3.795033308051643e-6, -0.382683128118515, 1.0] + > + iex> NxSignal.Waveforms.chirp(t, 10, 10, 1, method: :quadratic) + #Nx.Tensor< + f32[5] + [1.0, -0.9807833433151245, -9.958475288840418e-8, -0.5555803775787354, 1.0] + > + iex> NxSignal.Waveforms.chirp(t, 10, 10, 1, method: :quadratic, vertex_zero: false) + #Nx.Tensor< + f32[5] + [1.0, 0.5555850863456726, -7.490481493732659e-6, 0.98078453540802, 1.0] + > + iex> NxSignal.Waveforms.chirp(t, 10, 10, 1, method: :hyperbolic) + #Nx.Tensor< + f32[5] + [1.0, 0.8229323029518127, 0.9335360527038574, 0.013466471806168556, -0.8630329966545105] + > + iex> NxSignal.Waveforms.chirp(t, 10, 10, 1, method: :logarithmic) + #Nx.Tensor< + f32[5] + [1.0, 0.9989554286003113, -0.33371755480766296, -0.2700612545013428, 0.8558982610702515] + > + """ + @doc type: :waveforms + defn chirp(t, f0, t1, f1, opts \\ []) do + opts = keyword!(opts, phi: 0, vertex_zero: true, method: :linear) + + phase = + case {chirp_validate_method(opts[:method]), opts[:vertex_zero]} do + {:linear, _} -> + beta = (f1 - f0) / t1 + 2 * pi() * (f0 * t + 0.5 * beta * t ** 2) + + {:quadratic, true} -> + beta = (f1 - f0) / t1 ** 2 + 2 * pi() * (f0 * t + beta * t ** 3 / 3) + + {:quadratic, _} -> + beta = (f1 - f0) / t1 ** 2 + 2 * pi() * (f1 * t + beta * ((t1 - t) ** 3 - t1 ** 3) / 3) + + {:logarithmic, _} -> + cond do + f0 * f1 <= 0 -> + Nx.broadcast(:nan, t.shape) + + f0 == f1 -> + 2 * pi() * f0 * t + + true -> + beta = t1 / Nx.log(f1 / f0) + 2 * pi() * beta * f0 * ((f1 / f0) ** (t / t1) - 1.0) + end + + {:hyperbolic, _} -> + if f0 == f1 do + 2 * pi() * f0 * t + else + singular_point = -f1 * t1 / (f0 - f1) + 2 * pi() * (-singular_point * f0) * Nx.log(Nx.abs(1 - t / singular_point)) + end + end + + Nx.cos(phase + opts[:phi]) + end + + deftransformp chirp_validate_method(method) do + valid_methods = [:linear, :quadratic, :logarithmic, :hyperbolic] + + unless method in valid_methods do + raise ArgumentError, + "invalid method, must be one of #{inspect(valid_methods)}, got: #{inspect(method)}" + end + + method + end + + @doc """ + Frequency-swept cosine generator, with a time-dependent frequency. + + This function generates a sinusoidal function whose instantaneous + frequency varies with time. The frequency at time `t` is given by + the polynomial specified by the coefficients contained in `coefs`. + + See also: `chirp/5` + + ## Options + + * `:phi` - phase shift to be applied before calculating the `Nx.cos` + for the output. Defaults to 0. + * `:phi_unit` - determines if `:phi` is given in `:radians` or `:degrees`. + Defaults to `:radians`. + + ## Examples + + iex> t = Nx.linspace(0, 10, n: 5) + iex> NxSignal.Waveforms.polynomial_sweep(t, Nx.tensor([2, 0, 1])) + #Nx.Tensor< + f32[5] + [1.0, 0.866027295589447, -0.500006377696991, 1.7942518752533942e-5, -0.49998921155929565] + > + iex> NxSignal.Waveforms.polynomial_sweep(t, Nx.tensor([2, 0, 1]), phi: :math.pi() / 2) + #Nx.Tensor< + f32[5] + [-4.371138828673793e-8, 0.499999463558197, -0.8660194873809814, 1.0, 0.8660338521003723] + > + iex> NxSignal.Waveforms.polynomial_sweep(t, Nx.tensor([1, 0])) + #Nx.Tensor< + f32[5] + [1.0, 0.7071065306663513, -1.0, 0.7071084976196289, 1.0] + > + iex> NxSignal.Waveforms.polynomial_sweep(t, Nx.tensor([1, 0]), phi: 180, phi_unit: :degrees) + #Nx.Tensor< + f32[5] + [-1.0, -0.7071069478988647, 1.0, -0.7071129679679871, -1.0] + > + """ + @doc type: :waveforms + defn polynomial_sweep(t, coefs, opts \\ []) do + opts = keyword!(opts, phi: 0, phi_unit: :radians) + {n} = Nx.shape(coefs) + # assumes t is of shape {m} + iota = n - Nx.iota({n}) + t_poly = t ** Nx.new_axis(iota, 1) + + int_coefs = coefs / iota + + phase = Nx.dot(int_coefs, t_poly) + + phi = + case {opts[:phi], opts[:phi_unit]} do + {phi, :radians} -> phi + {phi, :degrees} -> phi * pi() / 180 + end + + Nx.cos(2 * pi() * phase + phi) + end + + @doc """ + Discrete delta function or unit basis vector. + + ## Options + + * `:index` - one of number, numerical tensor + with length equal to the rank of the given + shape, or `:midpoint`. `index: :midpoint`, + is a shortcut for inserting the impulse + at the index which corresponds to half of + each dimension. Defaults to 0. + + * `:type` - datatype for the output. Defaults to `:f32`. + + ## Examples + + iex> NxSignal.Waveforms.unit_impulse({2}) + #Nx.Tensor< + f32[2] + [1.0, 0.0] + > + + iex> NxSignal.Waveforms.unit_impulse({3, 5}, type: :s64, index: :midpoint) + #Nx.Tensor< + s64[3][5] + [ + [0, 0, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0] + ] + > + + iex> NxSignal.Waveforms.unit_impulse({3, 5}, index: Nx.tensor([[2, 3]]), type: :s64) + #Nx.Tensor< + s64[3][5] + [ + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 1, 0] + ] + > + """ + @doc type: :waveforms + deftransform unit_impulse(shape, opts \\ []) do + opts = Keyword.validate!(opts, index: 0, type: :f32) + index = unit_impulse_index(shape, opts[:index]) + + unit_impulse_n(index, Keyword.put(opts, :shape, shape)) + end + + defnp unit_impulse_n(index, opts \\ []) do + shape = opts[:shape] + type = opts[:type] + + zero = Nx.tensor(0, type: type) + + zeros = Nx.broadcast(zero, shape) + + Nx.indexed_put(zeros, index, 1) + end + + deftransformp unit_impulse_index(shape, index) do + n = Nx.rank(shape) + + case index do + :midpoint -> + shape + |> Tuple.to_list() + |> Enum.map(&div(&1, 2)) + |> then(&Nx.tensor(&1)) + + index -> + Nx.reshape(index, {n}) + end + end +end diff --git a/deps/nx_signal/lib/nx_signal/windows.ex b/deps/nx_signal/lib/nx_signal/windows.ex new file mode 100644 index 0000000000000000000000000000000000000000..c016f7ce163b5611fd020029d8f06693b7a39ce8 --- /dev/null +++ b/deps/nx_signal/lib/nx_signal/windows.ex @@ -0,0 +1,305 @@ +defmodule NxSignal.Windows do + @moduledoc """ + Common window functions. + """ + import Nx.Defn + + @pi :math.pi() + + @doc """ + Rectangular window. + + Useful for when no window function should be applied. + + ## Options + + * `:n` - the window length + * `:type` - the output type. Defaults to `s64` + + ## Examples + + iex> NxSignal.Windows.rectangular(n: 5) + #Nx.Tensor< + s64[5] + [1, 1, 1, 1, 1] + > + + iex> NxSignal.Windows.rectangular(n: 5, type: :f32) + #Nx.Tensor< + f32[5] + [1.0, 1.0, 1.0, 1.0, 1.0] + > + """ + @doc type: :windowing + defn rectangular(opts \\ []) do + opts = keyword!(opts, [:n, type: :s64]) + {n, opts} = pop_window_size(opts) + Nx.broadcast(Nx.tensor(1, type: opts[:type]), {n}) + end + + @doc """ + Bartlett triangular window. + + See also: `triangular/1` + + ## Options + + * `:n` - The window length. Mandatory option. + * `:type` - the output type for the window. Defaults to `{:f, 32}` + * `:name` - the axis name. Defaults to `nil` + + ## Examples + + iex> NxSignal.Windows.bartlett(n: 3) + #Nx.Tensor< + f32[3] + [0.0, 0.6666666865348816, 0.6666666269302368] + > + """ + @doc type: :windowing + defn bartlett(opts \\ []) do + opts = keyword!(opts, [:n, :name, type: {:f, 32}]) + {n, opts} = pop_window_size(opts) + name = opts[:name] + type = opts[:type] + + n_on_2 = div(n, 2) + left_size = n_on_2 + rem(n, 2) + left_idx = Nx.iota({left_size}, names: [name], type: type) + right_idx = Nx.iota({n_on_2}, names: [name], type: type) + left_size + + Nx.concatenate([ + left_idx * 2 / n, + 2 - right_idx * 2 / n + ]) + end + + @doc """ + Triangular window. + + See also: `bartlett/1` + + ## Options + + * `:n` - The window length. Mandatory option. + * `:type` - the output type for the window. Defaults to `{:f, 32}` + * `:name` - the axis name. Defaults to `nil` + + ## Examples + + iex> NxSignal.Windows.triangular(n: 3) + #Nx.Tensor< + f32[3] + [0.5, 1.0, 0.5] + > + """ + @doc type: :windowing + defn triangular(opts \\ []) do + opts = keyword!(opts, [:n, :name, type: {:f, 32}]) + {n, opts} = pop_window_size(opts) + name = opts[:name] + type = opts[:type] + + case rem(n, 2) do + 1 -> + # odd case + n_on_2 = div(n + 1, 2) + + idx = Nx.iota({n_on_2}, names: [name], type: type) + 1 + + left = idx * 2 / (n + 1) + Nx.concatenate([left, left |> Nx.reverse() |> Nx.slice([1], [Nx.size(left) - 1])]) + + 0 -> + # even case + n_on_2 = div(n + 1, 2) + + idx = Nx.iota({n_on_2}, names: [name], type: type) + 1 + + left = (2 * idx - 1) / n + Nx.concatenate([left, Nx.reverse(left)]) + end + end + + @doc """ + Blackman window. + + ## Options + + * `:n` - The window length. Mandatory option. + * `:is_periodic` - If `true`, produces a periodic window, + otherwise produces a symmetric window. Defaults to `true` + * `:type` - the output type for the window. Defaults to `{:f, 32}` + * `:name` - the axis name. Defaults to `nil` + + ## Examples + + iex> NxSignal.Windows.blackman(n: 5, is_periodic: false) + #Nx.Tensor< + f32[5] + [-1.4901161193847656e-8, 0.3400000333786011, 0.9999999403953552, 0.3400000333786011, -1.4901161193847656e-8] + > + + iex> NxSignal.Windows.blackman(n: 5, is_periodic: true) + #Nx.Tensor< + f32[5] + [-1.4901161193847656e-8, 0.20077012479305267, 0.8492299318313599, 0.8492299318313599, 0.20077012479305267] + > + + iex> NxSignal.Windows.blackman(n: 6, is_periodic: true, type: {:f, 32}) + #Nx.Tensor< + f32[6] + [-1.4901161193847656e-8, 0.12999999523162842, 0.6299999952316284, 0.9999999403953552, 0.6299999952316284, 0.12999999523162842] + > + """ + @doc type: :windowing + defn blackman(opts \\ []) do + opts = keyword!(opts, [:n, :name, is_periodic: true, type: {:f, 32}]) + {l, opts} = pop_window_size(opts) + name = opts[:name] + type = opts[:type] + is_periodic = opts[:is_periodic] + + l = + if is_periodic do + l + 1 + else + l + end + + m = div_ceil(l, 2) + + n = Nx.iota({m}, names: [name], type: type) + + left = + 0.42 - 0.5 * Nx.cos(2 * @pi * n / (l - 1)) + + 0.08 * Nx.cos(4 * @pi * n / (l - 1)) + + window = + if rem(l, 2) == 0 do + Nx.concatenate([left, Nx.reverse(left)]) + else + Nx.concatenate([left, left |> Nx.reverse() |> Nx.slice([1], [Nx.size(left) - 1])]) + end + + if is_periodic do + Nx.slice(window, [0], [Nx.size(window) - 1]) + else + window + end + end + + @doc """ + Hamming window. + + ## Options + + * `:n` - The window length. Mandatory option. + * `:is_periodic` - If `true`, produces a periodic window, + otherwise produces a symmetric window. Defaults to `true` + * `:type` - the output type for the window. Defaults to `{:f, 32}` + * `:name` - the axis name. Defaults to `nil` + + ## Examples + + iex> NxSignal.Windows.hamming(n: 5, is_periodic: true) + #Nx.Tensor< + f32[5] + [0.08000001311302185, 0.39785221219062805, 0.9121478796005249, 0.9121478199958801, 0.3978521227836609] + > + iex> NxSignal.Windows.hamming(n: 5, is_periodic: false) + #Nx.Tensor< + f32[5] + [0.08000001311302185, 0.5400000214576721, 1.0, 0.5400000214576721, 0.08000001311302185] + > + """ + @doc type: :windowing + defn hamming(opts \\ []) do + opts = keyword!(opts, [:n, :name, is_periodic: true, type: {:f, 32}]) + {l, opts} = pop_window_size(opts) + name = opts[:name] + type = opts[:type] + is_periodic = opts[:is_periodic] + + l = + if is_periodic do + l + 1 + else + l + end + + n = Nx.iota({l}, names: [name], type: type) + + window = 0.54 - 0.46 * Nx.cos(2 * @pi * n / (l - 1)) + + if is_periodic do + Nx.slice(window, [0], [l - 1]) + else + window + end + end + + @doc """ + Hann window. + + ## Options + + * `:n` - The window length. Mandatory option. + * `:is_periodic` - If `true`, produces a periodic window, + otherwise produces a symmetric window. Defaults to `true` + * `:type` - the output type for the window. Defaults to `{:f, 32}` + * `:name` - the axis name. Defaults to `nil` + + ## Examples + + iex> NxSignal.Windows.hann(n: 5, is_periodic: false) + #Nx.Tensor< + f32[5] + [0.0, 0.5, 1.0, 0.5, 0.0] + > + iex> NxSignal.Windows.hann(n: 5, is_periodic: true) + #Nx.Tensor< + f32[5] + [0.0, 0.34549152851104736, 0.9045085310935974, 0.9045084714889526, 0.3454914391040802] + > + """ + @doc type: :windowing + defn hann(opts \\ []) do + opts = keyword!(opts, [:n, :name, is_periodic: true, type: {:f, 32}]) + {l, opts} = pop_window_size(opts) + name = opts[:name] + type = opts[:type] + is_periodic = opts[:is_periodic] + + l = + if is_periodic do + l + 1 + else + l + end + + n = Nx.iota({l}, names: [name], type: type) + + window = 0.5 * (1 - Nx.cos(2 * @pi * n / (l - 1))) + + if is_periodic do + Nx.slice(window, [0], [l - 1]) + else + window + end + end + + deftransformp pop_window_size(opts) do + {n, opts} = Keyword.pop(opts, :n) + + unless n do + raise "missing :n option" + end + + {n, opts} + end + + deftransformp div_ceil(num, den) do + ceil(num / den) + end +end diff --git a/deps/nx_signal/mix.exs b/deps/nx_signal/mix.exs new file mode 100644 index 0000000000000000000000000000000000000000..362089d7a5c756511caf56806444381a2a366f97 --- /dev/null +++ b/deps/nx_signal/mix.exs @@ -0,0 +1,92 @@ +defmodule NxSignal.MixProject do + use Mix.Project + + @source_url "https://github.com/elixir-nx/nx_signal" + @version "0.2.0" + + def project do + [ + app: :nx_signal, + version: @version, + elixir: "~> 1.14", + start_permanent: Mix.env() == :prod, + elixirc_paths: elixirc_paths(Mix.env()), + deps: deps(), + docs: docs(), + name: "NxSignal", + description: "Digital Signal Processing extension for Nx", + package: package(), + preferred_cli_env: [ + docs: :docs, + "hex.publish": :docs + ] + ] + end + + defp elixirc_paths(:test), do: ["test/support", "lib"] + defp elixirc_paths(_), do: ["lib"] + + # Run "mix help compile.app" to learn about applications. + def application do + [ + extra_applications: [:logger] + ] + end + + defp docs do + [ + main: "NxSignal", + source_url_pattern: "#{@source_url}/blob/v#{@version}/nx-signal/%{path}#L%{line}", + before_closing_body_tag: &before_closing_body_tag/1, + extras: [ + "guides/filtering.livemd", + "guides/spectrogram.livemd" + ], + groups_for_extras: [ + Guides: Path.wildcard("guides/*.livemd") + ], + groups_for_functions: [ + "Functions: Time-Frequency": &(&1[:type] == :time_frequency), + "Functions: Windowing": &(&1[:type] == :windowing), + "Functions: Filters": &(&1[:type] == :filters), + "Functions: Waveforms": &(&1[:type] == :waveforms) + ] + ] + end + + # Run "mix help deps" to learn about dependencies. + defp deps do + [ + {:nx, "~> 0.6"}, + {:ex_doc, "~> 0.29", only: :docs} + ] + end + + defp package do + [ + maintainers: ["Paulo Valente"], + licenses: ["Apache-2.0"], + links: %{"GitHub" => @source_url} + ] + end + + defp before_closing_body_tag(:html) do + """ + + + + + """ + end + + defp before_closing_body_tag(_), do: "" +end diff --git a/deps/plug/lib/plug/adapters/cowboy.ex b/deps/plug/lib/plug/adapters/cowboy.ex new file mode 100644 index 0000000000000000000000000000000000000000..6ca2e9e00667c8ef2a176a398a2011d7729fa847 --- /dev/null +++ b/deps/plug/lib/plug/adapters/cowboy.ex @@ -0,0 +1,55 @@ +defmodule Plug.Adapters.Cowboy do + @moduledoc false + + @doc false + @deprecated "Use Plug.Cowboy.http/3 instead" + def http(plug, opts, cowboy_options \\ []) do + unless using_plug_cowboy?(), do: warn_and_raise() + Plug.Cowboy.http(plug, opts, cowboy_options) + end + + @doc false + @deprecated "Use Plug.Cowboy.https/3 instead" + def https(plug, opts, cowboy_options \\ []) do + unless using_plug_cowboy?(), do: warn_and_raise() + Plug.Cowboy.https(plug, opts, cowboy_options) + end + + @doc false + @deprecated "Use Plug.Cowboy.shutdown/1 instead" + def shutdown(ref) do + unless using_plug_cowboy?(), do: warn_and_raise() + Plug.Cowboy.shutdown(ref) + end + + @doc false + @deprecated "Use Plug.Cowboy.child_spec/4 instead" + def child_spec(scheme, plug, opts, cowboy_options \\ []) do + unless using_plug_cowboy?(), do: warn_and_raise() + Plug.Cowboy.child_spec(scheme, plug, opts, cowboy_options) + end + + @doc false + @deprecated "Use Plug.Cowboy.child_spec/1 instead" + def child_spec(opts) do + unless using_plug_cowboy?(), do: warn_and_raise() + Plug.Cowboy.child_spec(opts) + end + + defp using_plug_cowboy?() do + Code.ensure_loaded?(Plug.Cowboy) + end + + defp warn_and_raise() do + error = """ + please add the following dependency to your mix.exs: + {:plug_cowboy, "~> 1.0"} + This dependency is required by Plug.Adapters.Cowboy + which you may be using directly or indirectly. + Note you no longer need to depend on :cowboy directly. + """ + + IO.warn(error, []) + :erlang.raise(:exit, "plug_cowboy dependency missing", []) + end +end diff --git a/deps/plug/lib/plug/adapters/test/conn.ex b/deps/plug/lib/plug/adapters/test/conn.ex new file mode 100644 index 0000000000000000000000000000000000000000..ebec2025f3251f0ea0d1a51a27b81e1516796dc6 --- /dev/null +++ b/deps/plug/lib/plug/adapters/test/conn.ex @@ -0,0 +1,243 @@ +defmodule Plug.Adapters.Test.Conn do + @behaviour Plug.Conn.Adapter + @already_sent Plug.Conn.Adapter.already_sent() + @moduledoc false + + ## Test helpers + + def conn(%Plug.Conn{} = conn, method, uri, body_or_params) do + maybe_flush() + uri = URI.parse(uri) + + if is_binary(uri.path) and not String.starts_with?(uri.path, "/") do + # TODO: Convert to an error + IO.warn("the URI path used in plug tests must start with \"/\", got: #{inspect(uri.path)}") + end + + method = method |> to_string |> String.upcase() + query = uri.query || "" + owner = self() + + {params, {body, body_params}, {query, query_params}, req_headers} = + body_or_params(body_or_params, query, conn.req_headers, method) + + state = %{ + method: method, + params: params, + req_body: body, + chunks: nil, + ref: make_ref(), + owner: owner, + http_protocol: get_from_adapter(conn, :get_http_protocol, :"HTTP/1.1"), + peer_data: + get_from_adapter(conn, :get_peer_data, %{ + address: {127, 0, 0, 1}, + port: 111_317, + ssl_cert: nil + }), + sock_data: + get_from_adapter(conn, :get_sock_data, %{ + address: {127, 0, 0, 1}, + port: 111_318 + }), + ssl_data: get_from_adapter(conn, :get_ssl_data, nil) + } + + conn_port = if conn.port != 0, do: conn.port, else: 80 + + %{ + conn + | adapter: {__MODULE__, state}, + host: uri.host || conn.host || "www.example.com", + method: method, + path_info: split_path(uri.path), + port: uri.port || conn_port, + remote_ip: conn.remote_ip || {127, 0, 0, 1}, + req_headers: req_headers, + request_path: uri.path, + query_string: query, + query_params: query_params || %Plug.Conn.Unfetched{aspect: :query_params}, + body_params: body_params || %Plug.Conn.Unfetched{aspect: :body_params}, + params: params || %Plug.Conn.Unfetched{aspect: :params}, + scheme: (uri.scheme || "http") |> String.downcase() |> String.to_atom() + } + end + + ## Connection adapter + + def send_resp(%{method: "HEAD"} = state, status, headers, _body) do + do_send(state, status, headers, "") + end + + def send_resp(state, status, headers, body) do + do_send(state, status, headers, IO.iodata_to_binary(body)) + end + + def send_file(%{method: "HEAD"} = state, status, headers, _path, _offset, _length) do + do_send(state, status, headers, "") + end + + def send_file(state, status, headers, path, offset, length) do + %File.Stat{type: :regular, size: size} = File.stat!(path) + + length = + cond do + length == :all -> size + is_integer(length) -> length + end + + {:ok, data} = + File.open!(path, [:read, :binary], fn device -> + :file.pread(device, offset, length) + end) + + do_send(state, status, headers, data) + end + + def send_chunked(%{owner: owner} = state, _status, _headers) do + send(owner, @already_sent) + {:ok, "", %{state | chunks: ""}} + end + + def chunk(%{method: "HEAD"} = state, _body), do: {:ok, "", state} + + def chunk(%{chunks: chunks} = state, body) do + body = chunks <> IO.iodata_to_binary(body) + {:ok, body, %{state | chunks: body}} + end + + defp do_send(%{owner: owner, ref: ref} = state, status, headers, body) do + send(owner, @already_sent) + send(owner, {ref, {status, headers, body}}) + {:ok, body, state} + end + + def read_req_body(%{req_body: body} = state, opts \\ []) do + size = min(byte_size(body), Keyword.get(opts, :length, 8_000_000)) + data = :binary.part(body, 0, size) + rest = :binary.part(body, size, byte_size(body) - size) + + tag = + case rest do + "" -> :ok + _ -> :more + end + + {tag, data, %{state | req_body: rest}} + end + + def inform(%{owner: owner, ref: ref}, status, headers) do + send(owner, {ref, :inform, {status, headers}}) + :ok + end + + def upgrade(%{owner: owner, ref: ref}, :not_supported = protocol, opts) do + send(owner, {ref, :upgrade, {protocol, opts}}) + {:error, :not_supported} + end + + def upgrade(%{owner: owner, ref: ref} = state, protocol, opts) do + send(owner, {ref, :upgrade, {protocol, opts}}) + {:ok, state} + end + + def push(%{owner: owner, ref: ref}, path, headers) do + send(owner, {ref, :push, {path, headers}}) + :ok + end + + def get_peer_data(payload) do + Map.fetch!(payload, :peer_data) + end + + def get_sock_data(payload) do + Map.fetch!(payload, :sock_data) + end + + def get_ssl_data(payload) do + Map.fetch!(payload, :ssl_data) + end + + def get_http_protocol(payload) do + Map.fetch!(payload, :http_protocol) + end + + ## Private helpers + + defp get_from_adapter(conn, op, default) do + case conn.adapter do + {Plug.MissingAdapter, _} -> default + {adapter, payload} -> apply(adapter, op, [payload]) + end + end + + defp body_or_params(nil, query, headers, _method), do: {nil, {"", nil}, {query, nil}, headers} + + defp body_or_params(body, query, headers, _method) when is_binary(body) do + {nil, {body, nil}, {query, nil}, headers} + end + + defp body_or_params(params, query, headers, method) when is_list(params) do + body_or_params(Enum.into(params, %{}), query, headers, method) + end + + defp body_or_params(params, query, headers, method) + when is_map(params) and method in ["GET", "HEAD"] do + params = stringify_params(params, &to_string/1) + + from_query = Plug.Conn.Query.decode(query) + params = Map.merge(from_query, params) + + query = + params + |> Map.merge(from_query) + |> Plug.Conn.Query.encode() + + {params, {"", nil}, {query, params}, headers} + end + + defp body_or_params(params, query, headers, _method) when is_map(params) do + content_type_header = {"content-type", "multipart/mixed; boundary=plug_conn_test"} + content_type = List.keyfind(headers, "content-type", 0, content_type_header) + headers = List.keystore(headers, "content-type", 0, content_type) + + body_params = stringify_params(params, & &1) + query_params = Plug.Conn.Query.decode(query) + params = Map.merge(query_params, body_params) + + {params, {"--plug_conn_test--", body_params}, {query, query_params}, headers} + end + + defp stringify_params([{_, _} | _] = params, value_fun), + do: Enum.into(params, %{}, &stringify_kv(&1, value_fun)) + + defp stringify_params([_ | _] = params, value_fun), + do: Enum.map(params, &stringify_params(&1, value_fun)) + + defp stringify_params(%{__struct__: mod} = struct, _value_fun) when is_atom(mod), do: struct + defp stringify_params(fun, _value_fun) when is_function(fun), do: fun + + defp stringify_params(%{} = params, value_fun), + do: Enum.into(params, %{}, &stringify_kv(&1, value_fun)) + + defp stringify_params(other, value_fun), do: value_fun.(other) + + defp stringify_kv({k, v}, value_fun), do: {to_string(k), stringify_params(v, value_fun)} + + defp split_path(nil), do: [] + + defp split_path(path) do + segments = :binary.split(path, "/", [:global]) + for segment <- segments, segment != "", do: segment + end + + @already_sent {:plug_conn, :sent} + + defp maybe_flush() do + receive do + @already_sent -> :ok + after + 0 -> :ok + end + end +end diff --git a/deps/plug/lib/plug/conn/adapter.ex b/deps/plug/lib/plug/conn/adapter.ex new file mode 100644 index 0000000000000000000000000000000000000000..a39d725eefd52fab524f14cafaf859497035503c --- /dev/null +++ b/deps/plug/lib/plug/conn/adapter.ex @@ -0,0 +1,209 @@ +defmodule Plug.Conn.Adapter do + @moduledoc """ + Specification of the connection adapter API implemented by webservers. + + ## Implementation recommendations + + The `owner` field of `Plug.Conn` is deprecated and no longer needs to + be set by adapters. If you don't set the `owner` field, it is the + responsibility of the adapters to track the owner and send the + `already_sent/0` message below on any of the `send_*` callbacks. + """ + alias Plug.Conn + + @type http_protocol :: :"HTTP/1" | :"HTTP/1.1" | :"HTTP/2" | atom + @type payload :: term + @type peer_data :: %{ + address: :inet.ip_address(), + port: :inet.port_number(), + ssl_cert: binary | nil + } + @type sock_data :: %{ + address: :inet.ip_address(), + port: :inet.port_number() + } + @type ssl_data :: :ssl.connection_info() | nil + + @doc """ + The message to send to the request process on send callbacks. + """ + def already_sent do + {:plug_conn, :sent} + end + + @doc """ + Function used by adapters to create a new connection. + """ + def conn(adapter, method, uri, remote_ip, req_headers) do + %URI{path: path, host: host, port: port, query: qs, scheme: scheme} = uri + + %Plug.Conn{ + adapter: adapter, + host: host, + method: method, + path_info: split_path(path), + port: port, + remote_ip: remote_ip, + query_string: qs || "", + req_headers: req_headers, + request_path: path, + scheme: String.to_atom(scheme) + } + end + + defp split_path(path) do + segments = :binary.split(path, "/", [:global]) + for segment <- segments, segment != "", do: segment + end + + @doc """ + Sends the given status, headers and body as a response + back to the client. + + If the request has method `"HEAD"`, the adapter should + not send the response to the client. + + Webservers are advised to return `nil` as the sent_body, + as the body can no longer be manipulated. However, the + test implementation returns the actual body so it can + be used during testing. + + Webservers must send a `{:plug_conn, :sent}` message to the + process that called `Plug.Conn.Adapter.conn/5`. + """ + @callback send_resp( + payload, + status :: Conn.status(), + headers :: Conn.headers(), + body :: Conn.body() + ) :: + {:ok, sent_body :: binary | nil, payload} + + @doc """ + Sends the given status, headers and file as a response + back to the client. + + If the request has method `"HEAD"`, the adapter should + not send the response to the client. + + Webservers are advised to return `nil` as the sent_body, + as the body can no longer be manipulated. However, the + test implementation returns the actual body so it can + be used during testing. + + Webservers must send a `{:plug_conn, :sent}` message to the + process that called `Plug.Conn.Adapter.conn/5`. + """ + @callback send_file( + payload, + status :: Conn.status(), + headers :: Conn.headers(), + file :: binary, + offset :: integer, + length :: integer | :all + ) :: {:ok, sent_body :: binary | nil, payload} + + @doc """ + Sends the given status, headers as the beginning of + a chunked response to the client. If the connection uses a + protocol (such as HTTP/2) which does not support chunked encoding, + the response should be sent in a streaming manner using the + protocol's framing method. Likewise if the passed headers include + a `content-length` header, the response should be streamed using + content length framing. + + Webservers are advised to return `nil` as the sent_body, + since this function does not actually produce a body. + However, the test implementation returns an empty binary + as the body in order to be consistent with the built-up + body returned by subsequent calls to the test implementation's + `chunk/2` function + + Webservers must send a `{:plug_conn, :sent}` message to the + process that called `Plug.Conn.Adapter.conn/5`. + """ + @callback send_chunked(payload, status :: Conn.status(), headers :: Conn.headers()) :: + {:ok, sent_body :: binary | nil, payload} + + @doc """ + Sends a chunk in the chunked response. + + If the request has method `"HEAD"`, the adapter should + not send the response to the client. + + Webservers are advised to return `nil` as the sent_body, + since the complete sent body depends on the sum of all + calls to this function. However, the test implementation + tracks the overall body and payload so it can be used + during testing. + """ + @callback chunk(payload, body :: Conn.body()) :: + :ok | {:ok, sent_body :: binary | nil, payload} | {:error, term} + + @doc """ + Reads the request body. + + Read the docs in `Plug.Conn.read_body/2` for the supported + options and expected behaviour. + """ + @callback read_req_body(payload, options :: Keyword.t()) :: + {:ok, data :: binary, payload} + | {:more, data :: binary, payload} + | {:error, term} + + @doc """ + Push a resource to the client. + + If the adapter does not support server push then `{:error, :not_supported}` + should be returned. + + This callback no longer needs to be implemented, as browsers no longer support server push. + """ + @callback push(payload, path :: String.t(), headers :: Keyword.t()) :: :ok | {:error, term} + + @doc """ + Send an informational response to the client. + + If the adapter does not support inform, then `{:error, :not_supported}` + should be returned. + """ + @callback inform(payload, status :: Conn.status(), headers :: Keyword.t()) :: + :ok | {:ok, payload()} | {:error, term()} + + @doc """ + Attempt to upgrade the connection with the client. + + If the adapter does not support the indicated upgrade, then `{:error, :not_supported}` should be + be returned. + + If the adapter supports the indicated upgrade but is unable to proceed with it (due to + a negotiation error, invalid opts being passed to this function, or some other reason), then an + arbitrary error may be returned. Note that an adapter does not need to process the actual + upgrade within this function; it is a wholly supported failure mode for an adapter to attempt + the upgrade process later in the connection lifecycle and fail at that point. + """ + @callback upgrade(payload, protocol :: atom, opts :: term) :: {:ok, payload} | {:error, term} + + @doc """ + Returns peer information such as the address, port and ssl cert. + """ + @callback get_peer_data(payload) :: peer_data() + + @doc """ + Returns sock (local-side) information such as the address and port. + """ + @callback get_sock_data(payload) :: sock_data() + + @doc """ + Returns details of the negotiated SSL connection, if present. If the connection is not SSL, + returns nil + """ + @callback get_ssl_data(payload) :: ssl_data() + + @doc """ + Returns the HTTP protocol and its version. + """ + @callback get_http_protocol(payload) :: http_protocol + + @optional_callbacks push: 3, get_sock_data: 1, get_ssl_data: 1 +end diff --git a/deps/plug/lib/plug/conn/cookies.ex b/deps/plug/lib/plug/conn/cookies.ex new file mode 100644 index 0000000000000000000000000000000000000000..d97a5f64afc3e54758d9c8a2a0b85c4ec9e25eb1 --- /dev/null +++ b/deps/plug/lib/plug/conn/cookies.ex @@ -0,0 +1,153 @@ +defmodule Plug.Conn.Cookies do + @moduledoc """ + Conveniences for encoding and decoding cookies. + """ + + @doc """ + Decodes the given cookies as given in either a request or response header. + + If a cookie is invalid, it is automatically discarded from the result. + + ## Examples + + iex> decode("key1=value1;key2=value2") + %{"key1" => "value1", "key2" => "value2"} + + """ + def decode(cookie) when is_binary(cookie) do + Map.new(decode_kv(cookie, [])) + end + + defp decode_kv("", acc), do: acc + defp decode_kv(<>, acc) when h in [?\s, ?\t], do: decode_kv(t, acc) + defp decode_kv(kv, acc) when is_binary(kv), do: decode_key(kv, "", acc) + + defp decode_key(<>, _key, acc) when h in [?\s, ?\t, ?\r, ?\n, ?\v, ?\f], + do: skip_until_cc(t, acc) + + defp decode_key(<>, _key, acc), do: decode_kv(t, acc) + defp decode_key(<>, "", acc), do: skip_until_cc(t, acc) + defp decode_key(<>, key, acc), do: decode_value(t, "", 0, key, acc) + defp decode_key(<>, key, acc), do: decode_key(t, <>, acc) + defp decode_key(<<>>, _key, acc), do: acc + + defp decode_value(<>, value, spaces, key, acc), + do: decode_kv(t, [{key, trim_spaces(value, spaces)} | acc]) + + defp decode_value(<>, value, spaces, key, acc), + do: decode_value(t, <>, spaces + 1, key, acc) + + defp decode_value(<>, _value, _spaces, _key, acc) + when h in [?\t, ?\r, ?\n, ?\v, ?\f], + do: skip_until_cc(t, acc) + + defp decode_value(<>, value, _spaces, key, acc), + do: decode_value(t, <>, 0, key, acc) + + defp decode_value(<<>>, value, spaces, key, acc), + do: [{key, trim_spaces(value, spaces)} | acc] + + defp skip_until_cc(<>, acc), do: decode_kv(t, acc) + defp skip_until_cc(<<_, t::binary>>, acc), do: skip_until_cc(t, acc) + defp skip_until_cc(<<>>, acc), do: acc + + defp trim_spaces(value, 0), do: value + defp trim_spaces(value, spaces), do: binary_part(value, 0, byte_size(value) - spaces) + + @doc """ + Encodes the given cookies as expected in a response header. + + ## Examples + + iex> encode("key1", %{value: "value1"}) + "key1=value1; path=/; HttpOnly" + + iex> encode("key1", %{value: "value1", secure: true, path: "/example", http_only: false}) + "key1=value1; path=/example; secure" + """ + def encode(key, opts \\ %{}) when is_map(opts) do + value = Map.get(opts, :value) + path = Map.get(opts, :path, "/") + + IO.iodata_to_binary([ + "#{key}=#{value}; path=#{path}", + emit_if(opts[:domain], &["; domain=", &1]), + emit_if(opts[:max_age], &encode_max_age(&1, opts)), + emit_if(Map.get(opts, :secure, false), "; secure"), + emit_if(Map.get(opts, :http_only, true), "; HttpOnly"), + emit_if(Map.get(opts, :same_site, nil), &encode_same_site/1), + emit_if(opts[:extra], &["; ", &1]) + ]) + end + + defp encode_max_age(max_age, opts) do + time = Map.get(opts, :universal_time) || :calendar.universal_time() + time = add_seconds(time, max_age) + ["; expires=", rfc2822(time), "; max-age=", Integer.to_string(max_age)] + end + + defp encode_same_site(value) when is_binary(value), do: "; SameSite=#{value}" + + defp emit_if(value, fun_or_string) do + cond do + !value -> + [] + + is_function(fun_or_string) -> + fun_or_string.(value) + + is_binary(fun_or_string) -> + fun_or_string + end + end + + defp pad(number) when number in 0..9, do: <> + defp pad(number), do: Integer.to_string(number) + + defp rfc2822({{year, month, day} = date, {hour, minute, second}}) do + # Sat, 17 Apr 2010 14:00:00 GMT + [ + weekday_name(:calendar.day_of_the_week(date)), + ?,, + ?\s, + pad(day), + ?\s, + month_name(month), + ?\s, + Integer.to_string(year), + ?\s, + pad(hour), + ?:, + pad(minute), + ?:, + pad(second), + " GMT" + ] + end + + defp weekday_name(1), do: "Mon" + defp weekday_name(2), do: "Tue" + defp weekday_name(3), do: "Wed" + defp weekday_name(4), do: "Thu" + defp weekday_name(5), do: "Fri" + defp weekday_name(6), do: "Sat" + defp weekday_name(7), do: "Sun" + + defp month_name(1), do: "Jan" + defp month_name(2), do: "Feb" + defp month_name(3), do: "Mar" + defp month_name(4), do: "Apr" + defp month_name(5), do: "May" + defp month_name(6), do: "Jun" + defp month_name(7), do: "Jul" + defp month_name(8), do: "Aug" + defp month_name(9), do: "Sep" + defp month_name(10), do: "Oct" + defp month_name(11), do: "Nov" + defp month_name(12), do: "Dec" + + defp add_seconds(time, seconds_to_add) do + time_seconds = :calendar.datetime_to_gregorian_seconds(time) + :calendar.gregorian_seconds_to_datetime(time_seconds + seconds_to_add) + end +end diff --git a/deps/plug/lib/plug/conn/query.ex b/deps/plug/lib/plug/conn/query.ex new file mode 100644 index 0000000000000000000000000000000000000000..55463290940bd75c02377dbdedc5ba601d599f68 --- /dev/null +++ b/deps/plug/lib/plug/conn/query.ex @@ -0,0 +1,457 @@ +defmodule Plug.Conn.Query do + @moduledoc """ + Conveniences for decoding and encoding URL-encoded queries. + + Plug allows developers to build query strings that map to + Elixir structures in order to make manipulation of such structures + easier on the server side. Here are some examples: + + iex> decode("foo=bar")["foo"] + "bar" + + If a value is given more than once, the last value takes precedence: + + iex> decode("foo=bar&foo=baz")["foo"] + "baz" + + Nested structures can be created via `[key]`: + + iex> decode("foo[bar]=baz")["foo"]["bar"] + "baz" + + Lists are created with `[]`: + + iex> decode("foo[]=bar&foo[]=baz")["foo"] + ["bar", "baz"] + + > #### Nesting inside lists {: .error} + > + > Nesting inside lists is ambiguous and unspecified behaviour. + > Therefore, you should not rely on the decoding behaviour of + > `user[][foo]=1&user[][bar]=2`. + > + > As an alternative, you can explicitly specify the keys: + > + > # If foo and bar belong to the same entry + > user[0][foo]=1&user[0][bar]=2 + > + > # If foo and bar are different entries + > user[0][foo]=1&user[1][bar]=2 + + Keys without values are treated as empty strings, + according to https://url.spec.whatwg.org/#application/x-www-form-urlencoded: + + iex> decode("foo")["foo"] + "" + + Maps can be encoded: + + iex> encode(%{foo: "bar"}) + "foo=bar" + + Encoding keyword lists preserves the order of the fields: + + iex> encode([foo: "bar", baz: "bat"]) + "foo=bar&baz=bat" + + When encoding keyword lists with duplicate keys, the key that comes first + takes precedence: + + iex> encode([foo: "bar", foo: "bat"]) + "foo=bar" + + Encoding named lists: + + iex> encode(%{foo: ["bar", "baz"]}) + "foo[]=bar&foo[]=baz" + + Encoding nested structures: + + iex> encode(%{foo: %{bar: "baz"}}) + "foo[bar]=baz" + + It is only possible to encode maps inside lists if those maps have exactly one element. + In this case it is possible to encode the parameters using maps instead of lists: + + iex> encode(%{"list" => [%{"a" => 1, "b" => 2}]}) + ** (ArgumentError) cannot encode maps inside lists when the map has 0 or more than 1 element, got: %{\"a\" => 1, \"b\" => 2} + + iex> encode(%{"list" => %{0 => %{"a" => 1, "b" => 2}}}) + "list[0][a]=1&list[0][b]=2" + + For stateful decoding, see `decode_init/0`, `decode_each/2`, and `decode_done/2`. + """ + + @typedoc """ + Stateful decoder accumulator. + + See `decode_init/0`, `decode_each/2`, and `decode_done/2`. + """ + @typedoc since: "1.16.0" + @opaque decoder() :: map() + + @doc """ + Decodes the given `query`. + + The `query` is assumed to be encoded in the "x-www-form-urlencoded" format. + The format is decoded at first. Then, if `validate_utf8` is `true`, the decoded + result is validated for proper UTF-8 encoding. `validate_utf8` may also be + an atom with a custom exception to raise. + + `initial` is the initial "accumulator" where decoded values will be added. + + `invalid_exception` is the exception module for the exception to raise on + errors with decoding. + """ + @spec decode(String.t(), keyword(), module(), boolean()) :: %{optional(String.t()) => term()} + def decode( + query, + initial \\ [], + invalid_exception \\ Plug.Conn.InvalidQueryError, + validate_utf8 \\ true + ) + + def decode("", initial, _invalid_exception, _validate_utf8) do + Map.new(initial) + end + + def decode(query, initial, invalid_exception, validate_utf8) + when is_binary(query) do + parts = :binary.split(query, "&", [:global]) + + parts + |> Enum.reduce(decode_init(), &decode_www_pair(&1, &2, invalid_exception, validate_utf8)) + |> decode_done(initial) + end + + defp decode_www_pair("", acc, _invalid_exception, _validate_utf8) do + acc + end + + defp decode_www_pair(binary, acc, invalid_exception, validate_utf8) do + current = + case :binary.split(binary, "=") do + [key, value] -> + {decode_www_form(key, invalid_exception, validate_utf8), + decode_www_form(value, invalid_exception, validate_utf8)} + + [key] -> + {decode_www_form(key, invalid_exception, validate_utf8), ""} + end + + decode_each(current, acc) + end + + defp decode_www_form(value, invalid_exception, validate_utf8) do + binary = URI.decode_www_form(value) + + case validate_utf8 do + true -> Plug.Conn.Utils.validate_utf8!(binary, invalid_exception, "urlencoded params") + false -> :ok + module -> Plug.Conn.Utils.validate_utf8!(binary, module, "urlencoded params") + end + + binary + end + + @doc """ + Starts a stateful decoder. + + Use `decode_each/2` and `decode_done/2` to decode and complete. + See `decode_each/2` for examples. + """ + @spec decode_init() :: decoder() + def decode_init(), do: %{root: []} + + @doc """ + Decodes the given `pair` tuple. + + It parses the key and stores the value into the current + accumulator `decoder`. The keys and values are not assumed to be + encoded in `"x-www-form-urlencoded"`. + + ## Examples + + iex> decoder = Plug.Conn.Query.decode_init() + iex> decoder = Plug.Conn.Query.decode_each({"foo", "bar"}, decoder) + iex> decoder = Plug.Conn.Query.decode_each({"baz", "bat"}, decoder) + iex> Plug.Conn.Query.decode_done(decoder) + %{"baz" => "bat", "foo" => "bar"} + + """ + @spec decode_each({term(), term()}, decoder()) :: decoder() + def decode_each(pair, decoder) + + def decode_each({"", value}, map) do + insert_keys([{:root, ""}], value, map) + end + + def decode_each({key, value}, map) do + # Examples: + # + # users + # #=> [{:root, "users"}] + # + # users[foo] + # #=> [{"users", "foo"}, {:root, "users"}] + # + # users[foo][bar] + # #=> [{"users[foo]", "bar"}, {"users", "foo"}, {:root, "users"}] + # + keys = + with ?] <- :binary.last(key), + {pos, 1} when pos > 0 <- :binary.match(key, "[") do + value = binary_part(key, 0, pos) + pos = pos + 1 + rest = binary_part(key, pos, byte_size(key) - pos) + split_keys(rest, key, pos, pos, value, [{:root, value}]) + else + _ -> [{:root, key}] + end + + insert_keys(keys, value, map) + end + + defp split_keys(<>, binary, current_pos, start_pos, level, acc) do + value = split_key(binary, current_pos, start_pos) + next_level = binary_part(binary, 0, current_pos + 1) + split_keys(rest, binary, current_pos + 2, current_pos + 2, next_level, [{level, value} | acc]) + end + + defp split_keys(<>, binary, current_pos, start_pos, level, acc) do + value = split_key(binary, current_pos, start_pos) + [{level, value} | acc] + end + + defp split_keys(<<_, rest::binary>>, binary, current_pos, start_pos, level, acc) do + split_keys(rest, binary, current_pos + 1, start_pos, level, acc) + end + + defp split_key(_binary, start, start), do: nil + defp split_key(binary, current, start), do: binary_part(binary, start, current - start) + + defp insert_keys([{level, key} | rest], value, map) do + case map do + %{^level => entries} -> %{map | level => [{key, value} | entries]} + %{} -> insert_keys(rest, [:pointer | level], Map.put(map, level, [{key, value}])) + end + end + + defp insert_keys([], _value, map) do + map + end + + @doc """ + Finishes stateful decoding and returns a map with the decoded pairs. + + `decoder` is the stateful decoder returned by `decode_init/0` and `decode_each/2`. + `initial` is an enumerable of key-value pairs that functions as the initial + accumulator for the returned map (see examples below). + + ## Examples + + iex> decoder = Plug.Conn.Query.decode_init() + iex> decoder = Plug.Conn.Query.decode_each({"foo", "bar"}, decoder) + iex> Plug.Conn.Query.decode_done(decoder, %{"initial" => true}) + %{"foo" => "bar", "initial" => true} + + """ + @spec decode_done(decoder(), Enumerable.t()) :: %{optional(String.t()) => term()} + def decode_done(%{root: root} = decoder, initial \\ []) do + finalize_map(root, Enum.to_list(initial), decoder) + end + + defp finalize_pointer(key, map) do + case Map.fetch!(map, key) do + [{nil, _} | _] = entries -> finalize_list(entries, [], map) + entries -> finalize_map(entries, [], map) + end + end + + defp finalize_map([{key, [:pointer | pointer]} | rest], acc, map), + do: finalize_map(rest, [{key, finalize_pointer(pointer, map)} | acc], map) + + defp finalize_map([{nil, _} | rest], acc, map), + do: finalize_map(rest, acc, map) + + defp finalize_map([{_, _} = kv | rest], acc, map), + do: finalize_map(rest, [kv | acc], map) + + defp finalize_map([], acc, _map), + do: Map.new(acc) + + defp finalize_list([{nil, [:pointer | pointer]} | rest], acc, map), + do: finalize_list(rest, [finalize_pointer(pointer, map) | acc], map) + + defp finalize_list([{nil, value} | rest], acc, map), + do: finalize_list(rest, [value | acc], map) + + defp finalize_list([{_, _} | rest], acc, map), + do: finalize_list(rest, acc, map) + + defp finalize_list([], acc, _map), + do: acc + + @doc """ + Decodes the given tuple and stores it in the given accumulator. + + It parses the key and stores the value into the current + accumulator. The keys and values are not assumed to be + encoded in "x-www-form-urlencoded". + + Parameter lists are added to the accumulator in reverse + order, so be sure to pass the parameters in reverse order. + """ + @deprecated "Use decode_init/0, decode_each/2, and decode_done/2 instead" + def decode_pair({key, value} = _pair, acc) do + if key != "" and :binary.last(key) == ?] do + # Remove trailing ] + subkey = :binary.part(key, 0, byte_size(key) - 1) + + # Split the first [ then we will split on remaining ][. + # + # users[address][street #=> [ "users", "address][street" ] + # + assign_split(:binary.split(subkey, "["), value, acc, :binary.compile_pattern("][")) + else + assign_map(acc, key, value) + end + end + + defp assign_split(["", rest], value, acc, pattern) do + parts = :binary.split(rest, pattern) + + case acc do + [_ | _] -> [assign_split(parts, value, :none, pattern) | acc] + :none -> [assign_split(parts, value, :none, pattern)] + _ -> acc + end + end + + defp assign_split([key, rest], value, acc, pattern) do + parts = :binary.split(rest, pattern) + + case acc do + %{^key => current} when is_list(current) or is_map(current) -> + Map.put(acc, key, assign_split(parts, value, current, pattern)) + + %{^key => _} -> + acc + + %{} -> + Map.put(acc, key, assign_split(parts, value, :none, pattern)) + + _ -> + %{key => assign_split(parts, value, :none, pattern)} + end + end + + defp assign_split([""], nil, acc, _pattern) do + case acc do + [_ | _] -> acc + _ -> [] + end + end + + defp assign_split([""], value, acc, _pattern) do + case acc do + [_ | _] -> [value | acc] + :none -> [value] + _ -> acc + end + end + + defp assign_split([key], value, acc, _pattern) do + assign_map(acc, key, value) + end + + defp assign_map(acc, key, value) do + case acc do + %{^key => _} -> acc + %{} -> Map.put(acc, key, value) + _ -> %{key => value} + end + end + + @doc """ + Encodes the given map or list of tuples. + """ + @spec encode(Enumerable.t(), (term() -> binary())) :: binary() + def encode(kv, encoder \\ &to_string/1) do + IO.iodata_to_binary(encode_pair("", kv, encoder)) + end + + # covers structs + defp encode_pair(field, %{__struct__: struct} = map, encoder) when is_atom(struct) do + [field, ?= | encode_value(map, encoder)] + end + + # covers maps + defp encode_pair(parent_field, %{} = map, encoder) do + encode_kv(map, parent_field, encoder) + end + + # covers keyword lists + defp encode_pair(parent_field, list, encoder) when is_list(list) and is_tuple(hd(list)) do + encode_kv(Enum.uniq_by(list, &elem(&1, 0)), parent_field, encoder) + end + + # covers non-keyword lists + defp encode_pair(parent_field, list, encoder) when is_list(list) do + mapper = fn + value when is_map(value) and map_size(value) != 1 -> + raise ArgumentError, + "cannot encode maps inside lists when the map has 0 or more than 1 element, " <> + "got: #{inspect(value)}" + + value -> + [?&, encode_pair(parent_field <> "[]", value, encoder)] + end + + list + |> Enum.flat_map(mapper) + |> prune() + end + + # covers nil + defp encode_pair(field, nil, _encoder) do + [field, ?=] + end + + # encoder fallback + defp encode_pair(field, value, encoder) do + [field, ?= | encode_value(value, encoder)] + end + + defp encode_kv(kv, parent_field, encoder) do + mapper = fn + {_, value} when value in [%{}, []] -> + [] + + {field, value} -> + field = + if parent_field == "" do + encode_key(field) + else + parent_field <> "[" <> encode_key(field) <> "]" + end + + [?&, encode_pair(field, value, encoder)] + end + + kv + |> Enum.flat_map(mapper) + |> prune() + end + + defp encode_key(item) do + item |> to_string |> URI.encode_www_form() + end + + defp encode_value(item, encoder) do + item |> encoder.() |> URI.encode_www_form() + end + + defp prune([?& | t]), do: t + defp prune([]), do: [] +end diff --git a/deps/plug/lib/plug/conn/status.ex b/deps/plug/lib/plug/conn/status.ex new file mode 100644 index 0000000000000000000000000000000000000000..5d2696689b89ff809b55bf75cd5f7cf0ae3839ff --- /dev/null +++ b/deps/plug/lib/plug/conn/status.ex @@ -0,0 +1,183 @@ +defmodule Plug.Conn.Status do + @moduledoc """ + Conveniences for working with status codes. + """ + + custom_statuses = Application.compile_env(:plug, :statuses, %{}) + + aliased_statuses = [ + {422, :unprocessable_entity} + ] + + statuses = %{ + 100 => "Continue", + 101 => "Switching Protocols", + 102 => "Processing", + 103 => "Early Hints", + 200 => "OK", + 201 => "Created", + 202 => "Accepted", + 203 => "Non-Authoritative Information", + 204 => "No Content", + 205 => "Reset Content", + 206 => "Partial Content", + 207 => "Multi-Status", + 208 => "Already Reported", + 226 => "IM Used", + 300 => "Multiple Choices", + 301 => "Moved Permanently", + 302 => "Found", + 303 => "See Other", + 304 => "Not Modified", + 305 => "Use Proxy", + 306 => "Switch Proxy", + 307 => "Temporary Redirect", + 308 => "Permanent Redirect", + 400 => "Bad Request", + 401 => "Unauthorized", + 402 => "Payment Required", + 403 => "Forbidden", + 404 => "Not Found", + 405 => "Method Not Allowed", + 406 => "Not Acceptable", + 407 => "Proxy Authentication Required", + 408 => "Request Timeout", + 409 => "Conflict", + 410 => "Gone", + 411 => "Length Required", + 412 => "Precondition Failed", + 413 => "Request Entity Too Large", + 414 => "Request-URI Too Long", + 415 => "Unsupported Media Type", + 416 => "Requested Range Not Satisfiable", + 417 => "Expectation Failed", + 418 => "I'm a teapot", + 421 => "Misdirected Request", + 422 => "Unprocessable Content", + 423 => "Locked", + 424 => "Failed Dependency", + 425 => "Too Early", + 426 => "Upgrade Required", + 428 => "Precondition Required", + 429 => "Too Many Requests", + 431 => "Request Header Fields Too Large", + 451 => "Unavailable For Legal Reasons", + 500 => "Internal Server Error", + 501 => "Not Implemented", + 502 => "Bad Gateway", + 503 => "Service Unavailable", + 504 => "Gateway Timeout", + 505 => "HTTP Version Not Supported", + 506 => "Variant Also Negotiates", + 507 => "Insufficient Storage", + 508 => "Loop Detected", + 510 => "Not Extended", + 511 => "Network Authentication Required" + } + + reason_phrase_to_atom = fn reason_phrase -> + reason_phrase + |> String.downcase() + |> String.replace("'", "") + |> String.replace(~r/[^a-z0-9]/, "_") + |> String.to_atom() + end + + status_map_to_doc = fn statuses -> + statuses + |> Enum.sort_by(&elem(&1, 0)) + |> Enum.map(fn {code, reason_phrase} -> + atom = reason_phrase_to_atom.(reason_phrase) + " * `#{inspect(atom)}` - #{code}\n" + end) + end + + custom_status_doc = + if custom_statuses != %{} do + """ + ## Custom status codes + + #{status_map_to_doc.(custom_statuses)} + """ + end + + @doc """ + Returns the status code given an integer or a known atom. + + ## Known status codes + + The following status codes can be given as atoms with their + respective value shown next: + + #{status_map_to_doc.(statuses)} + #{custom_status_doc} + """ + @spec code(integer | atom) :: integer + def code(integer_or_atom) + + def code(integer) when integer in 100..999 do + integer + end + + for {code, reason_phrase} <- statuses do + atom = reason_phrase_to_atom.(reason_phrase) + def code(unquote(atom)), do: unquote(code) + end + + for {code, aliased_status} <- aliased_statuses do + def code(unquote(aliased_status)), do: unquote(code) + end + + # This ensures that both the default and custom statuses will work + for {code, reason_phrase} <- custom_statuses do + atom = reason_phrase_to_atom.(reason_phrase) + def code(unquote(atom)), do: unquote(code) + end + + @doc """ + Returns the atom for given integer. + + See `code/1` for the mapping. + """ + @spec reason_atom(integer) :: atom + def reason_atom(code) + + for {code, reason_phrase} <- Map.merge(statuses, custom_statuses) do + atom = reason_phrase_to_atom.(reason_phrase) + def reason_atom(unquote(code)), do: unquote(atom) + end + + def reason_atom(code) do + raise ArgumentError, "unknown status code #{inspect(code)}" + end + + @spec reason_phrase(integer) :: String.t() + def reason_phrase(integer) + + for {code, phrase} <- Map.merge(statuses, custom_statuses) do + def reason_phrase(unquote(code)), do: unquote(phrase) + end + + def reason_phrase(code) do + raise ArgumentError, """ + unknown status code #{inspect(code)} + + Custom codes can be defined in the configuration for the :plug application, + under the :statuses key (which contains a map of status codes as keys and + reason phrases as values). For example: + + config :plug, :statuses, %{998 => "Not An RFC Status Code"} + + After defining the config for custom statuses, Plug must be recompiled for + the changes to take place using: + + MIX_ENV=dev mix deps.clean plug --build + + Doing this will allow the use of the integer status code 998 as + well as the atom :not_an_rfc_status_code in many Plug functions. + For example: + + put_status(conn, :not_an_rfc_status_code) + """ + end +end diff --git a/deps/plug/lib/plug/conn/unfetched.ex b/deps/plug/lib/plug/conn/unfetched.ex new file mode 100644 index 0000000000000000000000000000000000000000..94b7b6430cb1c232b7db36aae80985ab98ba06b3 --- /dev/null +++ b/deps/plug/lib/plug/conn/unfetched.ex @@ -0,0 +1,47 @@ +defmodule Plug.Conn.Unfetched do + @moduledoc """ + A struct used as default on unfetched fields. + + The `:aspect` key of the struct specifies what field is still unfetched. + + ## Examples + + unfetched = %Plug.Conn.Unfetched{aspect: :cookies} + + """ + + defstruct [:aspect] + @type t :: %__MODULE__{aspect: atom()} + + @behaviour Access + + def fetch(%{aspect: aspect}, key) do + raise_unfetched(__ENV__.function, aspect, key) + end + + def get(%{aspect: aspect}, key, _value) do + raise_unfetched(__ENV__.function, aspect, key) + end + + def get_and_update(%{aspect: aspect}, key, _fun) do + raise_unfetched(__ENV__.function, aspect, key) + end + + def pop(%{aspect: aspect}, key) do + raise_unfetched(__ENV__.function, aspect, key) + end + + defp raise_unfetched({access, _}, aspect, key) do + raise ArgumentError, + "cannot #{access} key #{inspect(key)} from conn.#{aspect} " <> + "because they were not fetched" <> hint(aspect) + end + + defp hint(aspect) when aspect in [:cookies, :query_params], + do: ". Call Plug.Conn.fetch_#{aspect}/2, either as a plug or directly, to fetch it" + + defp hint(aspect) when aspect in [:params, :body_params], + do: ". Configure and invoke Plug.Parsers to set params based on the request" + + defp hint(_), do: "" +end diff --git a/deps/plug/lib/plug/conn/utils.ex b/deps/plug/lib/plug/conn/utils.ex new file mode 100644 index 0000000000000000000000000000000000000000..a98d09d216342c11866dbd3d5cb6bb2f7e173afc --- /dev/null +++ b/deps/plug/lib/plug/conn/utils.ex @@ -0,0 +1,341 @@ +defmodule Plug.Conn.Utils do + @moduledoc """ + Utilities for working with connection data + """ + + @type params :: %{optional(binary) => binary} + + @upper ?A..?Z + @lower ?a..?z + @alpha ?0..?9 + @other [?., ?-, ?+, ?_] + @space [?\s, ?\t] + @specials ~c|()<>@,;:\\"/[]?={}| + + @doc ~S""" + Parses media types (with wildcards). + + Type and subtype are case insensitive while the + sensitiveness of params depends on their keys and + therefore are not handled by this parser. + + Returns: + + * `{:ok, type, subtype, map_of_params}` if everything goes fine + * `:error` if the media type isn't valid + + ## Examples + + iex> media_type "text/plain" + {:ok, "text", "plain", %{}} + + iex> media_type "APPLICATION/vnd.ms-data+XML" + {:ok, "application", "vnd.ms-data+xml", %{}} + + iex> media_type "application/media_control+xml" + {:ok, "application", "media_control+xml", %{}} + + iex> media_type "text/*; q=1.0" + {:ok, "text", "*", %{"q" => "1.0"}} + + iex> media_type "*/*; q=1.0" + {:ok, "*", "*", %{"q" => "1.0"}} + + iex> media_type "x y" + :error + + iex> media_type "*/html" + :error + + iex> media_type "/" + :error + + iex> media_type "x/y z" + :error + + """ + @spec media_type(binary) :: {:ok, type :: binary, subtype :: binary, params} | :error + def media_type(binary) when is_binary(binary) do + case strip_spaces(binary) do + "*/*" <> t -> mt_params(t, "*", "*") + t -> mt_first(t, "") + end + end + + defp mt_first(<>, acc) when acc != "", do: mt_wildcard(t, acc) + + defp mt_first(<>, acc) when h in @upper, + do: mt_first(t, <>) + + defp mt_first(<>, acc) when h in @lower or h in @alpha or h == ?-, + do: mt_first(t, <>) + + defp mt_first(_, _acc), do: :error + + defp mt_wildcard(<>, first), do: mt_params(t, first, "*") + defp mt_wildcard(t, first), do: mt_second(t, "", first) + + defp mt_second(<>, acc, first) when h in @upper, + do: mt_second(t, <>, first) + + defp mt_second(<>, acc, first) when h in @lower or h in @alpha or h in @other, + do: mt_second(t, <>, first) + + defp mt_second(t, acc, first), do: mt_params(t, first, acc) + + defp mt_params(t, first, second) do + case strip_spaces(t) do + "" -> {:ok, first, second, %{}} + ";" <> t -> {:ok, first, second, params(t)} + _ -> :error + end + end + + @doc ~S""" + Parses content type (without wildcards). + + It is similar to `media_type/1` except wildcards are + not accepted in the type nor in the subtype. + + ## Examples + + iex> content_type "x-sample/json; charset=utf-8" + {:ok, "x-sample", "json", %{"charset" => "utf-8"}} + + iex> content_type "x-sample/json ; charset=utf-8 ; foo=bar" + {:ok, "x-sample", "json", %{"charset" => "utf-8", "foo" => "bar"}} + + iex> content_type "\r\n text/plain;\r\n charset=utf-8\r\n" + {:ok, "text", "plain", %{"charset" => "utf-8"}} + + iex> content_type "text/plain" + {:ok, "text", "plain", %{}} + + iex> content_type "x/*" + :error + + iex> content_type "*/*" + :error + + iex> content_type "something" + :error + + """ + @spec content_type(binary) :: {:ok, type :: binary, subtype :: binary, params} | :error + def content_type(binary) do + case media_type(binary) do + {:ok, _, "*", _} -> :error + {:ok, _, _, _} = ok -> ok + :error -> :error + end + end + + @doc ~S""" + Parses headers parameters. + + Keys are case insensitive and downcased, + invalid key-value pairs are discarded. + + ## Examples + + iex> params("foo=bar") + %{"foo" => "bar"} + + iex> params(" foo=bar ") + %{"foo" => "bar"} + + iex> params("FOO=bar") + %{"foo" => "bar"} + + iex> params("Foo=bar; baz=BOING") + %{"foo" => "bar", "baz" => "BOING"} + + iex> params("foo=BAR ; wat") + %{"foo" => "BAR"} + + iex> params("foo=\"bar\"; baz=\"boing\"") + %{"foo" => "bar", "baz" => "boing"} + + iex> params("foo=\"bar;\"; baz=\"boing\"") + %{"foo" => "bar;", "baz" => "boing"} + + iex> params("=") + %{} + + iex> params(";") + %{} + + iex> params("foo=") + %{} + + """ + @spec params(binary) :: params + def params(t) do + t + |> split_semicolon("", [], false) + |> Enum.reduce(%{}, ¶ms/2) + end + + defp params(param, acc) do + case params_key(strip_spaces(param), "") do + {k, v} -> Map.put(acc, k, v) + false -> acc + end + end + + defp params_key(<>, acc) when acc != "", do: params_value(t, acc) + + defp params_key(<>, _acc) + when h in @specials or h in @space or h < 32 or h === 127, + do: false + + defp params_key(<>, acc), do: params_key(t, <>) + defp params_key(<<>>, _acc), do: false + + defp params_value(token, key) do + case token(token) do + false -> false + value -> {key, value} + end + end + + @doc ~S""" + Parses a value as defined in [RFC-1341](http://www.w3.org/Protocols/rfc1341/4_Content-Type.html). + + For convenience, trims whitespace at the end of the token. + Returns `false` if the token is invalid. + + ## Examples + + iex> token("foo") + "foo" + + iex> token("foo-bar") + "foo-bar" + + iex> token("") + false + + iex> token(~s[""]) + "" + + iex> token(~S["\""]) + "\"" + + iex> token(~s["]) + false + + iex> token("foo ") + "foo" + + iex> token("foo bar") + false + + iex> token("") + false + + iex> token(" ") + "" + + """ + @spec token(binary) :: binary | false + def token(""), do: false + def token(<>), do: quoted_token(quoted, "") + def token(token), do: unquoted_token(token, "") + + defp quoted_token(<<>>, _acc), do: false + defp quoted_token(<>, acc), do: strip_spaces(t) == "" and acc + defp quoted_token(<>, acc), do: quoted_token(t, <>) + defp quoted_token(<>, acc), do: quoted_token(t, <>) + + defp unquoted_token(<<>>, acc), do: acc + defp unquoted_token("\r\n" <> t, acc), do: strip_spaces(t) == "" and acc + defp unquoted_token(<>, acc) when h in @space, do: strip_spaces(t) == "" and acc + + defp unquoted_token(<>, _acc) when h in @specials or h < 32 or h === 127, + do: false + + defp unquoted_token(<>, acc), do: unquoted_token(t, <>) + + @doc """ + Parses a comma-separated list of header values. + + ## Examples + + iex> list("foo, bar") + ["foo", "bar"] + + iex> list("foobar") + ["foobar"] + + iex> list("") + [] + + iex> list("empties, , are,, filtered") + ["empties", "are", "filtered"] + + iex> list("whitespace , , ,, is ,definitely,optional") + ["whitespace", "is", "definitely", "optional"] + + """ + @spec list(binary) :: [binary] + def list(binary) do + for elem <- :binary.split(binary, ",", [:global]), + stripped = strip_spaces(elem), + stripped != "", + do: stripped + end + + @doc """ + Validates the given binary is valid UTF-8. + """ + @spec validate_utf8!(binary, module, binary) :: :ok | no_return + def validate_utf8!(binary, exception, context) + + def validate_utf8!(<>, exception, context) do + do_validate_utf8!(binary, exception, context) + end + + defp do_validate_utf8!(<<_::utf8, rest::bits>>, exception, context) do + do_validate_utf8!(rest, exception, context) + end + + defp do_validate_utf8!(<>, exception, context) do + raise exception, "invalid UTF-8 on #{context}, got byte #{byte}" + end + + defp do_validate_utf8!(<<>>, _exception, _context) do + :ok + end + + ## Helpers + + defp strip_spaces("\r\n" <> t), do: strip_spaces(t) + defp strip_spaces(<>) when h in [?\s, ?\t], do: strip_spaces(t) + defp strip_spaces(t), do: trim_trailing(t) + + defp trim_trailing(binary), do: trim_trailing(binary, byte_size(binary)) + + defp trim_trailing(binary, pos) do + if pos > 0 and :binary.at(binary, pos - 1) in [?\s, ?\t] do + trim_trailing(binary, pos - 1) + else + binary_part(binary, 0, pos) + end + end + + defp downcase_char(char) when char in @upper, do: char + 32 + defp downcase_char(char), do: char + + defp split_semicolon(<<>>, <<>>, acc, _), do: acc + defp split_semicolon(<<>>, buffer, acc, _), do: [buffer | acc] + + defp split_semicolon(<>, buffer, acc, quoted?), + do: split_semicolon(rest, <>, acc, not quoted?) + + defp split_semicolon(<>, buffer, acc, false), + do: split_semicolon(rest, <<>>, [buffer | acc], false) + + defp split_semicolon(<>, buffer, acc, quoted?), + do: split_semicolon(rest, <>, acc, quoted?) +end diff --git a/deps/plug/lib/plug/conn/wrapper_error.ex b/deps/plug/lib/plug/conn/wrapper_error.ex new file mode 100644 index 0000000000000000000000000000000000000000..26ccc498956de24b440c4d3ea4ba43e5cac8a8be --- /dev/null +++ b/deps/plug/lib/plug/conn/wrapper_error.ex @@ -0,0 +1,38 @@ +defmodule Plug.Conn.WrapperError do + @moduledoc """ + Wraps the connection in an error which is meant + to be handled upper in the stack. + + Used by both `Plug.Debugger` and `Plug.ErrorHandler`. + """ + defexception [:conn, :kind, :reason, :stack] + + def message(%{kind: kind, reason: reason, stack: stack}) do + Exception.format_banner(kind, reason, stack) + end + + @doc """ + Reraises an error or a wrapped one. + """ + def reraise(%__MODULE__{stack: stack} = reason) do + :erlang.raise(:error, reason, stack) + end + + @deprecated "Use reraise/1 or reraise/4 instead" + def reraise(conn, kind, reason) do + reraise(conn, kind, reason, []) + end + + def reraise(_conn, :error, %__MODULE__{stack: stack} = reason, _stack) do + :erlang.raise(:error, reason, stack) + end + + def reraise(conn, :error, reason, stack) do + wrapper = %__MODULE__{conn: conn, kind: :error, reason: reason, stack: stack} + :erlang.raise(:error, wrapper, stack) + end + + def reraise(_conn, kind, reason, stack) do + :erlang.raise(kind, reason, stack) + end +end diff --git a/deps/plug/lib/plug/logger.ex b/deps/plug/lib/plug/logger.ex new file mode 100644 index 0000000000000000000000000000000000000000..f71c6bfebcd7ba37e1a2abdb75f4c8353e9d4a91 --- /dev/null +++ b/deps/plug/lib/plug/logger.ex @@ -0,0 +1,56 @@ +defmodule Plug.Logger do + @moduledoc """ + A plug for logging basic request information in the format: + + GET /index.html + Sent 200 in 572ms + + To use it, just plug it into the desired module. + + plug Plug.Logger, log: :debug + + ## Options + + * `:log` - The log level at which this plug should log its request info. + Default is `:info`. + The [list of supported levels](https://hexdocs.pm/logger/Logger.html#module-levels) + is available in the `Logger` documentation. + + """ + + require Logger + alias Plug.Conn + @behaviour Plug + + @impl true + def init(opts) do + Keyword.get(opts, :log, :info) + end + + @impl true + def call(conn, level) do + Logger.log(level, fn -> + [conn.method, ?\s, conn.request_path] + end) + + start = System.monotonic_time() + + Conn.register_before_send(conn, fn conn -> + Logger.log(level, fn -> + stop = System.monotonic_time() + diff = System.convert_time_unit(stop - start, :native, :microsecond) + status = Integer.to_string(conn.status) + + [connection_type(conn), ?\s, status, " in ", formatted_diff(diff)] + end) + + conn + end) + end + + defp formatted_diff(diff) when diff > 1000, do: [diff |> div(1000) |> Integer.to_string(), "ms"] + defp formatted_diff(diff), do: [Integer.to_string(diff), "µs"] + + defp connection_type(%{state: :set_chunked}), do: "Chunked" + defp connection_type(_), do: "Sent" +end diff --git a/deps/plug/lib/plug/parsers/json.ex b/deps/plug/lib/plug/parsers/json.ex new file mode 100644 index 0000000000000000000000000000000000000000..aed6aee28351c398fa04fbc9d0b55f25733e64ce --- /dev/null +++ b/deps/plug/lib/plug/parsers/json.ex @@ -0,0 +1,116 @@ +defmodule Plug.Parsers.JSON do + @moduledoc """ + Parses JSON request body. + + JSON documents that aren't maps (arrays, strings, numbers, etc) are parsed + into a `"_json"` key to allow proper param merging. + + An empty request body is parsed as an empty map. + + ## Options + + All options supported by `Plug.Conn.read_body/2` are also supported here. + They are repeated here for convenience: + + * `:length` - sets the maximum number of bytes to read from the request, + defaults to 8_000_000 bytes + * `:read_length` - sets the amount of bytes to read at one time from the + underlying socket to fill the chunk, defaults to 1_000_000 bytes + * `:read_timeout` - sets the timeout for each socket read, defaults to + 15_000ms + + So by default, `Plug.Parsers` will read 1_000_000 bytes at a time from the + socket with an overall limit of 8_000_000 bytes. + + The option `:nest_all_json`, when true, specifies all parsed JSON (including maps) + are parsed into a `"_json"` key. + """ + + @behaviour Plug.Parsers + + @impl true + def init(opts) do + {decoder, opts} = Keyword.pop(opts, :json_decoder) + {body_reader, opts} = Keyword.pop(opts, :body_reader, {Plug.Conn, :read_body, []}) + decoder = validate_decoder!(decoder) + {body_reader, decoder, opts} + end + + defp validate_decoder!(nil) do + raise ArgumentError, "JSON parser expects a :json_decoder option" + end + + defp validate_decoder!({module, fun, args} = mfa) + when is_atom(module) and is_atom(fun) and is_list(args) do + arity = length(args) + 1 + + if Code.ensure_compiled(module) != {:module, module} do + raise ArgumentError, + "invalid :json_decoder option. The module #{inspect(module)} is not " <> + "loaded and could not be found" + end + + if not function_exported?(module, fun, arity) do + raise ArgumentError, + "invalid :json_decoder option. The module #{inspect(module)} must " <> + "implement #{fun}/#{arity}" + end + + mfa + end + + defp validate_decoder!(decoder) when is_atom(decoder) do + validate_decoder!({decoder, :decode!, []}) + end + + defp validate_decoder!(decoder) do + raise ArgumentError, + "the :json_decoder option expects a module, or a three-element " <> + "tuple in the form of {module, function, extra_args}, got: #{inspect(decoder)}" + end + + @impl true + def parse(conn, "application", subtype, _headers, {{mod, fun, args}, decoder, opts}) do + if subtype == "json" or String.ends_with?(subtype, "+json") do + apply(mod, fun, [conn, opts | args]) |> decode(decoder, opts) + else + {:next, conn} + end + end + + def parse(conn, _type, _subtype, _headers, _opts) do + {:next, conn} + end + + defp decode({:ok, "", conn}, _decoder, _opts) do + {:ok, %{}, conn} + end + + defp decode({:ok, body, conn}, {module, fun, args}, opts) do + nest_all = Keyword.get(opts, :nest_all_json, false) + + try do + apply(module, fun, [body | args]) + rescue + e -> raise Plug.Parsers.ParseError, exception: e + else + terms when is_map(terms) and not nest_all -> + {:ok, terms, conn} + + terms -> + {:ok, %{"_json" => terms}, conn} + end + end + + defp decode({:more, _, conn}, _decoder, _opts) do + {:error, :too_large, conn} + end + + defp decode({:error, :timeout}, _decoder, _opts) do + raise Plug.TimeoutError + end + + defp decode({:error, _}, _decoder, _opts) do + raise Plug.BadRequestError + end +end diff --git a/deps/plug/lib/plug/parsers/multipart.ex b/deps/plug/lib/plug/parsers/multipart.ex new file mode 100644 index 0000000000000000000000000000000000000000..15b429e564b4d8e9b69d554d00f9ac3c7bfedf7b --- /dev/null +++ b/deps/plug/lib/plug/parsers/multipart.ex @@ -0,0 +1,311 @@ +defmodule Plug.Parsers.MULTIPART do + @moduledoc """ + Parses multipart request body. + + ## Options + + All options supported by `Plug.Conn.read_body/2` are also supported here. + They are repeated here for convenience: + + * `:length` - sets the maximum number of bytes to read from the request, + defaults to 8_000_000 bytes + + * `:read_length` - sets the amount of bytes to read at one time from the + underlying socket to fill the chunk, defaults to 1_000_000 bytes + + * `:read_timeout` - sets the timeout for each socket read, defaults to + 15_000ms + + So by default, `Plug.Parsers` will read 1_000_000 bytes at a time from the + socket with an overall limit of 8_000_000 bytes. + + Besides the options supported by `Plug.Conn.read_body/2`, the multipart parser + also checks for: + + * `:headers` - containing the same `:length`, `:read_length` + and `:read_timeout` options which are used explicitly for parsing multipart + headers + + * `:validate_utf8` - specifies whether multipart body parts should be validated + as utf8 binaries. It is either a boolean or a custom exception to raise + + * `:multipart_to_params` - a MFA that receives the multipart headers and the + connection and it must return a tuple of `{:ok, params, conn}` + + ## Multipart to params + + Once all multiparts are collected, they must be converted to params and this + can be customize with a MFA. The default implementation of this function + is equivalent to: + + def multipart_to_params(parts, conn) do + acc = + for {name, _headers, body} <- Enum.reverse(parts), + name != nil, + reduce: Plug.Conn.Query.decode_init() do + acc -> Plug.Conn.Query.decode_each({name, body}, acc) + end + + {:ok, Plug.Conn.Query.decode_done(acc), conn} + end + + As you can notice, it discards all multiparts without a name. If you want + to keep the unnamed parts, you can store all of them under a known prefix, + such as: + + def multipart_to_params(parts, conn) do + acc = + for {name, _headers, body} <- Enum.reverse(parts), + name != nil, + reduce: Plug.Conn.Query.decode_init() do + acc -> Plug.Conn.Query.decode_each({name || "_parts[]", body}, acc) + end + + {:ok, Plug.Conn.Query.decode_done(acc), conn} + end + + ## Dynamic configuration + + If you need to dynamically configure how `Plug.Parsers.MULTIPART` behave, + for example, based on the connection or another system parameter, one option + is to create your own parser that wraps it: + + defmodule MyMultipart do + @multipart Plug.Parsers.MULTIPART + + def init(opts) do + opts + end + + def parse(conn, "multipart", subtype, headers, opts) do + length = System.fetch_env!("UPLOAD_LIMIT") |> String.to_integer + opts = @multipart.init([length: length] ++ opts) + @multipart.parse(conn, "multipart", subtype, headers, opts) + end + + def parse(conn, _type, _subtype, _headers, _opts) do + {:next, conn} + end + end + + """ + + @behaviour Plug.Parsers + + @impl true + def init(opts) do + # Remove the length from options as it would attempt + # to eagerly read the body on the limit value. + {limit, opts} = Keyword.pop(opts, :length, 8_000_000) + + # The read length is now our effective length per call. + {read_length, opts} = Keyword.pop(opts, :read_length, 1_000_000) + opts = [length: read_length, read_length: read_length] ++ opts + + # The header options are handled individually. + {headers_opts, opts} = Keyword.pop(opts, :headers, []) + + unless is_integer(limit) do + raise ":length option for Plug.Parsers.MULTIPART must be an integer" + end + + m2p = opts[:multipart_to_params] || {__MODULE__, :multipart_to_params, [opts]} + {m2p, limit, headers_opts, opts} + end + + @impl true + def parse(conn, "multipart", subtype, _headers, opts_tuple) + when subtype in ["form-data", "mixed"] do + try do + parse_multipart(conn, opts_tuple) + rescue + # Do not ignore upload errors + e in [Plug.UploadError, Plug.Parsers.BadEncodingError] -> + reraise e, __STACKTRACE__ + + # All others are wrapped + e -> + reraise Plug.Parsers.ParseError.exception(exception: e), __STACKTRACE__ + end + end + + def parse(conn, _type, _subtype, _headers, _opts) do + {:next, conn} + end + + @doc false + def multipart_to_params(acc, conn, _opts) do + acc = + List.foldr(acc, Plug.Conn.Query.decode_init(), fn + {nil, _headers, _body}, acc -> acc + {name, _headers, body}, acc -> Plug.Conn.Query.decode_each({name, body}, acc) + end) + + {:ok, Plug.Conn.Query.decode_done(acc), conn} + end + + ## Multipart + + defp parse_multipart(conn, {m2p, limit, headers_opts, opts}) do + read_result = Plug.Conn.read_part_headers(conn, headers_opts) + {:ok, limit, acc, conn} = parse_multipart(read_result, limit, opts, headers_opts, []) + + if limit > 0 do + {mod, fun, args} = m2p + apply(mod, fun, [acc, conn | args]) + else + {:error, :too_large, conn} + end + end + + defp parse_multipart({:ok, headers, conn}, limit, opts, headers_opts, acc) when limit >= 0 do + {conn, limit, acc} = parse_multipart_headers(headers, conn, limit, opts, acc) + read_result = Plug.Conn.read_part_headers(conn, headers_opts) + parse_multipart(read_result, limit, opts, headers_opts, acc) + end + + defp parse_multipart({:ok, _headers, conn}, limit, _opts, _headers_opts, acc) do + {:ok, limit, acc, conn} + end + + defp parse_multipart({:done, conn}, limit, _opts, _headers_opts, acc) do + {:ok, limit, acc, conn} + end + + defp parse_multipart_headers(headers, conn, limit, opts, acc) do + case multipart_type(headers) do + {:binary, name} -> + {:ok, limit, body, conn} = + parse_multipart_body(Plug.Conn.read_part_body(conn, opts), limit, opts, "") + + case Keyword.get(opts, :validate_utf8, true) do + true -> + Plug.Conn.Utils.validate_utf8!(body, Plug.Parsers.BadEncodingError, "multipart body") + + false -> + :ok + + module -> + Plug.Conn.Utils.validate_utf8!(body, module, "multipart body") + end + + {conn, limit, [{name, headers, body} | acc]} + + {:file, name, path, %Plug.Upload{} = uploaded} -> + {:ok, file} = File.open(path, [:write, :binary, :delayed_write, :raw]) + + {:ok, limit, conn} = + parse_multipart_file(Plug.Conn.read_part_body(conn, opts), limit, opts, file) + + :ok = File.close(file) + {conn, limit, [{name, headers, uploaded} | acc]} + + :skip -> + {conn, limit, acc} + end + end + + defp parse_multipart_body({:more, tail, conn}, limit, opts, body) + when limit >= byte_size(tail) do + read_result = Plug.Conn.read_part_body(conn, opts) + parse_multipart_body(read_result, limit - byte_size(tail), opts, body <> tail) + end + + defp parse_multipart_body({:more, tail, conn}, limit, _opts, body) do + {:ok, limit - byte_size(tail), body, conn} + end + + defp parse_multipart_body({:ok, tail, conn}, limit, _opts, body) + when limit >= byte_size(tail) do + {:ok, limit - byte_size(tail), body <> tail, conn} + end + + defp parse_multipart_body({:ok, tail, conn}, limit, _opts, body) do + {:ok, limit - byte_size(tail), body, conn} + end + + defp parse_multipart_file({:more, tail, conn}, limit, opts, file) + when limit >= byte_size(tail) do + binwrite!(file, tail) + read_result = Plug.Conn.read_part_body(conn, opts) + parse_multipart_file(read_result, limit - byte_size(tail), opts, file) + end + + defp parse_multipart_file({:more, tail, conn}, limit, _opts, _file) do + {:ok, limit - byte_size(tail), conn} + end + + defp parse_multipart_file({:ok, tail, conn}, limit, _opts, file) + when limit >= byte_size(tail) do + binwrite!(file, tail) + {:ok, limit - byte_size(tail), conn} + end + + defp parse_multipart_file({:ok, tail, conn}, limit, _opts, _file) do + {:ok, limit - byte_size(tail), conn} + end + + ## Helpers + + defp binwrite!(device, contents) do + case IO.binwrite(device, contents) do + :ok -> + :ok + + {:error, reason} -> + raise Plug.UploadError, + "could not write to file #{inspect(device)} during upload " <> + "due to reason: #{inspect(reason)}" + end + end + + defp multipart_type(headers) do + with {_, disposition} <- List.keyfind(headers, "content-disposition", 0), + [_, params] <- :binary.split(disposition, ";"), + %{"name" => name} = params <- Plug.Conn.Utils.params(params) do + handle_disposition(params, name, headers) + else + _ -> {:binary, nil} + end + end + + defp handle_disposition(params, name, headers) do + case params do + %{"filename" => ""} -> + :skip + + %{"filename" => filename} -> + path = Plug.Upload.random_file!("multipart") + content_type = get_header(headers, "content-type") + upload = %Plug.Upload{filename: filename, path: path, content_type: content_type} + {:file, name, path, upload} + + %{"filename*" => ""} -> + :skip + + %{"filename*" => "utf-8''" <> filename} -> + filename = URI.decode(filename) + + Plug.Conn.Utils.validate_utf8!( + filename, + Plug.Parsers.BadEncodingError, + "multipart filename" + ) + + path = Plug.Upload.random_file!("multipart") + content_type = get_header(headers, "content-type") + upload = %Plug.Upload{filename: filename, path: path, content_type: content_type} + {:file, name, path, upload} + + %{} -> + {:binary, name} + end + end + + defp get_header(headers, key) do + case List.keyfind(headers, key, 0) do + {^key, value} -> value + nil -> nil + end + end +end diff --git a/deps/plug/lib/plug/parsers/urlencoded.ex b/deps/plug/lib/plug/parsers/urlencoded.ex new file mode 100644 index 0000000000000000000000000000000000000000..04260e30e869feb9b532068c1d9ff6179f1a05f4 --- /dev/null +++ b/deps/plug/lib/plug/parsers/urlencoded.ex @@ -0,0 +1,57 @@ +defmodule Plug.Parsers.URLENCODED do + @moduledoc """ + Parses urlencoded request body. + + ## Options + + All options supported by `Plug.Conn.read_body/2` are also supported here. + They are repeated here for convenience: + + * `:length` - sets the maximum number of bytes to read from the request, + defaults to 1_000_000 bytes + * `:read_length` - sets the amount of bytes to read at one time from the + underlying socket to fill the chunk, defaults to 1_000_000 bytes + * `:read_timeout` - sets the timeout for each socket read, defaults to + 15_000ms + + So by default, `Plug.Parsers` will read 1_000_000 bytes at a time from the + socket with an overall limit of 8_000_000 bytes. + """ + + @behaviour Plug.Parsers + + @impl true + def init(opts) do + opts = Keyword.put_new(opts, :length, 1_000_000) + Keyword.pop(opts, :body_reader, {Plug.Conn, :read_body, []}) + end + + @impl true + def parse(conn, "application", "x-www-form-urlencoded", _headers, {{mod, fun, args}, opts}) do + case apply(mod, fun, [conn, opts | args]) do + {:ok, body, conn} -> + validate_utf8 = Keyword.get(opts, :validate_utf8, true) + + {:ok, + Plug.Conn.Query.decode( + body, + %{}, + Plug.Parsers.BadEncodingError, + validate_utf8 + ), conn} + + {:more, _data, conn} -> + {:error, :too_large, conn} + + {:error, :timeout} -> + raise Plug.TimeoutError + + {:error, _} -> + raise Plug.BadRequestError + end + end + + def parse(conn, _type, _subtype, _headers, _opts) do + {:next, conn} + end +end diff --git a/deps/plug/lib/plug/router/utils.ex b/deps/plug/lib/plug/router/utils.ex new file mode 100644 index 0000000000000000000000000000000000000000..b24a697954058b9f14efaa8328301e6d2a5dc1b5 --- /dev/null +++ b/deps/plug/lib/plug/router/utils.ex @@ -0,0 +1,286 @@ +defmodule Plug.Router.InvalidSpecError do + defexception message: "invalid route specification" +end + +defmodule Plug.Router.MalformedURIError do + defexception message: "malformed URI", plug_status: 400 +end + +defmodule Plug.Router.Utils do + @moduledoc false + + @doc """ + Decodes path information for dispatching. + """ + def decode_path_info!(conn) do + Enum.map(conn.path_info, &URI.decode/1) + end + + @doc """ + Converts a given method to its connection representation. + + The request method is stored in the `Plug.Conn` struct as an uppercase string + (like `"GET"` or `"POST"`). This function converts `method` to that + representation. + + ## Examples + + iex> Plug.Router.Utils.normalize_method(:get) + "GET" + + """ + def normalize_method(method) do + method |> to_string |> String.upcase() + end + + @doc ~S""" + Builds the pattern that will be used to match against the request's host + (provided via the `:host`) option. + + If `host` is `nil`, a wildcard match (`_`) will be returned. If `host` ends + with a dot, a match like `"host." <> _` will be returned. + + ## Examples + + iex> Plug.Router.Utils.build_host_match(nil) + {:_, [], Plug.Router.Utils} + + iex> Plug.Router.Utils.build_host_match("foo.com") + "foo.com" + + iex> "api." |> Plug.Router.Utils.build_host_match() |> Macro.to_string() + "\"api.\" <> _" + + """ + def build_host_match(host) do + cond do + is_nil(host) -> quote do: _ + String.last(host) == "." -> quote do: unquote(host) <> _ + is_binary(host) -> host + end + end + + @doc """ + Generates a representation that will only match routes + according to the given `spec`. + + If a non-binary spec is given, it is assumed to be + custom match arguments and they are simply returned. + + ## Examples + + iex> Plug.Router.Utils.build_path_match("/foo/:id") + {[:id], ["foo", {:id, [], nil}]} + + """ + def build_path_match(path, context \\ nil) when is_binary(path) do + case build_path_clause(path, true, context) do + {params, match, true, _post_match} -> + {Enum.map(params, &String.to_atom(&1)), match} + + {_, _, _, _} -> + raise Plug.Router.InvalidSpecError, + "invalid dynamic path. Only letters, numbers, and underscore are allowed after : in " <> + inspect(path) + end + end + + @doc """ + Builds a list of path param names and var match pairs. + + This is used to build parameter maps from existing variables. + Excludes variables with underscore. + + ## Examples + + iex> Plug.Router.Utils.build_path_params_match(["id"]) + [{"id", {:id, [], nil}}] + iex> Plug.Router.Utils.build_path_params_match(["_id"]) + [] + + iex> Plug.Router.Utils.build_path_params_match([:id]) + [{"id", {:id, [], nil}}] + iex> Plug.Router.Utils.build_path_params_match([:_id]) + [] + + """ + def build_path_params_match(params, context \\ nil) + + def build_path_params_match([param | _] = params, context) when is_binary(param) do + params + |> Enum.reject(&match?("_" <> _, &1)) + |> Enum.map(&{&1, Macro.var(String.to_atom(&1), context)}) + end + + def build_path_params_match([param | _] = params, context) when is_atom(param) do + params + |> Enum.map(&{Atom.to_string(&1), Macro.var(&1, context)}) + |> Enum.reject(&match?({"_" <> _var, _macro}, &1)) + end + + def build_path_params_match([], _context) do + [] + end + + @doc """ + Builds a clause with match, guards, and post matches, + including the known parameters. + """ + def build_path_clause(path, guard, context \\ nil) when is_binary(path) do + compiled = :binary.compile_pattern(["\\:", "\\*", ":", "*"]) + + {params, match, guards, post_match} = + path + |> split() + |> build_path_clause([], [], [], [], context, compiled) + + if guard != true and guards != [] do + raise ArgumentError, "cannot use \"when\" guards in route when using suffix matches" + end + + params = params |> Enum.uniq() |> Enum.reverse() + guards = Enum.reduce(guards, guard, "e(do: unquote(&1) and unquote(&2))) + {params, match, guards, post_match} + end + + defp build_path_clause([segment | rest], params, match, guards, post_match, context, compiled) do + case :binary.matches(segment, compiled) do + [] -> + build_path_clause(rest, params, [segment | match], guards, post_match, context, compiled) + + [{prefix_size, match_length}] when match_length == 2 -> + suffix_size = byte_size(segment) - prefix_size - 2 + + <> = + segment + + escaped_segment = [prefix <> <> <> suffix | match] + build_path_clause(rest, params, escaped_segment, guards, post_match, context, compiled) + + [{prefix_size, _}] -> + suffix_size = byte_size(segment) - prefix_size - 1 + <> = segment + {param, suffix} = parse_suffix(suffix) + params = [param | params] + var = Macro.var(String.to_atom(param), context) + + case char do + ?* when suffix != "" -> + raise Plug.Router.InvalidSpecError, + "globs (*var) cannot be followed by suffixes, got: #{inspect(segment)}" + + ?* when rest != [] -> + raise Plug.Router.InvalidSpecError, + "globs (*var) must always be in the last path, got glob in: #{inspect(segment)}" + + ?* -> + submatch = + if prefix != "" do + IO.warn(""" + doing a prefix match with globs is deprecated, invalid segment #{inspect(segment)}. + + You can either replace by a single segment match: + + /foo/bar-:var + + Or by mixing single segment match with globs: + + /foo/bar-:var/*rest + """) + + quote do: [unquote(prefix) <> _ | _] = unquote(var) + else + var + end + + match = + case match do + [] -> + submatch + + [last | match] -> + Enum.reverse([quote(do: unquote(last) | unquote(submatch)) | match]) + end + + {params, match, guards, post_match} + + ?: -> + match = + if prefix == "", + do: [var | match], + else: [quote(do: unquote(prefix) <> unquote(var)) | match] + + {post_match, guards} = + if suffix == "" do + {post_match, guards} + else + guard = + quote do + binary_part( + unquote(var), + byte_size(unquote(var)) - unquote(byte_size(suffix)), + unquote(byte_size(suffix)) + ) == unquote(suffix) + end + + trim = + quote do + unquote(var) = String.trim_trailing(unquote(var), unquote(suffix)) + end + + {[trim | post_match], [guard | guards]} + end + + build_path_clause(rest, params, match, guards, post_match, context, compiled) + end + + [_ | _] -> + raise Plug.Router.InvalidSpecError, + "only one dynamic entry (:var or *glob) per path segment is allowed, got: " <> + inspect(segment) + end + end + + defp build_path_clause([], params, match, guards, post_match, _context, _compiled) do + {params, Enum.reverse(match), guards, post_match} + end + + defp parse_suffix(<>) when h in ?a..?z or h == ?_, + do: parse_suffix(t, <>) + + defp parse_suffix(suffix) do + raise Plug.Router.InvalidSpecError, + "invalid dynamic path. The characters : and * must be immediately followed by " <> + "lowercase letters or underscore, got: :#{suffix}" + end + + defp parse_suffix(<>, acc) + when h in ?a..?z or h in ?A..?Z or h in ?0..?9 or h == ?_, + do: parse_suffix(t, <>) + + defp parse_suffix(rest, acc), + do: {acc, rest} + + @doc """ + Splits the given path into several segments. + It ignores both leading and trailing slashes in the path. + + ## Examples + + iex> Plug.Router.Utils.split("/foo/bar") + ["foo", "bar"] + + iex> Plug.Router.Utils.split("/:id/*") + [":id", "*"] + + iex> Plug.Router.Utils.split("/foo//*_bar") + ["foo", "*_bar"] + + """ + def split(bin) do + for segment <- String.split(bin, "/"), segment != "", do: segment + end + + @deprecated "Use Plug.forward/4 instead" + defdelegate forward(conn, new_path, target, opts), to: Plug +end diff --git a/deps/plug/lib/plug/session/cookie.ex b/deps/plug/lib/plug/session/cookie.ex new file mode 100644 index 0000000000000000000000000000000000000000..7b7dcf13d768c24294f0f1676a76a71ff5e8371e --- /dev/null +++ b/deps/plug/lib/plug/session/cookie.ex @@ -0,0 +1,246 @@ +defmodule Plug.Session.COOKIE do + @moduledoc """ + Stores the session in a cookie. + + This cookie store is based on `Plug.Crypto.MessageVerifier` + and `Plug.Crypto.MessageEncryptor` which encrypts and signs + each cookie to ensure they can't be read nor tampered with. + + Since this store uses crypto features, it requires you to + set the `:secret_key_base` field in your connection. This + can be easily achieved with a plug: + + plug :put_secret_key_base + + def put_secret_key_base(conn, _) do + put_in conn.secret_key_base, "-- LONG STRING WITH AT LEAST 64 BYTES --" + end + + ## Options + + * `:secret_key_base` - the secret key base to built the cookie + signing/encryption on top of. If one is given on initialization, + the cookie store can precompute all relevant values at compilation + time. Otherwise, the value is taken from `conn.secret_key_base` + and cached. + + * `:encryption_salt` - a salt used with `conn.secret_key_base` to generate + a key for encrypting/decrypting a cookie, can be either a binary or + an MFA returning a binary; + + * `:signing_salt` - a salt used with `conn.secret_key_base` to generate a + key for signing/verifying a cookie, can be either a binary or + an MFA returning a binary; + + * `:key_iterations` - option passed to `Plug.Crypto.KeyGenerator` + when generating the encryption and signing keys. Defaults to 1000; + + * `:key_length` - option passed to `Plug.Crypto.KeyGenerator` + when generating the encryption and signing keys. Defaults to 32; + + * `:key_digest` - option passed to `Plug.Crypto.KeyGenerator` + when generating the encryption and signing keys. Defaults to `:sha256`; + + * `:serializer` - cookie serializer module that defines `encode/1` and + `decode/1` returning an `{:ok, value}` tuple. Defaults to + `:external_term_format`. + + * `:log` - Log level to use when the cookie cannot be decoded. + Defaults to `:debug`, can be set to false to disable it. + + * `:rotating_options` - additional list of options to use when decrypting and + verifying the cookie. These options are used only when the cookie could not + be decoded using primary options and are fetched on init so they cannot be + changed in runtime. Defaults to `[]`. + + ## Examples + + plug Plug.Session, store: :cookie, + key: "_my_app_session", + encryption_salt: "cookie store encryption salt", + signing_salt: "cookie store signing salt", + log: :debug + """ + + require Logger + @behaviour Plug.Session.Store + + alias Plug.Crypto.KeyGenerator + alias Plug.Crypto.MessageVerifier + alias Plug.Crypto.MessageEncryptor + + @impl true + def init(opts) do + build_opts(opts) + |> build_rotating_opts(opts[:rotating_options]) + |> Map.delete(:secret_key_base) + end + + @impl true + def get(conn, raw_cookie, opts) do + opts = Map.put(opts, :secret_key_base, conn.secret_key_base) + + [opts | opts.rotating_options] + |> Enum.find_value(:error, &read_raw_cookie(raw_cookie, &1)) + |> decode(opts.serializer, opts.log) + end + + @impl true + def put(conn, _sid, term, opts) do + %{serializer: serializer, key_opts: key_opts, signing_salt: signing_salt} = opts + binary = encode(term, serializer) + + case opts do + %{encryption_salt: nil} -> + MessageVerifier.sign(binary, derive(conn.secret_key_base, signing_salt, key_opts)) + + %{encryption_salt: encryption_salt} -> + MessageEncryptor.encrypt( + binary, + derive(conn.secret_key_base, encryption_salt, key_opts), + derive(conn.secret_key_base, signing_salt, key_opts) + ) + end + end + + @impl true + def delete(_conn, _sid, _opts) do + :ok + end + + defp encode(term, :external_term_format) do + :erlang.term_to_binary(term) + end + + defp encode(term, serializer) do + {:ok, binary} = serializer.encode(term) + binary + end + + defp decode({:ok, binary}, :external_term_format, log) do + {:term, + try do + Plug.Crypto.non_executable_binary_to_term(binary) + rescue + e -> + Logger.log( + log, + "Plug.Session could not decode incoming session cookie. Reason: " <> + Exception.message(e) + ) + + %{} + end} + end + + defp decode({:ok, binary}, serializer, _log) do + case serializer.decode(binary) do + {:ok, term} -> {:custom, term} + _ -> {:custom, %{}} + end + end + + defp decode(:error, _serializer, false) do + {nil, %{}} + end + + defp decode(:error, _serializer, log) do + Logger.log( + log, + "Plug.Session could not verify incoming session cookie. " <> + "This may happen when the session settings change or a stale cookie is sent." + ) + + {nil, %{}} + end + + defp prederive(secret_key_base, value, key_opts) + when is_binary(secret_key_base) and is_binary(value) do + {:prederived, derive(secret_key_base, value, Keyword.delete(key_opts, :cache))} + end + + defp prederive(_secret_key_base, value, _key_opts) do + value + end + + defp derive(_secret_key_base, {:prederived, value}, _key_opts) do + value + end + + defp derive(secret_key_base, {module, function, args}, key_opts) do + derive(secret_key_base, apply(module, function, args), key_opts) + end + + defp derive(secret_key_base, key, key_opts) do + secret_key_base + |> validate_secret_key_base() + |> KeyGenerator.generate(key, key_opts) + end + + defp validate_secret_key_base(nil), + do: raise(ArgumentError, "cookie store expects conn.secret_key_base to be set") + + defp validate_secret_key_base(secret_key_base) when byte_size(secret_key_base) < 64, + do: raise(ArgumentError, "cookie store expects conn.secret_key_base to be at least 64 bytes") + + defp validate_secret_key_base(secret_key_base), do: secret_key_base + + defp check_signing_salt(opts) do + case opts[:signing_salt] do + nil -> raise ArgumentError, "cookie store expects :signing_salt as option" + salt -> salt + end + end + + defp check_serializer(serializer) when is_atom(serializer), do: serializer + + defp check_serializer(_), + do: raise(ArgumentError, "cookie store expects :serializer option to be a module") + + defp read_raw_cookie(raw_cookie, opts) do + signing_salt = derive(opts.secret_key_base, opts.signing_salt, opts.key_opts) + + case opts do + %{encryption_salt: nil} -> + MessageVerifier.verify(raw_cookie, signing_salt) + + %{encryption_salt: _} -> + encryption_salt = derive(opts.secret_key_base, opts.encryption_salt, opts.key_opts) + + MessageEncryptor.decrypt(raw_cookie, encryption_salt, signing_salt) + end + |> case do + :error -> nil + result -> result + end + end + + defp build_opts(opts) do + encryption_salt = opts[:encryption_salt] + signing_salt = check_signing_salt(opts) + + iterations = Keyword.get(opts, :key_iterations, 1000) + length = Keyword.get(opts, :key_length, 32) + digest = Keyword.get(opts, :key_digest, :sha256) + log = Keyword.get(opts, :log, :debug) + secret_key_base = Keyword.get(opts, :secret_key_base) + key_opts = [iterations: iterations, length: length, digest: digest, cache: Plug.Keys] + + serializer = check_serializer(opts[:serializer] || :external_term_format) + + %{ + secret_key_base: secret_key_base, + encryption_salt: prederive(secret_key_base, encryption_salt, key_opts), + signing_salt: prederive(secret_key_base, signing_salt, key_opts), + key_opts: key_opts, + serializer: serializer, + log: log + } + end + + defp build_rotating_opts(opts, rotating_opts) when is_list(rotating_opts) do + Map.put(opts, :rotating_options, Enum.map(rotating_opts, &build_opts/1)) + end + + defp build_rotating_opts(opts, _), do: Map.put(opts, :rotating_options, []) +end diff --git a/deps/plug/lib/plug/session/ets.ex b/deps/plug/lib/plug/session/ets.ex new file mode 100644 index 0000000000000000000000000000000000000000..933ee5e0a994aa5c48bb2116e41d60e5513342ae --- /dev/null +++ b/deps/plug/lib/plug/session/ets.ex @@ -0,0 +1,98 @@ +defmodule Plug.Session.ETS do + @moduledoc """ + Stores the session in an in-memory ETS table. + + This store does not create the ETS table; it expects that an + existing named table with public properties is passed as an + argument. + + We don't recommend using this store in production as every + session will be stored in ETS and never cleaned until you + create a task responsible for cleaning up old entries. + + Also, since the store is in-memory, it means sessions are + not shared between servers. If you deploy to more than one + machine, using this store is again not recommended. + + This store, however, can be used as an example for creating + custom storages, based on Redis, Memcached, or a database + itself. + + ## Options + + * `:table` - ETS table name (required) + + For more information on ETS tables, visit the Erlang documentation at + http://www.erlang.org/doc/man/ets.html. + + ## Storage + + The data is stored in ETS in the following format: + + {sid :: String.t, data :: map, timestamp :: :erlang.timestamp} + + The timestamp is updated whenever there is a read or write to the + table and it may be used to detect if a session is still active. + + ## Examples + + # Create an ETS table when the application starts + :ets.new(:session, [:named_table, :public, read_concurrency: true]) + + # Use the session plug with the table name + plug Plug.Session, store: :ets, key: "sid", table: :session + + """ + + @behaviour Plug.Session.Store + + @max_tries 100 + + @impl true + def init(opts) do + Keyword.fetch!(opts, :table) + end + + @impl true + def get(_conn, sid, table) do + case :ets.lookup(table, sid) do + [{^sid, data, _timestamp}] -> + :ets.update_element(table, sid, {3, now()}) + {sid, data} + + [] -> + {nil, %{}} + end + end + + @impl true + def put(_conn, nil, data, table) do + put_new(data, table) + end + + def put(_conn, sid, data, table) do + :ets.insert(table, {sid, data, now()}) + sid + end + + @impl true + def delete(_conn, sid, table) do + :ets.delete(table, sid) + :ok + end + + defp put_new(data, table, counter \\ 0) + when counter < @max_tries do + sid = Base.encode64(:crypto.strong_rand_bytes(96)) + + if :ets.insert_new(table, {sid, data, now()}) do + sid + else + put_new(data, table, counter + 1) + end + end + + defp now() do + :os.timestamp() + end +end diff --git a/deps/plug/lib/plug/session/store.ex b/deps/plug/lib/plug/session/store.ex new file mode 100644 index 0000000000000000000000000000000000000000..7f83e02bdfc01608b4c4879508c1801b4fe5faf2 --- /dev/null +++ b/deps/plug/lib/plug/session/store.ex @@ -0,0 +1,71 @@ +defmodule Plug.Session.Store do + @moduledoc """ + Specification for session stores. + """ + + @doc """ + Gets the store name from an atom or a module. + + iex> Plug.Session.Store.get(CustomStore) + CustomStore + + iex> Plug.Session.Store.get(:cookie) + Plug.Session.COOKIE + + """ + def get(store) do + case Atom.to_string(store) do + "Elixir." <> _ -> store + reference -> Module.concat(Plug.Session, String.upcase(reference)) + end + end + + @typedoc """ + The internal reference to the session in the store. + """ + @type sid :: term | nil + + @typedoc """ + The cookie value that will be sent in cookie headers. This value should be + base64 encoded to avoid security issues. + """ + @type cookie :: binary + + @typedoc """ + The session contents, the final data to be stored after it has been built + with `Plug.Conn.put_session/3` and the other session manipulating functions. + """ + @type session :: map + + @doc """ + Initializes the store. + + The options returned from this function will be given + to `c:get/3`, `c:put/4` and `c:delete/3`. + """ + @callback init(opts :: Plug.opts()) :: Plug.opts() + + @doc """ + Parses the given cookie. + + Returns a session id and the session contents. The session id is any + value that can be used to identify the session by the store. + + The session id may be nil in case the cookie does not identify any + value in the store. The session contents must be a map. + """ + @callback get(conn :: Plug.Conn.t(), cookie, opts :: Plug.opts()) :: {sid, session} + + @doc """ + Stores the session associated with given session id. + + If `nil` is given as id, a new session id should be + generated and returned. + """ + @callback put(conn :: Plug.Conn.t(), sid, any, opts :: Plug.opts()) :: cookie + + @doc """ + Removes the session associated with given session id from the store. + """ + @callback delete(conn :: Plug.Conn.t(), sid, opts :: Plug.opts()) :: :ok +end diff --git a/deps/plug/lib/plug/telemetry.ex b/deps/plug/lib/plug/telemetry.ex new file mode 100644 index 0000000000000000000000000000000000000000..ce3d183eef7cc17bcfeb55178ea3e96ae1ef0fc8 --- /dev/null +++ b/deps/plug/lib/plug/telemetry.ex @@ -0,0 +1,89 @@ +defmodule Plug.Telemetry do + @moduledoc """ + A plug to instrument the pipeline with `:telemetry` events. + + When plugged, the event prefix is a required option: + + plug Plug.Telemetry, event_prefix: [:my, :plug] + + In the example above, two events will be emitted: + + * `[:my, :plug, :start]` - emitted when the plug is invoked. + The event carries the `system_time` as measurement. The metadata + is the whole `Plug.Conn` under the `:conn` key and any leftover + options given to the plug under `:options`. + + * `[:my, :plug, :stop]` - emitted right before the response is sent. + The event carries a single measurement, `:duration`, which is the + monotonic time difference between the stop and start events. + It has the same metadata as the start event, except the connection + has been updated. + + Note this plug measures the time between its invocation until a response + is sent. The `:stop` event is not guaranteed to be emitted in all error + cases, so this Plug cannot be used as a Telemetry span. + + ## Time unit + + The `:duration` measurements are presented in the `:native` time unit. + You can read more about it in the docs for `System.convert_time_unit/3`. + + ## Example + + defmodule InstrumentedPlug do + use Plug.Router + + plug :match + plug Plug.Telemetry, event_prefix: [:my, :plug] + plug Plug.Parsers, parsers: [:urlencoded, :multipart] + plug :dispatch + + get "/" do + send_resp(conn, 200, "Hello, world!") + end + end + + In this example, the stop event's `duration` includes the time + it takes to parse the request, dispatch it to the correct handler, + and execute the handler. The events are not emitted for requests + not matching any handlers, since the plug is placed after the match plug. + """ + + @behaviour Plug + + @impl true + def init(opts) do + {event_prefix, opts} = Keyword.pop(opts, :event_prefix) + + unless event_prefix do + raise ArgumentError, ":event_prefix is required" + end + + ensure_valid_event_prefix!(event_prefix) + start_event = event_prefix ++ [:start] + stop_event = event_prefix ++ [:stop] + {start_event, stop_event, opts} + end + + @impl true + def call(conn, {start_event, stop_event, opts}) do + start_time = System.monotonic_time() + metadata = %{conn: conn, options: opts} + :telemetry.execute(start_event, %{system_time: System.system_time()}, metadata) + + Plug.Conn.register_before_send(conn, fn conn -> + duration = System.monotonic_time() - start_time + :telemetry.execute(stop_event, %{duration: duration}, %{conn: conn, options: opts}) + conn + end) + end + + defp ensure_valid_event_prefix!(event_prefix) do + if is_list(event_prefix) && Enum.all?(event_prefix, &is_atom/1) do + :ok + else + raise ArgumentError, + "expected :event_prefix to be a list of atoms, got: #{inspect(event_prefix)}" + end + end +end diff --git a/deps/plug/lib/plug/templates/debugger.html.eex b/deps/plug/lib/plug/templates/debugger.html.eex new file mode 100644 index 0000000000000000000000000000000000000000..3859cf583932153228ed990cd5e0a3b4806c5111 --- /dev/null +++ b/deps/plug/lib/plug/templates/debugger.html.eex @@ -0,0 +1,1151 @@ + + + + + <%= h @title %> at <%= h method(@conn) %> <%= h @conn.request_path %> + + + + + + +
+ <%= if @style.logo do %> + + <% end %> + +
+
+ <%= h @title %> + at <%= h method(@conn) %> + <%= h @conn.request_path %> +
+
<%= @message %>
+
+ + <%= for %{label: label, encoded_handler: encoded_handler} <- @actions do %> +
+ + + +
+ <% end %> + + <%= if @banner do %> +
+ +
+ <% end %> + +
+ +
+ <%= for frame <- @frames do %> +
+ + + <%= if (snippet = frame.snippet) && snippet != [] do %> +
<%= for {index, line, highlight} <- snippet do %>"><%= h index %><%= h String.trim_trailing(line) %>
+<% end %>
+ <% else %> +
No code available.
+ <% end %> + +
+
+ <%= h frame.info %> + <%= if doc = frame.doc do %> + Docs + <% end %> + <%= if app = frame.app do %> + <%= h app %> + <% end %> +
+
+ + <%= if frame.args do %> +
+ Called with <%= length(frame.args) %> arguments +
    + <%= for arg <- frame.args do %> +
  1. <%= h inspect arg %>
  2. + <% end %> +
+
+ <% end %> + + <%= if frame.clauses do %> + <% {min, max, clauses} = frame.clauses %> +
+ Attempted function clauses (showing <%= min %> out of <%= max %>) +
+                                <%= for clause <- clauses do %>
+                                    <%= clause %>
+                                <% end %>
+                            
+
+ <% end %> +
+ <% end %> +
+ +
+
+ + +
+ +
    + <%= for frame <- @frames do %> +
  • + +
  • + <% end %> +
+
+
+
+ +
+ <%= if @params && @params != %{} do %> +
+ Params + <%= for {key, value} <- @params do %> +
+
<%= h key %>
+
<%= h inspect(value) %>
+
+ <% end %> +
+ <% end %> + +
+ Request info + +
+
URI:
+
<%= h url(@conn) %>
+
+ +
+
Query string:
+
<%= h @conn.query_string %>
+
+
+ +
+ Headers + <%= for {key, value} <- Enum.sort(@conn.req_headers) do %> +
+
<%= h key %>
+
<%= h value %>
+
+ <% end %> +
+ + <%= if @session && @session != %{} do %> +
+ Session + <%= for {key, value} <- @session do %> +
+
<%= h key %>
+
<%= h inspect(value) %>
+
+ <% end %> +
+ <% end %> +
+ + + + diff --git a/deps/plug/lib/plug/templates/debugger.md.eex b/deps/plug/lib/plug/templates/debugger.md.eex new file mode 100644 index 0000000000000000000000000000000000000000..8d1f008147fa192f963e123a7167b02ed4867171 --- /dev/null +++ b/deps/plug/lib/plug/templates/debugger.md.eex @@ -0,0 +1,24 @@ +# <%= @title %> at <%= method(@conn) %> <%= @conn.request_path %> + +Exception: + + <%= String.replace(@formatted, "\n", "\n ") %> + +## Connection details + +### Params + + <%= inspect(@params) %> + +### Request info + + * URI: <%= url(@conn) %> + * Query string: <%= @conn.query_string %> + +<%= if @full_version do %>### Headers + <%= for {key, value} <- Enum.sort(@conn.req_headers) do %> + * <%= key %>: <%= value %><% end %> + +<% end %>### Session + + <%= inspect(@session) %> diff --git a/deps/plug/lib/plug/upload/supervisor.ex b/deps/plug/lib/plug/upload/supervisor.ex new file mode 100644 index 0000000000000000000000000000000000000000..a13745172083529f1a25613c861a3219dd4fdb16 --- /dev/null +++ b/deps/plug/lib/plug/upload/supervisor.ex @@ -0,0 +1,34 @@ +defmodule Plug.Upload.Supervisor do + @moduledoc false + use Supervisor + + @temp_env_vars ~w(PLUG_TMPDIR TMPDIR TMP TEMP)s + @dir_table Plug.Upload.Dir + @path_table Plug.Upload.Path + @otp_vsn System.otp_release() |> String.to_integer() + @write_mode if @otp_vsn >= 25, do: :auto, else: true + @ets_opts [:public, :named_table, read_concurrency: true, write_concurrency: @write_mode] + + def start_link(args) do + Supervisor.start_link(__MODULE__, args, name: __MODULE__) + end + + @impl true + def init(_args) do + # Initialize the upload system + tmp = Enum.find_value(@temp_env_vars, "/tmp", &System.get_env/1) |> Path.expand() + cwd = Path.join(File.cwd!(), "tmp") + # Add a tiny random component to avoid clashes between nodes + suffix = :crypto.strong_rand_bytes(3) |> Base.url_encode64() + :persistent_term.put(Plug.Upload, {[tmp, cwd], suffix}) + :ets.new(@dir_table, [:set | @ets_opts]) + :ets.new(@path_table, [:duplicate_bag | @ets_opts]) + + children = [ + Plug.Upload.Terminator, + {PartitionSupervisor, child_spec: Plug.Upload, name: Plug.Upload} + ] + + Supervisor.init(children, strategy: :one_for_one) + end +end diff --git a/deps/plug/lib/plug/upload/terminator.ex b/deps/plug/lib/plug/upload/terminator.ex new file mode 100644 index 0000000000000000000000000000000000000000..db8d15fdb379ea5b5925f1813a8aede2c36d40eb --- /dev/null +++ b/deps/plug/lib/plug/upload/terminator.ex @@ -0,0 +1,27 @@ +defmodule Plug.Upload.Terminator do + @moduledoc false + use GenServer + + @path_table Plug.Upload.Path + + def start_link(_) do + GenServer.start_link(__MODULE__, :ok) + end + + @impl true + def init(:ok) do + Process.flag(:trap_exit, true) + {:ok, %{}} + end + + @impl true + def terminate(_reason, _state) do + folder = fn entry, :ok -> delete_path(entry) end + :ets.foldl(folder, :ok, @path_table) + end + + defp delete_path({_pid, path}) do + :file.delete(path, [:raw]) + :ok + end +end diff --git a/deps/plug/src/plug_multipart.erl b/deps/plug/src/plug_multipart.erl new file mode 100644 index 0000000000000000000000000000000000000000..fc5545999ee6458c79e7ff1e070773b91be6dad1 --- /dev/null +++ b/deps/plug/src/plug_multipart.erl @@ -0,0 +1,471 @@ +%% Copyright (c) 2014-2015, Loïc Hoguin +%% +%% Permission to use, copy, modify, and/or distribute this software for any +%% purpose with or without fee is hereby granted, provided that the above +%% copyright notice and this permission notice appear in all copies. +%% +%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +-module(plug_multipart). + +%% Parsing. +-export([parse_headers/2]). +-export([parse_body/2]). + +%% Building. +-export([boundary/0]). +-export([first_part/2]). +-export([part/2]). +-export([close/1]). + +%% Headers. +-export([form_data/1]). +-export([parse_content_disposition/1]). +-export([parse_content_transfer_encoding/1]). +-export([parse_content_type/1]). + +-type headers() :: [{iodata(), iodata()}]. +-export_type([headers/0]). + +-define(LC(C), case C of + $A -> $a; + $B -> $b; + $C -> $c; + $D -> $d; + $E -> $e; + $F -> $f; + $G -> $g; + $H -> $h; + $I -> $i; + $J -> $j; + $K -> $k; + $L -> $l; + $M -> $m; + $N -> $n; + $O -> $o; + $P -> $p; + $Q -> $q; + $R -> $r; + $S -> $s; + $T -> $t; + $U -> $u; + $V -> $v; + $W -> $w; + $X -> $x; + $Y -> $y; + $Z -> $z; + _ -> C +end). + +%% LOWER(Bin) +%% +%% Lowercase the entire binary string in a binary comprehension. + +-define(LOWER(Bin), << << ?LC(C) >> || << C >> <= Bin >>). + +%% LOWERCASE(Function, Rest, Acc, ...) +%% +%% To be included at the end of a case block. +%% Defined for up to 10 extra arguments. + +-define(LOWER(Function, Rest, Acc), case C of + $A -> Function(Rest, << Acc/binary, $a >>); + $B -> Function(Rest, << Acc/binary, $b >>); + $C -> Function(Rest, << Acc/binary, $c >>); + $D -> Function(Rest, << Acc/binary, $d >>); + $E -> Function(Rest, << Acc/binary, $e >>); + $F -> Function(Rest, << Acc/binary, $f >>); + $G -> Function(Rest, << Acc/binary, $g >>); + $H -> Function(Rest, << Acc/binary, $h >>); + $I -> Function(Rest, << Acc/binary, $i >>); + $J -> Function(Rest, << Acc/binary, $j >>); + $K -> Function(Rest, << Acc/binary, $k >>); + $L -> Function(Rest, << Acc/binary, $l >>); + $M -> Function(Rest, << Acc/binary, $m >>); + $N -> Function(Rest, << Acc/binary, $n >>); + $O -> Function(Rest, << Acc/binary, $o >>); + $P -> Function(Rest, << Acc/binary, $p >>); + $Q -> Function(Rest, << Acc/binary, $q >>); + $R -> Function(Rest, << Acc/binary, $r >>); + $S -> Function(Rest, << Acc/binary, $s >>); + $T -> Function(Rest, << Acc/binary, $t >>); + $U -> Function(Rest, << Acc/binary, $u >>); + $V -> Function(Rest, << Acc/binary, $v >>); + $W -> Function(Rest, << Acc/binary, $w >>); + $X -> Function(Rest, << Acc/binary, $x >>); + $Y -> Function(Rest, << Acc/binary, $y >>); + $Z -> Function(Rest, << Acc/binary, $z >>); + C -> Function(Rest, << Acc/binary, C >>) +end). + +-define(LOWER(Function, Rest, A0, Acc), case C of + $A -> Function(Rest, A0, << Acc/binary, $a >>); + $B -> Function(Rest, A0, << Acc/binary, $b >>); + $C -> Function(Rest, A0, << Acc/binary, $c >>); + $D -> Function(Rest, A0, << Acc/binary, $d >>); + $E -> Function(Rest, A0, << Acc/binary, $e >>); + $F -> Function(Rest, A0, << Acc/binary, $f >>); + $G -> Function(Rest, A0, << Acc/binary, $g >>); + $H -> Function(Rest, A0, << Acc/binary, $h >>); + $I -> Function(Rest, A0, << Acc/binary, $i >>); + $J -> Function(Rest, A0, << Acc/binary, $j >>); + $K -> Function(Rest, A0, << Acc/binary, $k >>); + $L -> Function(Rest, A0, << Acc/binary, $l >>); + $M -> Function(Rest, A0, << Acc/binary, $m >>); + $N -> Function(Rest, A0, << Acc/binary, $n >>); + $O -> Function(Rest, A0, << Acc/binary, $o >>); + $P -> Function(Rest, A0, << Acc/binary, $p >>); + $Q -> Function(Rest, A0, << Acc/binary, $q >>); + $R -> Function(Rest, A0, << Acc/binary, $r >>); + $S -> Function(Rest, A0, << Acc/binary, $s >>); + $T -> Function(Rest, A0, << Acc/binary, $t >>); + $U -> Function(Rest, A0, << Acc/binary, $u >>); + $V -> Function(Rest, A0, << Acc/binary, $v >>); + $W -> Function(Rest, A0, << Acc/binary, $w >>); + $X -> Function(Rest, A0, << Acc/binary, $x >>); + $Y -> Function(Rest, A0, << Acc/binary, $y >>); + $Z -> Function(Rest, A0, << Acc/binary, $z >>); + C -> Function(Rest, A0, << Acc/binary, C >>) +end). + +%% Parsing. +%% +%% The multipart format is defined in RFC 2045. + +%% @doc Parse the headers for the next multipart part. +%% +%% This function skips any preamble before the boundary. +%% The preamble may be retrieved using parse_body/2. +%% +%% This function will accept input of any size, it is +%% up to the caller to limit it if needed. + +-spec parse_headers(binary(), binary()) + -> more | {more, binary()} + | {ok, headers(), binary()} + | {done, binary()}. +%% If the stream starts with the boundary we can make a few assumptions +%% and quickly figure out if we got the complete list of headers. +parse_headers(<< "--", Stream/bits >>, Boundary) -> + BoundarySize = byte_size(Boundary), + case Stream of + %% Last boundary. Return the epilogue. + << Boundary:BoundarySize/binary, "--", Stream2/bits >> -> + {done, Stream2}; + << Boundary:BoundarySize/binary, Stream2/bits >> -> + %% We have all the headers only if there is a \r\n\r\n + %% somewhere in the data after the boundary. + case binary:match(Stream2, <<"\r\n\r\n">>) of + nomatch -> + more; + _ -> + before_parse_headers(Stream2) + end; + %% If there isn't enough to represent Boundary \r\n\r\n + %% then we definitely don't have all the headers. + _ when byte_size(Stream) < byte_size(Boundary) + 4 -> + more; + %% Otherwise we have preamble data to skip. + %% We still got rid of the first two misleading bytes. + _ -> + skip_preamble(Stream, Boundary) + end; +%% Otherwise we have preamble data to skip. +parse_headers(Stream, Boundary) -> + skip_preamble(Stream, Boundary). + +%% We need to find the boundary and a \r\n\r\n after that. +%% Since the boundary isn't at the start, it must be right +%% after a \r\n too. +skip_preamble(Stream, Boundary) -> + case binary:match(Stream, <<"\r\n--", Boundary/bits >>) of + %% No boundary, need more data. + nomatch -> + %% We can safely skip the size of the stream + %% minus the last 3 bytes which may be a partial boundary. + SkipSize = byte_size(Stream) - 3, + case SkipSize > 0 of + false -> + more; + true -> + << _:SkipSize/binary, Stream2/bits >> = Stream, + {more, Stream2} + end; + {Start, Length} -> + Start2 = Start + Length, + << _:Start2/binary, Stream2/bits >> = Stream, + case Stream2 of + %% Last boundary. Return the epilogue. + << "--", Stream3/bits >> -> + {done, Stream3}; + _ -> + case binary:match(Stream, <<"\r\n\r\n">>) of + %% We don't have the full headers. + nomatch -> + {more, Stream2}; + _ -> + before_parse_headers(Stream2) + end + end + end. + +before_parse_headers(<< "\r\n\r\n", Stream/bits >>) -> + %% This indicates that there are no headers, so we can abort immediately. + {ok, [], Stream}; +before_parse_headers(<< "\r\n", Stream/bits >>) -> + %% There is a line break right after the boundary, skip it. + parse_hd_name(Stream, [], <<>>). + +parse_hd_name(<< C, Rest/bits >>, H, SoFar) -> + case C of + $: -> parse_hd_before_value(Rest, H, SoFar); + $\s -> parse_hd_name_ws(Rest, H, SoFar); + $\t -> parse_hd_name_ws(Rest, H, SoFar); + _ -> ?LOWER(parse_hd_name, Rest, H, SoFar) + end. + +parse_hd_name_ws(<< C, Rest/bits >>, H, Name) -> + case C of + $\s -> parse_hd_name_ws(Rest, H, Name); + $\t -> parse_hd_name_ws(Rest, H, Name); + $: -> parse_hd_before_value(Rest, H, Name) + end. + +parse_hd_before_value(<< $\s, Rest/bits >>, H, N) -> + parse_hd_before_value(Rest, H, N); +parse_hd_before_value(<< $\t, Rest/bits >>, H, N) -> + parse_hd_before_value(Rest, H, N); +parse_hd_before_value(Buffer, H, N) -> + parse_hd_value(Buffer, H, N, <<>>). + +parse_hd_value(<< $\r, Rest/bits >>, Headers, Name, SoFar) -> + case Rest of + << "\n\r\n", Rest2/bits >> -> + {ok, [{Name, SoFar}|Headers], Rest2}; + << $\n, C, Rest2/bits >> when C =:= $\s; C =:= $\t -> + parse_hd_value(Rest2, Headers, Name, SoFar); + << $\n, Rest2/bits >> -> + parse_hd_name(Rest2, [{Name, SoFar}|Headers], <<>>) + end; +parse_hd_value(<< C, Rest/bits >>, H, N, SoFar) -> + parse_hd_value(Rest, H, N, << SoFar/binary, C >>). + +%% @doc Parse the body of the current multipart part. +%% +%% The body is everything until the next boundary. + +-spec parse_body(binary(), binary()) + -> {ok, binary()} | {ok, binary(), binary()} + | done | {done, binary()} | {done, binary(), binary()}. +parse_body(Stream, Boundary) -> + BoundarySize = byte_size(Boundary), + case Stream of + << "--", Boundary:BoundarySize/binary, _/bits >> -> + done; + _ -> + case binary:match(Stream, << "\r\n--", Boundary/bits >>) of + %% No boundary, check for a possible partial at the end. + %% Return more or less of the body depending on the result. + nomatch -> + StreamSize = byte_size(Stream), + From = StreamSize - BoundarySize - 3, + MatchOpts = if + %% Binary too small to contain boundary, check it fully. + From < 0 -> []; + %% Optimize, only check the end of the binary. + true -> [{scope, {From, StreamSize - From}}] + end, + case binary:match(Stream, <<"\r">>, MatchOpts) of + nomatch -> + {ok, Stream}; + {Pos, _} -> + case Stream of + << Body:Pos/binary >> -> + {ok, Body}; + << Body:Pos/binary, Rest/bits >> -> + {ok, Body, Rest} + end + end; + %% Boundary found, this is the last chunk of the body. + {Pos, _} -> + case Stream of + << Body:Pos/binary, "\r\n" >> -> + {done, Body}; + << Body:Pos/binary, "\r\n", Rest/bits >> -> + {done, Body, Rest}; + << Body:Pos/binary, Rest/bits >> -> + {done, Body, Rest} + end + end + end. + +%% Building. + +%% @doc Generate a new random boundary. +%% +%% The boundary generated has a low probability of ever appearing +%% in the data. + +-spec boundary() -> binary(). +boundary() -> + base64:encode(crypto:strong_rand_bytes(48)). + +%% @doc Return the first part's head. +%% +%% This works exactly like the part/2 function except there is +%% no leading \r\n. It's not required to use this function, +%% just makes the output a little smaller and prettier. + +-spec first_part(binary(), headers()) -> iodata(). +first_part(Boundary, Headers) -> + [<<"--">>, Boundary, <<"\r\n">>, headers_to_iolist(Headers, [])]. + +%% @doc Return a part's head. + +-spec part(binary(), headers()) -> iodata(). +part(Boundary, Headers) -> + [<<"\r\n--">>, Boundary, <<"\r\n">>, headers_to_iolist(Headers, [])]. + +headers_to_iolist([], Acc) -> + lists:reverse([<<"\r\n">>|Acc]); +headers_to_iolist([{N, V}|Tail], Acc) -> + %% We don't want to create a sublist so we list the + %% values in reverse order so that it gets reversed properly. + headers_to_iolist(Tail, [<<"\r\n">>, V, <<": ">>, N|Acc]). + +%% @doc Return the closing delimiter of the multipart message. + +-spec close(binary()) -> iodata(). +close(Boundary) -> + [<<"\r\n--">>, Boundary, <<"--">>]. + +%% Headers. + +%% @doc Convenience function for extracting information from headers +%% when parsing a multipart/form-data stream. + +-spec form_data(headers()) + -> {data, binary()} + | {file, binary(), binary(), binary(), binary()}. +form_data(Headers) -> + {_, DispositionBin} = lists:keyfind(<<"content-disposition">>, 1, Headers), + {<<"form-data">>, Params} = parse_content_disposition(DispositionBin), + {_, FieldName} = lists:keyfind(<<"name">>, 1, Params), + case lists:keyfind(<<"filename">>, 1, Params) of + false -> + {data, FieldName}; + {_, Filename} -> + Type = case lists:keyfind(<<"content-type">>, 1, Headers) of + false -> <<"text/plain">>; + {_, T} -> T + end, + %% Turns out this is unnecessary per RFC7578 4.7. + TransferEncoding = case lists:keyfind( + <<"content-transfer-encoding">>, 1, Headers) of + false -> <<"7bit">>; + {_, TE} -> TE + end, + {file, FieldName, Filename, Type, TransferEncoding} + end. + +%% @doc Parse an RFC 2183 content-disposition value. + +-spec parse_content_disposition(binary()) + -> {binary(), [{binary(), binary()}]}. +parse_content_disposition(Bin) -> + parse_cd_type(Bin, <<>>). + +parse_cd_type(<<>>, Acc) -> + {Acc, []}; +parse_cd_type(<< C, Rest/bits >>, Acc) -> + case C of + $; -> {Acc, parse_before_param(Rest, [])}; + $\s -> {Acc, parse_before_param(Rest, [])}; + $\t -> {Acc, parse_before_param(Rest, [])}; + _ -> ?LOWER(parse_cd_type, Rest, Acc) + end. + +%% @doc Parse an RFC 2045 content-transfer-encoding header. + +-spec parse_content_transfer_encoding(binary()) -> binary(). +parse_content_transfer_encoding(Bin) -> + ?LOWER(Bin). + +%% @doc Parse an RFC 2045 content-type header. + +-spec parse_content_type(binary()) + -> {binary(), binary(), [{binary(), binary()}]}. +parse_content_type(Bin) -> + parse_ct_type(Bin, <<>>). + +parse_ct_type(<< C, Rest/bits >>, Acc) -> + case C of + $/ -> parse_ct_subtype(Rest, Acc, <<>>); + _ -> ?LOWER(parse_ct_type, Rest, Acc) + end. + +parse_ct_subtype(<<>>, Type, Subtype) when Subtype =/= <<>> -> + {Type, Subtype, []}; +parse_ct_subtype(<< C, Rest/bits >>, Type, Acc) -> + case C of + $; -> {Type, Acc, parse_before_param(Rest, [])}; + $\s -> {Type, Acc, parse_before_param(Rest, [])}; + $\t -> {Type, Acc, parse_before_param(Rest, [])}; + _ -> ?LOWER(parse_ct_subtype, Rest, Type, Acc) + end. + +%% @doc Parse RFC 2045 parameters. + +parse_before_param(<<>>, Params) -> + lists:reverse(Params); +parse_before_param(<< C, Rest/bits >>, Params) -> + case C of + $; -> parse_before_param(Rest, Params); + $\s -> parse_before_param(Rest, Params); + $\t -> parse_before_param(Rest, Params); + _ -> ?LOWER(parse_param_name, Rest, Params, <<>>) + end. + +parse_param_name(<<>>, Params, Acc) -> + lists:reverse([{Acc, <<>>}|Params]); +parse_param_name(<< C, Rest/bits >>, Params, Acc) -> + case C of + $= -> parse_param_value(Rest, Params, Acc); + _ -> ?LOWER(parse_param_name, Rest, Params, Acc) + end. + +parse_param_value(<<>>, Params, Name) -> + lists:reverse([{Name, <<>>}|Params]); +parse_param_value(<< C, Rest/bits >>, Params, Name) -> + case C of + $" -> parse_param_quoted_value(Rest, Params, Name, <<>>); + $; -> parse_before_param(Rest, [{Name, <<>>}|Params]); + $\s -> parse_before_param(Rest, [{Name, <<>>}|Params]); + $\t -> parse_before_param(Rest, [{Name, <<>>}|Params]); + C -> parse_param_value(Rest, Params, Name, << C >>) + end. + +parse_param_value(<<>>, Params, Name, Acc) -> + lists:reverse([{Name, Acc}|Params]); +parse_param_value(<< C, Rest/bits >>, Params, Name, Acc) -> + case C of + $; -> parse_before_param(Rest, [{Name, Acc}|Params]); + $\s -> parse_before_param(Rest, [{Name, Acc}|Params]); + $\t -> parse_before_param(Rest, [{Name, Acc}|Params]); + C -> parse_param_value(Rest, Params, Name, << Acc/binary, C >>) + end. + +%% We expect a final $" so no need to test for <<>>. +parse_param_quoted_value(<< $\\, C, Rest/bits >>, Params, Name, Acc) -> + parse_param_quoted_value(Rest, Params, Name, << Acc/binary, C >>); +parse_param_quoted_value(<< $", Rest/bits >>, Params, Name, Acc) -> + parse_before_param(Rest, [{Name, Acc}|Params]); +parse_param_quoted_value(<< C, Rest/bits >>, Params, Name, Acc) + when C =/= $\r -> + parse_param_quoted_value(Rest, Params, Name, << Acc/binary, C >>). \ No newline at end of file diff --git a/deps/unpickler/.formatter.exs b/deps/unpickler/.formatter.exs new file mode 100644 index 0000000000000000000000000000000000000000..d2cda26eddc9110057ce9e8002585682217542cc --- /dev/null +++ b/deps/unpickler/.formatter.exs @@ -0,0 +1,4 @@ +# Used by "mix format" +[ + inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] +] diff --git a/deps/unpickler/.hex b/deps/unpickler/.hex new file mode 100644 index 0000000000000000000000000000000000000000..a73dc527f926ba3209f6337262846e8f0a38c102 Binary files /dev/null and b/deps/unpickler/.hex differ diff --git a/deps/unpickler/CHANGELOG.md b/deps/unpickler/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..c98774f35705fb39f863b413d610476ba99baedc --- /dev/null +++ b/deps/unpickler/CHANGELOG.md @@ -0,0 +1,10 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [v0.1.0](https://github.com/dashbitco/unpickler/tree/v0.1.0) (2022-12-05) + +Initial release. diff --git a/deps/unpickler/LICENSE b/deps/unpickler/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f433b1a53f5b830a205fd2df78e2b34974656c7b --- /dev/null +++ b/deps/unpickler/LICENSE @@ -0,0 +1,177 @@ + + 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 diff --git a/deps/unpickler/README.md b/deps/unpickler/README.md new file mode 100644 index 0000000000000000000000000000000000000000..988e5b49a61770a3130ea50bd1454918bc74c09d --- /dev/null +++ b/deps/unpickler/README.md @@ -0,0 +1,32 @@ +# Unpickler + +[![Actions Status](https://github.com/dashbitco/unpickler/workflows/Test/badge.svg)](https://github.com/dashbitco/unpickler/actions) +[![Docs](https://img.shields.io/badge/docs-gray.svg)](https://hexdocs.pm/unpickler) + +A library for loading data in the Python's [pickle](https://docs.python.org/3/library/pickle.html) format. + +## Installation + +You can add the `:unpickler` dependency to your `mix.exs`: + +```elixir +def deps do + [ + {:unpickler, "~> 0.1.0"} + ] +end +``` + +## License + +Copyright (C) 2022 Dashbit + + 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](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/deps/unpickler/hex_metadata.config b/deps/unpickler/hex_metadata.config new file mode 100644 index 0000000000000000000000000000000000000000..a308b098173b52fc24817bd64cc62cea8429f37e --- /dev/null +++ b/deps/unpickler/hex_metadata.config @@ -0,0 +1,15 @@ +{<<"app">>,<<"unpickler">>}. +{<<"build_tools">>,[<<"mix">>]}. +{<<"description">>, + <<"A library for loading data in the Python's pickle format">>}. +{<<"elixir">>,<<"~> 1.7">>}. +{<<"files">>, + [<<"lib">>,<<"lib/unpickler.ex">>,<<"lib/unpickler">>, + <<"lib/unpickler/object.ex">>,<<"lib/unpickler/global.ex">>, + <<".formatter.exs">>,<<"mix.exs">>,<<"README.md">>,<<"LICENSE">>, + <<"CHANGELOG.md">>]}. +{<<"licenses">>,[<<"Apache-2.0">>]}. +{<<"links">>,[{<<"GitHub">>,<<"https://github.com/dashbitco/unpickler">>}]}. +{<<"name">>,<<"unpickler">>}. +{<<"requirements">>,[]}. +{<<"version">>,<<"0.1.0">>}. diff --git a/deps/unpickler/lib/unpickler.ex b/deps/unpickler/lib/unpickler.ex new file mode 100644 index 0000000000000000000000000000000000000000..927546fca6761eb2aefc88a2d3ad754ba3eb712e --- /dev/null +++ b/deps/unpickler/lib/unpickler.ex @@ -0,0 +1,908 @@ +defmodule Unpickler do + @moduledoc """ + `Unpickler` is a library for loading data in the Python's + [pickle](https://docs.python.org/3/library/pickle.html) format. + + Supports all pickle protocols from 0 to 5. + """ + + alias Unpickler.Global + alias Unpickler.Object + + @doc ~S""" + Loads the given pickle binary. + + Basic literals and data structures are deserialized as corresponding + Elixir terms whenever possible. The pickle data may include arbitrary + Python objects, so in all other cases the `Unpickler.Object` struct + is used. This struct holds all the information that would be used for + object reconstruction. You can define a custom `:object_resolver` + function to recognise certain objects and map them to whatever data + structure you see fit. + + ## Object references + + Note that if the object hierarchy includes circular references, it + is inherently impossible to represent in Elixir. One example of such + data structure is a list with a reference to itself: + + ```python + x = [] + x.append(x) + ``` + + On the other hand, multiple references to the same object are restored + as expected, without duplicating memory, as in: + + ```python + x = [1, 2, 3] + y = (x, x) + ``` + + ## Options + + * `:object_resolver` - a function for constructing a custom term + corresponding to a Python object. Receives `Unpickler.Object` + as an argument and should return the term as `{:ok, term}` or + `:error` if not applicable + + * `:persistent_id_resolver` - a function returning an object for + the given persistent id. This function is required if the data + includes a persistent id, otherwise an error is raised + + ## Examples + + The scalar `1` would be loaded like so: + + iex> Unpickler.load!(<<128, 4, 75, 1, 46>>) + {1, ""} + + Next, a more complex data structure: + + ```python + [1, 2.0, "text", (None, True), {"key": "val"}, b"\x01\x00"] + ``` + + iex> data = + ...> <<128, 4, 149, 47, 0, 0, 0, 0, 0, 0, 0, 93, 148, 40, 75, 1, 71, 64, 0, 0, 0, 0, 0, 0, 0, + ...> 140, 4, 116, 101, 120, 116, 148, 78, 136, 134, 148, 125, 148, 140, 3, 107, 101, 121, + ...> 148, 140, 3, 118, 97, 108, 148, 115, 67, 2, 1, 0, 148, 101, 46>> + iex> Unpickler.load!(data) + {[1, 2.0, "text", {nil, true}, %{"key" => "val"}, <<1, 0>>], ""} + + ### Objects + + Other objects end up as `Unpickler.Object` + + ```python + from datetime import date + date.fromisoformat("2022-05-17") + ``` + + iex> data = + ...> <<128, 4, 149, 32, 0, 0, 0, 0, 0, 0, 0, 140, 8, 100, 97, 116, 101, 116, 105, 109, 101, + ...> 148, 140, 4, 100, 97, 116, 101, 148, 147, 148, 67, 4, 7, 230, 5, 17, 148, 133, 148, 82, + ...> 148, 46>> + iex> Unpickler.load!(data) + {%Unpickler.Object{ + append_items: [], + args: [<<7, 230, 5, 17>>], + constructor: "datetime.date", + kwargs: %{}, + set_items: [], + state: nil + }, ""} + + For those, we can customize construction by specifying an `:object_resolver` + + ```python + from datetime import date + date.fromisoformat("2022-05-17") + ``` + + iex> data = + ...> <<128, 4, 149, 32, 0, 0, 0, 0, 0, 0, 0, 140, 8, 100, 97, 116, 101, 116, 105, 109, 101, + ...> 148, 140, 4, 100, 97, 116, 101, 148, 147, 148, 67, 4, 7, 230, 5, 17, 148, 133, 148, 82, + ...> 148, 46>> + iex> object_resolver = fn + ...> # See https://github.com/python/cpython/blob/3.10/Lib/datetime.py#L1094-L1105 + ...> %{constructor: "datetime.date", args: [<>]} -> + ...> {:ok, date} = Date.new(year_hi * 256 + year_lo, month, day) + ...> {:ok, date} + ...> + ...> _ -> + ...> :error + ...> end + iex> Unpickler.load!(data, object_resolver: object_resolver) + {~D[2022-05-17], ""} + + """ + @spec load!(binary(), keyword()) :: {term(), rest :: binary()} + def load!(binary, opts \\ []) when is_binary(binary) and is_list(opts) do + object_resolver = opts[:object_resolver] + persistent_id_resolver = opts[:persistent_id_resolver] + + load_op(binary, %{ + stack: [], + metastack: [], + memo: %{}, + refs: %{}, + object_resolver: object_resolver, + persistent_id_resolver: persistent_id_resolver + }) + end + + @highest_protocol 5 + + # Operations + # + # A pickle file is essentially a list of instructions for so-called + # pickle machine (PM). Each instruction starts with a 1-byte opcode, + # which can be followed by arguments of arbitrary size. Those + # instructions try to replicate the original object step by step. + # + # To ensure compatibility, subsequent pickle protocols introduce new + # operations, but never change or drop existing ones. + # + # See [1] for a detailed description of the protocol and individual + # operations and [2] for the corresponding Python implementation. + # + # [1]: https://github.com/python/cpython/blob/3.11/Lib/pickletools.py + # [2]: https://github.com/python/cpython/blob/3.11/Lib/pickle.py + + # Protocol 0 and 1 + + @op_mark 40 + @op_stop 46 + @op_pop 48 + @op_pop_mark 49 + @op_dup 50 + @op_float 70 + @op_int 73 + @op_binint 74 + @op_binint1 75 + @op_long 76 + @op_binint2 77 + @op_none 78 + @op_persid 80 + @op_binpersid 81 + @op_reduce 82 + @op_string 83 + @op_binstring 84 + @op_short_binstring 85 + @op_unicode 86 + @op_binunicode 88 + @op_append 97 + @op_build 98 + @op_global 99 + @op_dict 100 + @op_empty_dict 125 + @op_appends 101 + @op_get 103 + @op_binget 104 + @op_inst 105 + @op_long_binget 106 + @op_list 108 + @op_empty_list 93 + @op_obj 111 + @op_put 112 + @op_binput 113 + @op_long_binput 114 + @op_setitem 115 + @op_tuple 116 + @op_empty_tuple 41 + @op_setitems 117 + @op_binfloat 71 + + # Protocol 2 + + @op_proto 128 + @op_newobj 129 + @op_ext1 130 + @op_ext2 131 + @op_ext4 132 + @op_tuple1 133 + @op_tuple2 134 + @op_tuple3 135 + @op_newtrue 136 + @op_newfalse 137 + @op_long1 138 + @op_long4 139 + + # Protocol 3 (Python 3.x) + + @op_binbytes 66 + @op_short_binbytes 67 + + # Protocol 4 + + @op_short_binunicode 140 + @op_binunicode8 141 + @op_binbytes8 142 + @op_empty_set 143 + @op_additems 144 + @op_frozenset 145 + @op_newobj_ex 146 + @op_stack_global 147 + @op_memoize 148 + @op_frame 149 + + # Protocol 5 + + @op_bytearray8 150 + @op_next_buffer 151 + @op_readonly_buffer 152 + + defp load_op(<>, state), do: load_op(opcode, rest, state) + + # Ways to spell integers + + defp load_op(@op_int, rest, state) do + {string, rest} = read_line(rest) + + value = + case string do + "01" -> true + "00" -> false + string -> String.to_integer(string) + end + + state = push(state, value) + load_op(rest, state) + end + + defp load_op(@op_binint, rest, state) do + <> = rest + state = push(state, int) + load_op(rest, state) + end + + defp load_op(@op_binint1, rest, state) do + <> = rest + state = push(state, int) + load_op(rest, state) + end + + defp load_op(@op_binint2, rest, state) do + <> = rest + state = push(state, int) + load_op(rest, state) + end + + defp load_op(@op_long, rest, state) do + {string, rest} = read_line(rest) + prefix_size = byte_size(string) - 1 + <> = string + int = String.to_integer(string) + state = push(state, int) + load_op(rest, state) + end + + defp load_op(@op_long1, rest, state) do + <> = rest + state = push(state, int) + load_op(rest, state) + end + + defp load_op(@op_long4, rest, state) do + << + size::integer-little-signed-size(32), + int::integer-little-signed-size(size)-unit(8), + rest::binary + >> = rest + + state = push(state, int) + load_op(rest, state) + end + + # Ways to spell strings (8-bit, not Unicode) + + defp load_op(@op_string, rest, state) do + {string, rest} = read_line(rest) + content_size = byte_size(string) - 2 + + string = + case string do + <> when q in [?', ?"] -> + Macro.unescape_string(string) + end + + state = push(state, string) + load_op(rest, state) + end + + defp load_op(@op_binstring, rest, state) do + <> = rest + state = push(state, string) + load_op(rest, state) + end + + defp load_op(@op_short_binstring, rest, state) do + <> = rest + state = push(state, string) + load_op(rest, state) + end + + # Bytes (protocol 3 and higher) + + defp load_op(@op_short_binbytes, rest, state) do + <> = rest + state = push(state, string) + load_op(rest, state) + end + + defp load_op(@op_binbytes, rest, state) do + <> = rest + state = push(state, string) + load_op(rest, state) + end + + defp load_op(@op_binbytes8, rest, state) do + <> = rest + state = push(state, string) + load_op(rest, state) + end + + # Bytearray (protocol 5 and higher) + + defp load_op(@op_bytearray8, rest, state) do + <> = rest + state = push(state, string) + load_op(rest, state) + end + + # Out-of-band buffer (protocol 5 and higher) + + defp load_op(@op_next_buffer, _rest, _state) do + unsupported_out_of_bound_buffers!() + end + + defp load_op(@op_readonly_buffer, rest, state) do + load_op(rest, state) + end + + # Ways to spell None + + defp load_op(@op_none, rest, state) do + state = push(state, nil) + load_op(rest, state) + end + + # Ways to spell bools, starting with proto 2 + + defp load_op(@op_newtrue, rest, state) do + state = push(state, true) + load_op(rest, state) + end + + defp load_op(@op_newfalse, rest, state) do + state = push(state, false) + load_op(rest, state) + end + + # Ways to spell Unicode strings + + defp load_op(@op_unicode, rest, state) do + # Note that Python encodes the string using raw-unicode-escape, + # so that it fits into ASCII, however this opcode is obsolete, + # so we keep it as is as our best effort + {string, rest} = read_line(rest) + state = push(state, string) + load_op(rest, state) + end + + defp load_op(@op_short_binunicode, rest, state) do + <> = rest + state = push(state, string) + load_op(rest, state) + end + + defp load_op(@op_binunicode, rest, state) do + <> = rest + state = push(state, string) + load_op(rest, state) + end + + defp load_op(@op_binunicode8, rest, state) do + <> = rest + state = push(state, string) + load_op(rest, state) + end + + # Ways to spell floats + + defp load_op(@op_float, rest, state) do + {string, rest} = read_line(rest) + float = String.to_float(string) + state = push(state, float) + load_op(rest, state) + end + + defp load_op(@op_binfloat, rest, state) do + <> = rest + state = push(state, float) + load_op(rest, state) + end + + # Ways to build lists + + defp load_op(@op_empty_list, rest, state) do + state = push(state, []) + load_op(rest, state) + end + + defp load_op(@op_append, rest, state) do + {item, state} = pop(state) + + state = + update_head(state, fn + list when is_list(list) -> list ++ [item] + %Object{} = object -> Object.append_many(object, [item]) + end) + + load_op(rest, state) + end + + defp load_op(@op_appends, rest, state) do + {items, state} = pop_mark(state) + elems = Enum.reverse(items) + + state = + update_head(state, fn + list when is_list(list) -> list ++ elems + %Object{} = object -> Object.append_many(object, elems) + end) + + load_op(rest, state) + end + + defp load_op(@op_list, rest, state) do + {items, state} = pop_mark(state) + list = Enum.reverse(items) + state = push(state, list) + load_op(rest, state) + end + + # Ways to build tuples + + defp load_op(@op_empty_tuple, rest, state) do + state = push(state, {}) + load_op(rest, state) + end + + defp load_op(@op_tuple, rest, state) do + {items, state} = pop_mark(state) + tuple = items |> Enum.reverse() |> List.to_tuple() + state = push(state, tuple) + load_op(rest, state) + end + + defp load_op(@op_tuple1, rest, state) do + {elem, state} = pop(state) + state = push(state, {elem}) + load_op(rest, state) + end + + defp load_op(@op_tuple2, rest, state) do + {[elem2, elem1], state} = pop_many(state, 2) + state = push(state, {elem1, elem2}) + load_op(rest, state) + end + + defp load_op(@op_tuple3, rest, state) do + {[elem3, elem2, elem1], state} = pop_many(state, 3) + state = push(state, {elem1, elem2, elem3}) + load_op(rest, state) + end + + # Ways to build dicts + + defp load_op(@op_empty_dict, rest, state) do + state = push(state, %{}) + load_op(rest, state) + end + + defp load_op(@op_dict, rest, state) do + {items, state} = pop_mark(state) + map = items |> stack_items_to_pairs() |> Map.new() + state = push(state, map) + load_op(rest, state) + end + + defp load_op(@op_setitem, rest, state) do + {[val, key], state} = pop_many(state, 2) + + state = + update_head(state, fn + %Object{} = object -> Object.set_many(object, [{key, val}]) + %{} = map -> Map.put(map, key, val) + end) + + load_op(rest, state) + end + + defp load_op(@op_setitems, rest, state) do + {items, state} = pop_mark(state) + + pairs = stack_items_to_pairs(items) + + state = + update_head(state, fn + %Object{} = object -> Object.set_many(object, pairs) + %{} = map -> Enum.into(pairs, map) + end) + + load_op(rest, state) + end + + # Ways to build sets + + defp load_op(@op_empty_set, rest, state) do + state = push(state, MapSet.new()) + load_op(rest, state) + end + + defp load_op(@op_additems, rest, state) do + {items, state} = pop_mark(state) + state = update_head(state, fn set -> Enum.into(items, set) end) + load_op(rest, state) + end + + # Way to build frozensets + + defp load_op(@op_frozenset, rest, state) do + {items, state} = pop_mark(state) + set = MapSet.new(items) + state = push(state, set) + load_op(rest, state) + end + + # Stack manipulation + + defp load_op(@op_pop, rest, state) do + {_item, state} = pop(state) + load_op(rest, state) + end + + defp load_op(@op_dup, rest, state) do + state = update_in(state.stack, fn [item | stack] -> [item, item | stack] end) + load_op(rest, state) + end + + defp load_op(@op_mark, rest, state) do + state = push_mark(state) + load_op(rest, state) + end + + defp load_op(@op_pop_mark, rest, state) do + {_items, state} = pop_mark(state) + load_op(rest, state) + end + + # Memo manipulation + + defp load_op(@op_get, rest, state) do + {string, rest} = read_line(rest) + idx = String.to_integer(string) + state = push_from_memo(state, idx) + load_op(rest, state) + end + + defp load_op(@op_binget, rest, state) do + <> = rest + state = push_from_memo(state, idx) + load_op(rest, state) + end + + defp load_op(@op_long_binget, rest, state) do + <> = rest + state = push_from_memo(state, idx) + load_op(rest, state) + end + + defp load_op(@op_put, rest, state) do + {string, rest} = read_line(rest) + idx = String.to_integer(string) + state = memoize(state, idx) + load_op(rest, state) + end + + defp load_op(@op_binput, rest, state) do + <> = rest + state = memoize(state, idx) + load_op(rest, state) + end + + defp load_op(@op_long_binput, rest, state) do + <> = rest + state = memoize(state, idx) + load_op(rest, state) + end + + defp load_op(@op_memoize, rest, state) do + idx = map_size(state.memo) + state = memoize(state, idx) + load_op(rest, state) + end + + # Access the extension registry (predefined objects) + + defp load_op(@op_ext1, _rest, _state) do + unsupported_extension_registry!() + end + + defp load_op(@op_ext2, _rest, _state) do + unsupported_extension_registry!() + end + + defp load_op(@op_ext4, _rest, _state) do + unsupported_extension_registry!() + end + + # Push a class or function reference onto the stack + + defp load_op(@op_global, rest, state) do + {module, rest} = read_line(rest) + {name, rest} = read_line(rest) + global = Global.new(module, name) + state = push(state, global) + load_op(rest, state) + end + + defp load_op(@op_stack_global, rest, state) do + {[name, module], state} = pop_many(state, 2) + global = Global.new(module, name) + state = push(state, global) + load_op(rest, state) + end + + # Ways to build objects of classes pickle doesn't know about + + defp load_op(@op_reduce, rest, state) do + {[args_tuple, callable], state} = pop_many(state, 2) + args = Tuple.to_list(args_tuple) + object = Object.new(callable, args, %{}) + state = push(state, object) + load_op(rest, state) + end + + defp load_op(@op_build, rest, state) do + {object_state, state} = pop(state) + + state = + update_head(state, fn %Object{} = object -> + Object.set_state(object, object_state) + end) + + load_op(rest, state) + end + + defp load_op(@op_inst, rest, state) do + {module, rest} = read_line(rest) + {name, rest} = read_line(rest) + {items, state} = pop_mark(state) + args = Enum.reverse(items) + class = Global.new(module, name) + object = Object.new(class, args, %{}) + state = push(state, object) + load_op(rest, state) + end + + defp load_op(@op_obj, rest, state) do + {items, state} = pop_mark(state) + [class | args] = Enum.reverse(items) + object = Object.new(class, args, %{}) + state = push(state, object) + load_op(rest, state) + end + + defp load_op(@op_newobj, rest, state) do + {[args_tuple, class], state} = pop_many(state, 2) + args = Tuple.to_list(args_tuple) + new_method = Global.new(class, "__new__") + object = Object.new(new_method, [class | args], %{}) + state = push(state, object) + load_op(rest, state) + end + + defp load_op(@op_newobj_ex, rest, state) do + {[kwargs, args_tuple, class], state} = pop_many(state, 3) + args = Tuple.to_list(args_tuple) + new_method = Global.new(class, "__new__") + object = Object.new(new_method, [class | args], kwargs) + state = push(state, object) + load_op(rest, state) + end + + # Machine control + + defp load_op(@op_proto, rest, state) do + <> = rest + + if proto > @highest_protocol do + raise "unsupported pickle protocol: #{proto}" + end + + load_op(rest, state) + end + + defp load_op(@op_stop, rest, state) do + {item, %{stack: []}} = pop(state) + {item, rest} + end + + # Framing support + + defp load_op(@op_frame, rest, state) do + <<_size::integer-little-size(64), rest::binary>> = rest + # Since we work on an in-memory data, framing is not applicable + load_op(rest, state) + end + + # Ways to deal with persistent ids + + defp load_op(@op_persid, rest, state) do + {id, rest} = read_line(rest) + value = load_persistent_id(state, id) + state = push(state, value) + load_op(rest, state) + end + + defp load_op(@op_binpersid, rest, state) do + {id, state} = pop(state) + value = load_persistent_id(state, id) + state = push(state, value) + load_op(rest, state) + end + + defp push(%{stack: stack} = state, item) do + %{state | stack: [item | stack]} + end + + defp pop(%{stack: [item | stack]} = state) do + state = %{state | stack: stack} + {[item], state} = finalize_stack_items(state, [item]) + {item, state} + end + + defp pop_many(state, count) do + {items, stack} = Enum.split(state.stack, count) + state = %{state | stack: stack} + finalize_stack_items(state, items) + end + + defp update_head(%{stack: [ref | _]} = state, fun) when is_reference(ref) do + update_in(state.refs[ref], fun) + end + + defp update_head(%{stack: [item | stack]} = state, fun) do + %{state | stack: [fun.(item) | stack]} + end + + defp push_mark(%{stack: stack, metastack: metastack} = state) do + %{state | stack: [], metastack: [stack | metastack]} + end + + defp pop_mark(%{stack: stack, metastack: [prev_stack | metastack]} = state) do + state = %{state | stack: prev_stack, metastack: metastack} + finalize_stack_items(state, stack) + end + + defp memoize(%{stack: [item | stack]} = state, idx) do + # We memoize an object from the stack, however subsequent operations + # can modify that object on the stack. In Python the memo only holds + # a reference to that object and mutability ensures it stays in sync. + # To achieve a similar behaviour, whenever an object is memoized we + # replace it with a random reference, both on the stack and in the + # memo, and we keep the referenced object in a single place + + ref = make_ref() + state = put_in(state.refs[ref], item) + state = put_in(state.memo[idx], ref) + %{state | stack: [ref | stack]} + end + + defp push_from_memo(state, idx) do + item = state.memo[idx] + push(state, item) + end + + defp finalize_stack_items(state, items) do + # When a Unpickler.Object is removed from the stack, it should + # include all the relevant information, so we try resolving it + # to a more specific term. Also, we replace object references + # with the actual values + + Enum.map_reduce(items, state, fn + ref, state when is_reference(ref) -> + state = update_in(state.refs[ref], &resolve_object(&1, state)) + {state.refs[ref], state} + + item, state -> + {resolve_object(item, state), state} + end) + end + + defp resolve_object(%Object{} = object, state) do + with :error <- built_in_resolver(object), + :error <- if(state.object_resolver, do: state.object_resolver.(object), else: :error) do + object + else + {:ok, value} -> + value + + other -> + raise "expected object resolver to return {:ok, term} or :error, got: #{inspect(other)}" + end + end + + defp resolve_object(item, _state), do: item + + defp built_in_resolver(%{constructor: "builtins.getattr", args: [%Global{} = global, name]}) do + {:ok, Global.new(global, name)} + end + + defp built_in_resolver(%{constructor: "builtins.bytearray", args: args}) do + case args do + [] -> {:ok, <<>>} + [binary] -> {:ok, binary} + end + end + + defp built_in_resolver(%{constructor: "_codecs.encode", args: [binary, "latin1"]}) do + # In protocol <= 2 bytes are stored as a string and deserialized by encoding + {:ok, :unicode.characters_to_binary(binary, :utf8, :latin1)} + end + + defp built_in_resolver(_), do: :error + + defp read_line(binary) do + [line, rest] = :binary.split(binary, "\n") + {line, rest} + end + + defp stack_items_to_pairs(items) do + items + |> Enum.chunk_every(2) + |> Enum.reverse() + |> Enum.map(fn [val, key] -> {key, val} end) + end + + defp load_persistent_id(state, id) do + if resolver = state.persistent_id_resolver do + resolver.(id) + else + raise "encountered persistent id: #{inspect(id)}, but no resolver was specified. " <> + "Make sure to pass the :persistent_id_resolver option" + end + end + + defp unsupported_out_of_bound_buffers!() do + # The out-of-band buffer mechanism is designed primarily for cases + # where the pickle stream is sent between Python processes, rather + # than persisted to a file, and it aims to to reduce memory copies. + # + # We focus on mere deserialization, so this feature is not relevant + # for our implementation. + # + # [1]: https://peps.python.org/pep-0574 + + raise "out-of-band buffers are not supported" + end + + defp unsupported_extension_registry!() do + # The extension registry is a mechanism for reducing the pickle + # size by replacing common (, ) refernces with a + # single numerical code. An extension defines such mapping, but + # since pickles are meant to be context-free, this doesn't seem + # to be used in practice. + # + # If there is ever a set of standardized extensions we can handle + # those and also support an option for user-defined extensions. + # + # [1]: https://peps.python.org/pep-0307/#the-extension-registry + # [2]: https://github.com/python/cpython/blob/3.11/Lib/copyreg.py#L164-L171 + + raise "pickle extension registry is not supported" + end +end diff --git a/deps/unpickler/lib/unpickler/global.ex b/deps/unpickler/lib/unpickler/global.ex new file mode 100644 index 0000000000000000000000000000000000000000..9c9503576c504ab4e4c49092cfccce921e9f8595 --- /dev/null +++ b/deps/unpickler/lib/unpickler/global.ex @@ -0,0 +1,20 @@ +defmodule Unpickler.Global do + @moduledoc """ + Represents a reference to a global class or function. + """ + + defstruct [:scope, :name] + + @doc false + def new(scope, name) do + %__MODULE__{scope: scope, name: name} + end + + @doc false + def path(global) do + scope_to_path(global.scope) <> "." <> global.name + end + + defp scope_to_path(scope) when is_binary(scope), do: scope + defp scope_to_path(%__MODULE__{} = scope), do: path(scope) +end diff --git a/deps/unpickler/lib/unpickler/object.ex b/deps/unpickler/lib/unpickler/object.ex new file mode 100644 index 0000000000000000000000000000000000000000..bdbe51421db892f178234a0531d78f8db34d3072 --- /dev/null +++ b/deps/unpickler/lib/unpickler/object.ex @@ -0,0 +1,56 @@ +defmodule Unpickler.Object do + @moduledoc """ + Represents a Python object. + + This struct includes all the information that would be used for + object reconstruction. Refer to the pickle documentation for more + details. + + ## Information + + The following fields are available: + + * `:constructor` - name of the class or function called to build + the object + + * `:args` - a list of arguments passed to the constructor + + * `:kwargs` - a map with keyword arguments passed to the constructor + + * `:state` - a value passed to the `__setstate__` method if applicable + + * `:append_items` - a list of values to append to the object + + * `:set_items` - a list of key-value pairs to set on the object + + """ + + defstruct [:constructor, :args, :kwargs, :state, :append_items, :set_items] + + @doc false + def new(global, args, kwargs) do + %__MODULE__{ + constructor: Unpickler.Global.path(global), + args: args, + kwargs: kwargs, + state: nil, + append_items: [], + set_items: [] + } + end + + @doc false + def set_state(object, state) do + %{object | state: state} + end + + @doc false + def append_many(object, items) do + update_in(object.append_items, &(&1 ++ items)) + end + + @doc false + def set_many(object, pairs) do + update_in(object.set_items, &(&1 ++ pairs)) + end +end diff --git a/deps/unpickler/mix.exs b/deps/unpickler/mix.exs new file mode 100644 index 0000000000000000000000000000000000000000..55b3dc77df6b9a1c24f89c96397e69e30e0cf918 --- /dev/null +++ b/deps/unpickler/mix.exs @@ -0,0 +1,51 @@ +defmodule Unpickler.MixProject do + use Mix.Project + + @version "0.1.0" + @description "A library for loading data in the Python's pickle format" + + def project do + [ + app: :unpickler, + version: @version, + description: @description, + name: "Unpickler", + elixir: "~> 1.7", + start_permanent: Mix.env() == :prod, + deps: deps(), + docs: docs(), + package: package() + ] + end + + def application do + [] + end + + defp deps do + [ + {:ex_doc, "~> 0.29", only: :dev, runtime: false} + ] + end + + defp docs do + [ + main: "Unpickler", + source_url: "https://github.com/dashbitco/unpickler", + source_ref: "v#{@version}", + extras: ["notebooks/examples.livemd"], + groups_for_modules: [ + Types: [Unpickler.Global, Unpickler.Object] + ] + ] + end + + def package do + [ + licenses: ["Apache-2.0"], + links: %{ + "GitHub" => "https://github.com/dashbitco/unpickler" + } + ] + end +end