secretflow.utils#
secretflow.utils.cloudpickle#
This file mainly borrows from ray.cloudpickle.cloudpickle_fast.py.
We introduce a custom serialization omitting code positions, e.g., function filename, first line no, .etc.
It is useful for some scenarios that need to generate the signature of a function deterministicly and is used to sign python functions to execute in TEE.
Classes:
|
Functions:
|
Serialize obj as a string of bytes allocated in memory. |
- class secretflow.utils.cloudpickle.CodePositionIndependentCloudPickler(file, protocol=None, buffer_callback=None)[源代码]#
基类:
CloudPickler
Attributes:
Methods:
dump
(obj)Write a pickled representation of the given object to the open file.
__init__
(file[, protocol, buffer_callback])reducer_override
(obj)Type-agnostic reducing callback for function and classes.
- dispatch_table = ChainMap({<class 'classmethod'>: <function _classmethod_reduce>, <class '_io.TextIOWrapper'>: <function _file_reduce>, <class 'logging.Logger'>: <function _logger_reduce>, <class 'logging.RootLogger'>: <function _root_logger_reduce>, <class 'memoryview'>: <function _memoryview_reduce>, <class 'property'>: <function _property_reduce>, <class 'staticmethod'>: <function _classmethod_reduce>, <class 'cell'>: <function _cell_reduce>, <class 'code'>: <function _code_reduce>, <class 'getset_descriptor'>: <function _getset_descriptor_reduce>, <class 'module'>: <function _module_reduce>, <class 'method'>: <function _method_reduce>, <class 'mappingproxy'>: <function _mappingproxy_reduce>, <class '_weakrefset.WeakSet'>: <function _weakset_reduce>, <class 'typing.TypeVar'>: <function _typevar_reduce>, <class 'dict_keys'>: <function _dict_keys_reduce>, <class 'dict_values'>: <function _dict_values_reduce>, <class 'dict_items'>: <function _dict_items_reduce>, <class 'odict_keys'>: <function _odict_keys_reduce>, <class 'odict_values'>: <function _odict_values_reduce>, <class 'odict_items'>: <function _odict_items_reduce>}, {<class 'complex'>: <function pickle_complex>, <class 're.Pattern'>: <function _pickle>, <class 'soupsieve.css_types.Selector'>: <function _pickle>, <class 'soupsieve.css_types.SelectorNull'>: <function _pickle>, <class 'soupsieve.css_types.SelectorTag'>: <function _pickle>, <class 'soupsieve.css_types.SelectorAttribute'>: <function _pickle>, <class 'soupsieve.css_types.SelectorContains'>: <function _pickle>, <class 'soupsieve.css_types.SelectorNth'>: <function _pickle>, <class 'soupsieve.css_types.SelectorLang'>: <function _pickle>, <class 'soupsieve.css_types.SelectorList'>: <function _pickle>, <class 'soupsieve.css_match.SoupSieve'>: <function _pickle>, <class 'numpy.ufunc'>: <function _ufunc_reduce>, <class 'numpy._DTypeMeta'>: <function _DType_reduce>, <class 'uarray._Function'>: <function pickle_function>, <class 'uarray._BackendState'>: <function pickle_state>, <class 'uarray._SetBackendContext'>: <function pickle_set_backend_context>, <class 'uarray._SkipBackendContext'>: <function pickle_skip_backend_context>, <class 'torch.layout'>: <function <lambda>>})#
- reducer_override(obj)[源代码]#
Type-agnostic reducing callback for function and classes.
For performance reasons, subclasses of the C _pickle.Pickler class cannot register custom reducers for functions and classes in the dispatch_table. Reducer for such types must instead implemented in the special reducer_override method.
Note that method will be called for any object except a few builtin-types (int, lists, dicts etc.), which differs from reducers in the Pickler’s dispatch_table, each of them being invoked for objects of a specific type only.
This property comes in handy for classes: although most classes are instances of the
type
metaclass, some of them can be instances of other custom metaclasses (such as enum.EnumMeta for example). In particular, the metaclass will likely not be known in advance, and thus cannot be special-cased using an entry in the dispatch_table. reducer_override, among other things, allows us to register a reducer that will be called for any class, independently of its type.Notes:
reducer_override has the priority over dispatch_table-registered
reducers. * reducer_override can be used to fix other limitations of
cloudpickle for other types that suffered from type-specific reducers, such as Exceptions. See cloudpipe/cloudpickle#248
secretflow.utils.compressor#
Classes:
Abstract base class for cross device data compressor |
|
|
|
|
Random sparse compressor compress data by randomly set element to zero. |
|
Topk sparse compressor use topK algorithm to transfer dense matrix into sparse matrix. |
|
Stc sparser, sample TopK element from original Weights TODO: rewrite in sl compress manner |
|
Stc sparser, sample TopK element from original Weights TODO: rewrite in sl compress manner |
Functions:
|
Encode the sparse matrix |
|
Decode the compressed sparse matrix |
- class secretflow.utils.compressor.Compressor[源代码]#
基类:
ABC
Abstract base class for cross device data compressor
Methods:
compress
(data)Compress data before send.
decompress
(data)Decompress data after receive.
iscompressed
(data)Checks whether data or data array has been compressed.
- abstract compress(data: Union[ndarray, List[ndarray]]) Union[Any, List[Any]] [源代码]#
Compress data before send.
- 参数:
data (Union[np.ndarray, List[np.ndarray]]) – data need to compress.
- 返回:
compressed data.
- 返回类型:
Union[Any, List[Any]]
- class secretflow.utils.compressor.SparseCompressor(sparse_rate: float)[源代码]#
基类:
Compressor
Methods:
__init__
(sparse_rate)Initialize
compress
(data)Compress data to sparse matrix before send.
decompress
(data)Decompress data from sparse matrix to dense after received.
iscompressed
(data)Checks whether data or data array has been compressed.
- compress(data: Union[ndarray, List[ndarray]]) Union[spmatrix, List[spmatrix]] [源代码]#
Compress data to sparse matrix before send.
- 参数:
data (Union[np.ndarray, List[np.ndarray]]) – data need to compress.
- 返回:
compressed data.
- 返回类型:
Union[sparse.spmatrix, List[sparse.spmatrix]]
- class secretflow.utils.compressor.RandomSparse(sparse_rate: float)[源代码]#
-
Random sparse compressor compress data by randomly set element to zero.
Methods:
__init__
(sparse_rate)Initialize
- class secretflow.utils.compressor.TopkSparse(sparse_rate: float)[源代码]#
-
Topk sparse compressor use topK algorithm to transfer dense matrix into sparse matrix.
Methods:
__init__
(sparse_rate)Initialize
- class secretflow.utils.compressor.STCSparse(sparse_rate: float)[源代码]#
基类:
object
Stc sparser, sample TopK element from original Weights TODO: rewrite in sl compress manner
Methods:
__init__
(sparse_rate)
- class secretflow.utils.compressor.SCRSparse(threshold: float)[源代码]#
基类:
object
Stc sparser, sample TopK element from original Weights TODO: rewrite in sl compress manner
Methods:
__init__
(threshold)get_dimension
(index_value, threshold)
secretflow.utils.errors#
Exceptions:
Raise when already exists. |
|
Raise when invalid argument. |
|
Raise if not found. |
|
Raise if party not found. |
|
Raise when unexpected. |
|
Raise if http code is not 200 |
secretflow.utils.hash#
Functions:
|
secretflow.utils.io#
Functions:
|
get rows count from file |
secretflow.utils.logging#
Functions:
|
|
secretflow.utils.ndarray_bigint#
Functions:
|
|
|
|
|
|
|
Classes:
|
secretflow.utils.ndarray_encoding#
Functions:
|
Encode float ndarray to uint64 finite field. |
|
Decode ndarray from uint64 finite field to the float. |
- secretflow.utils.ndarray_encoding.encode(m: ndarray, fxp_bits: int) ndarray [源代码]#
Encode float ndarray to uint64 finite field. Float will times 2**fxp_bits firstly.
- 参数:
m (np.ndarray) – the ndarray to encode.
fraction_precision (int) – keep how many decimal digits after the dot. Must provide if ndarray dtype is float.
- 返回:
the encoded ndarray.
- 返回类型:
np.ndarray
- secretflow.utils.ndarray_encoding.decode(m: ndarray, fxp_bits: int) ndarray [源代码]#
Decode ndarray from uint64 finite field to the float. Fraction precision shall be corresponding to encoding fraction precision.
- 参数:
m (np.ndarray) – the ndarray to decode.
fxp_bits (int) – the decimal digits to keep when encoding float. Must provide if the original dtype is float.
- 返回:
the decoded float ndarray.
- 返回类型:
np.ndarray
secretflow.utils.random#
Functions:
|
secretflow.utils.ray_compatibility#
Functions:
Whther the current ray version is less 2.0.0. |
secretflow.utils.sigmoid#
Functions:
|
taylor series referenced from: https://mortendahl.github.io/2017/04/17/private-deep-learning-with-mpc/ |
|
taylor series referenced from: https://mortendahl.github.io/2017/04/17/private-deep-learning-with-mpc/ |
|
taylor series referenced from: https://mortendahl.github.io/2017/04/17/private-deep-learning-with-mpc/ |
|
f(x) = 0.5 + 0.125x if -4 <= x <= 4 |
|
https://dergipark.org.tr/en/download/article-file/54559 Dataflow implementation of sigmoid function: F(x) = 0.5 * ( x / ( 1 + |x| ) ) + 0.5 df_sig has higher precision than sr_sig if x in [-2, 2] |
|
https://en.wikipedia.org/wiki/Sigmoid_function#Examples Square Root approximation functions: F(x) = 0.5 * ( x / ( 1 + x^2 )^0.5 ) + 0.5 sr_sig almost perfect fit to sigmoid if x out of range [-3,3] |
|
Polynomial fitting |
|
mix ls7 & sr sig, use ls7 if |x| < 4 , else use sr. |
|
|
|
Classes:
|
An enumeration. |
- secretflow.utils.sigmoid.t1_sig(x, limit: bool = True)[源代码]#
taylor series referenced from: https://mortendahl.github.io/2017/04/17/private-deep-learning-with-mpc/
- secretflow.utils.sigmoid.t3_sig(x, limit: bool = True)[源代码]#
taylor series referenced from: https://mortendahl.github.io/2017/04/17/private-deep-learning-with-mpc/
- secretflow.utils.sigmoid.t5_sig(x, limit: bool = True)[源代码]#
taylor series referenced from: https://mortendahl.github.io/2017/04/17/private-deep-learning-with-mpc/
- secretflow.utils.sigmoid.seg3_sig(x)[源代码]#
- f(x) = 0.5 + 0.125x if -4 <= x <= 4
1 if x > 4 0 if -4 > x
- secretflow.utils.sigmoid.df_sig(x)[源代码]#
https://dergipark.org.tr/en/download/article-file/54559 Dataflow implementation of sigmoid function: F(x) = 0.5 * ( x / ( 1 + |x| ) ) + 0.5 df_sig has higher precision than sr_sig if x in [-2, 2]
- secretflow.utils.sigmoid.sr_sig(x)[源代码]#
https://en.wikipedia.org/wiki/Sigmoid_function#Examples Square Root approximation functions: F(x) = 0.5 * ( x / ( 1 + x^2 )^0.5 ) + 0.5 sr_sig almost perfect fit to sigmoid if x out of range [-3,3]
- secretflow.utils.sigmoid.mix_sig(x)[源代码]#
mix ls7 & sr sig, use ls7 if |x| < 4 , else use sr. has higher precision in all input range. NOTICE: this method is very expensive, only use for hessian matrix.
secretflow.utils.testing#
Functions:
Return an unused port |
|
|
Generate SPU cluster_def for testing purposes. |
|
- secretflow.utils.testing.cluster_def(parties: List[str], runtime_config=None) Dict[str, Any] [源代码]#
Generate SPU cluster_def for testing purposes.
- 参数:
parties (List[str]) – parties of SPU devices. Must be more than 1 party,
runtime_config (optional) –
runtime_config of SPU device. More details refer to
- Defaults to None and use default runtime config.
If 3 parties are present, protocol would be set to ABY3 and field to FM128.
2. Otherwise, protocol would be set to SEMI2k and field to FM128. Other options are using default values.
- 返回:
An SPU cluster_def to initiate an SPU device.
- 返回类型:
Dict[str, Any]