Skip to content

Commit 1915603

Browse files
theory-in-progressdependabot[bot]vfdev-5
authored
Merge common and specific code-templates (#260)
* Added functionality for merging of common and specific templates - Merges the common template into specific template - Uses replace in js to find the tag and replace with the common code - Uses ejs to render * Merge common and Specific code-templates - Modified the code in fetchTemplates so that any live updates from vue in genCode is not overwritten - Dynamically fetches the common code if the file exists, else proceeds with the code from specific file - Created new function mergeCode to merge codes from specific and common templates using ejs, the code tag being `#:::- replace_here :::#` - The function takes in strings of specific file and common file and returns the rendered code using ejs - The code tag is present in specific template which will be replaced with the code from common template * Handle error code-tag is present in a file but file is missing in Common-template - The if else statements throw an error when replace ejs code-tag is present in the specific file, but the common file is also missing in the common template - This handles the error by just replacing the replace_here tag with an empty string, since this tag is not defined for the second render * Update branch with changes from main * chore(deps): bump playwright-chromium from 1.33.0 to 1.35.1 (#255) Bumps [playwright-chromium](https://github.com/Microsoft/playwright) from 1.33.0 to 1.35.1. - [Release notes](https://github.com/Microsoft/playwright/releases) - [Commits](microsoft/playwright@v1.33.0...v1.35.1) --- updated-dependencies: - dependency-name: playwright-chromium dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump semver from 7.3.5 to 7.5.2 (#254) Bumps [semver](https://github.com/npm/node-semver) from 7.3.5 to 7.5.2. - [Release notes](https://github.com/npm/node-semver/releases) - [Changelog](https://github.com/npm/node-semver/blob/main/CHANGELOG.md) - [Commits](npm/node-semver@v7.3.5...v7.5.2) --- updated-dependencies: - dependency-name: semver dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: vfdev <[email protected]> * chore(deps): bump ejs from 3.1.6 to 3.1.9 (#253) Bumps [ejs](https://github.com/mde/ejs) from 3.1.6 to 3.1.9. - [Release notes](https://github.com/mde/ejs/releases) - [Commits](mde/ejs@v3.1.6...v3.1.9) --- updated-dependencies: - dependency-name: ejs dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump prismjs from 1.26.0 to 1.29.0 (#245) Bumps [prismjs](https://github.com/PrismJS/prism) from 1.26.0 to 1.29.0. - [Release notes](https://github.com/PrismJS/prism/releases) - [Changelog](https://github.com/PrismJS/prism/blob/master/CHANGELOG.md) - [Commits](PrismJS/prism@v1.26.0...v1.29.0) --- updated-dependencies: - dependency-name: prismjs dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * chore(deps): bump @vitejs/plugin-vue from 2.1.0 to 2.3.4 (#251) Bumps [@vitejs/plugin-vue](https://github.com/vitejs/vite-plugin-vue/tree/HEAD/packages/plugin-vue) from 2.1.0 to 2.3.4. - [Release notes](https://github.com/vitejs/vite-plugin-vue/releases) - [Changelog](https://github.com/vitejs/vite-plugin-vue/blob/main/packages/plugin-vue/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite-plugin-vue/commits/HEAD/packages/plugin-vue) --- updated-dependencies: - dependency-name: "@vitejs/plugin-vue" dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: vfdev <[email protected]> * Restructured config (#243) * Restructured config - Restructured config so that arguments are defined in cofing.yaml * Fix main.py * MOdified tests according to new config restructuring * Updating remaining templates with restructured config * Update according to original config args * Configs for all the templates - Created new yaml files for testing the code - These are the test args that will be run when we run the tests * Modified tests according to new config structure * Fix typo * Correct backend argument to be passed in command line * Pass backend argument as a command line argument * Modifying the config structure in template-common --------- Co-authored-by: vfdev <[email protected]> * chore(deps): bump prettier from 2.5.1 to 2.8.8 (#259) Bumps [prettier](https://github.com/prettier/prettier) from 2.5.1 to 2.8.8. - [Release notes](https://github.com/prettier/prettier/releases) - [Changelog](https://github.com/prettier/prettier/blob/main/CHANGELOG.md) - [Commits](prettier/prettier@2.5.1...2.8.8) --- updated-dependencies: - dependency-name: prettier dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: vfdev <[email protected]> --------- Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: vfdev <[email protected]> * Code format * Changed code tag to `from_template_common` * Refactoring the redundant/repeating code in utils.py - Removes the repeating code in the specific templates - The common code is stored in src/templates/template-common * Fix lint of utils.py * Refactoring the redundant/repeating code in config.yaml - Removes the repeating code in the specific templates - The common code is stored in src/templates/template-common * Refactoring the redundant/repeating code in main.py - Removes the repeating code in the specific templates - The common code is stored in src/templates/template-common * MOdify lint options - added min_lint - flake8 tests now run on the rendered code in dist-tests/ * Deleting the script check_copies.py and the command in workflow - We do not need the script now since the code from common and specific don't have an intersection now * Add lint in tests and modify min_lint in lint * Modify render with replace using js on vision-classification template * Install formatting tools in tests job * Change code tags from `#:::- from_template_common :::#` to `#::= from_template_common ::#` handle flake import errors - Changed the code tags to match `.replace()` - handled the flake import errors by including if else statements using ejs rendering * Modifying trainers.py to include the if else statements for unused imports * Removes any usort skip statements in the final code - Making replacement globally * Added usort skip statements for certain imports in trainers.py - Formatting * Modified tests, imports, workflow - Modified tests to check if rendered code is present and unzipped - Modified imports to include `Engine` - Modified workflow so that dir `dist-tests` are removed * Added type hints for functions in template-vision-segmentation/trainers.py * Formatting modifications - added __DEV_CONFIG__.json to prettierignore - start dev server on port 5000 - add F821 non imported objects to flake8 tests - utils Formatting - trainers Formatting --------- Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: vfdev <[email protected]>
1 parent 52b75ba commit 1915603

File tree

21 files changed

+72
-1191
lines changed

21 files changed

+72
-1191
lines changed

.github/workflows/ci.yml

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ jobs:
7070
pip uninstall -y tqdm
7171
npm install -g pnpm
7272
pnpm i --frozen-lockfile --color
73+
bash scripts/run_code_style.sh install
7374
# Show all installed dependencies
7475
pip list
7576
@@ -81,6 +82,7 @@ jobs:
8182
- run: pnpm build
8283
- run: pnpm test:ci
8384
- run: sh ./scripts/run_tests.sh unzip
85+
- run: pnpm lint
8486

8587
- name: 'Run ${{ matrix.template }} ${{ matrix.test }}'
8688
run: sh ./scripts/run_tests.sh ${{ matrix.test }} ${{ matrix.template }}
@@ -108,5 +110,4 @@ jobs:
108110
- run: pip install -Uq pip wheel && bash scripts/run_code_style.sh install
109111
- run: npm install -g pnpm
110112
- run: pnpm i --frozen-lockfile --color
111-
- run: pnpm lint
112-
- run: python scripts/check_copies.py
113+
- run: pnpm min_lint

.prettierignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
dist
22
pnpm-lock.yaml
3+
**/__DEV_CONFIG__.json

package.json

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,14 @@
22
"name": "@pytorch-ignite/code-generator",
33
"version": "0.3.0",
44
"scripts": {
5-
"dev": "vite",
5+
"dev": "vite --port 5000",
66
"build": "vite build",
77
"serve": "vite preview",
8-
"test": "jest --color --runInBand",
8+
"test": "rm -rf ./dist-tests && jest --color --runInBand",
99
"test:ci": "start-server-and-test --expect 200 serve http://127.0.0.1:5000 test",
1010
"release": "node scripts/release.js",
1111
"fmt": "prettier --write . && bash scripts/run_code_style.sh fmt",
12+
"min_lint": "prettier --check . && bash scripts/run_code_style.sh min_lint",
1213
"lint": "prettier --check . && bash scripts/run_code_style.sh lint"
1314
},
1415
"dependencies": {

scripts/check_copies.py

Lines changed: 0 additions & 42 deletions
This file was deleted.

scripts/run_code_style.sh

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,12 @@
33
set -xeu
44

55
if [ $1 == "lint" ]; then
6+
# Check that ./dist-tests/ exists and code is unzipped
7+
ls ./dist-tests/vision-classification-all/main.py
8+
ufmt diff .
9+
flake8 --select F401,F821 ./dist-tests # find unused imports and non imported objects
10+
elif [ $1 == "min_lint" ]; then
611
ufmt diff .
7-
flake8 --select F401 . # find unused imports
812
elif [ $1 == "fmt" ]; then
913
ufmt format .
1014
elif [ $1 == "install" ]; then

src/store.js

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,15 @@ export function saveConfig(key, value) {
5959
}
6060
}
6161

62+
// merges the code from the common and specific files using ejs
63+
function mergeCode(specificFileText, commonFileText) {
64+
const replaced = specificFileText.replace(
65+
/#::= from_template_common ::#/g,
66+
commonFileText
67+
)
68+
return replaced
69+
}
70+
6271
// render the code if there are fetched files for current selected template
6372
export function genCode() {
6473
const currentFiles = files[store.config.template]
@@ -78,6 +87,7 @@ export function genCode() {
7887
)
7988
// trim ` #`
8089
.replace(/\s{4}#$/gim, '')
90+
.replace(/ # usort: skip/g, '')
8191
}
8292
if (isDev) {
8393
store.code[__DEV_CONFIG_FILE__] =
@@ -98,7 +108,14 @@ export async function fetchTemplates(template) {
98108
files[template] = {}
99109
for (const filename of templates[template]) {
100110
const response = await fetch(`${url}/${template}/${filename}`)
101-
files[template][filename] = await response.text()
111+
const text_specific = await response.text()
112+
// Dynamically fetch the common templates-code, if the file exists in common,
113+
// then render the replace_here code tag using ejs template
114+
// If the file doesn't exist in common, then it will fetch an empty string
115+
// then the code tag is replaced with empty string
116+
const res_common = await fetch(`${url}/template-common/${filename}`)
117+
const text_common = await res_common.text()
118+
files[template][filename] = mergeCode(text_specific, text_common)
102119
}
103120

104121
// calling genCode explicitly here

src/templates/template-common/main.py

Lines changed: 4 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,3 @@
1-
ckpt_handler_train, ckpt_handler_eval = setup_handlers(
2-
trainer, evaluator, config, to_save_train, to_save_eval
3-
)
4-
5-
#::: if (it.logger) { :::#
6-
if rank == 0:
7-
exp_logger.close()
8-
#::: } :::#
9-
10-
#::: if (it.save_training || it.save_evaluation) { :::#
11-
# show last checkpoint names
12-
logger.info(
13-
"Last training checkpoint name - %s",
14-
ckpt_handler_train.last_checkpoint,
15-
)
16-
17-
logger.info(
18-
"Last evaluation checkpoint name - %s",
19-
ckpt_handler_eval.last_checkpoint,
20-
)
21-
#::: } :::#
22-
23-
241
# main entrypoint
252
def main():
263
config = setup_config()
@@ -42,3 +19,7 @@ def main():
4219
with idist.Parallel(config.backend) as p:
4320
p.run(run, config=config)
4421
#::: } :::#
22+
23+
24+
if __name__ == "__main__":
25+
main()

src/templates/template-common/utils.py

Lines changed: 24 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,34 @@
1010
import yaml
1111
from ignite.contrib.engines import common
1212
from ignite.engine import Engine
13+
14+
#::: if (it.save_training || it.save_evaluation || it.patience || it.terminate_on_nan || it.limit_sec) { :::#
1315
from ignite.engine.events import Events
14-
from ignite.handlers import Checkpoint, DiskSaver, global_step_from_engine
16+
17+
#::: } :::#
18+
#::: if (it.save_training || it.save_evaluation) { :::#
19+
from ignite.handlers import (
20+
Checkpoint,
21+
DiskSaver,
22+
global_step_from_engine,
23+
) # usort: skip
24+
25+
#::: } else { :::#
26+
from ignite.handlers import Checkpoint
27+
28+
#::: } :::#
29+
#::: if (it.patience) { :::#
1530
from ignite.handlers.early_stopping import EarlyStopping
31+
32+
#::: } :::#
33+
#::: if (it.terminate_on_nan) { :::#
1634
from ignite.handlers.terminate_on_nan import TerminateOnNan
35+
36+
#::: } :::#
37+
#::: if (it.limit_sec) { :::#
1738
from ignite.handlers.time_limit import TimeLimit
39+
40+
#::: } :::#
1841
from ignite.utils import setup_logger
1942

2043

@@ -141,72 +164,6 @@ def setup_logging(config: Any) -> Logger:
141164
return logger
142165

143166

144-
#::: if (it.save_training || it.save_evaluation || it.patience || it.terminate_on_nan || it.limit_sec) { :::#
145-
146-
147-
def setup_handlers(
148-
trainer: Engine,
149-
evaluator: Engine,
150-
config: Any,
151-
to_save_train: Optional[dict] = None,
152-
to_save_eval: Optional[dict] = None,
153-
):
154-
"""Setup Ignite handlers."""
155-
156-
ckpt_handler_train = ckpt_handler_eval = None
157-
#::: if (it.save_training || it.save_evaluation) { :::#
158-
# checkpointing
159-
saver = DiskSaver(config.output_dir / "checkpoints", require_empty=False)
160-
#::: if (it.save_training) { :::#
161-
ckpt_handler_train = Checkpoint(
162-
to_save_train,
163-
saver,
164-
filename_prefix=config.filename_prefix,
165-
n_saved=config.n_saved,
166-
)
167-
trainer.add_event_handler(
168-
Events.ITERATION_COMPLETED(every=config.save_every_iters),
169-
ckpt_handler_train,
170-
)
171-
#::: } :::#
172-
#::: if (it.save_evaluation) { :::#
173-
global_step_transform = None
174-
if to_save_train.get("trainer", None) is not None:
175-
global_step_transform = global_step_from_engine(to_save_train["trainer"])
176-
ckpt_handler_eval = Checkpoint(
177-
to_save_eval,
178-
saver,
179-
filename_prefix="best",
180-
n_saved=config.n_saved,
181-
global_step_transform=global_step_transform,
182-
)
183-
evaluator.add_event_handler(Events.EPOCH_COMPLETED(every=1), ckpt_handler_eval)
184-
#::: } :::#
185-
#::: } :::#
186-
187-
#::: if (it.patience) { :::#
188-
# early stopping
189-
190-
es = EarlyStopping(config.patience, score_fn, trainer)
191-
evaluator.add_event_handler(Events.EPOCH_COMPLETED, es)
192-
#::: } :::#
193-
194-
#::: if (it.terminate_on_nan) { :::#
195-
# terminate on nan
196-
trainer.add_event_handler(Events.ITERATION_COMPLETED, TerminateOnNan())
197-
#::: } :::#
198-
199-
#::: if (it.limit_sec) { :::#
200-
# time limit
201-
trainer.add_event_handler(Events.ITERATION_COMPLETED, TimeLimit(config.limit_sec))
202-
#::: } :::#
203-
#::: if (it.save_training || it.save_evaluation) { :::#
204-
return ckpt_handler_train, ckpt_handler_eval
205-
#::: } :::#
206-
207-
208-
#::: } :::#
209-
210167
#::: if (it.logger) { :::#
211168

212169

Lines changed: 1 addition & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,4 @@
1-
seed: 666
2-
data_path: ./
3-
train_batch_size: 32
4-
eval_batch_size: 32
5-
num_workers: 4
6-
max_epochs: 20
7-
train_epoch_length: 1000
8-
eval_epoch_length: 1000
9-
use_amp: false
10-
debug: false
1+
#::= from_template_common ::#
112
model: bert-base-uncased
123
model_dir: /tmp/model
134
tokenizer_dir: /tmp/tokenizer
@@ -18,45 +9,3 @@ weight_decay: 0.01
189
num_warmup_epochs: 0
1910
max_length: 256
2011
lr: 0.00005
21-
22-
#::: if (it.dist === 'spawn') { :::#
23-
# distributed spawn
24-
nproc_per_node: #:::= it.nproc_per_node :::#
25-
#::: if (it.nnodes) { :::#
26-
# distributed multi node spawn
27-
nnodes: #:::= it.nnodes :::#
28-
#::: if (it.nnodes > 1) { :::#
29-
node_rank: 0
30-
master_addr: #:::= it.master_addr :::#
31-
master_port: #:::= it.master_port :::#
32-
#::: } :::#
33-
#::: } :::#
34-
#::: } :::#
35-
36-
#::: if (it.filename_prefix) { :::#
37-
filename_prefix: #:::= it.filename_prefix :::#
38-
#::: } :::#
39-
40-
#::: if (it.n_saved) { :::#
41-
n_saved: #:::= it.n_saved :::#
42-
#::: } :::#
43-
44-
#::: if (it.save_every_iters) { :::#
45-
save_every_iters: #:::= it.save_every_iters :::#
46-
#::: } :::#
47-
48-
#::: if (it.patience) { :::#
49-
patience: #:::= it.patience :::#
50-
#::: } :::#
51-
52-
#::: if (it.limit_sec) { :::#
53-
limit_sec: #:::= it.limit_sec :::#
54-
#::: } :::#
55-
56-
#::: if (it.output_dir) { :::#
57-
output_dir: #:::= it.output_dir :::#
58-
#::: } :::#
59-
60-
#::: if (it.log_every_iters) { :::#
61-
log_every_iters: #:::= it.log_every_iters :::#
62-
#::: } :::#

src/templates/template-text-classification/main.py

Lines changed: 1 addition & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -173,28 +173,4 @@ def _():
173173
#::: } :::#
174174

175175

176-
# main entrypoint
177-
def main():
178-
config = setup_config()
179-
#::: if (it.dist === 'spawn') { :::#
180-
#::: if (it.nproc_per_node && it.nnodes > 1 && it.master_addr && it.master_port) { :::#
181-
kwargs = {
182-
"nproc_per_node": config.nproc_per_node,
183-
"nnodes": config.nnodes,
184-
"node_rank": config.node_rank,
185-
"master_addr": config.master_addr,
186-
"master_port": config.master_port,
187-
}
188-
#::: } else if (it.nproc_per_node) { :::#
189-
kwargs = {"nproc_per_node": config.nproc_per_node}
190-
#::: } :::#
191-
with idist.Parallel(config.backend, **kwargs) as p:
192-
p.run(run, config=config)
193-
#::: } else { :::#
194-
with idist.Parallel(config.backend) as p:
195-
p.run(run, config=config)
196-
#::: } :::#
197-
198-
199-
if __name__ == "__main__":
200-
main()
176+
#::= from_template_common ::#

0 commit comments

Comments
 (0)