Skip to content

setup linting - #19

Merged
mschrimpf merged 8 commits into
mainfrom
mschrimpf/pylint
Oct 16, 2022
Merged

mschrimpf merged 8 commits into
mainfrom
mschrimpf/pylint

Conversation

@mschrimpf

Copy link
Copy Markdown
Member

No description provided.

@mschrimpf

Copy link
Copy Markdown
Member Author

Running a linter works now, but current linting score is very poor, so the check fails

@mschrimpf
mschrimpf requested a review from kvfairchild October 13, 2022 14:47
@kvfairchild

Copy link
Copy Markdown
Contributor

Did we want to combine this with black and/or autopep8 for automatic cleanup?

@mschrimpf

Copy link
Copy Markdown
Member Author

I think it would be great if we could add black/autopep8, but would see that as a separate PR -- @benlipkin @kvfairchild do either of you have experience with running these automatically?

@kvfairchild

Copy link
Copy Markdown
Contributor

Not sure about the latter, but there's an official Actions integration for black

@mschrimpf
mschrimpf merged commit d5a7510 into main Oct 16, 2022
@mschrimpf
mschrimpf deleted the mschrimpf/pylint branch October 16, 2022 12:42
mschrimpf pushed a commit that referenced this pull request Oct 26, 2022
https://github.com/language-brainscore/langbrainscore/tree/e28e8b368463831a9563970964468fa690a82436

Squash commits together:

Initial commit

remove 'fuzzy potato' from readme

Initial commit pt/ 2: set up some poetry stuff and make placeholder dirs and files

quick readme update

Rename langbrainscore/models/encoder.py to langbrainscore/interface/encoder.py

Rename langbrainscore/models/__init__.py to langbrainscore/interface/__init__.py

Create __main__.py

Create .gitkeep

Create test_distilgpt2_vs_pereira18.py

hi

oops

templates for utils

Rename stimuli_utils.py to stim_utils.py

metrics and mapping

ignore vim files

added setup.py

separate specific encoder implementations into a new directory ("encoding" for now)

start writing a test script using distilgpt2 and Pereira18

move encoder implementations out as per prev commit (-2)

placeholder directories for mappings and metrics

start writing example use cases

create a dataset file to wrap datasets

moved this file elsewhere actually

housekeeping

more writing the encoder class(es)

rename encoding to encoder

add init file to encodung directory

update poetry install cmd

Rename spearman_r.py to spearman_rho.py

Update rank_acc.py

implement some basic dataset methods

Update encoder_utils.py

rename silico to ann

more on implementing the dataset classes

implement stuff in the brainencoder

tmeporary example script in the root dir for now (will move into examples/ later)

import stmts in the init

ideally we don't need specific classes for each neuroimaging dataset

implement mapping class

quick placeholder metric implementation

more progress on the mock dataset script

add setup.py file

implement a nice-looking logging module

use log() in some places to logging

clean up mock data script and add helpful comments and print stmts

	renamed:    ../mock_data.py -> mock_data.py

add some visual separators to the test script

meaningully name y_hat and y instead of just ":output"

switch up the order of returned lists

rename pyproject toml for now; interferes with setup.py based installation

TODO: there's some redundancy in the encode()

preliminary HFEncoder stuff

plans to include colorama colorization in the future for nicer output

HuggingFace spelled out might be less ambiguous

do all management with the toml only

edits to the toml

committing updated lock file

git should ignore symlink to data/ for now

do not add data/ directory to the repo

populate intro and usage instructions in the readme

more readme stuff: add an inline ~MWE

enforce type of dataset in brainencoder init

authored-by: benlipkin <[email protected]>

remove weird line endings

adding helpful log messages to xarray sandbox to help understand what xarray is doing and how to use it

add doption to  specify a 'cmap' regardless of message type

MWE

minor style edit

start an interpreter at the end of the file to play with XArray objects

