splintering 1.0.0__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.
Files changed (31) hide show
  1. splintering-1.0.0/.github/workflows/python-publish.yml +70 -0
  2. splintering-1.0.0/.gitignore +10 -0
  3. splintering-1.0.0/LICENSE +21 -0
  4. splintering-1.0.0/PKG-INFO +92 -0
  5. splintering-1.0.0/README.md +68 -0
  6. splintering-1.0.0/pyproject.toml +42 -0
  7. splintering-1.0.0/scripts/demo.py +48 -0
  8. splintering-1.0.0/scripts/hebrew/cognitive_evaluation.py +25 -0
  9. splintering-1.0.0/scripts/hebrew/compare_vocabs.py +49 -0
  10. splintering-1.0.0/scripts/hebrew/compare_vocabs_for_dicta_bert.py +26 -0
  11. splintering-1.0.0/scripts/hebrew/trigram_lm.py +15 -0
  12. splintering-1.0.0/scripts/logger.py +14 -0
  13. splintering-1.0.0/scripts/main.py +82 -0
  14. splintering-1.0.0/scripts/params.py +90 -0
  15. splintering-1.0.0/scripts/train_tokenizer.py +35 -0
  16. splintering-1.0.0/src/splintering/__init__.py +0 -0
  17. splintering-1.0.0/src/splintering/experiments/__init__.py +0 -0
  18. splintering-1.0.0/src/splintering/experiments/cognitive_evaluation.py +100 -0
  19. splintering-1.0.0/src/splintering/experiments/compare_vocabs.py +81 -0
  20. splintering-1.0.0/src/splintering/experiments/compare_vocabs_for_dicta_bert.py +77 -0
  21. splintering-1.0.0/src/splintering/experiments/trigram_lm.py +51 -0
  22. splintering-1.0.0/src/splintering/text_processors.py +239 -0
  23. splintering-1.0.0/src/splintering/trainer.py +168 -0
  24. splintering-1.0.0/src/splintering/utils/__init__.py +0 -0
  25. splintering-1.0.0/src/splintering/utils/corpus_tools.py +134 -0
  26. splintering-1.0.0/src/splintering/utils/format_static_checks_results_file.py +332 -0
  27. splintering-1.0.0/src/splintering/utils/languages.py +141 -0
  28. splintering-1.0.0/src/splintering/utils/logger.py +23 -0
  29. splintering-1.0.0/src/splintering/utils/misc.py +88 -0
  30. splintering-1.0.0/src/splintering/utils/path_utils.py +62 -0
  31. splintering-1.0.0/src/splintering/utils/static_checks.py +196 -0
