flash1dkmeans 0.0.1__tar.gz

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.
@@ -0,0 +1,160 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
@@ -0,0 +1,8 @@
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
4
+ # Editor-based HTTP Client requests
5
+ /httpRequests/
6
+ # Datasource local storage ignored files
7
+ /dataSources/
8
+ /dataSources.local.xml
@@ -0,0 +1,15 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="PYTHON_MODULE" version="4">
3
+ <component name="NewModuleRootManager">
4
+ <content url="file://$MODULE_DIR$">
5
+ <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
6
+ <excludeFolder url="file://$MODULE_DIR$/venv" />
7
+ </content>
8
+ <orderEntry type="jdk" jdkName="Python 3.11 (flash1dkmeans)" jdkType="Python SDK" />
9
+ <orderEntry type="sourceFolder" forTests="false" />
10
+ </component>
11
+ <component name="PyDocumentationSettings">
12
+ <option name="format" value="PLAIN" />
13
+ <option name="myDocStringFormat" value="Plain" />
14
+ </component>
15
+ </module>
@@ -0,0 +1,15 @@
1
+ <component name="InspectionProjectProfileManager">
2
+ <profile version="1.0">
3
+ <option name="myName" value="Project Default" />
4
+ <inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
5
+ <option name="ignoredPackages">
6
+ <value>
7
+ <list size="2">
8
+ <item index="0" class="java.lang.String" itemvalue="torch" />
9
+ <item index="1" class="java.lang.String" itemvalue="threadpoolctl" />
10
+ </list>
11
+ </value>
12
+ </option>
13
+ </inspection_tool>
14
+ </profile>
15
+ </component>
@@ -0,0 +1,6 @@
1
+ <component name="InspectionProjectProfileManager">
2
+ <settings>
3
+ <option name="USE_PROJECT_PROFILE" value="false" />
4
+ <version value="1.0" />
5
+ </settings>
6
+ </component>
@@ -0,0 +1,7 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="Black">
4
+ <option name="sdkName" value="Python 3.11 (flash1dkmeans)" />
5
+ </component>
6
+ <component name="ProjectRootManager" version="2" project-jdk-name="Python 3.11 (flash1dkmeans)" project-jdk-type="Python SDK" />
7
+ </project>
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/flash1dkmeans.iml" filepath="$PROJECT_DIR$/.idea/flash1dkmeans.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="" vcs="Git" />
5
+ </component>
6
+ </project>
@@ -0,0 +1,151 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="AutoImportSettings">
4
+ <option name="autoReloadType" value="SELECTIVE" />
5
+ </component>
6
+ <component name="ChangeListManager">
7
+ <list default="true" id="1ba58836-480f-43dd-9244-0130cb4b0f23" name="Changes" comment="">
8
+ <change afterPath="$PROJECT_DIR$/tests/k_cluster.py" afterDir="false" />
9
+ <change afterPath="$PROJECT_DIR$/tests/two_cluster.py" afterDir="false" />
10
+ <change beforePath="$PROJECT_DIR$/README.md" beforeDir="false" afterPath="$PROJECT_DIR$/README.md" afterDir="false" />
11
+ <change beforePath="$PROJECT_DIR$/src/flash1dkmeans/__init__.py" beforeDir="false" afterPath="$PROJECT_DIR$/src/flash1dkmeans/__init__.py" afterDir="false" />
12
+ <change beforePath="$PROJECT_DIR$/src/flash1dkmeans/main.py" beforeDir="false" afterPath="$PROJECT_DIR$/src/flash1dkmeans/main.py" afterDir="false" />
13
+ <change beforePath="$PROJECT_DIR$/src/flash1dkmeans/n_cluster.py" beforeDir="false" afterPath="$PROJECT_DIR$/src/flash1dkmeans/k_cluster.py" afterDir="false" />
14
+ <change beforePath="$PROJECT_DIR$/src/flash1dkmeans/two_cluster.py" beforeDir="false" afterPath="$PROJECT_DIR$/src/flash1dkmeans/two_cluster.py" afterDir="false" />
15
+ <change beforePath="$PROJECT_DIR$/src/flash1dkmeans/utils.py" beforeDir="false" afterPath="$PROJECT_DIR$/src/flash1dkmeans/utils.py" afterDir="false" />
16
+ </list>
17
+ <option name="SHOW_DIALOG" value="false" />
18
+ <option name="HIGHLIGHT_CONFLICTS" value="true" />
19
+ <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
20
+ <option name="LAST_RESOLUTION" value="IGNORE" />
21
+ </component>
22
+ <component name="FileTemplateManagerImpl">
23
+ <option name="RECENT_TEMPLATES">
24
+ <list>
25
+ <option value="Python Script" />
26
+ </list>
27
+ </option>
28
+ </component>
29
+ <component name="Git.Settings">
30
+ <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" />
31
+ </component>
32
+ <component name="GitHubPullRequestSearchHistory">{
33
+ &quot;lastFilter&quot;: {
34
+ &quot;state&quot;: &quot;OPEN&quot;,
35
+ &quot;assignee&quot;: &quot;SyphonArch&quot;
36
+ }
37
+ }</component>
38
+ <component name="GithubPullRequestsUISettings">{
39
+ &quot;selectedUrlAndAccountId&quot;: {
40
+ &quot;url&quot;: &quot;https://github.com/SyphonArch/flash1dkmeans.git&quot;,
41
+ &quot;accountId&quot;: &quot;78a9a325-3645-4dd5-ba30-89d57dcfc76e&quot;
42
+ }
43
+ }</component>
44
+ <component name="ProjectColorInfo">{
45
+ &quot;associatedIndex&quot;: 0
46
+ }</component>
47
+ <component name="ProjectId" id="2g0ckhIOtcRZbf0wuNcUZcsVEhk" />
48
+ <component name="ProjectViewState">
49
+ <option name="hideEmptyMiddlePackages" value="true" />
50
+ <option name="showLibraryContents" value="true" />
51
+ </component>
52
+ <component name="PropertiesComponent"><![CDATA[{
53
+ "keyToString": {
54
+ "RunOnceActivity.ShowReadmeOnStart": "true",
55
+ "git-widget-placeholder": "main",
56
+ "node.js.detected.package.eslint": "true",
57
+ "node.js.detected.package.tslint": "true",
58
+ "node.js.selected.package.eslint": "(autodetect)",
59
+ "node.js.selected.package.tslint": "(autodetect)",
60
+ "nodejs_package_manager_path": "npm",
61
+ "settings.editor.selected.configurable": "preferences.keymap",
62
+ "vue.rearranger.settings.migration": "true"
63
+ }
64
+ }]]></component>
65
+ <component name="SharedIndexes">
66
+ <attachedChunks>
67
+ <set>
68
+ <option value="bundled-js-predefined-1d06a55b98c1-91d5c284f522-JavaScript-PY-241.15989.155" />
69
+ <option value="bundled-python-sdk-babbdf50b680-7c6932dee5e4-com.jetbrains.pycharm.pro.sharedIndexes.bundled-PY-241.15989.155" />
70
+ </set>
71
+ </attachedChunks>
72
+ </component>
73
+ <component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
74
+ <component name="TaskManager">
75
+ <task active="true" id="Default" summary="Default task">
76
+ <changelist id="1ba58836-480f-43dd-9244-0130cb4b0f23" name="Changes" comment="" />
77
+ <created>1714838079481</created>
78
+ <option name="number" value="Default" />
79
+ <option name="presentableId" value="Default" />
80
+ <updated>1714838079481</updated>
81
+ <workItem from="1714838080524" duration="170000" />
82
+ <workItem from="1714838257640" duration="1013000" />
83
+ <workItem from="1714888190868" duration="167000" />
84
+ <workItem from="1714898221385" duration="481000" />
85
+ <workItem from="1714899699435" duration="2811000" />
86
+ <workItem from="1714905466256" duration="19526000" />
87
+ </task>
88
+ <task id="LOCAL-00001" summary="Drop start_idx and stop_idx">
89
+ <option name="closed" value="true" />
90
+ <created>1714905994757</created>
91
+ <option name="number" value="00001" />
92
+ <option name="presentableId" value="LOCAL-00001" />
93
+ <option name="project" value="LOCAL" />
94
+ <updated>1714905994757</updated>
95
+ </task>
96
+ <task id="LOCAL-00002" summary="Fix logic and semantics">
97
+ <option name="closed" value="true" />
98
+ <created>1714906248163</created>
99
+ <option name="number" value="00002" />
100
+ <option name="presentableId" value="LOCAL-00002" />
101
+ <option name="project" value="LOCAL" />
102
+ <updated>1714906248163</updated>
103
+ </task>
104
+ <task id="LOCAL-00003" summary="Add back start_idx and stop_idx">
105
+ <option name="closed" value="true" />
106
+ <created>1714912137226</created>
107
+ <option name="number" value="00003" />
108
+ <option name="presentableId" value="LOCAL-00003" />
109
+ <option name="project" value="LOCAL" />
110
+ <updated>1714912137226</updated>
111
+ </task>
112
+ <task id="LOCAL-00004" summary="Implementation without start_idx and stop_idx">
113
+ <option name="closed" value="true" />
114
+ <created>1714912671224</created>
115
+ <option name="number" value="00004" />
116
+ <option name="presentableId" value="LOCAL-00004" />
117
+ <option name="project" value="LOCAL" />
118
+ <updated>1714912671224</updated>
119
+ </task>
120
+ <task id="LOCAL-00005" summary="Add start_idx and stop_idx">
121
+ <option name="closed" value="true" />
122
+ <created>1714916169153</created>
123
+ <option name="number" value="00005" />
124
+ <option name="presentableId" value="LOCAL-00005" />
125
+ <option name="project" value="LOCAL" />
126
+ <updated>1714916169153</updated>
127
+ </task>
128
+ <task id="LOCAL-00006" summary="Initial complete implementation">
129
+ <option name="closed" value="true" />
130
+ <created>1714922815609</created>
131
+ <option name="number" value="00006" />
132
+ <option name="presentableId" value="LOCAL-00006" />
133
+ <option name="project" value="LOCAL" />
134
+ <updated>1714922815609</updated>
135
+ </task>
136
+ <option name="localTasksCounter" value="7" />
137
+ <servers />
138
+ </component>
139
+ <component name="TypeScriptGeneratedFilesManager">
140
+ <option name="version" value="3" />
141
+ </component>
142
+ <component name="VcsManagerConfiguration">
143
+ <MESSAGE value="Drop start_idx and stop_idx" />
144
+ <MESSAGE value="Fix logic and semantics" />
145
+ <MESSAGE value="Add back start_idx and stop_idx" />
146
+ <MESSAGE value="Implementation without start_idx and stop_idx" />
147
+ <MESSAGE value="Add start_idx and stop_idx" />
148
+ <MESSAGE value="Initial complete implementation" />
149
+ <option name="LAST_COMMIT_MESSAGE" value="Initial complete implementation" />
150
+ </component>
151
+ </project>
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Jake Hyun
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,128 @@
1
+ Metadata-Version: 2.3
2
+ Name: flash1dkmeans
3
+ Version: 0.0.1
4
+ Summary: An optimized K-means implementation for the one-dimensional case.
5
+ Project-URL: Homepage, https://github.com/SyphonArch/flash1dkmeans
6
+ Project-URL: Issues, https://github.com/SyphonArch/flash1dkmeans/issues
7
+ Author-email: Jake Hyun <jake.hyun@hotmail.com>
8
+ License-File: LICENSE
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.8
13
+ Requires-Dist: numba~=0.59.1
14
+ Requires-Dist: numpy~=1.26.4
15
+ Description-Content-Type: text/markdown
16
+
17
+ # flash1dkmeans
18
+ An optimized K-means implementation for the one-dimensional case
19
+
20
+ Exploits the fact that one-dimensional data can be sorted.
21
+
22
+ Numba acceleration is used, so callers can further use parallelization with Numba's `@njit(parallel=True)`
23
+ if multiple instances of the algorithm are run in parallel.
24
+
25
+ ## Features
26
+
27
+ ### Two clusters
28
+
29
+ Guaranteed to find the optimal solution for two clusters.
30
+
31
+ ### K clusters
32
+
33
+ Uses the K-means++ initialization algorithm to find the initial centroids.
34
+ Then uses the Lloyd's algorithm to find the final centroids, except with optimizations for the one-dimensional case.
35
+
36
+ ## Time Complexity
37
+
38
+ - **2 clusters**: O(log(n))
39
+ - (+ (O(n) for prefix sum calculation if not provided))
40
+ - **k clusters**: O(k * 2 + log(k) * log(n) + max_iter * log(n) * k)
41
+ (+ (O(n) for prefix sum calculation if not provided))
42
+
43
+ This is a significant improvement over the standard K-means algorithm, which has a time complexity of O(n * k * max_iter),
44
+ even excluding the time complexity of the K-means++ initialization.
45
+
46
+ ## How fast is it?
47
+
48
+ TODO: Comparision with sklearn's KMeans
49
+
50
+
51
+ ## Installation
52
+ ```bash
53
+ pip install flash1dkmeans
54
+ ```
55
+
56
+ ## Usage
57
+
58
+ ### Basic usage
59
+ ```python
60
+ from flash1dkmeans import kmeans_1d
61
+
62
+ data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
63
+ k = 2
64
+
65
+ centroids, labels = kmeans_1d(data, k)
66
+ ```
67
+
68
+ ### More Options
69
+ ```python
70
+ from flash1dkmeans import kmeans_1d
71
+ import numpy as np
72
+
73
+ data = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0])
74
+ weights = np.random.random_sample(data.shape)
75
+ k = 3
76
+
77
+ centroids, labels = kmeans_1d(
78
+ data, k,
79
+ sample_weights=weights, # sample weights
80
+ n_local_trials=(2 + int(np.log(k))), # number of local tries
81
+ max_iter=100, # maximum number of iterations
82
+ )
83
+ ```
84
+
85
+ ### Even More Options
86
+ ```python
87
+ from flash1dkmeans import kmeans_1d
88
+ import numpy as np
89
+
90
+ n, k = 1024, 4
91
+
92
+ # Generate random data
93
+ data = np.random.random_sample(n)
94
+ data = np.sort(data)
95
+
96
+ # Generate random weights
97
+ weights = np.random.random_sample(data.shape)
98
+
99
+ # Calculate prefix sums
100
+ weights_prefix_sum = np.cumsum(weights)
101
+ weighted_X_prefix_sum = np.cumsum(data * weights)
102
+ weighted_X_squared_prefix_sum = np.cumsum(data ** 2 * weights)
103
+
104
+ middle_idx = n // 2
105
+
106
+ # Providing prefix sums reduces redundant calculations
107
+ # This is useful when the algorithm is run multiple times on different segments of the data
108
+ for start_idx, stop_idx in [(0, middle_idx), (middle_idx, n)]:
109
+ centroids, cluster_borders = kmeans_1d(
110
+ data, k, # Note how the sample weights are not provided when the prefix sums are provided
111
+ n_local_trials=(2 + int(np.log(k))), # number of local tries
112
+ max_iter=100, # maximum number of iterations
113
+ return_cluster_borders=True, # return cluster borders instead of labels
114
+ weights_prefix_sum=weights_prefix_sum, # prefix sum of the sample weights, leave empty for unwieghted data
115
+ weighted_X_prefix_sum=weighted_X_prefix_sum, # prefix sum of the weighted data
116
+ weighted_X_squared_prefix_sum=weighted_X_squared_prefix_sum, # prefix sum of the squared weighted data
117
+ start_idx=start_idx, # start index of the data
118
+ stop_idx=stop_idx, # stop index of the data
119
+ )
120
+ ```
121
+
122
+ ## Notes
123
+
124
+ This repository has been created to be used in [Any-Precision-LLM](https://github.com/SNU-ARC/any-precision-llm) project,
125
+ where multiple 1D K-means instances are run in parallel for LLM quantization.
126
+
127
+ However the algorithm is general and can be used for any 1D K-means problem.
128
+
@@ -0,0 +1,112 @@
1
+ # flash1dkmeans
2
+ An optimized K-means implementation for the one-dimensional case
3
+
4
+ Exploits the fact that one-dimensional data can be sorted.
5
+
6
+ Numba acceleration is used, so callers can further use parallelization with Numba's `@njit(parallel=True)`
7
+ if multiple instances of the algorithm are run in parallel.
8
+
9
+ ## Features
10
+
11
+ ### Two clusters
12
+
13
+ Guaranteed to find the optimal solution for two clusters.
14
+
15
+ ### K clusters
16
+
17
+ Uses the K-means++ initialization algorithm to find the initial centroids.
18
+ Then uses the Lloyd's algorithm to find the final centroids, except with optimizations for the one-dimensional case.
19
+
20
+ ## Time Complexity
21
+
22
+ - **2 clusters**: O(log(n))
23
+ - (+ (O(n) for prefix sum calculation if not provided))
24
+ - **k clusters**: O(k * 2 + log(k) * log(n) + max_iter * log(n) * k)
25
+ (+ (O(n) for prefix sum calculation if not provided))
26
+
27
+ This is a significant improvement over the standard K-means algorithm, which has a time complexity of O(n * k * max_iter),
28
+ even excluding the time complexity of the K-means++ initialization.
29
+
30
+ ## How fast is it?
31
+
32
+ TODO: Comparision with sklearn's KMeans
33
+
34
+
35
+ ## Installation
36
+ ```bash
37
+ pip install flash1dkmeans
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ ### Basic usage
43
+ ```python
44
+ from flash1dkmeans import kmeans_1d
45
+
46
+ data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]
47
+ k = 2
48
+
49
+ centroids, labels = kmeans_1d(data, k)
50
+ ```
51
+
52
+ ### More Options
53
+ ```python
54
+ from flash1dkmeans import kmeans_1d
55
+ import numpy as np
56
+
57
+ data = np.array([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0])
58
+ weights = np.random.random_sample(data.shape)
59
+ k = 3
60
+
61
+ centroids, labels = kmeans_1d(
62
+ data, k,
63
+ sample_weights=weights, # sample weights
64
+ n_local_trials=(2 + int(np.log(k))), # number of local tries
65
+ max_iter=100, # maximum number of iterations
66
+ )
67
+ ```
68
+
69
+ ### Even More Options
70
+ ```python
71
+ from flash1dkmeans import kmeans_1d
72
+ import numpy as np
73
+
74
+ n, k = 1024, 4
75
+
76
+ # Generate random data
77
+ data = np.random.random_sample(n)
78
+ data = np.sort(data)
79
+
80
+ # Generate random weights
81
+ weights = np.random.random_sample(data.shape)
82
+
83
+ # Calculate prefix sums
84
+ weights_prefix_sum = np.cumsum(weights)
85
+ weighted_X_prefix_sum = np.cumsum(data * weights)
86
+ weighted_X_squared_prefix_sum = np.cumsum(data ** 2 * weights)
87
+
88
+ middle_idx = n // 2
89
+
90
+ # Providing prefix sums reduces redundant calculations
91
+ # This is useful when the algorithm is run multiple times on different segments of the data
92
+ for start_idx, stop_idx in [(0, middle_idx), (middle_idx, n)]:
93
+ centroids, cluster_borders = kmeans_1d(
94
+ data, k, # Note how the sample weights are not provided when the prefix sums are provided
95
+ n_local_trials=(2 + int(np.log(k))), # number of local tries
96
+ max_iter=100, # maximum number of iterations
97
+ return_cluster_borders=True, # return cluster borders instead of labels
98
+ weights_prefix_sum=weights_prefix_sum, # prefix sum of the sample weights, leave empty for unwieghted data
99
+ weighted_X_prefix_sum=weighted_X_prefix_sum, # prefix sum of the weighted data
100
+ weighted_X_squared_prefix_sum=weighted_X_squared_prefix_sum, # prefix sum of the squared weighted data
101
+ start_idx=start_idx, # start index of the data
102
+ stop_idx=stop_idx, # stop index of the data
103
+ )
104
+ ```
105
+
106
+ ## Notes
107
+
108
+ This repository has been created to be used in [Any-Precision-LLM](https://github.com/SNU-ARC/any-precision-llm) project,
109
+ where multiple 1D K-means instances are run in parallel for LLM quantization.
110
+
111
+ However the algorithm is general and can be used for any 1D K-means problem.
112
+
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "flash1dkmeans"
7
+ version = "0.0.1"
8
+ authors = [
9
+ { name="Jake Hyun", email="jake.hyun@hotmail.com" },
10
+ ]
11
+ description = "An optimized K-means implementation for the one-dimensional case."
12
+ readme = "README.md"
13
+ requires-python = ">=3.8"
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+ dependencies = [
20
+ "numba~=0.59.1",
21
+ "numpy~=1.26.4"
22
+ ]
23
+
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/SyphonArch/flash1dkmeans"
27
+ Issues = "https://github.com/SyphonArch/flash1dkmeans/issues"
@@ -0,0 +1 @@
1
+ from .main import kmeans_1d