r""" apply(fn) Applies ``fn`` recursively to every submodule (as returned by ``.children()``) as well as self. Typical use includes initializing the parameters of a model. Args: fn (:class:`Module` -> None): function to be applied to each submodu
(self: T, fn: Callable[["Module"], None])
| 1354 | return self |
| 1355 | |
| 1356 | def apply(self: T, fn: Callable[["Module"], None]) -> T: |
| 1357 | r""" |
| 1358 | apply(fn) |
| 1359 | |
| 1360 | Applies ``fn`` recursively to every submodule (as returned by ``.children()``) |
| 1361 | as well as self. Typical use includes initializing the parameters of a model. |
| 1362 | |
| 1363 | Args: |
| 1364 | fn (:class:`Module` -> None): function to be applied to each submodule |
| 1365 | |
| 1366 | Returns: |
| 1367 | Module: self |
| 1368 | |
| 1369 | Example:: |
| 1370 | |
| 1371 | >>> import oneflow as flow |
| 1372 | >>> import oneflow.nn as nn |
| 1373 | >>> @flow.no_grad() |
| 1374 | ... def init_weights(m): |
| 1375 | ... print(m) |
| 1376 | ... if type(m) == nn.Linear: |
| 1377 | ... m.weight.fill_(1.0) |
| 1378 | ... print(m.weight) |
| 1379 | >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) |
| 1380 | >>> net.apply(init_weights) |
| 1381 | Linear(in_features=2, out_features=2, bias=True) |
| 1382 | tensor([[1., 1.], |
| 1383 | [1., 1.]], dtype=oneflow.float32, requires_grad=True) |
| 1384 | Linear(in_features=2, out_features=2, bias=True) |
| 1385 | tensor([[1., 1.], |
| 1386 | [1., 1.]], dtype=oneflow.float32, requires_grad=True) |
| 1387 | Sequential( |
| 1388 | (0): Linear(in_features=2, out_features=2, bias=True) |
| 1389 | (1): Linear(in_features=2, out_features=2, bias=True) |
| 1390 | ) |
| 1391 | Sequential( |
| 1392 | (0): Linear(in_features=2, out_features=2, bias=True) |
| 1393 | (1): Linear(in_features=2, out_features=2, bias=True) |
| 1394 | ) |
| 1395 | """ |
| 1396 | if self.cpg is not None: |
| 1397 | self.cpg = None |
| 1398 | warnings.warn( |
| 1399 | "deleted ContiguousParamsGroup since creating it before " |
| 1400 | "apply operations like to(), to_global() will cause error." |
| 1401 | ) |
| 1402 | |
| 1403 | for module in self.children(): |
| 1404 | module.apply(fn) |
| 1405 | fn(self) |
| 1406 | return self |
| 1407 | |
| 1408 | def to_empty(self: T, *, device: Union[str, flow.device]) -> T: |
| 1409 | r"""Moves the parameters and buffers to the specified device without copying storage. |