Comments (2)
Hey @cgarciae , thanks for the FR! In general we try to keep Haiku fairly lean and encourage features (e.g. training loops, optimizers etc) to be solved in other libraries (then they can benefit all JAX users not just Haiku users) or built from existing Haiku/JAX features.
Wrt using existing features, you might consider using hk.set_state
for this. This is a fairly general mechanism in Haiku for logging values associated with modules. You could use hk.data_structures.filter
to extract all losses from the state dict:
def f(x):
y = hk.nets.ResNet50(1000)(x, True)
loss_1 = y.sum()
loss_2 = loss_1 ** 2
hk.set_state("loss_1", loss_1)
return loss_2
f = hk.transform_with_state(f)
rng = jax.random.PRNGKey(42)
x = jnp.ones([1, 224, 224, 3])
params, state = f.init(rng, x)
# Apply as usual:
params, state = f.apply(params, state, rng, x)
# Extract losses from state:
is_loss = lambda m, n, v: n.startswith("loss")
losses = hk.data_structures.filter(is_loss, state)
print(losses) # frozendict({'~': frozendict({'loss_1': DeviceArray(0., dtype=float32)})})
If you want to implement this as a standalone feature (e.g. decoupled from hk.set_state
) then I've forked the following from @ibab who has implemented something similar (his version is more robust with thread safety and nesting).
from contextlib import contextmanager
loggers = []
@contextmanager
def context():
data = {}
loggers.append(data)
try:
yield data
finally:
loggers.pop()
def log(name, value):
# NOTE: log(..) ignored when not logging.
if loggers:
data = loggers[-1]
data[name] = value
def f(x):
x = x ** 2
log("a", x)
x = x ** 2
log("b", x)
return x
def g():
with context() as data:
y = f(2)
return y, data
y, data = g()
assert y == 16
assert data == {'a': 4, 'b': 16}
I hope that's useful, please feel free to reopen if this does not solve your usecase.
from dm-haiku.
Thanks for the info @tomhennigan ! I think set_state
+ filters can achieve what I am looking for :)
I didn't realize set_state
could be called without a corresponding get_state
.
I still think a first class logger would be nice / less error prone but fortunately its not a blocker.
from dm-haiku.
Related Issues (20)
- More fine-grained mixed-precision configuration HOT 2
- Suggestion: alias `Transformed`(WithState) apply to __call__ HOT 2
- Is there a way to load parameters from Flax model? HOT 2
- Support model examples HOT 7
- Change to jax.interpreters.xla for JAX==0.4.14 HOT 3
- Warning: hk.LayerNorm when used in transformer decoder causes violation of autoregressive property HOT 1
- Reservoir Computing with Haiku
- Efficiency difference in using jax.lax.fori_loop vs looping over identical layers? HOT 2
- Please publish requirements.txt fix to pip
- How to use `apply` with additional parameters? HOT 1
- hk.Conv2DTranspose takes FOREVER to initialize and compile HOT 1
- 0.4.16 timeline HOT 2
- How to export haiku network parameters into Pytorch network?
- Modules got silently "reused" with `hk.vmap` HOT 2
- Wrong gradients in a Haiku network
- Direct Feedback Alignment
- Issue with wheels including docs and examples folder
- `haiku.experimental.flax` is not part of newest pip release HOT 1
- Train multiple hk.nets.MLP with one optimizer HOT 2
- TypeError: 'type' object is not subscriptable HOT 4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from dm-haiku.