add xarray to dependencies

update the lock file

ben's xarray examples

Update .gitignore

mock dataset now in xarray

some updates to dataset to work with the xarray fmt

added some todo notes

updated lockfile

currently use the Dataset rther than Braindataset until TODOs resolved

more TODOs

more tiny steps to getting the new format to work; driver: test_mock_data

Update encoder.py

Update encoder.py

first draft of get_activations function

add ANN encoder tests to the test mock data file

move brain encoder implementation from interface to encoder submodule

start implementing the ANN encoder class

fix submodules and imports

migrate stuff to lbs.encoder rather than implementing within the lbs.interface

added rsa class

minor typing fix in rsa

Update .gitignore

	new file:   data/.gitkeep

Create .gitkeep

started benchmark packaging script

Update README.md

poetry update

WIP ann encode() method

Update test_mock_data.py

working on encode()

create encode function

more work on ANN encode; MWE in place i think

reduce # of stims for quick testing

adding CV and grouped kfolds functionality to Mapping.py

add missing import typing

rename file Mapping to mapping

fix return variable name

rename mapping to mapping_tools; bugfixes in Mapping class

add some tests for KFold

mapping --> mapping_tools

use ridge_cv with one of them

get rid of the old splits mech, now we have a separate method to handle it

need the .sel() syntax to index into the xarray dataset for cv splits

call fit() in the test script

try to set up CI/CD

add author info and a dev dep (pdoc)

fix syntax error in CI config

install missing dep: curl

update poetry.lock

remove poetry as a dependency of the project

update lockfile

try to get cryptography deps installed

add correct pkg names for deb

remove unused deps added due to poetry

add ipython as a dev dependency

updated lockfile

remove ipython imports from library

ignore docs directory locally

update with correct ssh key fingerprint

add docker instruction

add circle ci status badges

edits to install section

add folder for tests

add mypy and pytest and coverage for testing and type checking

updated gitignore with some paths

add pytest, mypy, and coverage to CI

bugfixes acc to circleci complaints

error in coverage command

try adding || true to exit with code 0 upon test failure

forget pipe in multiple commands leads to non execution in Move coverage results job

docs maybe get overwritten without attach to workspace arg

change order of tasks, maybe that"ll help?

add ls cmd to figure out whats up; for now move test mock data back to examples

make -r repository_url explicit in cmd. will gh-pages actually deploy now?

gh-pages takes strictly a relative path!

add import so code coverage monitors module

import encoder classes from implementations, not interface file

add all testing/coverage commands to a bash script

add pytest-html to generate html report of unit tests

update config to run testing bash script rather than individual commands

try to bugfix testing script

bugfix in call to coverage.py

remove lingering mv statement from config that went into the testing bash script

why is coverage report still not appering

change persist arg in docs-build

another attempt to consolidate tests and coverage into gh-oages

fix -d arg to coverage.py

try combining tests and docs build into same job

the problem with coverage not uploading couldve been gitignore

