Skip to content
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

[nnx] add PathContains Filter #4011

Merged
merged 1 commit into from
Jun 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions flax/nnx/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from .nnx import compat as compat
from .nnx import traversals as traversals
from .nnx.filterlib import All as All
from .nnx.filterlib import PathContains as PathContains
from .nnx.filterlib import Not as Not
from .nnx.graph import GraphDef as GraphDef
from .nnx.graph import GraphState as GraphState
Expand Down
9 changes: 8 additions & 1 deletion flax/nnx/nnx/filterlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import builtins
import dataclasses
from flax.typing import PathParts
from flax.typing import Key, PathParts
import typing as tp

if tp.TYPE_CHECKING:
Expand Down Expand Up @@ -66,6 +66,13 @@ class WithTag:
def __call__(self, path: PathParts, x: tp.Any):
return isinstance(x, _HasTag) and x.tag == self.tag

@dataclasses.dataclass
class PathContains:
key: Key

def __call__(self, path: PathParts, x: tp.Any):
return self.key in path


@dataclasses.dataclass
class OfType:
Expand Down
33 changes: 33 additions & 0 deletions flax/nnx/tests/filters_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# Copyright 2024 The Flax Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from absl.testing import absltest

from flax import nnx


class TestFilters(absltest.TestCase):
def test_path_contains(self):
class Model(nnx.Module):
def __init__(self, rngs):
self.backbone = nnx.Linear(2, 3, rngs=rngs)
self.head = nnx.Linear(3, 10, rngs=rngs)

model = Model(nnx.Rngs(0))

head_state = nnx.state(model, nnx.PathContains('head'))

self.assertIn('head', head_state)
self.assertNotIn('backbone', head_state)
Loading