(obj, f, protocol)
| 421 | |
| 422 | |
| 423 | def _pickle_save(obj, f, protocol): |
| 424 | # TODO(weixin):add support for BytesIO. |
| 425 | if not isinstance(protocol, int): |
| 426 | raise ValueError( |
| 427 | f"The 'protocol' MUST be `int`, but received {type(protocol)}" |
| 428 | ) |
| 429 | |
| 430 | if protocol < 2 or protocol > 4: |
| 431 | raise ValueError( |
| 432 | f"Expected 1<'protocol'<5, but received protocol={protocol}" |
| 433 | ) |
| 434 | |
| 435 | def reduce_varbase(self): |
| 436 | if ( |
| 437 | self.is_dense() |
| 438 | and self.place.is_custom_place() |
| 439 | and core.is_compiled_with_custom_device('npu') |
| 440 | ): |
| 441 | data = np.array(paddle._C_ops.npu_identity(self, -1).cpu()) |
| 442 | else: |
| 443 | data = np.array(self.cpu()) |
| 444 | name = self.name |
| 445 | |
| 446 | return (tuple, ((name, data),)) |
| 447 | |
| 448 | def reduce_DenseTensor(self): |
| 449 | p = core.Place() |
| 450 | p.set_place(paddle.CPUPlace()) |
| 451 | if self._place().is_custom_place(): |
| 452 | data = np.array(paddle._C_ops.npu_identity(self, -1)._copy(p)) |
| 453 | else: |
| 454 | data = np.array(self._copy(p)) |
| 455 | |
| 456 | return (_reconstruct_dense_tensor_data, (data,)) |
| 457 | |
| 458 | def reduce_Layer(self): |
| 459 | raise ValueError( |
| 460 | "paddle do not support saving `paddle.nn.Layer` object." |
| 461 | ) |
| 462 | |
| 463 | dispatch_table_layer = {} |
| 464 | |
| 465 | def create_layer_dispatch_table(layer): |
| 466 | dispatch_table_layer[layer.__class__] = reduce_Layer |
| 467 | return layer |
| 468 | |
| 469 | _parse_every_object( |
| 470 | obj, |
| 471 | lambda v: isinstance(v, paddle.nn.Layer), |
| 472 | create_layer_dispatch_table, |
| 473 | ) |
| 474 | |
| 475 | def add_dispatch_table(): |
| 476 | # This is not a good method, because the pickle module has been modified. |
| 477 | pickle.dispatch_table[core.eager.Tensor] = reduce_varbase |
| 478 | pickle.dispatch_table[EagerParamBase] = reduce_varbase |
| 479 | pickle.dispatch_table[core.DenseTensor] = reduce_DenseTensor |
| 480 | pickle.dispatch_table.update(dispatch_table_layer) |
no test coverage detected