the issue was coverage.py outputting a stray .gitignore file in the coverage output dir >:(

add development metrics such as unit test, code coverage report links

add semantic versioning spiel to readme

create a Makefile

add some clarification on environments and poetry using makefile

get to the point where we make a call to brainscore.score()

establish a mapping using NaN-removed data (some TODOs remain)

utilize the acerage_over_time flag

write a BrainScore() class

just add a TODO

bugfix: we were dropping timeid here a long time ago

write brainscore ABC

placeholder Mapping and Metric ABCs

write a Mapping() class

root of the module namespace import stmts

update poetry lockfile

minor renaming in same tests

implement scoring per neuroid per timeid and aggregation across cv folds for a stateful brainscore object

now handle timeid

minor edits to type annotations and tqdm desc

bugfix in assigning cvfoldid as a coord

test with real data

remove stray tkinter import added by VScode

Update README.md

add RSA, RDM

test cases

Update brain.py

Update ann.py

Update ann.py

Update ann.py

mapping edits

TODO in mapping

remove weird stray line

some packaged pereira data to test later

WIP debugging of the encoder and cv splits in the mapping class/method

small change to reflect the new data shapes

Delete anntest.py

Create ann_edited.py

change the behavior of np.unique() in context group wise processing. now preserves original order

refactor how tokenized current stim is extracted. still WIP: handle special tokens for bidir models

score() returns aggregated scores; scores_unfolded stores the full scores

split "passage" dimension value at underscore to behave as we expect it to

towards accommodating bidirectional context but extracting only the current stim representation. in partial fulfilment of #19 (excludes special tokens in individual stim length computation, but includes them in the overall context anyway, so extraction is still affected)

fixed timeid frmo getting dropped on average_time=True, now singleton

added back in neuroid and timeid metadata to brsc scores object

modularize parts of mapping and add permute X

WIP dirty commit of ann: trying to fix extracting correct stim from bidir because of special tokens

cleaned up fluff and added some assertions to mapping class

fixed typo bug :0

cleaned up brain encoder and added some assertions; interface is now parallel to ann encoder

cleaned type annotations in encoder interface

fixed some errors in type checking

fixed example in readme for new API

fix brain encoder in example script

delete an archaic test file

edits to reflect new Brain Encoder API: no longer need to initialize it with a dataset

add alphas used in cv to the scores xarrays; if no alphas are used (e.g. LinReg), np.nans are silently placed instead.

ANN encoder clean-up: assertions, delete superfluous stuff, migrate a bit of code to funcs, change aggregation args

ann encoder bug in edge cases (where case plays a role?)

revamped whole metrics interface and module, now more structured, better assertions, and easier to add to

cleaning, comments, typing, no changes to functional behavior

dataset must have subject coord to be used by ceiling etc.

updated Mapping and BrainScore API to be more modular, part of a larger refactoring to handle IdentityMapping scenario more elegantly, and improve efficiency and potential parallelization of metric evaluation

empty commit to test slack integration

more encoder refactoring, moved some stuff to utils

cleaned and repartitioned loop over neuroids from brainscore object to get handled by mapping; leads to some changes in internal interface but ultimately cleaner and more elegant and easily supports IdentityMap+RSA now; still needs to be tidied up and documented and all hyperparmeters/metadata recovered in final score object

more interface refactoring at intersection of mapping, metric, and brainscore modules; still some cleaning up to be done; added new xarray util; added new function to brainscore which joins Y, Y_pred, and scores in a single dataset; Y_pred now contains cvfoldid and alphas, can easily be expanded to add other attributes and hyperparameters from mapping; RSA runs, but score is low likely due to current nan impting approach, worth exploring

improved consistency of dataset interface

comments in interface classes

mapping and brainscore assertions and variable renaming

fixed discrepancy in object returns by metrics; tested CKA

typing adjustment: np.array is a function, np.ndarray is the type

edit links to unit tests, type checks, etc.

edit circle CI badge URL

ignore netcdf files

add a tqdm bar to previous pereira test script (minor)

implement "from_file_or_url" classmethod to read from a csv file adhering to a certain format

add 'wandb' as a dev dependency; upon maturity of using wandb in our codebase, we can consider moving it to 'main'

make space for wandb in `logging`

write new test script for loading Dataset from csv file without manual packaging

add TODO to be more elegant in the error handling here

begin writing caching utility; currently makes folders

fix the special token offset issue (#19)

make sure to add back the minimal required coordinates as well: "stimulus" and "subject"

change `dict + dict_` to `{**dict, **dict_}` for python3.8 compat

change some column names; `subject` and `stimulus` should be added by default even without specifying it in metadata (ref. #18)

allow subject_index=None and assume entire data is from a single subject (#19)

change `read_netcdf` to `load_netcdf` to be clear that it is an existing packaged dataset. also no longer silently overwrite using to_netcdf(). instead show a warning and then overwrite.

clean up signature and re-do documentation for Dataset.from_file_or_url

refactor imports

use GPU if available (#22)

some refactoring and style in ann.py

implement __repr__ for _ModelEncoder interface

to_netcdf and from_netcdf methods taken from the Dataset class

start adding support for caching by adding a new interface called `Cacheable`. all classes we want to be able to cache and recover from cache must subclass this interface

setting the stage to make downstream objects cacheable

incorporated score split coord

implement ANN preprocessing function + change ANN encoder packaging into xarray

added pls mapping

add zarr to main dependencies

ignore xarray, zarr, etc caching outputs

add a basic caching implementation in general and for Dataset object to start with

test caching behavior for pereira dataset script

more ignores for zarr

fix serialization issue in emb preproc

add _cv to linridge

start draft ann encoder check class

added basic ceiling feature; interface integration open to adjustment

rm unused script

add pereira18 to a script within benchmarks module

fix docstring for Dataset; remove redundant __init__ to help support caching behavior

remove repr() to fall back on default repr() from _Cacheable

MWE implementation of caching and recovering from cache for _Cacheable-implementing classes

add a "dataset_name" attribute on _Dataset for identifiability. defaults to None

add a test for caching behavior; currently tests Dataset

update lockfile and pyproject.toml

added neuroid split coord for rsa, cka, and other identity maps

add sparsity tools

initial code for model card (config info, variance explained, sparsity)

ceilings now have same dimensionality as scoring

fix how nan == nan is treated in xarrays in the _Cacheable.__eq__ method

add some docstrings to cache testing stuff

clean old, unused directory

deleted:    langbrainscore/benchmark_packaging/.gitkeep
deleted:    langbrainscore/benchmark_packaging/package_benchmarks.py

add yapf to dev deps

write docstrings in xarray utils

simplify case method

write an `EncoderRepresentations` dataclass to support caching of ANN outputs

add tuple to supported cacheable attributes

move many of the params to __init__ so they become attrs of self and are cached with `HugingFaceEncoder`

add `enforce` for some runtime type checking

Update .gitignore

migrate encoder resources to separate script

update test script args

remove enforce

kw_only kwarg is not valid before 3.10

add mtg notes

remove enforce imports

bugfixes about naming EncoderRepresentations dataclass

handle the case of the new EncoderRepresentations class

fix if-stmt aboiding ceiling and scores recomputation

tuple preproc

working version of ANN encoder check (similarity across layers)

cosine similarity from me and aalok :)

add model card to example script

Update ann.py

dimensionality projection during ceiling calculation

first step in writing the test_ann_encoder test, currently using the same data (so it should trivially match up)

import submodule at module level init

bump transformers to 4.11.3

edits in EncoderCheck

hacky way to make getattr to fall back on the xarray instance

create directory called notebooks just as a placeholder

we still want an AttributeError on original object, not on xarray, if our hack fails

add placeholder line where we should check for cached ANN EncoderRepresentations

caching/override flag to the encode() method

couple of TODOs WIP related to extracting context and caching

remove emb_case argument from test script

implemented new robust context group integration

get rid of casing in ann encoder

fix slice

Update ann.py

otherwise it still goes into edit dist...

WIP method to extract tokens using HuggingFace tokenizer internal method "token_to_chars"

bugfixes in new indices extraction method to work with pytorch tensors

test it on bert with bidirectional context (edits to pereira script)

modify/comment-out some things causing incompatibility with BERT

extract token span of interest and optionally prepend/append reprs corresponding to the special tokens (e.g. [CLS], [SEP])

add 'verbosity' and some minor edits related to cache

add a dataset_name to the pereira dataset

use a template method that creates EncoderRepresentation objects for later modification

dealing with dtype=obj in xarrays

bunch of spammy code formatting changes >:(

"fix" dtypes of the xarray as part of Dataset() init

add util function to fix dtypes

code formatting

nltk no longer needed

started testing load from parquet; in progress

add docstrings and minor edits to HF encoder

add missing import to test file

remove strip from ANN HF encoder: whichever spacing user inputs will be encoded and *not* stripped

add 'include_special_tokens' args in EncoderRepresentations for caching

temporary possible-fix pending more investigation for failing script; towards #18

add formatter to prereqs

use built-in packaging method to declutter test script

change init file import stmt in benchmarks submodule

misc formatting edits

migrate the giant context loop to utils as a stateless function; declutter ANN method

remove old method for computing tokenized offset

reorganize some representations analysis stuff by moving it to utils

placeholder location for future analysis/evaluation of representations

bugix: Path vs str

tpye annotation fmt

bring back original packaging script; handle caching and loading cached dataset

fix forget to pass in dataset so the dataset name wasn't being used to load from cache

minor edits

bugfix re: migration to utils

add verbosity toggle for logging within Mapping()

make last few remaining classes inherit from `_Cacheable`

resolve path before getting its parent so we can run the file within its directory

WIP prototype of langbrainscore CLI

flesh out benchmarks submodule with a loader function by key

formatting edits

migrate "verbosity_check" into within logging.log function

unify `.encode()` API in Brain encoder also

rename "resources" to "preprocessing" in utils

add docs; some enhancements to logging method

decluttering and refactoring

minor refactoring changes

create a "params" @Property on Cacheable objects for easy retrieval of pkey params. the same method is now used to create the identifier string for caching

added support to parallelize benchmark packaging; needs to be tested on cluster

preliminary support for null permutation baselines; needs further testing

model card generic

revamp decomposition and sparsity

mapping between names and config files in HF

return dictionaries with values from layer analyses

start modifying code from Timkey & van Schijndel 2021 for anisotropy

preprocessing calsses mapping moved to "preprocessing" file in utils; and some refactoring

stray log stmt

allow BrainScore to accept `EncoderRepresentations` objects rather than only xarrays

rename `metrics` to `metric` in `langbrainscore.interface`

minor bugfix/refactoring edit

refactor class Metric, which does not inherit from `_Cacheable`, so would be problematic. instead, directly use specific `_Metric` subclasses such as CKA, RSA, KendallTau

formatting

refactoring to be compatible with CLI caching/recompute flags

more helpful error message if score() hasn;t been called but brainscore.__str__ is called

formatting edits

add tqdm in the mapping loop

complete MWE of CLI; print out brainscore at the end; auto-infer model type if omitted

rename pereira benchmark name; remove "nat_stories"

fix benchmark name

separate Network filtering as separate benchmarks in loader function

don't compulsively cache; possibly addresses at least part of #35

explore adding additional attributes to BrainEncoder: measurement type, e.g., fmri

make cacheable object representation more shell-friendly

refactoring

formatting

add an emphasized "announce" cmap to logging

minor formatting

minor edits in CLI flow

add a pereira2018 benchmark for MD

use tqdm in null permutations method

write helper wandb logging methods in logging utils

use wandb logging utils functions to log params to wandb

bugfix: need `.cpu()` before `.numpy()` when running on GPU

handle params that are dicts; e.g. hparams of a ridgecv

use joblib in mapping fit_transform for learning a model per neuroid

make sample_ and neuroid_split_coord part of Mapping and BrainScore objects; they were previously not tracked

allow tokenizers parallellelism explicitly

gitignore wandb logs

brainscore methods no longer take split coords as args; it is part of the object

brainscore methods no longer take split coords as args; it is part of the object
mschrimpf added a commit that referenced this pull request Oct 26, 2022
* setup linting

* use python 3.8 only

* poetry install

* replace poetry with pip

* fix pip syntax

* added pylint-exit; fail only on critical errors

Co-authored-by: Ben Lipkin <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants