-
Notifications
You must be signed in to change notification settings - Fork 123
Correct implementation of weight tying #625
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
seanmor5
wants to merge
1
commit into
main
Choose a base branch
from
real-weight-tying
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -916,23 +916,11 @@ defmodule Axon.Compiler do | |||||||||||||||||||||||||
| else | ||||||||||||||||||||||||||
| # Parameters are just accessed in the layer sub-map of the nested | ||||||||||||||||||||||||||
| # parameter map, so we just need to extract them and then apply | ||||||||||||||||||||||||||
| # freezing and dtype policy | ||||||||||||||||||||||||||
| # freezing and dtype policy. Parameters may be SharedParameter | ||||||||||||||||||||||||||
| # structs for tied weights, which are resolved to their source. | ||||||||||||||||||||||||||
| parameter_inputs = | ||||||||||||||||||||||||||
| Enum.map(layer_params, fn %{name: v, frozen: frz} -> | ||||||||||||||||||||||||||
| param = params[name][v] | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| cond do | ||||||||||||||||||||||||||
| param != nil -> | ||||||||||||||||||||||||||
| safe_policy_cast(maybe_freeze(param, frz), policy, :compute) | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| true -> | ||||||||||||||||||||||||||
| raise ArgumentError, | ||||||||||||||||||||||||||
| "parameter #{inspect(v)} for layer: #{inspect(name)} in" <> | ||||||||||||||||||||||||||
| " was not present in the given parameter map, this can" <> | ||||||||||||||||||||||||||
| " happen if you are using parameters intended for another" <> | ||||||||||||||||||||||||||
| " model or did not initialize portions of your model with" <> | ||||||||||||||||||||||||||
| " Axon.init/3" | ||||||||||||||||||||||||||
| end | ||||||||||||||||||||||||||
| resolve_parameter!(params, name, v, frz, policy) | ||||||||||||||||||||||||||
| end) | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| # Reorder the inputs according to the original input ordering | ||||||||||||||||||||||||||
|
|
@@ -1188,5 +1176,42 @@ defmodule Axon.Compiler do | |||||||||||||||||||||||||
| defp propagating_none?(%Axon.None{__propagate__: true}), do: true | ||||||||||||||||||||||||||
| defp propagating_none?(_), do: false | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| defp resolve_parameter!(params, layer_name, param_name, freeze?, policy) do | ||||||||||||||||||||||||||
| # Special case where this is a SharedParameter at the layer level, so we | ||||||||||||||||||||||||||
| # need to resolve that before forwarding. Otherwise this falls through and | ||||||||||||||||||||||||||
| # is handled at the next step | ||||||||||||||||||||||||||
| layer_params = | ||||||||||||||||||||||||||
| with %Axon.ModelState.SharedParameter{path: path} <- params[layer_name] do | ||||||||||||||||||||||||||
| get_in(params, path) | ||||||||||||||||||||||||||
| end | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| parameter = | ||||||||||||||||||||||||||
| case layer_params[param_name] do | ||||||||||||||||||||||||||
| nil -> | ||||||||||||||||||||||||||
| raise ArgumentError, | ||||||||||||||||||||||||||
| "parameter #{inspect(param_name)} for layer: #{inspect(layer_name)}" <> | ||||||||||||||||||||||||||
| " was not present in the given parameter map, this can" <> | ||||||||||||||||||||||||||
| " happen if you are using parameters intended for another" <> | ||||||||||||||||||||||||||
| " model or did not initialize portions of your model with" <> | ||||||||||||||||||||||||||
| " Axon.init/3" | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| %Axon.ModelState.SharedParameter{path: path, transform: transform} -> | ||||||||||||||||||||||||||
| tensor = | ||||||||||||||||||||||||||
| with nil <- get_in(params, path) do | ||||||||||||||||||||||||||
| raise ArgumentError, | ||||||||||||||||||||||||||
| "shared parameter for #{inspect(param_name)} in layer:" <> | ||||||||||||||||||||||||||
| " #{inspect(layer_name)}, references non-existent parameter" <> | ||||||||||||||||||||||||||
| " #{inspect(path)}" | ||||||||||||||||||||||||||
| end | ||||||||||||||||||||||||||
|
Comment on lines
+1200
to
+1205
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| if transform, do: transform.(tensor), else: tensor | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| parameter -> | ||||||||||||||||||||||||||
| parameter | ||||||||||||||||||||||||||
| end | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| safe_policy_cast(maybe_freeze(parameter, freeze?), policy, :compute) | ||||||||||||||||||||||||||
| end | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| defp us_to_ms(time), do: Float.round(time / 1000, 1) | ||||||||||||||||||||||||||
| end | ||||||||||||||||||||||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| defmodule Axon.ModelState.SharedParameter do | ||
| # Represents a tied or shared parameter for layers whose | ||
| # weights are connected but don't necessarily perform the | ||
| # same operation. This implements the Nx.Container behavior | ||
| # and contains an access path to the parameter that holds the | ||
| # original weight. | ||
|
|
||
| @moduledoc false | ||
|
|
||
| @derive {Nx.Container, containers: [], keep: [:path, :transform]} | ||
| defstruct [:path, :transform] | ||
|
|
||
| def new(path, opts \\ []) do | ||
| %__MODULE__{ | ||
| path: path, | ||
| transform: Keyword.get(opts, :transform) | ||
| } | ||
| end | ||
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,86 @@ | ||
| defmodule Axon.ModelStateTest do | ||
| use ExUnit.Case, async: true | ||
|
|
||
| alias Axon.ModelState | ||
|
|
||
| describe "tie/4" do | ||
| test "creates shared parameter at destination path" do | ||
| model = | ||
| Axon.input("input", shape: {nil, 2}) | ||
| |> Axon.dense(4, name: "dense_0") | ||
| |> Axon.dense(4, name: "dense_1") | ||
|
|
||
| {init_fn, _} = Axon.build(model) | ||
| model_state = init_fn.(Nx.template({1, 2}, :f32), ModelState.empty()) | ||
|
|
||
| tied = ModelState.tie(model_state, ["dense_1", "kernel"], ["dense_0", "kernel"]) | ||
|
|
||
| assert %Axon.ModelState.SharedParameter{path: ["dense_0", "kernel"], transform: nil} = | ||
| tied.data["dense_1"]["kernel"] | ||
| end | ||
|
|
||
| test "stores transform function" do | ||
| model = | ||
| Axon.input("input", shape: {nil, 2}) | ||
| |> Axon.dense(4, name: "dense_0") | ||
| |> Axon.dense(4, name: "dense_1") | ||
|
|
||
| {init_fn, _} = Axon.build(model) | ||
| model_state = init_fn.(Nx.template({1, 2}, :f32), ModelState.empty()) | ||
|
|
||
| tied = | ||
| ModelState.tie( | ||
| model_state, | ||
| ["dense_1", "kernel"], | ||
| ["dense_0", "kernel"], | ||
| transform: &Nx.transpose/1 | ||
| ) | ||
|
|
||
| assert %Axon.ModelState.SharedParameter{transform: transform} = | ||
| tied.data["dense_1"]["kernel"] | ||
|
|
||
| assert is_function(transform, 1) | ||
| end | ||
| end | ||
|
|
||
| describe "trainable_parameters/1 with tied weights" do | ||
| test "excludes tied parameters" do | ||
| model = | ||
| Axon.input("input", shape: {nil, 2}) | ||
| |> Axon.dense(4, name: "dense_0") | ||
| |> Axon.dense(4, name: "dense_1") | ||
|
|
||
| {init_fn, _} = Axon.build(model) | ||
| model_state = init_fn.(Nx.template({1, 2}, :f32), ModelState.empty()) | ||
|
|
||
| # Before tying, both layers have kernel in trainable params | ||
| trainable_before = ModelState.trainable_parameters(model_state) | ||
| assert Map.has_key?(trainable_before["dense_0"], "kernel") | ||
| assert Map.has_key?(trainable_before["dense_1"], "kernel") | ||
|
|
||
| # After tying, dense_1 kernel should be excluded | ||
| tied = ModelState.tie(model_state, ["dense_1", "kernel"], ["dense_0", "kernel"]) | ||
| trainable_after = ModelState.trainable_parameters(tied) | ||
|
|
||
| assert Map.has_key?(trainable_after["dense_0"], "kernel") | ||
| refute Map.has_key?(trainable_after["dense_1"], "kernel") | ||
| assert Map.has_key?(trainable_after["dense_1"], "bias") | ||
| end | ||
|
|
||
| test "excludes layer when all parameters are tied" do | ||
| model = | ||
| Axon.input("input", shape: {nil, 2}) | ||
| |> Axon.dense(4, name: "dense_0", use_bias: false) | ||
| |> Axon.dense(4, name: "dense_1", use_bias: false) | ||
|
|
||
| {init_fn, _} = Axon.build(model) | ||
| model_state = init_fn.(Nx.template({1, 2}, :f32), ModelState.empty()) | ||
|
|
||
| tied = ModelState.tie(model_state, ["dense_1", "kernel"], ["dense_0", "kernel"]) | ||
| trainable = ModelState.trainable_parameters(tied) | ||
|
|
||
| assert Map.has_key?(trainable, "dense_0") | ||
| refute Map.has_key?(trainable, "dense_1") | ||
| end | ||
| end | ||
| end |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this is slightly more readable