@@ -0,0 +1,70 @@
1
+ # This workflow will upload a Python Package to PyPI when a release is created
2
+ # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries
3
+
4
+ # This workflow uses actions that are not certified by GitHub.
5
+ # They are provided by a third-party and are governed by
6
+ # separate terms of service, privacy policy, and support
7
+ # documentation.
8
+
9
+ name: Upload Python Package
10
+
11
+ on:
12
+ release:
13
+ types: [published]
14
+
15
+ permissions:
16
+ contents: read
17
+
18
+ jobs:
19
+ release-build:
20
+ runs-on: ubuntu-latest
21
+
22
+ steps:
23
+ - uses: actions/checkout@v4
24
+
25
+ - uses: actions/setup-python@v5
26
+ with:
27
+ python-version: "3.x"
28
+
29
+ - name: Build release distributions
30
+ run: |
31
+ # NOTE: put your own distribution build steps here.
32
+ python -m pip install build
33
+ python -m build
34
+
35
+ - name: Upload distributions
36
+ uses: actions/upload-artifact@v4
37
+ with:
38
+ name: release-dists
39
+ path: dist/
40
+
41
+ pypi-publish:
42
+ runs-on: ubuntu-latest
43
+ needs:
44
+ - release-build
45
+ permissions:
46
+ # IMPORTANT: this permission is mandatory for trusted publishing
47
+ id-token: write
48
+
49
+ # Dedicated environments with protections for publishing are strongly recommended.
50
+ # For more information, see: https://docs.github.com/en/actions/deployment/targeting-different-environments/using-environments-for-deployment#deployment-protection-rules
51
+ environment:
52
+ name: pypi
53
+ # OPTIONAL: uncomment and update to include your PyPI project URL in the deployment status:
54
+ # url: https://pypi.org/p/YOURPROJECT
55
+ #
56
+ # ALTERNATIVE: if your GitHub Release name is the PyPI project version string
57
+ # ALTERNATIVE: exactly, uncomment the following line instead:
58
+ # url: https://pypi.org/project/YOURPROJECT/${{ github.event.release.name }}
59
+
60
+ steps:
61
+ - name: Retrieve release distributions
62
+ uses: actions/download-artifact@v4
63
+ with:
64
+ name: release-dists
65
+ path: dist/
66
+
67
+ - name: Publish release distributions to PyPI
68
+ uses: pypa/gh-action-pypi-publish@release/v1
69
+ with:
70
+ packages-dir: dist/
@@ -0,0 +1,10 @@
1
+ /.idea/
2
+ *corpora_tokenized/
3
+ *corpora/
4
+ *splinter/
5
+ *tokenizers/
6
+ *trigram_models/
7
+ *logs/
8
+ *__pycache__/
9
+ /data/
10
+ /raw_data/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 MeLeL lab, Ben-Gurion University
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,92 @@
1
+ Metadata-Version: 2.5
2
+ Name: splintering
3
+ Version: 1.0.0
4
+ Summary: Splinter is a text pre-processing step which rearranges characters into a linear form that better represents nonconcatenative morphologies, enabling meaningful contiguous segments to be found by a subword tokenizer.
5
+ Project-URL: Source, https://github.com/MeLeLBGU/Splintering
6
+ Project-URL: Issues, https://github.com/MeLeLBGU/Splintering/issues
7
+ Author-email: Bar Gazit <bargazi@post.bgu.ac.il>, Shaltiel Shmidman <shaltieltzion@gmail.com>, Avi Shmidman <avi.shmidman@biu.ac.il>, Yuval Pinter <uvp@cs.bgu.ac.il>
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.10
13
+ Requires-Dist: datasets
14
+ Requires-Dist: nltk
15
+ Requires-Dist: numpy<2.0.0
16
+ Requires-Dist: openpyxl~=3.1.5
17
+ Requires-Dist: pandas
18
+ Requires-Dist: scikit-learn
19
+ Requires-Dist: scipy
20
+ Requires-Dist: sentencepiece
21
+ Requires-Dist: tokenization-scorer~=1.1.6
22
+ Requires-Dist: tqdm
23
+ Description-Content-Type: text/markdown
24
+
25
+ # Splintering
26
+ This repository contains the code used in [Splintering Nonconcatenative Languages for Better Tokenization](https://aclanthology.org/2025.findings-acl.1151/).
27
+
28
+ It contains the Splinter algorithm as well as the intrinsic evaluation code.
29
+
30
+ The downstream evaluation DictaBERT-Splinter models can be found [here](https://huggingface.co/dicta-il/dictabert-splinter).
31
+
32
+ The following example trains Splinter on Hebrew Wikipedia, encodes the training corpus, and uses it to train a BPE tokenizer:
33
+
34
+ ```python
35
+ # Training:
36
+ from splintering.trainer import SplinterTrainer
37
+ from splintering.text_processors import TextProcessorWithEncoding
38
+ from splintering.utils.languages import LanguageUtilsFactory
39
+ from splintering.utils.path_utils import get_tokenizer_path, get_corpus_path
40
+ from splintering.utils.misc import get_corpus_name
41
+
42
+ language = 'he'
43
+ train_dataset_path = 'wikimedia/wikipedia'
44
+ train_dataset_name = f'20231101.{language}'
45
+ language_utils = LanguageUtilsFactory.get_by_language(language)
46
+
47
+ # - Create the reductions map, and map the reductions in it into new Unicode characters
48
+ splinter_trainer = SplinterTrainer(language_utils)
49
+ reductions_map, new_unicode_chars_map, _ = splinter_trainer.train(train_dataset_path, train_dataset_name, None)
50
+
51
+ # Application:
52
+ # - Splinter the corpus
53
+ text_processor = TextProcessorWithEncoding(language_utils, reductions_map, new_unicode_chars_map)
54
+ text_processor.save_corpus_as_text_file(train_dataset_path, train_dataset_name)
55
+
56
+ # - Train tokenizer on the splintered corpus
57
+ tokenizer_corpus_path = get_corpus_path(get_corpus_name(train_dataset_path, train_dataset_name))
58
+ tokenizer_type = 'bpe'
59
+ vocab_size = 128_000
60
+
61
+ from scripts.train_tokenizer import train_tokenizer # Thin wrapper around SentencePiece; you can use any package that takes a string corpus.
62
+ tokenizer_path = get_tokenizer_path(tokenizer_type=tokenizer_type, vocab_size=vocab_size)
63
+ train_tokenizer(tokenizer_type=tokenizer_type, vocab_size=vocab_size, input_path=tokenizer_corpus_path,
64
+ output_path=tokenizer_path)
65
+ ```
66
+
67
+ ## Citation
68
+
69
+ If you use Splinter in your research, please cite ```Splintering Nonconcatenative Languages for Better Tokenization```:
70
+
71
+ ```
72
+ @inproceedings{gazit-etal-2025-splintering,
73
+ title = "Splintering Nonconcatenative Languages for Better Tokenization",
74
+ author = "Gazit, Bar and
75
+ Shmidman, Shaltiel and
76
+ Shmidman, Avi and
77
+ Pinter, Yuval",
78
+ editor = "Che, Wanxiang and
79
+ Nabende, Joyce and
80
+ Shutova, Ekaterina and
81
+ Pilehvar, Mohammad Taher",
82
+ booktitle = "Findings of the {A}ssociation for {C}omputational {L}inguistics: {ACL} 2025",
83
+ month = jul,
84
+ year = "2025",
85
+ address = "Vienna, Austria",
86
+ publisher = "Association for Computational Linguistics",
87
+ url = "https://aclanthology.org/2025.findings-acl.1151/",
88
+ doi = "10.18653/v1/2025.findings-acl.1151",
89
+ pages = "22405--22417",
90
+ ISBN = "979-8-89176-256-5"
91
+ }
92
+ ```
@@ -0,0 +1,68 @@
1
+ # Splintering
2
+ This repository contains the code used in [Splintering Nonconcatenative Languages for Better Tokenization](https://aclanthology.org/2025.findings-acl.1151/).
3
+
4
+ It contains the Splinter algorithm as well as the intrinsic evaluation code.
5
+
6
+ The downstream evaluation DictaBERT-Splinter models can be found [here](https://huggingface.co/dicta-il/dictabert-splinter).
7
+
8
+ The following example trains Splinter on Hebrew Wikipedia, encodes the training corpus, and uses it to train a BPE tokenizer:
9
+
10
+ ```python
11
+ # Training:
12
+ from splintering.trainer import SplinterTrainer
13
+ from splintering.text_processors import TextProcessorWithEncoding
14
+ from splintering.utils.languages import LanguageUtilsFactory
15
+ from splintering.utils.path_utils import get_tokenizer_path, get_corpus_path
16
+ from splintering.utils.misc import get_corpus_name
17
+
18
+ language = 'he'
19
+ train_dataset_path = 'wikimedia/wikipedia'
20
+ train_dataset_name = f'20231101.{language}'
21
+ language_utils = LanguageUtilsFactory.get_by_language(language)
22
+
23
+ # - Create the reductions map, and map the reductions in it into new Unicode characters
24
+ splinter_trainer = SplinterTrainer(language_utils)
25
+ reductions_map, new_unicode_chars_map, _ = splinter_trainer.train(train_dataset_path, train_dataset_name, None)
26
+
27
+ # Application:
28
+ # - Splinter the corpus
29
+ text_processor = TextProcessorWithEncoding(language_utils, reductions_map, new_unicode_chars_map)
30
+ text_processor.save_corpus_as_text_file(train_dataset_path, train_dataset_name)
31
+
32
+ # - Train tokenizer on the splintered corpus
33
+ tokenizer_corpus_path = get_corpus_path(get_corpus_name(train_dataset_path, train_dataset_name))
34
+ tokenizer_type = 'bpe'
35
+ vocab_size = 128_000
36
+
37
+ from scripts.train_tokenizer import train_tokenizer # Thin wrapper around SentencePiece; you can use any package that takes a string corpus.
38
+ tokenizer_path = get_tokenizer_path(tokenizer_type=tokenizer_type, vocab_size=vocab_size)
39
+ train_tokenizer(tokenizer_type=tokenizer_type, vocab_size=vocab_size, input_path=tokenizer_corpus_path,
40
+ output_path=tokenizer_path)
41
+ ```
42
+
43
+ ## Citation
44
+
45
+ If you use Splinter in your research, please cite ```Splintering Nonconcatenative Languages for Better Tokenization```:
46
+
47
+ ```
48
+ @inproceedings{gazit-etal-2025-splintering,
49
+ title = "Splintering Nonconcatenative Languages for Better Tokenization",
50
+ author = "Gazit, Bar and
51
+ Shmidman, Shaltiel and
52
+ Shmidman, Avi and
53
+ Pinter, Yuval",
54
+ editor = "Che, Wanxiang and
55
+ Nabende, Joyce and
56
+ Shutova, Ekaterina and
57
+ Pilehvar, Mohammad Taher",
58
+ booktitle = "Findings of the {A}ssociation for {C}omputational {L}inguistics: {ACL} 2025",
59
+ month = jul,
60
+ year = "2025",
61
+ address = "Vienna, Austria",
62
+ publisher = "Association for Computational Linguistics",
63
+ url = "https://aclanthology.org/2025.findings-acl.1151/",
64
+ doi = "10.18653/v1/2025.findings-acl.1151",
65
+ pages = "22405--22417",
66
+ ISBN = "979-8-89176-256-5"
67
+ }
68
+ ```
@@ -0,0 +1,42 @@
1
+ [project]
2
+ name = "splintering"
3
+ version = "1.0.0"
4
+ requires-python = ">= 3.10"
5
+
6
+ authors = [
7
+ {name = "Bar Gazit", email = "bargazi@post.bgu.ac.il"},
8
+ {name = "Shaltiel Shmidman", email = "shaltieltzion@gmail.com"},
9
+ {name = "Avi Shmidman", email = "avi.shmidman@biu.ac.il"},
10
+ {name = "Yuval Pinter", email = "uvp@cs.bgu.ac.il"},
11
+ ]
12
+ description = "Splinter is a text pre-processing step which rearranges characters into a linear form that better represents nonconcatenative morphologies, enabling meaningful contiguous segments to be found by a subword tokenizer."
13
+ classifiers = [
14
+ "Programming Language :: Python :: 3",
15
+ "License :: OSI Approved :: MIT License",
16
+ "Operating System :: OS Independent",
17
+ ]
18
+ readme = "README.md"
19
+
20
+ dependencies = [
21
+ "numpy < 2.0.0",
22
+ "scipy",
23
+ "scikit-learn",
24
+ "pandas",
25
+ "nltk",
26
+ "tqdm",
27
+ "sentencepiece",
28
+ "datasets",
29
+ "tokenization-scorer ~= 1.1.6",
30
+ "openpyxl ~= 3.1.5",
31
+ ]
32
+
33
+ [project.urls]
34
+ Source = "https://github.com/MeLeLBGU/Splintering"
35
+ Issues = "https://github.com/MeLeLBGU/Splintering/issues"
36
+
37
+ [build-system]
38
+ requires = ["hatchling"]
39
+ build-backend = "hatchling.build"
40
+
41
+ [tool.hatch.build.targets.wheel]
42
+ packages = ["src/splintering"]
@@ -0,0 +1,48 @@
1
+ from scripts.params import set_run_params, get_dummy_experiment
2
+ from scripts.logger import get_logger, initialize_logger
3
+
4
+ import os
5
+ import sentencepiece as spm
6
+
7
+ from splintering.text_processors import TextProcessorForDemo
8
+ from splintering.utils.languages import LanguageUtilsFactory
9
+ from splintering.utils.languages import LanguageUtilsInterface
10
+ from splintering.utils.path_utils import get_logs_dir, get_tokenizers_dir
11
+ from splintering.utils.misc import (get_reductions_map_from_file, get_new_unicode_chars_map_from_file,
12
+ get_new_unicode_chars_inverted_map_from_file)
13
+
14
+
15
+ def demo(text: str, language_utils: LanguageUtilsInterface) -> None:
16
+ get_logger().info(f'\nOriginal text: \n{text}')
17
+ text_processor = get_processor(language_utils)
18
+ non_encoded_text, encoded_text = text_processor.process(text)
19
+ get_logger().info(f'\n\nNon-encoded splintered text: \n{non_encoded_text}')
20
+ get_logger().info(f'\n\nEncoded splintered text: \n{encoded_text}')
21
+ decoded_text, original_text = text_processor.undo_process(encoded_text)
22
+ get_logger().info(f'\n\nDecoded splintered text: \n{decoded_text}')
23
+ get_logger().info(f'\n\nBack to original text: \n{original_text}')
24
+
25
+
26
+ def get_processor(language_utils: LanguageUtilsInterface) -> TextProcessorForDemo:
27
+ reductions_map = get_reductions_map_from_file()
28
+ new_unicode_chars_map = get_new_unicode_chars_map_from_file()
29
+ new_unicode_chars_inverted_map = get_new_unicode_chars_inverted_map_from_file()
30
+ text_processor = TextProcessorForDemo(language_utils, reductions_map, new_unicode_chars_map, new_unicode_chars_inverted_map)
31
+ return text_processor
32
+
33
+
34
+ def tokenize_example(text: str, tokenizer_type: str, vocab_size: int) -> None:
35
+ tokenizer_path = f'{get_tokenizers_dir()}/{tokenizer_type}_{vocab_size}.model'
36
+ sp_tokenizer = spm.SentencePieceProcessor(model_file=tokenizer_path)
37
+ encoded_text = " ".join([str(token_id) for token_id in sp_tokenizer.encode(text)])
38
+ get_logger().info(f'tokenized example: {encoded_text}')
39
+
40
+
41
+ if __name__ == '__main__':
42
+ experiment = get_dummy_experiment('2025-01-21-hebrew-letters_subset')
43
+ set_run_params(experiment)
44
+ os.makedirs(get_logs_dir(), exist_ok=True)
45
+ initialize_logger()
46
+ get_logger().info(f'Logs will be saved here: {get_logs_dir()}')
47
+ # tokenize_example("עבודה לעבוד במעבדה", "bpe", 128000)
48
+ demo("נגרר", LanguageUtilsFactory.get_by_language("he"))
@@ -0,0 +1,25 @@
1
+ from scripts.params import experiments, set_run_params, get_run_params
2
+ from scripts.logger import get_logger, initialize_logger
3
+
4
+ from splintering.utils.path_utils import create_experiment_dirs, get_tokenizer_path
5
+ from splintering.utils.misc import add_static_result_to_file
6
+ from splintering.experiments.cognitive_evaluation import tokenize_cognitive_evaluation_file, run_cognitive_evaluation
7
+
8
+ task_id = 0
9
+ experiment = experiments[task_id]
10
+ experiment["TASK_ID"] = task_id
11
+ set_run_params(experiment)
12
+ create_experiment_dirs()
13
+ initialize_logger()
14
+ get_logger().info(f'Experiment started')
15
+ try:
16
+ for tokenizer_type in get_run_params("TOKENIZERS_TYPES"):
17
+ for vocab_size in get_run_params("TOKENIZERS_VOCAB_SIZES"):
18
+ tokenizer_path = get_tokenizer_path(tokenizer_type=tokenizer_type, vocab_size=vocab_size)
19
+ tokenize_cognitive_evaluation_file(tokenizer_path, tokenizer_type, vocab_size)
20
+ cognitive_evaluation = run_cognitive_evaluation(tokenizer_type, vocab_size)
21
+ add_static_result_to_file(cognitive_evaluation)
22
+ except Exception as e:
23
+ get_logger().exception(f'Experiment failed with error: \n{e}')
24
+ exit(1)
25
+ get_logger().info(f'Experiment finished')
@@ -0,0 +1,49 @@
1
+ from scripts.params import set_run_params, get_all_letters_template, get_run_params
2
+
3
+ from splintering.utils.languages import LanguageUtilsFactory
4
+ from splintering.utils.path_utils import get_logs_dir
5
+ from splintering.experiments.compare_vocabs import list_all_vocab_files, decode_splintered_vocab, compare_vocabs
6
+
7
+
8
+ def main(all_letters_vocabs_file_path: str, baseline_vocabs_file_path: str):
9
+ experiment = get_all_letters_template()
10
+ experiment["TASK_ID"] = '1000000'
11
+ experiment['TOKENIZERS_VOCAB_SIZES'] = [128000, 64000, 32000, 10000, 2000, 1000, 800]
12
+ set_run_params(experiment)
13
+
14
+ import os
15
+ os.makedirs(get_logs_dir(), exist_ok=True)
16
+
17
+ # clean old runs results
18
+ output_path = f'{get_logs_dir()}/vocabs_comparison.txt'
19
+ if os.path.exists(output_path):
20
+ os.remove(output_path)
21
+
22
+ all_letters_vocab_files = list_all_vocab_files(all_letters_vocabs_file_path)
23
+ baseline_vocab_files = list_all_vocab_files(baseline_vocabs_file_path)
24
+
25
+ language_utils = LanguageUtilsFactory.get_by_language(get_run_params("LANGUAGE"))
26
+ for vocab_file in all_letters_vocab_files.keys():
27
+ baseline_vocab_file = baseline_vocab_files.get(vocab_file)
28
+ with open(baseline_vocab_file, 'r', encoding='utf-8') as file:
29
+ baseline_vocab = file.read().splitlines()
30
+ baseline_vocab = [token.split('\t')[0] for token in baseline_vocab]
31
+
32
+ splinter_vocab_file = all_letters_vocab_files.get(vocab_file)
33
+ with open(splinter_vocab_file, 'r', encoding='utf-8') as file:
34
+ splinter_vocab = [line.rstrip("\n") for line in file]
35
+ splinter_decoded_vocab = decode_splintered_vocab(splinter_vocab, language_utils)
36
+
37
+ with open(f'{get_logs_dir()}/{vocab_file}_decoded.txt', 'w', encoding='utf-8') as file:
38
+ file.write("\n".join(splinter_decoded_vocab))
39
+
40
+ results = compare_vocabs(baseline_vocab, splinter_decoded_vocab)
41
+ with open(output_path, 'a', encoding='utf-8') as file:
42
+ file.write(f"\n\n{vocab_file}:\n")
43
+ file.write("\n".join(results))
44
+
45
+
46
+ main(
47
+ all_letters_vocabs_file_path = './experiments/2025-01-21-hebrew-all_letters/results/tokenizers',
48
+ baseline_vocabs_file_path = './experiments/2025-01-21-hebrew-baseline/results/tokenizers'
49
+ )
@@ -0,0 +1,26 @@
1
+ from scripts.params import set_run_params, get_all_letters_template
2
+
3
+ from splintering.utils.path_utils import get_logs_dir
4
+ from splintering.utils.languages import HebrewUtils
5
+ from splintering.experiments.compare_vocabs_for_dicta_bert import get_dicta_bert_tokens, compare_vocabs
6
+
7
+
8
+ experiment = get_all_letters_template()
9
+ experiment['EXPERIMENT_NAME'] = '2025-01-06-compare_vocabs_dicta_bert' # all letters
10
+ experiment["TASK_ID"] = '1000000'
11
+ experiment['TOKENIZERS_VOCAB_SIZES'] = [128000, 64000, 32000, 10000, 2000, 1000, 800]
12
+ set_run_params(experiment)
13
+
14
+ import os
15
+ os.makedirs(get_logs_dir(), exist_ok=True)
16
+
17
+ language_utils = HebrewUtils()
18
+ output_path = f'{get_logs_dir()}/vocabs_comparison.txt'
19
+ baseline_vocab, splinter_decoded_vocab = get_dicta_bert_tokens(language_utils)
20
+
21
+ with open(f'{get_logs_dir()}/SplinterDictaBert - Vocab - decoded.txt', 'w', encoding='utf-8') as file:
22
+ file.write("\n".join(splinter_decoded_vocab))
23
+
24
+ results = compare_vocabs(baseline_vocab, splinter_decoded_vocab)
25
+ with open(output_path, 'a') as file:
26
+ file.write("\n".join(results))
@@ -0,0 +1,15 @@
1
+ from scripts.params import get_dummy_experiment, set_run_params
2
+ from scripts.logger import get_logger, initialize_logger
3
+
4
+ from splintering.utils.path_utils import get_trigram_models_dir, get_corpora_tokenized_dir, get_logs_dir
5
+ from splintering.experiments.trigram_lm import test_perplexity
6
+
7
+
8
+ experiment = get_dummy_experiment('2025-01-01-trigram_lm_perplexity')
9
+ set_run_params(experiment)
10
+
11
+ import os
12
+ os.makedirs(get_logs_dir(), exist_ok=True)
13
+ os.makedirs(get_trigram_models_dir(), exist_ok=True)
14
+ initialize_logger()
15
+ perplexity = test_perplexity(corpus_name='hebrew_diacritized_pre_modern_unigram_10000', train_model=True)
@@ -0,0 +1,14 @@
1
+ import json
2
+
3
+ from scripts.params import get_all_run_params
4
+ from splintering.utils.logger import initialize_logger as _init, get_logger
5
+
6
+
7
+ def initialize_logger():
8
+ _init()
9
+ logger = get_logger()
10
+
11
+ # log run params
12
+ logger.info("********** RUN PARAMETERS **********")
13
+ run_params_str = json.dumps(get_all_run_params(), indent='\t')
14
+ logger.info(f"\n{run_params_str}\n\n\n")
@@ -0,0 +1,82 @@
1
+ from scripts.params import experiments, get_run_params, set_run_params
2
+ from scripts.logger import get_logger, initialize_logger
3
+
4
+ from splintering.utils.corpus_tools import CorpusTokenizer
5
+ from splintering.trainer import SplinterTrainer
6
+ from splintering.text_processors import TextProcessorBaseline, TextProcessorWithEncoding
7
+ from splintering.utils.languages import LanguageUtilsFactory
8
+ from splintering.utils.static_checks import run_static_checks, run_types_length_distribution
9
+ from scripts.train_tokenizer import train_tokenizer
10
+ from splintering.utils.path_utils import create_experiment_dirs, get_tokenizer_path, get_corpus_path, get_tokenized_corpus_path
11
+ from splintering.utils.misc import add_static_result_to_file, get_corpus_name
12
+
13
+
14
+ def run():
15
+ language_utils = LanguageUtilsFactory.get_by_language(get_run_params("LANGUAGE"))
16
+ train_dataset_path = get_run_params("SPLINTER_TRAINING_CORPUS_PATH")
17
+ train_dataset_name = get_run_params("SPLINTER_TRAINING_CORPUS_NAME")
18
+ letters_subset = get_run_params("SPLINTER_LETTERS_SUBSET")
19
+
20
+ if get_run_params("SAVE_CORPORA_INTO_FILE"):
21
+ # this is a splinter experiment
22
+ if get_run_params("IS_ENCODED"):
23
+ splinter_trainer = SplinterTrainer(language_utils)
24
+ reductions_map, new_unicode_chars_map, _ = splinter_trainer.train(train_dataset_path, train_dataset_name, letters_subset)
25
+ text_processor = TextProcessorWithEncoding(language_utils, reductions_map, new_unicode_chars_map)
26
+
27
+ # this is a baseline experiment - no splinter
28
+ else:
29
+ text_processor = TextProcessorBaseline(language_utils)
30
+
31
+ # save entire corpora as text files, encoded or not
32
+ text_processor.save_corpus_as_text_file(train_dataset_path, train_dataset_name)
33
+ language_utils.save_additional_corpora_for_evaluation(text_processor)
34
+
35
+ # train tokenizers of different type (unigram / bpe), resulting in different vocab size
36
+ if get_run_params("TRAIN_TOKENIZERS"):
37
+ tokenizer_corpus_path = get_corpus_path(get_corpus_name(train_dataset_path, train_dataset_name))
38
+ for tokenizer_type in get_run_params("TOKENIZERS_TYPES"):
39
+ for vocab_size in get_run_params("TOKENIZERS_VOCAB_SIZES"):
40
+ tokenizer_path = get_tokenizer_path(tokenizer_type=tokenizer_type, vocab_size=vocab_size)
41
+ train_tokenizer(tokenizer_type=tokenizer_type, vocab_size=vocab_size, input_path=tokenizer_corpus_path, output_path=tokenizer_path)
42
+
43
+ # for each trained tokenizer
44
+ for tokenizer_type in get_run_params("TOKENIZERS_TYPES"):
45
+ for vocab_size in get_run_params("TOKENIZERS_VOCAB_SIZES"):
46
+ # tokenize corpora into files
47
+ if get_run_params("TOKENIZE_CORPORA"):
48
+ tokenizer_path = get_tokenizer_path(tokenizer_type=tokenizer_type, vocab_size=vocab_size)
49
+ for corpus_name in get_run_params("STATIC_CHECKS_CORPORA"):
50
+ corpus_path = get_corpus_path(corpus_name)
51
+ tokenized_corpus_path = get_tokenized_corpus_path(corpus_name, tokenizer_type, vocab_size)
52
+ CorpusTokenizer().tokenize_corpus_into_file(tokenizer_path, corpus_path, tokenized_corpus_path)
53
+
54
+ # run static checks on tokenized corpora
55
+ if get_run_params("RUN_STATIC_CHECKS"):
56
+ types_length_distribution = run_types_length_distribution(tokenizer_type, vocab_size)
57
+ add_static_result_to_file(types_length_distribution)
58
+
59
+ for corpus_name in get_run_params("STATIC_CHECKS_CORPORA"):
60
+ corpus_path = get_corpus_path(corpus_name)
61
+ tokenized_corpus_path = get_tokenized_corpus_path(corpus_name, tokenizer_type, vocab_size)
62
+ tokenizer_path = get_tokenizer_path(tokenizer_type=tokenizer_type, vocab_size=vocab_size)
63
+ results = run_static_checks(corpus_path, tokenized_corpus_path, tokenizer_path, vocab_size)
64
+ add_static_result_to_file(results)
65
+
66
+
67
+ if __name__ == '__main__':
68
+ import os
69
+ slurm_array_task_id = os.getenv('SLURM_ARRAY_TASK_ID')
70
+ task_id = (int(slurm_array_task_id) - 1) if slurm_array_task_id else 0
71
+ experiment = experiments[task_id]
72
+ experiment["TASK_ID"] = task_id
73
+ set_run_params(experiment)
74
+ create_experiment_dirs()
75
+ initialize_logger()
76
+ get_logger().info(f'Experiment {task_id + 1} started')
77
+ try:
78
+ run()
79
+ except Exception as e:
80
+ get_logger().exception(f'Experiment {task_id + 1} failed with error: \n{e}')
81
+ exit(1)
82
+ get_logger().info(f'Experiment {task_id + 1} finished')
@@ -0,0 +1,90 @@
1
+ import copy
2
+ from datetime import datetime, timezone
3
+
4
+
5
+ run_params = {} # value is filled by set_run_params in main
6
+
7
+ def set_run_params(params):
8
+ global run_params
9
+ run_params = params
10
+ run_params["TIMESTAMP"] = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
11
+
12
+
13
+ def get_run_params(key):
14
+ global run_params
15
+ return run_params[key]
16
+
17
+
18
+ def get_all_run_params():
19
+ global run_params
20
+ return run_params
21
+
22
+ LANGUAGE = 'he'
23
+ LANGUAGE_FULL = 'hebrew'
24
+ EXPERIMENT_DATE = '2025-01-21'
25
+
26
+ if LANGUAGE == 'he':
27
+ STATIC_CHECKS_CORPORA = ['hebrew_diacritized_pre_modern', 'HeNLP_HeDC4']
28
+ else:
29
+ STATIC_CHECKS_CORPORA = [f'wikimedia_wikipedia_20231101_{LANGUAGE}']
30
+
31
+ experiment_template = {
32
+ 'LANGUAGE': LANGUAGE,
33
+ 'SAVE_CORPORA_INTO_FILE': False,
34
+ 'SPLINTER_TRAINING_CORPUS_PATH': 'wikimedia/wikipedia',
35
+ 'SPLINTER_TRAINING_CORPUS_NAME': f'20231101.{LANGUAGE}',
36
+ 'TRAIN_TOKENIZERS': False,
37
+ 'TOKENIZERS_TYPES': ['unigram', 'bpe'],
38
+ 'TOKENIZE_CORPORA': False,
39
+ 'RUN_STATIC_CHECKS': True,
40
+ 'STATIC_CHECKS_CORPORA': STATIC_CHECKS_CORPORA,
41
+ }
42
+
43
+
44
+ def get_all_letters_template():
45
+ all_letters_template = copy.deepcopy(experiment_template)
46
+ all_letters_template['EXPERIMENT_NAME'] = f'{EXPERIMENT_DATE}-{LANGUAGE_FULL}-all_letters' # all letters
47
+ all_letters_template['IS_ENCODED'] = True
48
+ all_letters_template['SPLINTER_LETTERS_SUBSET'] = None # None = all letters
49
+ return all_letters_template
50
+
51
+
52
+ def get_letters_subset_template():
53
+ letters_subset_template = copy.deepcopy(experiment_template)
54
+ letters_subset_template['EXPERIMENT_NAME'] = f'{EXPERIMENT_DATE}-{LANGUAGE_FULL}-letters_subset' # letters subset
55
+ letters_subset_template['IS_ENCODED'] = True
56
+ letters_subset_template['SPLINTER_LETTERS_SUBSET'] = ["א", "ב", "ה", "ו", "י", "כ", "ל", "מ", "נ", "ש", "ת"]
57
+ return letters_subset_template
58
+
59
+
60
+ def get_baseline_template():
61
+ baseline_template = copy.deepcopy(experiment_template)
62
+ baseline_template['EXPERIMENT_NAME'] = f'{EXPERIMENT_DATE}-{LANGUAGE_FULL}-baseline' # baseline
63
+ baseline_template['IS_ENCODED'] = False # False = baseline experiment
64
+ baseline_template['SPLINTER_LETTERS_SUBSET'] = None
65
+ return baseline_template
66
+
67
+
68
+ def split_to_separate_runs(template):
69
+ runs = []
70
+ vocab_sizes = [128000, 64000, 32000, 10000, 2000, 1000, 800]
71
+ for vocab_size in vocab_sizes:
72
+ run = copy.deepcopy(template)
73
+ run['TOKENIZERS_VOCAB_SIZES'] = [vocab_size]
74
+ runs.append(run)
75
+ return runs
76
+
77
+
78
+ def get_dummy_experiment(experiment_name: str):
79
+ experiment = copy.deepcopy(get_baseline_template())
80
+ experiment['EXPERIMENT_NAME'] = experiment_name
81
+ experiment["TASK_ID"] = '1000000'
82
+ experiment['TOKENIZERS_VOCAB_SIZES'] = [128000]
83
+ return experiment
84
+
85
+
86
+ experiments = []
87
+ experiments.extend(split_to_separate_runs(get_all_letters_template()))
88
+ if LANGUAGE == 'he':
89
+ experiments.extend(split_to_separate_runs(get_letters_subset_template()))
90
+ experiments.extend(split_to_separate_runs(get_baseline_template()))