maxframe 2.0.0b2__cp37-cp37m-win32.whl → 2.3.0rc1__cp37-cp37m-win32.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of maxframe might be problematic. Click here for more details.
- maxframe/__init__.py +1 -0
- maxframe/_utils.cp37-win32.pyd +0 -0
- maxframe/_utils.pyx +14 -1
- maxframe/codegen/core.py +9 -8
- maxframe/codegen/spe/core.py +1 -1
- maxframe/codegen/spe/dataframe/__init__.py +1 -0
- maxframe/codegen/spe/dataframe/accessors/base.py +18 -0
- maxframe/codegen/spe/dataframe/accessors/dict_.py +25 -130
- maxframe/codegen/spe/dataframe/accessors/list_.py +12 -48
- maxframe/codegen/spe/dataframe/accessors/struct_.py +28 -0
- maxframe/codegen/spe/dataframe/arithmetic.py +7 -2
- maxframe/codegen/spe/dataframe/groupby.py +88 -0
- maxframe/codegen/spe/dataframe/indexing.py +99 -4
- maxframe/codegen/spe/dataframe/merge.py +38 -1
- maxframe/codegen/spe/dataframe/misc.py +11 -33
- maxframe/codegen/spe/dataframe/reduction.py +32 -9
- maxframe/codegen/spe/dataframe/reshape.py +46 -0
- maxframe/codegen/spe/dataframe/sort.py +39 -18
- maxframe/codegen/spe/dataframe/tests/accessors/test_dict.py +9 -15
- maxframe/codegen/spe/dataframe/tests/accessors/test_list.py +4 -7
- maxframe/codegen/spe/dataframe/tests/accessors/test_struct.py +75 -0
- maxframe/codegen/spe/dataframe/tests/indexing/test_iloc.py +20 -1
- maxframe/codegen/spe/dataframe/tests/indexing/test_loc.py +35 -0
- maxframe/codegen/spe/dataframe/tests/misc/test_misc.py +0 -32
- maxframe/codegen/spe/dataframe/tests/test_groupby.py +81 -18
- maxframe/codegen/spe/dataframe/tests/test_merge.py +27 -1
- maxframe/codegen/spe/dataframe/tests/test_reduction.py +13 -0
- maxframe/codegen/spe/dataframe/tests/test_reshape.py +79 -0
- maxframe/codegen/spe/dataframe/tests/test_sort.py +20 -0
- maxframe/codegen/spe/dataframe/tseries.py +9 -0
- maxframe/codegen/spe/learn/contrib/lightgbm.py +4 -3
- maxframe/codegen/spe/learn/contrib/tests/test_xgboost.py +2 -1
- maxframe/codegen/spe/learn/metrics/__init__.py +1 -1
- maxframe/codegen/spe/learn/metrics/_ranking.py +76 -0
- maxframe/codegen/spe/learn/metrics/pairwise.py +51 -0
- maxframe/codegen/spe/learn/metrics/tests/test_pairwise.py +36 -0
- maxframe/codegen/spe/learn/metrics/tests/test_ranking.py +59 -0
- maxframe/codegen/spe/tensor/__init__.py +3 -0
- maxframe/codegen/spe/tensor/datasource.py +1 -0
- maxframe/codegen/spe/tensor/fft.py +74 -0
- maxframe/codegen/spe/tensor/linalg.py +29 -2
- maxframe/codegen/spe/tensor/misc.py +79 -25
- maxframe/codegen/spe/tensor/spatial.py +45 -0
- maxframe/codegen/spe/tensor/statistics.py +44 -0
- maxframe/codegen/spe/tensor/tests/test_fft.py +64 -0
- maxframe/codegen/spe/tensor/tests/test_linalg.py +15 -1
- maxframe/codegen/spe/tensor/tests/test_misc.py +52 -2
- maxframe/codegen/spe/tensor/tests/test_spatial.py +33 -0
- maxframe/codegen/spe/tensor/tests/test_statistics.py +15 -1
- maxframe/codegen/spe/tests/test_spe_codegen.py +6 -12
- maxframe/codegen/spe/utils.py +2 -0
- maxframe/config/config.py +73 -9
- maxframe/config/tests/test_validators.py +13 -1
- maxframe/config/validators.py +49 -0
- maxframe/conftest.py +54 -17
- maxframe/core/accessor.py +2 -2
- maxframe/core/base.py +2 -1
- maxframe/core/entity/core.py +5 -0
- maxframe/core/entity/tileables.py +3 -1
- maxframe/core/graph/core.cp37-win32.pyd +0 -0
- maxframe/core/graph/entity.py +8 -3
- maxframe/core/mode.py +6 -1
- maxframe/core/operator/base.py +9 -2
- maxframe/core/operator/core.py +10 -2
- maxframe/core/operator/utils.py +13 -0
- maxframe/dataframe/__init__.py +12 -5
- maxframe/dataframe/accessors/__init__.py +1 -1
- maxframe/dataframe/accessors/compat.py +45 -0
- maxframe/dataframe/accessors/datetime_/__init__.py +4 -1
- maxframe/dataframe/accessors/dict_/contains.py +7 -16
- maxframe/dataframe/accessors/dict_/core.py +48 -0
- maxframe/dataframe/accessors/dict_/getitem.py +17 -21
- maxframe/dataframe/accessors/dict_/length.py +7 -16
- maxframe/dataframe/accessors/dict_/remove.py +6 -18
- maxframe/dataframe/accessors/dict_/setitem.py +8 -18
- maxframe/dataframe/accessors/dict_/tests/test_dict_accessor.py +62 -22
- maxframe/dataframe/accessors/list_/__init__.py +2 -2
- maxframe/dataframe/accessors/list_/core.py +48 -0
- maxframe/dataframe/accessors/list_/getitem.py +12 -19
- maxframe/dataframe/accessors/list_/length.py +7 -16
- maxframe/dataframe/accessors/list_/tests/test_list_accessor.py +11 -9
- maxframe/dataframe/accessors/string_/__init__.py +4 -1
- maxframe/dataframe/accessors/struct_/__init__.py +37 -0
- maxframe/dataframe/accessors/struct_/accessor.py +39 -0
- maxframe/dataframe/accessors/struct_/core.py +43 -0
- maxframe/dataframe/accessors/struct_/dtypes.py +53 -0
- maxframe/dataframe/accessors/struct_/field.py +123 -0
- maxframe/dataframe/accessors/struct_/tests/__init__.py +13 -0
- maxframe/dataframe/accessors/struct_/tests/test_struct_accessor.py +91 -0
- maxframe/dataframe/arithmetic/__init__.py +18 -4
- maxframe/dataframe/arithmetic/between.py +106 -0
- maxframe/dataframe/arithmetic/dot.py +237 -0
- maxframe/dataframe/arithmetic/maximum.py +33 -0
- maxframe/dataframe/arithmetic/minimum.py +33 -0
- maxframe/dataframe/arithmetic/{around.py → round.py} +11 -7
- maxframe/dataframe/core.py +161 -224
- maxframe/dataframe/datasource/__init__.py +18 -0
- maxframe/dataframe/datasource/core.py +6 -0
- maxframe/dataframe/datasource/direct.py +57 -0
- maxframe/dataframe/datasource/from_dict.py +124 -0
- maxframe/dataframe/datasource/from_index.py +1 -1
- maxframe/dataframe/datasource/from_records.py +77 -0
- maxframe/dataframe/datasource/from_tensor.py +109 -41
- maxframe/dataframe/datasource/read_csv.py +21 -14
- maxframe/dataframe/datasource/read_odps_query.py +29 -6
- maxframe/dataframe/datasource/read_odps_table.py +32 -10
- maxframe/dataframe/datasource/read_parquet.py +38 -39
- maxframe/dataframe/datasource/tests/test_datasource.py +37 -0
- maxframe/dataframe/datastore/__init__.py +11 -1
- maxframe/dataframe/datastore/direct.py +268 -0
- maxframe/dataframe/datastore/to_csv.py +29 -41
- maxframe/dataframe/datastore/to_odps.py +36 -4
- maxframe/dataframe/extensions/__init__.py +20 -4
- maxframe/dataframe/extensions/apply_chunk.py +32 -6
- maxframe/dataframe/extensions/cartesian_chunk.py +153 -0
- maxframe/dataframe/extensions/collect_kv.py +126 -0
- maxframe/dataframe/extensions/extract_kv.py +177 -0
- maxframe/dataframe/extensions/flatjson.py +2 -1
- maxframe/dataframe/extensions/map_reduce.py +263 -0
- maxframe/dataframe/extensions/rebalance.py +62 -0
- maxframe/dataframe/extensions/tests/test_apply_chunk.py +9 -2
- maxframe/dataframe/extensions/tests/test_extensions.py +54 -0
- maxframe/dataframe/extensions/tests/test_map_reduce.py +135 -0
- maxframe/dataframe/groupby/__init__.py +17 -2
- maxframe/dataframe/groupby/aggregation.py +86 -49
- maxframe/dataframe/groupby/apply.py +1 -1
- maxframe/dataframe/groupby/apply_chunk.py +19 -5
- maxframe/dataframe/groupby/core.py +116 -16
- maxframe/dataframe/groupby/cum.py +4 -25
- maxframe/dataframe/groupby/expanding.py +264 -0
- maxframe/dataframe/groupby/fill.py +1 -1
- maxframe/dataframe/groupby/getitem.py +12 -5
- maxframe/dataframe/groupby/head.py +11 -1
- maxframe/dataframe/groupby/rank.py +136 -0
- maxframe/dataframe/groupby/rolling.py +206 -0
- maxframe/dataframe/groupby/shift.py +114 -0
- maxframe/dataframe/groupby/tests/test_groupby.py +0 -5
- maxframe/dataframe/indexing/__init__.py +22 -2
- maxframe/dataframe/indexing/droplevel.py +195 -0
- maxframe/dataframe/indexing/filter.py +169 -0
- maxframe/dataframe/indexing/get_level_values.py +76 -0
- maxframe/dataframe/indexing/iat.py +45 -0
- maxframe/dataframe/indexing/iloc.py +152 -12
- maxframe/dataframe/indexing/insert.py +46 -18
- maxframe/dataframe/indexing/loc.py +287 -7
- maxframe/dataframe/indexing/reindex.py +14 -5
- maxframe/dataframe/indexing/rename.py +6 -0
- maxframe/dataframe/indexing/rename_axis.py +2 -2
- maxframe/dataframe/indexing/reorder_levels.py +143 -0
- maxframe/dataframe/indexing/reset_index.py +33 -6
- maxframe/dataframe/indexing/sample.py +8 -0
- maxframe/dataframe/indexing/setitem.py +3 -3
- maxframe/dataframe/indexing/swaplevel.py +185 -0
- maxframe/dataframe/indexing/take.py +99 -0
- maxframe/dataframe/indexing/truncate.py +140 -0
- maxframe/dataframe/indexing/where.py +0 -11
- maxframe/dataframe/indexing/xs.py +148 -0
- maxframe/dataframe/merge/__init__.py +15 -1
- maxframe/dataframe/merge/append.py +97 -98
- maxframe/dataframe/merge/combine.py +244 -0
- maxframe/dataframe/merge/combine_first.py +120 -0
- maxframe/dataframe/merge/compare.py +387 -0
- maxframe/dataframe/merge/concat.py +183 -0
- maxframe/dataframe/merge/update.py +271 -0
- maxframe/dataframe/misc/__init__.py +28 -11
- maxframe/dataframe/misc/_duplicate.py +10 -4
- maxframe/dataframe/misc/apply.py +1 -1
- maxframe/dataframe/misc/check_unique.py +82 -0
- maxframe/dataframe/misc/clip.py +145 -0
- maxframe/dataframe/misc/describe.py +175 -9
- maxframe/dataframe/misc/drop.py +31 -0
- maxframe/dataframe/misc/drop_duplicates.py +2 -2
- maxframe/dataframe/misc/duplicated.py +2 -2
- maxframe/dataframe/misc/get_dummies.py +5 -1
- maxframe/dataframe/misc/infer_dtypes.py +251 -0
- maxframe/dataframe/misc/isin.py +2 -2
- maxframe/dataframe/misc/map.py +125 -18
- maxframe/dataframe/misc/repeat.py +159 -0
- maxframe/dataframe/misc/tests/test_misc.py +48 -3
- maxframe/dataframe/misc/to_numeric.py +3 -0
- maxframe/dataframe/misc/transform.py +12 -5
- maxframe/dataframe/misc/transpose.py +13 -1
- maxframe/dataframe/misc/valid_index.py +115 -0
- maxframe/dataframe/misc/value_counts.py +38 -4
- maxframe/dataframe/missing/checkna.py +14 -6
- maxframe/dataframe/missing/dropna.py +5 -0
- maxframe/dataframe/missing/fillna.py +1 -1
- maxframe/dataframe/missing/replace.py +7 -4
- maxframe/dataframe/reduction/__init__.py +35 -16
- maxframe/dataframe/reduction/aggregation.py +43 -14
- maxframe/dataframe/reduction/all.py +2 -2
- maxframe/dataframe/reduction/any.py +2 -2
- maxframe/dataframe/reduction/argmax.py +103 -0
- maxframe/dataframe/reduction/argmin.py +103 -0
- maxframe/dataframe/reduction/core.py +80 -24
- maxframe/dataframe/reduction/count.py +13 -9
- maxframe/dataframe/reduction/cov.py +166 -0
- maxframe/dataframe/reduction/cummax.py +2 -2
- maxframe/dataframe/reduction/cummin.py +2 -2
- maxframe/dataframe/reduction/cumprod.py +2 -2
- maxframe/dataframe/reduction/cumsum.py +2 -2
- maxframe/dataframe/reduction/custom_reduction.py +2 -2
- maxframe/dataframe/reduction/idxmax.py +185 -0
- maxframe/dataframe/reduction/idxmin.py +185 -0
- maxframe/dataframe/reduction/kurtosis.py +37 -30
- maxframe/dataframe/reduction/max.py +2 -2
- maxframe/dataframe/reduction/mean.py +9 -7
- maxframe/dataframe/reduction/median.py +2 -2
- maxframe/dataframe/reduction/min.py +2 -2
- maxframe/dataframe/reduction/mode.py +144 -0
- maxframe/dataframe/reduction/nunique.py +19 -11
- maxframe/dataframe/reduction/prod.py +18 -13
- maxframe/dataframe/reduction/reduction_size.py +2 -2
- maxframe/dataframe/reduction/sem.py +13 -9
- maxframe/dataframe/reduction/skew.py +31 -27
- maxframe/dataframe/reduction/str_concat.py +10 -7
- maxframe/dataframe/reduction/sum.py +18 -14
- maxframe/dataframe/reduction/tests/test_reduction.py +12 -0
- maxframe/dataframe/reduction/unique.py +20 -3
- maxframe/dataframe/reduction/var.py +16 -12
- maxframe/dataframe/reshape/__init__.py +38 -0
- maxframe/dataframe/{misc → reshape}/pivot.py +1 -0
- maxframe/dataframe/{misc → reshape}/pivot_table.py +1 -0
- maxframe/dataframe/reshape/unstack.py +114 -0
- maxframe/dataframe/sort/__init__.py +16 -1
- maxframe/dataframe/sort/argsort.py +68 -0
- maxframe/dataframe/sort/core.py +2 -1
- maxframe/dataframe/sort/nlargest.py +238 -0
- maxframe/dataframe/sort/nsmallest.py +228 -0
- maxframe/dataframe/sort/rank.py +147 -0
- maxframe/dataframe/statistics/__init__.py +3 -3
- maxframe/dataframe/statistics/corr.py +1 -0
- maxframe/dataframe/statistics/quantile.py +2 -2
- maxframe/dataframe/tests/test_typing.py +104 -0
- maxframe/dataframe/tests/test_utils.py +66 -2
- maxframe/dataframe/tseries/__init__.py +19 -0
- maxframe/dataframe/tseries/at_time.py +61 -0
- maxframe/dataframe/tseries/between_time.py +122 -0
- maxframe/dataframe/typing_.py +185 -0
- maxframe/dataframe/utils.py +125 -52
- maxframe/dataframe/window/aggregation.py +8 -4
- maxframe/dataframe/window/core.py +14 -1
- maxframe/dataframe/window/ewm.py +1 -3
- maxframe/dataframe/window/expanding.py +37 -35
- maxframe/dataframe/window/rolling.py +49 -39
- maxframe/dataframe/window/tests/test_expanding.py +1 -7
- maxframe/dataframe/window/tests/test_rolling.py +1 -1
- maxframe/env.py +7 -4
- maxframe/errors.py +2 -2
- maxframe/io/odpsio/schema.py +9 -3
- maxframe/io/odpsio/tableio.py +7 -2
- maxframe/io/odpsio/tests/test_schema.py +198 -83
- maxframe/learn/__init__.py +10 -2
- maxframe/learn/cluster/__init__.py +15 -0
- maxframe/learn/cluster/_kmeans.py +782 -0
- maxframe/learn/contrib/llm/core.py +18 -7
- maxframe/learn/contrib/llm/deploy/__init__.py +13 -0
- maxframe/learn/contrib/llm/deploy/config.py +221 -0
- maxframe/learn/contrib/llm/deploy/core.py +247 -0
- maxframe/learn/contrib/llm/deploy/framework.py +35 -0
- maxframe/learn/contrib/llm/deploy/loader.py +360 -0
- maxframe/learn/contrib/llm/deploy/tests/__init__.py +13 -0
- maxframe/learn/contrib/llm/deploy/tests/test_register_models.py +359 -0
- maxframe/learn/contrib/llm/models/__init__.py +1 -0
- maxframe/learn/contrib/llm/models/dashscope.py +12 -6
- maxframe/learn/contrib/llm/models/managed.py +76 -11
- maxframe/learn/contrib/llm/models/openai.py +72 -0
- maxframe/learn/contrib/llm/tests/__init__.py +13 -0
- maxframe/learn/contrib/llm/tests/test_core.py +34 -0
- maxframe/learn/contrib/llm/tests/test_openai.py +187 -0
- maxframe/learn/contrib/llm/tests/test_text_gen.py +155 -0
- maxframe/learn/contrib/llm/text.py +348 -42
- maxframe/learn/contrib/models.py +4 -1
- maxframe/learn/contrib/xgboost/classifier.py +2 -0
- maxframe/learn/contrib/xgboost/core.py +113 -4
- maxframe/learn/contrib/xgboost/predict.py +4 -2
- maxframe/learn/contrib/xgboost/regressor.py +5 -0
- maxframe/learn/contrib/xgboost/train.py +7 -2
- maxframe/learn/core.py +66 -0
- maxframe/learn/linear_model/_base.py +58 -1
- maxframe/learn/linear_model/_lin_reg.py +1 -1
- maxframe/learn/metrics/__init__.py +6 -0
- maxframe/learn/metrics/_classification.py +145 -0
- maxframe/learn/metrics/_ranking.py +477 -0
- maxframe/learn/metrics/_scorer.py +60 -0
- maxframe/learn/metrics/pairwise/__init__.py +21 -0
- maxframe/learn/metrics/pairwise/core.py +77 -0
- maxframe/learn/metrics/pairwise/cosine.py +115 -0
- maxframe/learn/metrics/pairwise/euclidean.py +176 -0
- maxframe/learn/metrics/pairwise/haversine.py +96 -0
- maxframe/learn/metrics/pairwise/manhattan.py +80 -0
- maxframe/learn/metrics/pairwise/pairwise.py +127 -0
- maxframe/learn/metrics/pairwise/pairwise_distances_topk.py +121 -0
- maxframe/learn/metrics/pairwise/rbf_kernel.py +51 -0
- maxframe/learn/metrics/tests/__init__.py +13 -0
- maxframe/learn/metrics/tests/test_scorer.py +26 -0
- maxframe/learn/preprocessing/_data/min_max_scaler.py +34 -23
- maxframe/learn/preprocessing/_data/standard_scaler.py +34 -25
- maxframe/learn/utils/__init__.py +2 -1
- maxframe/learn/utils/checks.py +1 -2
- maxframe/learn/utils/core.py +59 -0
- maxframe/learn/utils/extmath.py +79 -9
- maxframe/learn/utils/odpsio.py +262 -0
- maxframe/learn/utils/validation.py +2 -2
- maxframe/lib/compat.py +40 -0
- maxframe/lib/dtypes_extension/__init__.py +16 -1
- maxframe/lib/dtypes_extension/_fake_arrow_dtype.py +604 -0
- maxframe/lib/dtypes_extension/blob.py +304 -0
- maxframe/lib/dtypes_extension/dtypes.py +40 -0
- maxframe/lib/dtypes_extension/tests/test_blob.py +88 -0
- maxframe/lib/dtypes_extension/tests/test_dtypes.py +16 -1
- maxframe/lib/dtypes_extension/tests/test_fake_arrow_dtype.py +75 -0
- maxframe/lib/filesystem/_oss_lib/common.py +124 -50
- maxframe/lib/filesystem/_oss_lib/glob.py +1 -1
- maxframe/lib/filesystem/_oss_lib/handle.py +21 -25
- maxframe/lib/filesystem/base.py +1 -1
- maxframe/lib/filesystem/core.py +1 -1
- maxframe/lib/filesystem/oss.py +115 -46
- maxframe/lib/filesystem/tests/test_oss.py +74 -36
- maxframe/lib/mmh3.cp37-win32.pyd +0 -0
- maxframe/lib/wrapped_pickle.py +10 -0
- maxframe/opcodes.py +41 -15
- maxframe/protocol.py +12 -0
- maxframe/remote/core.py +4 -0
- maxframe/serialization/__init__.py +11 -2
- maxframe/serialization/arrow.py +38 -13
- maxframe/serialization/blob.py +32 -0
- maxframe/serialization/core.cp37-win32.pyd +0 -0
- maxframe/serialization/core.pyx +39 -1
- maxframe/serialization/exception.py +2 -4
- maxframe/serialization/numpy.py +11 -0
- maxframe/serialization/pandas.py +46 -9
- maxframe/serialization/serializables/core.py +2 -2
- maxframe/serialization/tests/test_serial.py +31 -4
- maxframe/tensor/__init__.py +38 -8
- maxframe/tensor/arithmetic/__init__.py +19 -10
- maxframe/tensor/arithmetic/core.py +2 -2
- maxframe/tensor/arithmetic/iscomplexobj.py +53 -0
- maxframe/tensor/arithmetic/tests/test_arithmetic.py +6 -9
- maxframe/tensor/core.py +6 -2
- maxframe/tensor/datasource/tests/test_datasource.py +2 -1
- maxframe/tensor/extensions/__init__.py +2 -0
- maxframe/tensor/extensions/apply_chunk.py +3 -3
- maxframe/tensor/extensions/rebalance.py +65 -0
- maxframe/tensor/fft/__init__.py +32 -0
- maxframe/tensor/fft/core.py +168 -0
- maxframe/tensor/fft/fft.py +112 -0
- maxframe/tensor/fft/fft2.py +118 -0
- maxframe/tensor/fft/fftfreq.py +80 -0
- maxframe/tensor/fft/fftn.py +123 -0
- maxframe/tensor/fft/fftshift.py +79 -0
- maxframe/tensor/fft/hfft.py +112 -0
- maxframe/tensor/fft/ifft.py +114 -0
- maxframe/tensor/fft/ifft2.py +115 -0
- maxframe/tensor/fft/ifftn.py +123 -0
- maxframe/tensor/fft/ifftshift.py +73 -0
- maxframe/tensor/fft/ihfft.py +93 -0
- maxframe/tensor/fft/irfft.py +118 -0
- maxframe/tensor/fft/irfft2.py +62 -0
- maxframe/tensor/fft/irfftn.py +114 -0
- maxframe/tensor/fft/rfft.py +116 -0
- maxframe/tensor/fft/rfft2.py +63 -0
- maxframe/tensor/fft/rfftfreq.py +87 -0
- maxframe/tensor/fft/rfftn.py +113 -0
- maxframe/tensor/indexing/fill_diagonal.py +1 -7
- maxframe/tensor/linalg/__init__.py +7 -0
- maxframe/tensor/linalg/_einsumfunc.py +1025 -0
- maxframe/tensor/linalg/cholesky.py +117 -0
- maxframe/tensor/linalg/einsum.py +339 -0
- maxframe/tensor/linalg/lstsq.py +100 -0
- maxframe/tensor/linalg/matrix_norm.py +75 -0
- maxframe/tensor/linalg/norm.py +249 -0
- maxframe/tensor/linalg/solve.py +72 -0
- maxframe/tensor/linalg/solve_triangular.py +2 -2
- maxframe/tensor/linalg/vector_norm.py +113 -0
- maxframe/tensor/misc/__init__.py +24 -1
- maxframe/tensor/misc/argwhere.py +72 -0
- maxframe/tensor/misc/array_split.py +46 -0
- maxframe/tensor/misc/broadcast_arrays.py +57 -0
- maxframe/tensor/misc/copyto.py +130 -0
- maxframe/tensor/misc/delete.py +104 -0
- maxframe/tensor/misc/dsplit.py +68 -0
- maxframe/tensor/misc/ediff1d.py +74 -0
- maxframe/tensor/misc/expand_dims.py +85 -0
- maxframe/tensor/misc/flip.py +90 -0
- maxframe/tensor/misc/fliplr.py +64 -0
- maxframe/tensor/misc/flipud.py +68 -0
- maxframe/tensor/misc/hsplit.py +85 -0
- maxframe/tensor/misc/insert.py +139 -0
- maxframe/tensor/misc/moveaxis.py +83 -0
- maxframe/tensor/misc/result_type.py +88 -0
- maxframe/tensor/misc/roll.py +124 -0
- maxframe/tensor/misc/rollaxis.py +77 -0
- maxframe/tensor/misc/shape.py +89 -0
- maxframe/tensor/misc/split.py +190 -0
- maxframe/tensor/misc/tile.py +109 -0
- maxframe/tensor/misc/vsplit.py +74 -0
- maxframe/tensor/reduction/array_equal.py +2 -1
- maxframe/tensor/sort/__init__.py +2 -0
- maxframe/tensor/sort/argpartition.py +98 -0
- maxframe/tensor/sort/partition.py +228 -0
- maxframe/tensor/spatial/__init__.py +15 -0
- maxframe/tensor/spatial/distance/__init__.py +17 -0
- maxframe/tensor/spatial/distance/cdist.py +421 -0
- maxframe/tensor/spatial/distance/pdist.py +398 -0
- maxframe/tensor/spatial/distance/squareform.py +153 -0
- maxframe/tensor/special/__init__.py +159 -21
- maxframe/tensor/special/airy.py +55 -0
- maxframe/tensor/special/bessel.py +199 -0
- maxframe/tensor/special/core.py +65 -4
- maxframe/tensor/special/ellip_func_integrals.py +155 -0
- maxframe/tensor/special/ellip_harm.py +55 -0
- maxframe/tensor/special/err_fresnel.py +223 -0
- maxframe/tensor/special/gamma_funcs.py +303 -0
- maxframe/tensor/special/hypergeometric_funcs.py +69 -0
- maxframe/tensor/special/info_theory.py +189 -0
- maxframe/tensor/special/misc.py +21 -0
- maxframe/tensor/statistics/__init__.py +6 -0
- maxframe/tensor/statistics/corrcoef.py +77 -0
- maxframe/tensor/statistics/cov.py +222 -0
- maxframe/tensor/statistics/digitize.py +126 -0
- maxframe/tensor/statistics/histogram.py +520 -0
- maxframe/tensor/statistics/median.py +85 -0
- maxframe/tensor/statistics/ptp.py +89 -0
- maxframe/tensor/utils.py +3 -3
- maxframe/tests/test_udf.py +61 -0
- maxframe/tests/test_utils.py +51 -6
- maxframe/tests/utils.py +0 -2
- maxframe/typing_.py +2 -0
- maxframe/udf.py +130 -9
- maxframe/utils.py +254 -27
- {maxframe-2.0.0b2.dist-info → maxframe-2.3.0rc1.dist-info}/METADATA +3 -3
- {maxframe-2.0.0b2.dist-info → maxframe-2.3.0rc1.dist-info}/RECORD +442 -264
- maxframe_client/fetcher.py +35 -4
- maxframe_client/session/odps.py +7 -2
- maxframe_client/session/task.py +8 -1
- maxframe_client/tests/test_fetcher.py +76 -3
- maxframe_client/tests/test_session.py +28 -1
- maxframe/dataframe/arrays.py +0 -864
- /maxframe/dataframe/{misc → reshape}/melt.py +0 -0
- /maxframe/dataframe/{misc → reshape}/stack.py +0 -0
- {maxframe-2.0.0b2.dist-info → maxframe-2.3.0rc1.dist-info}/WHEEL +0 -0
- {maxframe-2.0.0b2.dist-info → maxframe-2.3.0rc1.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,1025 @@
|
|
|
1
|
+
# Copyright 1999-2025 Alibaba Group Holding Ltd.
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
import itertools
|
|
16
|
+
|
|
17
|
+
from ..datasource.array import tensor as astensor
|
|
18
|
+
|
|
19
|
+
__all__ = ["parse_einsum_input", "einsum_path"]
|
|
20
|
+
|
|
21
|
+
einsum_symbols = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
22
|
+
einsum_symbols_set = set(einsum_symbols)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _flop_count(idx_contraction, inner, num_terms, size_dictionary):
|
|
26
|
+
"""
|
|
27
|
+
Computes the number of FLOPS in the contraction.
|
|
28
|
+
|
|
29
|
+
Parameters
|
|
30
|
+
----------
|
|
31
|
+
idx_contraction : iterable
|
|
32
|
+
The indices involved in the contraction
|
|
33
|
+
inner : bool
|
|
34
|
+
Does this contraction require an inner product?
|
|
35
|
+
num_terms : int
|
|
36
|
+
The number of terms in a contraction
|
|
37
|
+
size_dictionary : dict
|
|
38
|
+
The size of each of the indices in idx_contraction
|
|
39
|
+
|
|
40
|
+
Returns
|
|
41
|
+
-------
|
|
42
|
+
flop_count : int
|
|
43
|
+
The total number of FLOPS required for the contraction.
|
|
44
|
+
|
|
45
|
+
Examples
|
|
46
|
+
--------
|
|
47
|
+
|
|
48
|
+
>>> _flop_count('abc', False, 1, {'a': 2, 'b':3, 'c':5})
|
|
49
|
+
30
|
|
50
|
+
|
|
51
|
+
>>> _flop_count('abc', True, 2, {'a': 2, 'b':3, 'c':5})
|
|
52
|
+
60
|
|
53
|
+
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
overall_size = _compute_size_by_dict(idx_contraction, size_dictionary)
|
|
57
|
+
op_factor = max(1, num_terms - 1)
|
|
58
|
+
if inner:
|
|
59
|
+
op_factor += 1
|
|
60
|
+
|
|
61
|
+
return overall_size * op_factor
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _compute_size_by_dict(indices, idx_dict):
|
|
65
|
+
"""
|
|
66
|
+
Computes the product of the elements in indices based on the dictionary
|
|
67
|
+
idx_dict.
|
|
68
|
+
|
|
69
|
+
Parameters
|
|
70
|
+
----------
|
|
71
|
+
indices : iterable
|
|
72
|
+
Indices to base the product on.
|
|
73
|
+
idx_dict : dictionary
|
|
74
|
+
Dictionary of index sizes
|
|
75
|
+
|
|
76
|
+
Returns
|
|
77
|
+
-------
|
|
78
|
+
ret : int
|
|
79
|
+
The resulting product.
|
|
80
|
+
|
|
81
|
+
Examples
|
|
82
|
+
--------
|
|
83
|
+
>>> _compute_size_by_dict('abbc', {'a': 2, 'b':3, 'c':5})
|
|
84
|
+
90
|
|
85
|
+
|
|
86
|
+
"""
|
|
87
|
+
ret = 1
|
|
88
|
+
for i in indices:
|
|
89
|
+
ret *= idx_dict[i]
|
|
90
|
+
return ret
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _find_contraction(positions, input_sets, output_set):
|
|
94
|
+
"""
|
|
95
|
+
Finds the contraction for a given set of input and output sets.
|
|
96
|
+
|
|
97
|
+
Parameters
|
|
98
|
+
----------
|
|
99
|
+
positions : iterable
|
|
100
|
+
Integer positions of terms used in the contraction.
|
|
101
|
+
input_sets : list
|
|
102
|
+
List of sets that represent the lhs side of the einsum subscript
|
|
103
|
+
output_set : set
|
|
104
|
+
Set that represents the rhs side of the overall einsum subscript
|
|
105
|
+
|
|
106
|
+
Returns
|
|
107
|
+
-------
|
|
108
|
+
new_result : set
|
|
109
|
+
The indices of the resulting contraction
|
|
110
|
+
remaining : list
|
|
111
|
+
List of sets that have not been contracted, the new set is appended to
|
|
112
|
+
the end of this list
|
|
113
|
+
idx_removed : set
|
|
114
|
+
Indices removed from the entire contraction
|
|
115
|
+
idx_contraction : set
|
|
116
|
+
The indices used in the current contraction
|
|
117
|
+
|
|
118
|
+
Examples
|
|
119
|
+
--------
|
|
120
|
+
|
|
121
|
+
# A simple dot product test case
|
|
122
|
+
>>> pos = (0, 1)
|
|
123
|
+
>>> isets = [set('ab'), set('bc')]
|
|
124
|
+
>>> oset = set('ac')
|
|
125
|
+
>>> _find_contraction(pos, isets, oset)
|
|
126
|
+
({'a', 'c'}, [{'a', 'c'}], {'b'}, {'a', 'b', 'c'})
|
|
127
|
+
|
|
128
|
+
# A more complex case with additional terms in the contraction
|
|
129
|
+
>>> pos = (0, 2)
|
|
130
|
+
>>> isets = [set('abd'), set('ac'), set('bdc')]
|
|
131
|
+
>>> oset = set('ac')
|
|
132
|
+
>>> _find_contraction(pos, isets, oset)
|
|
133
|
+
({'a', 'c'}, [{'a', 'c'}, {'a', 'c'}], {'b', 'd'}, {'a', 'b', 'c', 'd'})
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
idx_contract = set()
|
|
137
|
+
idx_remain = output_set.copy()
|
|
138
|
+
remaining = []
|
|
139
|
+
for ind, value in enumerate(input_sets):
|
|
140
|
+
if ind in positions:
|
|
141
|
+
idx_contract |= value
|
|
142
|
+
else:
|
|
143
|
+
remaining.append(value)
|
|
144
|
+
idx_remain |= value
|
|
145
|
+
|
|
146
|
+
new_result = idx_remain & idx_contract
|
|
147
|
+
idx_removed = idx_contract - new_result
|
|
148
|
+
remaining.append(new_result)
|
|
149
|
+
|
|
150
|
+
return (new_result, remaining, idx_removed, idx_contract)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _optimal_path(input_sets, output_set, idx_dict, memory_limit):
|
|
154
|
+
"""
|
|
155
|
+
Computes all possible pair contractions, sieves the results based
|
|
156
|
+
on ``memory_limit`` and returns the lowest cost path. This algorithm
|
|
157
|
+
scales factorial with respect to the elements in the list ``input_sets``.
|
|
158
|
+
|
|
159
|
+
Parameters
|
|
160
|
+
----------
|
|
161
|
+
input_sets : list
|
|
162
|
+
List of sets that represent the lhs side of the einsum subscript
|
|
163
|
+
output_set : set
|
|
164
|
+
Set that represents the rhs side of the overall einsum subscript
|
|
165
|
+
idx_dict : dictionary
|
|
166
|
+
Dictionary of index sizes
|
|
167
|
+
memory_limit : int
|
|
168
|
+
The maximum number of elements in a temporary array
|
|
169
|
+
|
|
170
|
+
Returns
|
|
171
|
+
-------
|
|
172
|
+
path : list
|
|
173
|
+
The optimal contraction order within the memory limit constraint.
|
|
174
|
+
|
|
175
|
+
Examples
|
|
176
|
+
--------
|
|
177
|
+
>>> isets = [set('abd'), set('ac'), set('bdc')]
|
|
178
|
+
>>> oset = set()
|
|
179
|
+
>>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}
|
|
180
|
+
>>> _optimal_path(isets, oset, idx_sizes, 5000)
|
|
181
|
+
[(0, 2), (0, 1)]
|
|
182
|
+
"""
|
|
183
|
+
|
|
184
|
+
full_results = [(0, [], input_sets)]
|
|
185
|
+
for iteration in range(len(input_sets) - 1):
|
|
186
|
+
iter_results = []
|
|
187
|
+
|
|
188
|
+
# Compute all unique pairs
|
|
189
|
+
for curr in full_results:
|
|
190
|
+
cost, positions, remaining = curr
|
|
191
|
+
for con in itertools.combinations(range(len(input_sets) - iteration), 2):
|
|
192
|
+
# Find the contraction
|
|
193
|
+
cont = _find_contraction(con, remaining, output_set)
|
|
194
|
+
new_result, new_input_sets, idx_removed, idx_contract = cont
|
|
195
|
+
|
|
196
|
+
# Sieve the results based on memory_limit
|
|
197
|
+
new_size = _compute_size_by_dict(new_result, idx_dict)
|
|
198
|
+
if new_size > memory_limit:
|
|
199
|
+
continue
|
|
200
|
+
|
|
201
|
+
# Build (total_cost, positions, indices_remaining)
|
|
202
|
+
total_cost = cost + _flop_count(
|
|
203
|
+
idx_contract, idx_removed, len(con), idx_dict
|
|
204
|
+
)
|
|
205
|
+
new_pos = positions + [con]
|
|
206
|
+
iter_results.append((total_cost, new_pos, new_input_sets))
|
|
207
|
+
|
|
208
|
+
# Update combinatorial list, if we did not find anything return best
|
|
209
|
+
# path + remaining contractions
|
|
210
|
+
if iter_results:
|
|
211
|
+
full_results = iter_results
|
|
212
|
+
else:
|
|
213
|
+
path = min(full_results, key=lambda x: x[0])[1]
|
|
214
|
+
path += [tuple(range(len(input_sets) - iteration))]
|
|
215
|
+
return path
|
|
216
|
+
|
|
217
|
+
# If we have not found anything return single einsum contraction
|
|
218
|
+
if len(full_results) == 0:
|
|
219
|
+
return [tuple(range(len(input_sets)))]
|
|
220
|
+
|
|
221
|
+
path = min(full_results, key=lambda x: x[0])[1]
|
|
222
|
+
return path
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _parse_possible_contraction(
|
|
226
|
+
positions, input_sets, output_set, idx_dict, memory_limit, path_cost, naive_cost
|
|
227
|
+
):
|
|
228
|
+
"""Compute the cost (removed size + flops) and resultant indices for
|
|
229
|
+
performing the contraction specified by ``positions``.
|
|
230
|
+
|
|
231
|
+
Parameters
|
|
232
|
+
----------
|
|
233
|
+
positions : tuple of int
|
|
234
|
+
The locations of the proposed tensors to contract.
|
|
235
|
+
input_sets : list of sets
|
|
236
|
+
The indices found on each tensors.
|
|
237
|
+
output_set : set
|
|
238
|
+
The output indices of the expression.
|
|
239
|
+
idx_dict : dict
|
|
240
|
+
Mapping of each index to its size.
|
|
241
|
+
memory_limit : int
|
|
242
|
+
The total allowed size for an intermediary tensor.
|
|
243
|
+
path_cost : int
|
|
244
|
+
The contraction cost so far.
|
|
245
|
+
naive_cost : int
|
|
246
|
+
The cost of the unoptimized expression.
|
|
247
|
+
|
|
248
|
+
Returns
|
|
249
|
+
-------
|
|
250
|
+
cost : (int, int)
|
|
251
|
+
A tuple containing the size of any indices removed, and the flop cost.
|
|
252
|
+
positions : tuple of int
|
|
253
|
+
The locations of the proposed tensors to contract.
|
|
254
|
+
new_input_sets : list of sets
|
|
255
|
+
The resulting new list of indices if this proposed contraction is performed.
|
|
256
|
+
|
|
257
|
+
"""
|
|
258
|
+
|
|
259
|
+
# Find the contraction
|
|
260
|
+
contract = _find_contraction(positions, input_sets, output_set)
|
|
261
|
+
idx_result, new_input_sets, idx_removed, idx_contract = contract
|
|
262
|
+
|
|
263
|
+
# Sieve the results based on memory_limit
|
|
264
|
+
new_size = _compute_size_by_dict(idx_result, idx_dict)
|
|
265
|
+
if new_size > memory_limit:
|
|
266
|
+
return None
|
|
267
|
+
|
|
268
|
+
# Build sort tuple
|
|
269
|
+
old_sizes = (_compute_size_by_dict(input_sets[p], idx_dict) for p in positions)
|
|
270
|
+
removed_size = sum(old_sizes) - new_size
|
|
271
|
+
|
|
272
|
+
# NB: removed_size used to be just the size of any removed indices i.e.:
|
|
273
|
+
# helpers.compute_size_by_dict(idx_removed, idx_dict)
|
|
274
|
+
cost = _flop_count(idx_contract, idx_removed, len(positions), idx_dict)
|
|
275
|
+
sort = (-removed_size, cost)
|
|
276
|
+
|
|
277
|
+
# Sieve based on total cost as well
|
|
278
|
+
if (path_cost + cost) > naive_cost:
|
|
279
|
+
return None
|
|
280
|
+
|
|
281
|
+
# Add contraction to possible choices
|
|
282
|
+
return [sort, positions, new_input_sets]
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _update_other_results(results, best):
|
|
286
|
+
"""Update the positions and provisional input_sets of ``results`` based on
|
|
287
|
+
performing the contraction result ``best``. Remove any involving the tensors
|
|
288
|
+
contracted.
|
|
289
|
+
|
|
290
|
+
Parameters
|
|
291
|
+
----------
|
|
292
|
+
results : list
|
|
293
|
+
List of contraction results produced by ``_parse_possible_contraction``.
|
|
294
|
+
best : list
|
|
295
|
+
The best contraction of ``results`` i.e. the one that will be performed.
|
|
296
|
+
|
|
297
|
+
Returns
|
|
298
|
+
-------
|
|
299
|
+
mod_results : list
|
|
300
|
+
The list of modified results, updated with outcome of ``best`` contraction.
|
|
301
|
+
"""
|
|
302
|
+
|
|
303
|
+
best_con = best[1]
|
|
304
|
+
bx, by = best_con
|
|
305
|
+
mod_results = []
|
|
306
|
+
|
|
307
|
+
for cost, (x, y), con_sets in results:
|
|
308
|
+
# Ignore results involving tensors just contracted
|
|
309
|
+
if x in best_con or y in best_con:
|
|
310
|
+
continue
|
|
311
|
+
|
|
312
|
+
# Update the input_sets
|
|
313
|
+
del con_sets[by - int(by > x) - int(by > y)]
|
|
314
|
+
del con_sets[bx - int(bx > x) - int(bx > y)]
|
|
315
|
+
con_sets.insert(-1, best[2][-1])
|
|
316
|
+
|
|
317
|
+
# Update the position indices
|
|
318
|
+
mod_con = x - int(x > bx) - int(x > by), y - int(y > bx) - int(y > by)
|
|
319
|
+
mod_results.append((cost, mod_con, con_sets))
|
|
320
|
+
|
|
321
|
+
return mod_results
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def _greedy_path(input_sets, output_set, idx_dict, memory_limit):
|
|
325
|
+
"""
|
|
326
|
+
Finds the path by contracting the best pair until the input list is
|
|
327
|
+
exhausted. The best pair is found by minimizing the tuple
|
|
328
|
+
``(-prod(indices_removed), cost)``. What this amounts to is prioritizing
|
|
329
|
+
matrix multiplication or inner product operations, then Hadamard like
|
|
330
|
+
operations, and finally outer operations. Outer products are limited by
|
|
331
|
+
``memory_limit``. This algorithm scales cubically with respect to the
|
|
332
|
+
number of elements in the list ``input_sets``.
|
|
333
|
+
|
|
334
|
+
Parameters
|
|
335
|
+
----------
|
|
336
|
+
input_sets : list
|
|
337
|
+
List of sets that represent the lhs side of the einsum subscript
|
|
338
|
+
output_set : set
|
|
339
|
+
Set that represents the rhs side of the overall einsum subscript
|
|
340
|
+
idx_dict : dictionary
|
|
341
|
+
Dictionary of index sizes
|
|
342
|
+
memory_limit_limit : int
|
|
343
|
+
The maximum number of elements in a temporary array
|
|
344
|
+
|
|
345
|
+
Returns
|
|
346
|
+
-------
|
|
347
|
+
path : list
|
|
348
|
+
The greedy contraction order within the memory limit constraint.
|
|
349
|
+
|
|
350
|
+
Examples
|
|
351
|
+
--------
|
|
352
|
+
>>> isets = [set('abd'), set('ac'), set('bdc')]
|
|
353
|
+
>>> oset = set()
|
|
354
|
+
>>> idx_sizes = {'a': 1, 'b':2, 'c':3, 'd':4}
|
|
355
|
+
>>> _greedy_path(isets, oset, idx_sizes, 5000)
|
|
356
|
+
[(0, 2), (0, 1)]
|
|
357
|
+
"""
|
|
358
|
+
|
|
359
|
+
# Handle trivial cases that leaked through
|
|
360
|
+
if len(input_sets) == 1:
|
|
361
|
+
return [(0,)]
|
|
362
|
+
elif len(input_sets) == 2:
|
|
363
|
+
return [(0, 1)]
|
|
364
|
+
|
|
365
|
+
# Build up a naive cost
|
|
366
|
+
contract = _find_contraction(range(len(input_sets)), input_sets, output_set)
|
|
367
|
+
idx_result, new_input_sets, idx_removed, idx_contract = contract
|
|
368
|
+
naive_cost = _flop_count(idx_contract, idx_removed, len(input_sets), idx_dict)
|
|
369
|
+
|
|
370
|
+
# Initially iterate over all pairs
|
|
371
|
+
comb_iter = itertools.combinations(range(len(input_sets)), 2)
|
|
372
|
+
known_contractions = []
|
|
373
|
+
|
|
374
|
+
path_cost = 0
|
|
375
|
+
path = []
|
|
376
|
+
|
|
377
|
+
for iteration in range(len(input_sets) - 1):
|
|
378
|
+
# Iterate over all pairs on first step, only previously found pairs on subsequent steps
|
|
379
|
+
for positions in comb_iter:
|
|
380
|
+
# Always initially ignore outer products
|
|
381
|
+
if input_sets[positions[0]].isdisjoint(input_sets[positions[1]]):
|
|
382
|
+
continue
|
|
383
|
+
|
|
384
|
+
result = _parse_possible_contraction(
|
|
385
|
+
positions,
|
|
386
|
+
input_sets,
|
|
387
|
+
output_set,
|
|
388
|
+
idx_dict,
|
|
389
|
+
memory_limit,
|
|
390
|
+
path_cost,
|
|
391
|
+
naive_cost,
|
|
392
|
+
)
|
|
393
|
+
if result is not None:
|
|
394
|
+
known_contractions.append(result)
|
|
395
|
+
|
|
396
|
+
# If we do not have a inner contraction, rescan pairs including outer products
|
|
397
|
+
if len(known_contractions) == 0: # pragma: no cover
|
|
398
|
+
# Then check the outer products
|
|
399
|
+
for positions in itertools.combinations(range(len(input_sets)), 2):
|
|
400
|
+
result = _parse_possible_contraction(
|
|
401
|
+
positions,
|
|
402
|
+
input_sets,
|
|
403
|
+
output_set,
|
|
404
|
+
idx_dict,
|
|
405
|
+
memory_limit,
|
|
406
|
+
path_cost,
|
|
407
|
+
naive_cost,
|
|
408
|
+
)
|
|
409
|
+
if result is not None:
|
|
410
|
+
known_contractions.append(result)
|
|
411
|
+
|
|
412
|
+
# If we still did not find any remaining contractions, default back to einsum like behavior
|
|
413
|
+
if len(known_contractions) == 0:
|
|
414
|
+
path.append(tuple(range(len(input_sets))))
|
|
415
|
+
break
|
|
416
|
+
|
|
417
|
+
# Sort based on first index
|
|
418
|
+
best = min(known_contractions, key=lambda x: x[0])
|
|
419
|
+
|
|
420
|
+
# Now propagate as many unused contractions as possible to next iteration
|
|
421
|
+
known_contractions = _update_other_results(known_contractions, best)
|
|
422
|
+
|
|
423
|
+
# Next iteration only compute contractions with the new tensor
|
|
424
|
+
# All other contractions have been accounted for
|
|
425
|
+
input_sets = best[2]
|
|
426
|
+
new_tensor_pos = len(input_sets) - 1
|
|
427
|
+
comb_iter = ((i, new_tensor_pos) for i in range(new_tensor_pos))
|
|
428
|
+
|
|
429
|
+
# Update path and total cost
|
|
430
|
+
path.append(best[1])
|
|
431
|
+
path_cost += best[0][1]
|
|
432
|
+
|
|
433
|
+
return path
|
|
434
|
+
|
|
435
|
+
|
|
436
|
+
def _can_dot(inputs, result, idx_removed):
|
|
437
|
+
"""
|
|
438
|
+
Checks if we can use BLAS (np.tensordot) call and its beneficial to do so.
|
|
439
|
+
|
|
440
|
+
Parameters
|
|
441
|
+
----------
|
|
442
|
+
inputs : list of str
|
|
443
|
+
Specifies the subscripts for summation.
|
|
444
|
+
result : str
|
|
445
|
+
Resulting summation.
|
|
446
|
+
idx_removed : set
|
|
447
|
+
Indices that are removed in the summation
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
Returns
|
|
451
|
+
-------
|
|
452
|
+
type : bool
|
|
453
|
+
Returns true if BLAS should and can be used, else False
|
|
454
|
+
|
|
455
|
+
Notes
|
|
456
|
+
-----
|
|
457
|
+
If the operations is BLAS level 1 or 2 and is not already aligned
|
|
458
|
+
we default back to einsum as the memory movement to copy is more
|
|
459
|
+
costly than the operation itself.
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
Examples
|
|
463
|
+
--------
|
|
464
|
+
|
|
465
|
+
# Standard GEMM operation
|
|
466
|
+
>>> _can_dot(['ij', 'jk'], 'ik', set('j'))
|
|
467
|
+
True
|
|
468
|
+
|
|
469
|
+
# Can use the standard BLAS, but requires odd data movement
|
|
470
|
+
>>> _can_dot(['ijj', 'jk'], 'ik', set('j'))
|
|
471
|
+
False
|
|
472
|
+
|
|
473
|
+
# DDOT where the memory is not aligned
|
|
474
|
+
>>> _can_dot(['ijk', 'ikj'], '', set('ijk'))
|
|
475
|
+
False
|
|
476
|
+
|
|
477
|
+
"""
|
|
478
|
+
|
|
479
|
+
# All `dot` calls remove indices
|
|
480
|
+
if len(idx_removed) == 0:
|
|
481
|
+
return False
|
|
482
|
+
|
|
483
|
+
# BLAS can only handle two operands
|
|
484
|
+
if len(inputs) != 2:
|
|
485
|
+
return False
|
|
486
|
+
|
|
487
|
+
input_left, input_right = inputs
|
|
488
|
+
|
|
489
|
+
for c in set(input_left + input_right):
|
|
490
|
+
# can't deal with repeated indices on same input or more than 2 total
|
|
491
|
+
nl, nr = input_left.count(c), input_right.count(c)
|
|
492
|
+
if (nl > 1) or (nr > 1) or (nl + nr > 2):
|
|
493
|
+
return False
|
|
494
|
+
|
|
495
|
+
# can't do implicit summation or dimension collapse e.g.
|
|
496
|
+
# "ab,bc->c" (implicitly sum over 'a')
|
|
497
|
+
# "ab,ca->ca" (take diagonal of 'a')
|
|
498
|
+
if nl + nr - 1 == int(c in result):
|
|
499
|
+
return False
|
|
500
|
+
|
|
501
|
+
# Build a few temporaries
|
|
502
|
+
set_left = set(input_left)
|
|
503
|
+
set_right = set(input_right)
|
|
504
|
+
keep_left = set_left - idx_removed
|
|
505
|
+
keep_right = set_right - idx_removed
|
|
506
|
+
rs = len(idx_removed)
|
|
507
|
+
|
|
508
|
+
# At this point we are a DOT, GEMV, or GEMM operation
|
|
509
|
+
|
|
510
|
+
# Handle inner products
|
|
511
|
+
|
|
512
|
+
# DDOT with aligned data
|
|
513
|
+
if input_left == input_right:
|
|
514
|
+
return True
|
|
515
|
+
|
|
516
|
+
# DDOT without aligned data (better to use einsum)
|
|
517
|
+
if set_left == set_right:
|
|
518
|
+
return False
|
|
519
|
+
|
|
520
|
+
# Handle the 4 possible (aligned) GEMV or GEMM cases
|
|
521
|
+
|
|
522
|
+
# GEMM or GEMV no transpose
|
|
523
|
+
if input_left[-rs:] == input_right[:rs]:
|
|
524
|
+
return True
|
|
525
|
+
|
|
526
|
+
# GEMM or GEMV transpose both
|
|
527
|
+
if input_left[:rs] == input_right[-rs:]:
|
|
528
|
+
return True
|
|
529
|
+
|
|
530
|
+
# GEMM or GEMV transpose right
|
|
531
|
+
if input_left[-rs:] == input_right[-rs:]:
|
|
532
|
+
return True
|
|
533
|
+
|
|
534
|
+
# GEMM or GEMV transpose left
|
|
535
|
+
if input_left[:rs] == input_right[:rs]:
|
|
536
|
+
return True
|
|
537
|
+
|
|
538
|
+
# Einsum is faster than GEMV if we have to copy data
|
|
539
|
+
if not keep_left or not keep_right:
|
|
540
|
+
return False
|
|
541
|
+
|
|
542
|
+
# We are a matrix-matrix product, but we need to copy data
|
|
543
|
+
return True
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def parse_einsum_input(operands):
|
|
547
|
+
"""
|
|
548
|
+
A reproduction of einsum c side einsum parsing in python.
|
|
549
|
+
|
|
550
|
+
Returns
|
|
551
|
+
-------
|
|
552
|
+
input_strings : str
|
|
553
|
+
Parsed input strings
|
|
554
|
+
output_string : str
|
|
555
|
+
Parsed output string
|
|
556
|
+
operands : list of array_like
|
|
557
|
+
The operands to use in the numpy contraction
|
|
558
|
+
|
|
559
|
+
Examples
|
|
560
|
+
--------
|
|
561
|
+
The operand list is simplified to reduce printing:
|
|
562
|
+
|
|
563
|
+
>>> import maxframe.tensor as mt
|
|
564
|
+
>>> mt.random.seed(123)
|
|
565
|
+
>>> a = mt.random.rand(4, 4)
|
|
566
|
+
>>> b = mt.random.rand(4, 4, 4)
|
|
567
|
+
>>> parse_einsum_input(('...a,...a->...', a, b))
|
|
568
|
+
('za,xza', 'xz', [a, b]) # may vary
|
|
569
|
+
|
|
570
|
+
>>> parse_einsum_input((a, [Ellipsis, 0], b, [Ellipsis, 0]))
|
|
571
|
+
('za,xza', 'xz', [a, b]) # may vary
|
|
572
|
+
"""
|
|
573
|
+
|
|
574
|
+
if len(operands) == 0:
|
|
575
|
+
raise ValueError("No input operands")
|
|
576
|
+
|
|
577
|
+
if isinstance(operands[0], str):
|
|
578
|
+
subscripts = operands[0].replace(" ", "")
|
|
579
|
+
operands = [astensor(v) for v in operands[1:]]
|
|
580
|
+
|
|
581
|
+
# Ensure all characters are valid
|
|
582
|
+
for s in subscripts:
|
|
583
|
+
if s in ".,->":
|
|
584
|
+
continue
|
|
585
|
+
if s not in einsum_symbols:
|
|
586
|
+
raise ValueError(f"Character {s} is not a valid symbol.")
|
|
587
|
+
|
|
588
|
+
else: # pragma: no cover
|
|
589
|
+
tmp_operands = list(operands)
|
|
590
|
+
operand_list = []
|
|
591
|
+
subscript_list = []
|
|
592
|
+
for p in range(len(operands) // 2):
|
|
593
|
+
operand_list.append(tmp_operands.pop(0))
|
|
594
|
+
subscript_list.append(tmp_operands.pop(0))
|
|
595
|
+
|
|
596
|
+
output_list = tmp_operands[-1] if len(tmp_operands) else None
|
|
597
|
+
operands = [astensor(v) for v in operand_list]
|
|
598
|
+
subscripts = ""
|
|
599
|
+
last = len(subscript_list) - 1
|
|
600
|
+
for num, sub in enumerate(subscript_list):
|
|
601
|
+
for s in sub:
|
|
602
|
+
if s is Ellipsis:
|
|
603
|
+
subscripts += "..."
|
|
604
|
+
elif isinstance(s, int):
|
|
605
|
+
subscripts += einsum_symbols[s]
|
|
606
|
+
else:
|
|
607
|
+
raise TypeError(
|
|
608
|
+
"For this input type lists must contain "
|
|
609
|
+
"either int or Ellipsis"
|
|
610
|
+
)
|
|
611
|
+
if num != last:
|
|
612
|
+
subscripts += ","
|
|
613
|
+
|
|
614
|
+
if output_list is not None:
|
|
615
|
+
subscripts += "->"
|
|
616
|
+
for s in output_list:
|
|
617
|
+
if s is Ellipsis:
|
|
618
|
+
subscripts += "..."
|
|
619
|
+
elif isinstance(s, int):
|
|
620
|
+
subscripts += einsum_symbols[s]
|
|
621
|
+
else:
|
|
622
|
+
raise TypeError(
|
|
623
|
+
"For this input type lists must contain "
|
|
624
|
+
"either int or Ellipsis"
|
|
625
|
+
)
|
|
626
|
+
# Check for proper "->"
|
|
627
|
+
if ("-" in subscripts) or (">" in subscripts):
|
|
628
|
+
invalid = (subscripts.count("-") > 1) or (subscripts.count(">") > 1)
|
|
629
|
+
if invalid or (subscripts.count("->") != 1):
|
|
630
|
+
raise ValueError("Subscripts can only contain one '->'.")
|
|
631
|
+
|
|
632
|
+
# Parse ellipses
|
|
633
|
+
if "." in subscripts:
|
|
634
|
+
used = subscripts.replace(".", "").replace(",", "").replace("->", "")
|
|
635
|
+
unused = list(einsum_symbols_set - set(used))
|
|
636
|
+
ellipse_inds = "".join(unused)
|
|
637
|
+
longest = 0
|
|
638
|
+
|
|
639
|
+
if "->" in subscripts:
|
|
640
|
+
input_tmp, output_sub = subscripts.split("->")
|
|
641
|
+
split_subscripts = input_tmp.split(",")
|
|
642
|
+
out_sub = True
|
|
643
|
+
else:
|
|
644
|
+
split_subscripts = subscripts.split(",")
|
|
645
|
+
out_sub = False
|
|
646
|
+
|
|
647
|
+
for num, sub in enumerate(split_subscripts):
|
|
648
|
+
if "." in sub:
|
|
649
|
+
if (sub.count(".") != 3) or (sub.count("...") != 1):
|
|
650
|
+
raise ValueError("Invalid Ellipses.")
|
|
651
|
+
|
|
652
|
+
# Take into account numerical values
|
|
653
|
+
if operands[num].shape == ():
|
|
654
|
+
ellipse_count = 0
|
|
655
|
+
else:
|
|
656
|
+
ellipse_count = max(operands[num].ndim, 1)
|
|
657
|
+
ellipse_count -= len(sub) - 3
|
|
658
|
+
|
|
659
|
+
if ellipse_count > longest:
|
|
660
|
+
longest = ellipse_count
|
|
661
|
+
|
|
662
|
+
if ellipse_count < 0:
|
|
663
|
+
raise ValueError("Ellipses lengths do not match.")
|
|
664
|
+
elif ellipse_count == 0:
|
|
665
|
+
split_subscripts[num] = sub.replace("...", "")
|
|
666
|
+
else:
|
|
667
|
+
rep_inds = ellipse_inds[-ellipse_count:]
|
|
668
|
+
split_subscripts[num] = sub.replace("...", rep_inds)
|
|
669
|
+
|
|
670
|
+
subscripts = ",".join(split_subscripts)
|
|
671
|
+
if longest == 0:
|
|
672
|
+
out_ellipse = ""
|
|
673
|
+
else:
|
|
674
|
+
out_ellipse = ellipse_inds[-longest:]
|
|
675
|
+
|
|
676
|
+
if out_sub:
|
|
677
|
+
subscripts += "->" + output_sub.replace("...", out_ellipse)
|
|
678
|
+
else:
|
|
679
|
+
# Special care for outputless ellipses
|
|
680
|
+
output_subscript = ""
|
|
681
|
+
tmp_subscripts = subscripts.replace(",", "")
|
|
682
|
+
for s in sorted(set(tmp_subscripts)):
|
|
683
|
+
if s not in (einsum_symbols):
|
|
684
|
+
raise ValueError(f"Character {s} is not a valid symbol.")
|
|
685
|
+
if tmp_subscripts.count(s) == 1:
|
|
686
|
+
output_subscript += s
|
|
687
|
+
normal_inds = "".join(sorted(set(output_subscript) - set(out_ellipse)))
|
|
688
|
+
|
|
689
|
+
subscripts += "->" + out_ellipse + normal_inds
|
|
690
|
+
|
|
691
|
+
# Build output string if does not exist
|
|
692
|
+
if "->" in subscripts:
|
|
693
|
+
input_subscripts, output_subscript = subscripts.split("->")
|
|
694
|
+
else:
|
|
695
|
+
input_subscripts = subscripts
|
|
696
|
+
# Build output subscripts
|
|
697
|
+
tmp_subscripts = subscripts.replace(",", "")
|
|
698
|
+
output_subscript = ""
|
|
699
|
+
for s in sorted(set(tmp_subscripts)):
|
|
700
|
+
if s not in einsum_symbols:
|
|
701
|
+
raise ValueError(f"Character {s} is not a valid symbol.")
|
|
702
|
+
if tmp_subscripts.count(s) == 1:
|
|
703
|
+
output_subscript += s
|
|
704
|
+
|
|
705
|
+
# Make sure output subscripts are in the input
|
|
706
|
+
for char in output_subscript:
|
|
707
|
+
if char not in input_subscripts:
|
|
708
|
+
raise ValueError(f"Output character {char} did not appear in the input")
|
|
709
|
+
|
|
710
|
+
# Make sure number operands is equivalent to the number of terms
|
|
711
|
+
if len(input_subscripts.split(",")) != len(operands):
|
|
712
|
+
raise ValueError(
|
|
713
|
+
"Number of einsum subscripts must be equal to the number of operands."
|
|
714
|
+
)
|
|
715
|
+
|
|
716
|
+
return (input_subscripts, output_subscript, operands)
|
|
717
|
+
|
|
718
|
+
|
|
719
|
+
def _einsum_path_dispatcher(*operands, **kwargs):
|
|
720
|
+
# NOTE: technically, we should only dispatch on array-like arguments, not
|
|
721
|
+
# subscripts (given as strings). But separating operands into
|
|
722
|
+
# arrays/subscripts is a little tricky/slow (given einsum's two supported
|
|
723
|
+
# signatures), so as a practical shortcut we dispatch on everything.
|
|
724
|
+
# Strings will be ignored for dispatching since they don't define
|
|
725
|
+
# __array_function__.
|
|
726
|
+
return operands
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
def einsum_path(*operands, **kwargs):
|
|
730
|
+
"""
|
|
731
|
+
einsum_path(subscripts, *operands, optimize='greedy')
|
|
732
|
+
|
|
733
|
+
Evaluates the lowest cost contraction order for an einsum expression by
|
|
734
|
+
considering the creation of intermediate arrays.
|
|
735
|
+
|
|
736
|
+
Parameters
|
|
737
|
+
----------
|
|
738
|
+
subscripts : str
|
|
739
|
+
Specifies the subscripts for summation.
|
|
740
|
+
*operands : list of array_like
|
|
741
|
+
These are the arrays for the operation.
|
|
742
|
+
optimize : {bool, list, tuple, 'greedy', 'optimal'}
|
|
743
|
+
Choose the type of path. If a tuple is provided, the second argument is
|
|
744
|
+
assumed to be the maximum intermediate size created. If only a single
|
|
745
|
+
argument is provided the largest input or output array size is used
|
|
746
|
+
as a maximum intermediate size.
|
|
747
|
+
|
|
748
|
+
* if a list is given that starts with ``einsum_path``, uses this as the
|
|
749
|
+
contraction path
|
|
750
|
+
* if False no optimization is taken
|
|
751
|
+
* if True defaults to the 'greedy' algorithm
|
|
752
|
+
* 'optimal' An algorithm that combinatorially explores all possible
|
|
753
|
+
ways of contracting the listed tensors and choosest the least costly
|
|
754
|
+
path. Scales exponentially with the number of terms in the
|
|
755
|
+
contraction.
|
|
756
|
+
* 'greedy' An algorithm that chooses the best pair contraction
|
|
757
|
+
at each step. Effectively, this algorithm searches the largest inner,
|
|
758
|
+
Hadamard, and then outer products at each step. Scales cubically with
|
|
759
|
+
the number of terms in the contraction. Equivalent to the 'optimal'
|
|
760
|
+
path for most contractions.
|
|
761
|
+
|
|
762
|
+
Default is 'greedy'.
|
|
763
|
+
|
|
764
|
+
Returns
|
|
765
|
+
-------
|
|
766
|
+
path : list of tuples
|
|
767
|
+
A list representation of the einsum path.
|
|
768
|
+
string_repr : str
|
|
769
|
+
A printable representation of the einsum path.
|
|
770
|
+
|
|
771
|
+
Notes
|
|
772
|
+
-----
|
|
773
|
+
The resulting path indicates which terms of the input contraction should be
|
|
774
|
+
contracted first, the result of this contraction is then appended to the
|
|
775
|
+
end of the contraction list. This list can then be iterated over until all
|
|
776
|
+
intermediate contractions are complete.
|
|
777
|
+
|
|
778
|
+
See Also
|
|
779
|
+
--------
|
|
780
|
+
einsum, linalg.multi_dot
|
|
781
|
+
|
|
782
|
+
Examples
|
|
783
|
+
--------
|
|
784
|
+
|
|
785
|
+
We can begin with a chain dot example. In this case, it is optimal to
|
|
786
|
+
contract the ``b`` and ``c`` tensors first as represented by the first
|
|
787
|
+
element of the path ``(1, 2)``. The resulting tensor is added to the end
|
|
788
|
+
of the contraction and the remaining contraction ``(0, 1)`` is then
|
|
789
|
+
completed.
|
|
790
|
+
|
|
791
|
+
>>> np.random.seed(123)
|
|
792
|
+
>>> a = np.random.rand(2, 2)
|
|
793
|
+
>>> b = np.random.rand(2, 5)
|
|
794
|
+
>>> c = np.random.rand(5, 2)
|
|
795
|
+
>>> path_info = np.einsum_path('ij,jk,kl->il', a, b, c, optimize='greedy')
|
|
796
|
+
>>> print(path_info[0])
|
|
797
|
+
['einsum_path', (1, 2), (0, 1)]
|
|
798
|
+
>>> print(path_info[1])
|
|
799
|
+
Complete contraction: ij,jk,kl->il # may vary
|
|
800
|
+
Naive scaling: 4
|
|
801
|
+
Optimized scaling: 3
|
|
802
|
+
Naive FLOP count: 1.600e+02
|
|
803
|
+
Optimized FLOP count: 5.600e+01
|
|
804
|
+
Theoretical speedup: 2.857
|
|
805
|
+
Largest intermediate: 4.000e+00 elements
|
|
806
|
+
-------------------------------------------------------------------------
|
|
807
|
+
scaling current remaining
|
|
808
|
+
-------------------------------------------------------------------------
|
|
809
|
+
3 kl,jk->jl ij,jl->il
|
|
810
|
+
3 jl,ij->il il->il
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
A more complex index transformation example.
|
|
814
|
+
|
|
815
|
+
>>> I = np.random.rand(10, 10, 10, 10)
|
|
816
|
+
>>> C = np.random.rand(10, 10)
|
|
817
|
+
>>> path_info = np.einsum_path('ea,fb,abcd,gc,hd->efgh', C, C, I, C, C,
|
|
818
|
+
... optimize='greedy')
|
|
819
|
+
|
|
820
|
+
>>> print(path_info[0])
|
|
821
|
+
['einsum_path', (0, 2), (0, 3), (0, 2), (0, 1)]
|
|
822
|
+
>>> print(path_info[1])
|
|
823
|
+
Complete contraction: ea,fb,abcd,gc,hd->efgh # may vary
|
|
824
|
+
Naive scaling: 8
|
|
825
|
+
Optimized scaling: 5
|
|
826
|
+
Naive FLOP count: 8.000e+08
|
|
827
|
+
Optimized FLOP count: 8.000e+05
|
|
828
|
+
Theoretical speedup: 1000.000
|
|
829
|
+
Largest intermediate: 1.000e+04 elements
|
|
830
|
+
--------------------------------------------------------------------------
|
|
831
|
+
scaling current remaining
|
|
832
|
+
--------------------------------------------------------------------------
|
|
833
|
+
5 abcd,ea->bcde fb,gc,hd,bcde->efgh
|
|
834
|
+
5 bcde,fb->cdef gc,hd,cdef->efgh
|
|
835
|
+
5 cdef,gc->defg hd,defg->efgh
|
|
836
|
+
5 defg,hd->efgh efgh->efgh
|
|
837
|
+
"""
|
|
838
|
+
|
|
839
|
+
# Make sure all keywords are valid
|
|
840
|
+
valid_contract_kwargs = ["optimize", "einsum_call"]
|
|
841
|
+
unknown_kwargs = [k for (k, v) in kwargs.items() if k not in valid_contract_kwargs]
|
|
842
|
+
if len(unknown_kwargs):
|
|
843
|
+
raise TypeError(f"Did not understand the following kwargs: {unknown_kwargs!r}")
|
|
844
|
+
|
|
845
|
+
# Figure out what the path really is
|
|
846
|
+
path_type = kwargs.pop("optimize", True)
|
|
847
|
+
if path_type is True:
|
|
848
|
+
path_type = "greedy"
|
|
849
|
+
if path_type is None:
|
|
850
|
+
path_type = False
|
|
851
|
+
|
|
852
|
+
memory_limit = None
|
|
853
|
+
|
|
854
|
+
# No optimization or a named path algorithm
|
|
855
|
+
if (path_type is False) or isinstance(path_type, str):
|
|
856
|
+
pass
|
|
857
|
+
|
|
858
|
+
# Given an explicit path
|
|
859
|
+
elif len(path_type) and (path_type[0] == "einsum_path"): # pragma: no cover
|
|
860
|
+
pass
|
|
861
|
+
|
|
862
|
+
# Path tuple with memory limit
|
|
863
|
+
elif (
|
|
864
|
+
(len(path_type) == 2)
|
|
865
|
+
and isinstance(path_type[0], str)
|
|
866
|
+
and isinstance(path_type[1], (int, float))
|
|
867
|
+
): # pragma: no cover
|
|
868
|
+
memory_limit = int(path_type[1])
|
|
869
|
+
path_type = path_type[0]
|
|
870
|
+
|
|
871
|
+
else: # pragma: no cover
|
|
872
|
+
raise TypeError(f"Did not understand the path: {path_type}")
|
|
873
|
+
|
|
874
|
+
# Hidden option, only einsum should call this
|
|
875
|
+
einsum_call_arg = kwargs.pop("einsum_call", False)
|
|
876
|
+
|
|
877
|
+
# Python side parsing
|
|
878
|
+
input_subscripts, output_subscript, operands = parse_einsum_input(operands)
|
|
879
|
+
|
|
880
|
+
# Build a few useful list and sets
|
|
881
|
+
input_list = input_subscripts.split(",")
|
|
882
|
+
input_sets = [set(x) for x in input_list]
|
|
883
|
+
output_set = set(output_subscript)
|
|
884
|
+
indices = set(input_subscripts.replace(",", ""))
|
|
885
|
+
|
|
886
|
+
# Get length of each unique dimension and ensure all dimensions are correct
|
|
887
|
+
dimension_dict = {}
|
|
888
|
+
broadcast_indices = [[] for x in range(len(input_list))]
|
|
889
|
+
for tnum, term in enumerate(input_list):
|
|
890
|
+
sh = operands[tnum].shape
|
|
891
|
+
if len(sh) != len(term):
|
|
892
|
+
raise ValueError(
|
|
893
|
+
"Einstein sum subscript %s does not contain the "
|
|
894
|
+
"correct number of indices for operand %d."
|
|
895
|
+
% (input_subscripts[tnum], tnum)
|
|
896
|
+
)
|
|
897
|
+
for cnum, char in enumerate(term):
|
|
898
|
+
dim = sh[cnum]
|
|
899
|
+
|
|
900
|
+
# Build out broadcast indices
|
|
901
|
+
if dim == 1:
|
|
902
|
+
broadcast_indices[tnum].append(char)
|
|
903
|
+
|
|
904
|
+
if char in dimension_dict.keys():
|
|
905
|
+
# For broadcasting cases we always want the largest dim size
|
|
906
|
+
if dimension_dict[char] == 1:
|
|
907
|
+
dimension_dict[char] = dim
|
|
908
|
+
elif dim not in (1, dimension_dict[char]):
|
|
909
|
+
raise ValueError(
|
|
910
|
+
"Size of label '%s' for operand %d (%d) "
|
|
911
|
+
"does not match previous terms (%d)."
|
|
912
|
+
% (char, tnum, dimension_dict[char], dim)
|
|
913
|
+
)
|
|
914
|
+
else:
|
|
915
|
+
dimension_dict[char] = dim
|
|
916
|
+
|
|
917
|
+
# Convert broadcast inds to sets
|
|
918
|
+
broadcast_indices = [set(x) for x in broadcast_indices]
|
|
919
|
+
|
|
920
|
+
# Compute size of each input array plus the output array
|
|
921
|
+
size_list = [
|
|
922
|
+
_compute_size_by_dict(term, dimension_dict)
|
|
923
|
+
for term in input_list + [output_subscript]
|
|
924
|
+
]
|
|
925
|
+
max_size = max(size_list)
|
|
926
|
+
|
|
927
|
+
if memory_limit is None:
|
|
928
|
+
memory_arg = max_size
|
|
929
|
+
else:
|
|
930
|
+
memory_arg = memory_limit
|
|
931
|
+
|
|
932
|
+
# Compute naive cost
|
|
933
|
+
# This isn't quite right, need to look into exactly how einsum does this
|
|
934
|
+
inner_product = (sum(len(x) for x in input_sets) - len(indices)) > 0
|
|
935
|
+
naive_cost = _flop_count(indices, inner_product, len(input_list), dimension_dict)
|
|
936
|
+
|
|
937
|
+
# Compute the path
|
|
938
|
+
if (path_type is False) or (len(input_list) in [1, 2]) or (indices == output_set):
|
|
939
|
+
# Nothing to be optimized, leave it to einsum
|
|
940
|
+
path = [tuple(range(len(input_list)))]
|
|
941
|
+
elif path_type == "greedy":
|
|
942
|
+
path = _greedy_path(input_sets, output_set, dimension_dict, memory_arg)
|
|
943
|
+
elif path_type == "optimal":
|
|
944
|
+
path = _optimal_path(input_sets, output_set, dimension_dict, memory_arg)
|
|
945
|
+
elif path_type[0] == "einsum_path": # pragma: no cover
|
|
946
|
+
path = path_type[1:]
|
|
947
|
+
else: # pragma: no cover
|
|
948
|
+
raise KeyError("Path name %s not found", path_type)
|
|
949
|
+
|
|
950
|
+
cost_list, scale_list, size_list, contraction_list = [], [], [], []
|
|
951
|
+
|
|
952
|
+
# Build contraction tuple (positions, gemm, einsum_str, remaining)
|
|
953
|
+
for cnum, contract_inds in enumerate(path):
|
|
954
|
+
# Make sure we remove inds from right to left
|
|
955
|
+
contract_inds = tuple(sorted(list(contract_inds), reverse=True))
|
|
956
|
+
|
|
957
|
+
contract = _find_contraction(contract_inds, input_sets, output_set)
|
|
958
|
+
out_inds, input_sets, idx_removed, idx_contract = contract
|
|
959
|
+
|
|
960
|
+
cost = _flop_count(
|
|
961
|
+
idx_contract, idx_removed, len(contract_inds), dimension_dict
|
|
962
|
+
)
|
|
963
|
+
cost_list.append(cost)
|
|
964
|
+
scale_list.append(len(idx_contract))
|
|
965
|
+
size_list.append(_compute_size_by_dict(out_inds, dimension_dict))
|
|
966
|
+
|
|
967
|
+
bcast = set()
|
|
968
|
+
tmp_inputs = []
|
|
969
|
+
for x in contract_inds:
|
|
970
|
+
tmp_inputs.append(input_list.pop(x))
|
|
971
|
+
bcast |= broadcast_indices.pop(x)
|
|
972
|
+
|
|
973
|
+
new_bcast_inds = bcast - idx_removed
|
|
974
|
+
|
|
975
|
+
# If we're broadcasting, nix blas
|
|
976
|
+
if not len(idx_removed & bcast):
|
|
977
|
+
do_blas = _can_dot(tmp_inputs, out_inds, idx_removed)
|
|
978
|
+
else:
|
|
979
|
+
do_blas = False
|
|
980
|
+
|
|
981
|
+
# Last contraction
|
|
982
|
+
if (cnum - len(path)) == -1:
|
|
983
|
+
idx_result = output_subscript
|
|
984
|
+
else:
|
|
985
|
+
sort_result = [(dimension_dict[ind], ind) for ind in out_inds]
|
|
986
|
+
idx_result = "".join([x[1] for x in sorted(sort_result)])
|
|
987
|
+
|
|
988
|
+
input_list.append(idx_result)
|
|
989
|
+
broadcast_indices.append(new_bcast_inds)
|
|
990
|
+
einsum_str = ",".join(tmp_inputs) + "->" + idx_result
|
|
991
|
+
|
|
992
|
+
contraction = (contract_inds, idx_removed, einsum_str, input_list[:], do_blas)
|
|
993
|
+
contraction_list.append(contraction)
|
|
994
|
+
|
|
995
|
+
opt_cost = sum(cost_list) + 1
|
|
996
|
+
|
|
997
|
+
if einsum_call_arg:
|
|
998
|
+
return (operands, contraction_list)
|
|
999
|
+
|
|
1000
|
+
# Return the path along with a nice string representation
|
|
1001
|
+
overall_contraction = input_subscripts + "->" + output_subscript
|
|
1002
|
+
header = ("scaling", "current", "remaining")
|
|
1003
|
+
|
|
1004
|
+
speedup = naive_cost / opt_cost
|
|
1005
|
+
max_i = max(size_list)
|
|
1006
|
+
|
|
1007
|
+
path_print = " Complete contraction: %s\n" % overall_contraction # noqa: E221
|
|
1008
|
+
path_print += " Naive scaling: %d\n" % len(indices)
|
|
1009
|
+
path_print += " Optimized scaling: %d\n" % max(scale_list)
|
|
1010
|
+
path_print += " Naive FLOP count: %.3e\n" % naive_cost
|
|
1011
|
+
path_print += " Optimized FLOP count: %.3e\n" % opt_cost
|
|
1012
|
+
path_print += " Theoretical speedup: %3.3f\n" % speedup
|
|
1013
|
+
path_print += " Largest intermediate: %.3e elements\n" % max_i
|
|
1014
|
+
path_print += "-" * 74 + "\n"
|
|
1015
|
+
path_print += "%6s %24s %40s\n" % header
|
|
1016
|
+
path_print += "-" * 74
|
|
1017
|
+
|
|
1018
|
+
for n, contraction in enumerate(contraction_list):
|
|
1019
|
+
inds, idx_rm, einsum_str, remaining, blas = contraction
|
|
1020
|
+
remaining_str = ",".join(remaining) + "->" + output_subscript
|
|
1021
|
+
path_run = (scale_list[n], einsum_str, remaining_str)
|
|
1022
|
+
path_print += "\n%4d %24s %40s" % path_run
|
|
1023
|
+
|
|
1024
|
+
path = ["einsum_path"] + path
|
|
1025
|
+
return path, path_print
|