code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def _textual_index_column( table: Table, text_: Union[str, TextClause, ColumnElement[Any]] ) -> Union[ColumnElement[Any], Column[Any]]: """a workaround for the Index construct's severe lack of flexibility""" if isinstance(text_, str): c = Column(text_, sqltypes.NULLTYPE) table.append_column(...
a workaround for the Index construct's severe lack of flexibility
_textual_index_column
python
sqlalchemy/alembic
alembic/util/sqla_compat.py
https://github.com/sqlalchemy/alembic/blob/master/alembic/util/sqla_compat.py
MIT
def non_native_boolean(self): """test will fail if native boolean is provided""" return exclusions.fails_if( exclusions.LambdaPredicate( lambda config: config.db.dialect.supports_native_boolean ) )
test will fail if native boolean is provided
non_native_boolean
python
sqlalchemy/alembic
tests/requirements.py
https://github.com/sqlalchemy/alembic/blob/master/tests/requirements.py
MIT
def non_native_boolean_check_constraint(self): """backend creates a check constraint for booleans if enabled""" return exclusions.only_on( exclusions.LambdaPredicate( lambda config: not config.db.dialect.supports_native_boolean and config.db.dialect.non_nativ...
backend creates a check constraint for booleans if enabled
non_native_boolean_check_constraint
python
sqlalchemy/alembic
tests/requirements.py
https://github.com/sqlalchemy/alembic/blob/master/tests/requirements.py
MIT
def reflects_pk_names(self): """Target driver reflects the name of primary key constraints.""" return exclusions.fails_on_everything_except( "postgresql", "oracle", "mssql", "sybase", "sqlite" )
Target driver reflects the name of primary key constraints.
reflects_pk_names
python
sqlalchemy/alembic
tests/requirements.py
https://github.com/sqlalchemy/alembic/blob/master/tests/requirements.py
MIT
def test_render_diffs_batch(self): """test a full render in batch mode including indentation""" template_args = {} self.context.opts["render_as_batch"] = True autogenerate._render_migration_diffs(self.context, template_args) eq_( template_args["upgrades"], ...
test a full render in batch mode including indentation
test_render_diffs_batch
python
sqlalchemy/alembic
tests/test_autogen_composition.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_autogen_composition.py
MIT
def test_render_diffs_extras(self): """test a full render including indentation (include and schema)""" template_args = {} self.context.opts.update( { "include_object": _default_include_object, "include_schemas": True, } ) ...
test a full render including indentation (include and schema)
test_render_diffs_extras
python
sqlalchemy/alembic
tests/test_autogen_composition.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_autogen_composition.py
MIT
def test_diffs_order(self): """ Added in order to test that child tables(tables with FKs) are generated before their parent tables """ ctx = self.autogen_context uo = ops.UpgradeOps(ops=[]) autogenerate._produce_net_changes(ctx, uo) diffs = uo.as_diffs() ...
Added in order to test that child tables(tables with FKs) are generated before their parent tables
test_diffs_order
python
sqlalchemy/alembic
tests/test_autogen_diffs.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_autogen_diffs.py
MIT
def test_nothing_changed_cols_unsorted(self): """test #1240 MySQL doubles unique constraints as indexes, so we need to make sure we aren't comparing index sigs to unique constraint sigs, which we were doing previously by mistake. As their signatures were compatible, things "wo...
test #1240 MySQL doubles unique constraints as indexes, so we need to make sure we aren't comparing index sigs to unique constraint sigs, which we were doing previously by mistake. As their signatures were compatible, things "worked" but once index sigs changed col name sortin...
test_nothing_changed_cols_unsorted
python
sqlalchemy/alembic
tests/test_autogen_indexes.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_autogen_indexes.py
MIT
def test_repr_custom_type(self, modname, construct): """test #1167 as well as other user defined type variations""" self.autogen_context.opts["user_module_prefix"] = None class MyType(UserDefinedType): pass if modname == "sqlaname": MyType.__module__ = mod = "s...
test #1167 as well as other user defined type variations
test_repr_custom_type
python
sqlalchemy/alembic
tests/test_autogen_render.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_autogen_render.py
MIT
def test_render_check_constraint_renamed(self): """test that constraints from autogenerate render with the naming convention name explicitly. These names should be frozen into the migration scripts so that they remain the same if the application's naming convention changes. How...
test that constraints from autogenerate render with the naming convention name explicitly. These names should be frozen into the migration scripts so that they remain the same if the application's naming convention changes. However, op.create_table() and others need to be careful that ...
test_render_check_constraint_renamed
python
sqlalchemy/alembic
tests/test_autogen_render.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_autogen_render.py
MIT
def test_config_file_failure_modes(self): """with two config files supported at the same time, test failure modes with multiple --config directives """ c1 = config.CommandLine() with expect_raises_message( util.CommandError, "only one ini file may be indicated" ...
with two config files supported at the same time, test failure modes with multiple --config directives
test_config_file_failure_modes
python
sqlalchemy/alembic
tests/test_command.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_command.py
MIT
def test_config_file_resolution( self, args, expected_toml, expected_conf, pop_alembic_config_env ): """with two config files supported at the same time, test resolution of --config / ALEMBIC_CONFIG to always "do what's expected" """ c1 = config.CommandLine() if "ALE...
with two config files supported at the same time, test resolution of --config / ALEMBIC_CONFIG to always "do what's expected"
test_config_file_resolution
python
sqlalchemy/alembic
tests/test_command.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_command.py
MIT
def test_init_file_relative_version_token( self, template, directory, toml_file_name, config_file_name, expected_toml_location, expected_ini_location, clear_staging_dir, ): """in 1.16.0 with the advent of pyproject.toml, we are also rendering ...
in 1.16.0 with the advent of pyproject.toml, we are also rendering the script_location value relative to the ``%(here)s`` token, if the given path is a relative path. ``%(here)s`` is relative to the owning config file either alembic.ini or pyproject.toml.
test_init_file_relative_version_token
python
sqlalchemy/alembic
tests/test_command.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_command.py
MIT
def test_add_column_schema_type(self): """Test that a schema type generates its constraints....""" context = op_fixture() op.add_column( "t1", Column("c1", Boolean(create_constraint=True), nullable=False) ) context.assert_( "ALTER TABLE t1 ADD COLUMN c1 BO...
Test that a schema type generates its constraints....
test_add_column_schema_type
python
sqlalchemy/alembic
tests/test_op.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_op.py
MIT
def test_add_column_schema_type_checks_rule(self): """Test that a schema type doesn't generate a constraint based on check rule.""" context = op_fixture("postgresql") op.add_column( "t1", Column("c1", Boolean(create_constraint=True), nullable=False) ) context....
Test that a schema type doesn't generate a constraint based on check rule.
test_add_column_schema_type_checks_rule
python
sqlalchemy/alembic
tests/test_op.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_op.py
MIT
def test_add_foreign_key_composite_self_referential(self): """test #1215 the same column name is present on both sides. """ context = op_fixture() op.create_foreign_key( "fk_test", "t1", "t1", ["foo", "bar"], ["bat", "bar"] ) context.assert_( ...
test #1215 the same column name is present on both sides.
test_add_foreign_key_composite_self_referential
python
sqlalchemy/alembic
tests/test_op.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_op.py
MIT
def test_primary_key_skip(self): """Test that SERIAL cols are just skipped""" t1 = Table( "sometable", self.metadata, Column("id", Integer, primary_key=True) ) t2 = Table( "sometable", MetaData(), Column("id", Integer, primary_key=True) ) assert no...
Test that SERIAL cols are just skipped
test_primary_key_skip
python
sqlalchemy/alembic
tests/test_postgresql.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_postgresql.py
MIT
def test_inline_exclude_constraint_text(self): """test for #1184. Requires SQLAlchemy 2.0.5 due to issue https://github.com/sqlalchemy/sqlalchemy/issues/9401 """ autogen_context = self.autogen_context m = MetaData() t = Table( "TTable", ...
test for #1184. Requires SQLAlchemy 2.0.5 due to issue https://github.com/sqlalchemy/sqlalchemy/issues/9401
test_inline_exclude_constraint_text
python
sqlalchemy/alembic
tests/test_postgresql.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_postgresql.py
MIT
def test_ignore_for_non_recursive(self, non_recursive_fixture): """test traversal is non-recursive when the feature is not enabled (subdirectories are ignored). """ self._setup_revision_files( [ "r0", "r1", ("dir_1", ["r2", "r...
test traversal is non-recursive when the feature is not enabled (subdirectories are ignored).
test_ignore_for_non_recursive
python
sqlalchemy/alembic
tests/test_script_consumption.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_script_consumption.py
MIT
def test_downgrade_to_existing(self): """test for #838; downgrade to a revision that's already in current heads, but is not itself a head.""" self._assert_downgrade( self.a.revision, [self.a.revision], [], {self.a.revision} )
test for #838; downgrade to a revision that's already in current heads, but is not itself a head.
test_downgrade_to_existing
python
sqlalchemy/alembic
tests/test_version_traversal.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py
MIT
def test_downgrade_to_existing_head(self): """test for #839; downgrade to a revision that's already in current heads, which *is* itself a head.""" self._assert_downgrade( self.e.revision, [self.e.revision], [], {self.e.revision} )
test for #839; downgrade to a revision that's already in current heads, which *is* itself a head.
test_downgrade_to_existing_head
python
sqlalchemy/alembic
tests/test_version_traversal.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py
MIT
def test_relative_downgrade_baseplus2(self): """base+2 points to b, no branch label, drop everything above b.""" self._assert_downgrade( "base+2", [self.d2.revision, self.d1.revision], [ self.down_(self.d1), self.down_(self.c1), ...
base+2 points to b, no branch label, drop everything above b.
test_relative_downgrade_baseplus2
python
sqlalchemy/alembic
tests/test_version_traversal.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py
MIT
def test_relative_downgrade_branchplus2(self): """ Correct behaviour (per https://github.com/sqlalchemy/alembic/pull/763#issuecomment-738741297) Only the c2branch should be downgraded, right back to base+2 = b """ self._assert_downgrade( "c2branch@base+2", ...
Correct behaviour (per https://github.com/sqlalchemy/alembic/pull/763#issuecomment-738741297) Only the c2branch should be downgraded, right back to base+2 = b
test_relative_downgrade_branchplus2
python
sqlalchemy/alembic
tests/test_version_traversal.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py
MIT
def test_downgrade_single_branch_c1branch(self): """Use branch label to specify the branch to downgrade.""" self._assert_downgrade( f"c1branch@{self.b.revision}", (self.c1.revision, self.d2.revision), [ self.down_(self.c1), ], {...
Use branch label to specify the branch to downgrade.
test_downgrade_single_branch_c1branch
python
sqlalchemy/alembic
tests/test_version_traversal.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py
MIT
def test_downgrade_single_branch_c1branch_from_d1_head(self): """Use branch label to specify the branch (where the branch label is not on the head revision).""" self._assert_downgrade( f"c2branch@{self.b.revision}", (self.c1.revision, self.d2.revision), [ ...
Use branch label to specify the branch (where the branch label is not on the head revision).
test_downgrade_single_branch_c1branch_from_d1_head
python
sqlalchemy/alembic
tests/test_version_traversal.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py
MIT
def test_downgrade_single_branch_c2(self): """Use a revision on the branch (not head) to specify the branch.""" self._assert_downgrade( f"{self.c2.revision}@{self.b.revision}", (self.d1.revision, self.d2.revision), [ self.down_(self.d2), ...
Use a revision on the branch (not head) to specify the branch.
test_downgrade_single_branch_c2
python
sqlalchemy/alembic
tests/test_version_traversal.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py
MIT
def test_downgrade_single_branch_d1(self): """Use the head revision to specify the branch.""" self._assert_downgrade( f"{self.d1.revision}@{self.b.revision}", (self.d1.revision, self.d2.revision), [ self.down_(self.d1), self.down_(self....
Use the head revision to specify the branch.
test_downgrade_single_branch_d1
python
sqlalchemy/alembic
tests/test_version_traversal.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py
MIT
def test_downgrade_no_effect_branched(self): """Added for good measure when there are multiple branches.""" self._assert_downgrade( self.c2.revision, [self.d1.revision, self.c2.revision], [], {self.d1.revision, self.c2.revision}, ) self._as...
Added for good measure when there are multiple branches.
test_downgrade_no_effect_branched
python
sqlalchemy/alembic
tests/test_version_traversal.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py
MIT
def setup_class(cls): """ 33e21c000cfe -> 178d4e761bbd (head), 2bef33cb3a58, 3904558db1c6, 968330f320d -> 33e21c000cfe (mergepoint) 46c99f866004 -> 18f46b42410d (head), 2bef33cb3a58, 3904558db1c6, 968330f320d -> 46c99f866004 (mergepoint) f0fa4315825 -> 3904558db1c6 (bran...
33e21c000cfe -> 178d4e761bbd (head), 2bef33cb3a58, 3904558db1c6, 968330f320d -> 33e21c000cfe (mergepoint) 46c99f866004 -> 18f46b42410d (head), 2bef33cb3a58, 3904558db1c6, 968330f320d -> 46c99f866004 (mergepoint) f0fa4315825 -> 3904558db1c6 (branchpoint), --------------...
setup_class
python
sqlalchemy/alembic
tests/test_version_traversal.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py
MIT
def test_downgrade_independent_branch(self): """c2branch depends on c1branch so can be taken down on its own. Current behaviour also takes down the dependency unnecessarily.""" self._assert_downgrade( f"c2branch@{self.b.revision}", (self.d1.revision, self.d2.revision), ...
c2branch depends on c1branch so can be taken down on its own. Current behaviour also takes down the dependency unnecessarily.
test_downgrade_independent_branch
python
sqlalchemy/alembic
tests/test_version_traversal.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py
MIT
def test_downgrade_branch_dependency(self): """c2branch depends on c1branch so taking down c1branch requires taking down both""" destination = f"c1branch@{self.b.revision}" source = self.d1.revision, self.d2.revision revs = self.env._downgrade_revs(destination, source) # ...
c2branch depends on c1branch so taking down c1branch requires taking down both
test_downgrade_branch_dependency
python
sqlalchemy/alembic
tests/test_version_traversal.py
https://github.com/sqlalchemy/alembic/blob/master/tests/test_version_traversal.py
MIT
def build_instruction_kwargs(row: dict) -> dict: """Builds the list of `kwargs` for each instruction in `instruction_id_list`.""" kwargs = row["kwargs"] if kwargs is None: return {"valid_kwargs_json": False} try: kwargs = json.loads(row["kwargs"]) except json.JSONDecodeError: ...
Builds the list of `kwargs` for each instruction in `instruction_id_list`.
build_instruction_kwargs
python
huggingface/smollm
text/data/smoltalk/constraints/filter_ifeval_data.py
https://github.com/huggingface/smollm/blob/master/text/data/smoltalk/constraints/filter_ifeval_data.py
Apache-2.0
def filter_not_valid_rows(row: dict) -> bool: """Filters out rows which their JSON kwargs are not valid or that the instructions in their `instruction_id_list` conflict each other.""" valid_kwargs_json = row["valid_kwargs_json"] if not valid_kwargs_json: return False instruction_id_list = r...
Filters out rows which their JSON kwargs are not valid or that the instructions in their `instruction_id_list` conflict each other.
filter_not_valid_rows
python
huggingface/smollm
text/data/smoltalk/constraints/filter_ifeval_data.py
https://github.com/huggingface/smollm/blob/master/text/data/smoltalk/constraints/filter_ifeval_data.py
Apache-2.0
def get_ifeval_results(row: dict) -> dict: """Checks if the `response` correct is OK using the IFEval benchmark code from `lm-evaluation-harness`.""" results = [row["response"]] doc = row.copy() doc["kwargs"] = json.loads(doc["kwargs"]) try: return process_results(doc, results) except Ex...
Checks if the `response` correct is OK using the IFEval benchmark code from `lm-evaluation-harness`.
get_ifeval_results
python
huggingface/smollm
text/data/smoltalk/constraints/filter_ifeval_data.py
https://github.com/huggingface/smollm/blob/master/text/data/smoltalk/constraints/filter_ifeval_data.py
Apache-2.0
def update_summary_chat(self, chat_display: tk.Text, sender: str, message: str): """Update the summary chat display with new message""" chat_display.config(state='normal') # Add the message with appropriate styling chat_display.insert(tk.END, "\n") # Add spacing chat_di...
Update the summary chat display with new message
update_summary_chat
python
huggingface/smollm
tools/smol_tools/demo_tkinter.py
https://github.com/huggingface/smollm/blob/master/tools/smol_tools/demo_tkinter.py
Apache-2.0
def process_summary_question(self, original_text: str, question: str, chat_display: tk.Text, chat_input: tk.Text): """Process a follow-up question about the summarized text""" if not question.strip(): return # Clear input chat_inpu...
Process a follow-up question about the summarized text
process_summary_question
python
huggingface/smollm
tools/smol_tools/demo_tkinter.py
https://github.com/huggingface/smollm/blob/master/tools/smol_tools/demo_tkinter.py
Apache-2.0
def get_weather(city: str) -> str: """ Returns the weather forecast for a given city. Args: city: The name of the city. Returns: A string with a mock weather forecast. """ url = 'https://wttr.in/{}?format=+%C,+%t'.format(city) res = requests.get(url).text return f"The ...
Returns the weather forecast for a given city. Args: city: The name of the city. Returns: A string with a mock weather forecast.
get_weather
python
huggingface/smollm
tools/smol_tools/smol_tools/agent.py
https://github.com/huggingface/smollm/blob/master/tools/smol_tools/smol_tools/agent.py
Apache-2.0
def open_webbrowser(url: str) -> str: """ This is a tool that opens a web browser to the given website. If the user asks to open a website or a browser, you should use this tool. Args: url: The url to open. """ webbrowser.open(url) return f"I opened {url.replace('https://', '').repl...
This is a tool that opens a web browser to the given website. If the user asks to open a website or a browser, you should use this tool. Args: url: The url to open.
open_webbrowser
python
huggingface/smollm
tools/smol_tools/smol_tools/agent.py
https://github.com/huggingface/smollm/blob/master/tools/smol_tools/smol_tools/agent.py
Apache-2.0
def _warm_up(self): """Warm up the model with a test prompt""" print(f"Warming up {self.__class__.__name__}...") test_text = "This is a test message to warm up the model." # Consume the generator to complete the warm-up for _ in self.process(test_text): pass p...
Warm up the model with a test prompt
_warm_up
python
huggingface/smollm
tools/smol_tools/smol_tools/base.py
https://github.com/huggingface/smollm/blob/master/tools/smol_tools/smol_tools/base.py
Apache-2.0
def _create_chat_completion( self, messages: List[Dict[str, str]], temperature: float = 0.4, top_p: float = 0.9, top_k: int = 50, repeat_penalty: float = 1.2, max_tokens: int = 256 ) -> Generator[str, None, None]: """Helper method to create chat comp...
Helper method to create chat completions with standard parameters
_create_chat_completion
python
huggingface/smollm
tools/smol_tools/smol_tools/base.py
https://github.com/huggingface/smollm/blob/master/tools/smol_tools/smol_tools/base.py
Apache-2.0
def start_new_chat(self): """Start a new chat with a unique ID""" self.current_chat_id = datetime.now().strftime("%Y%m%d_%H%M%S") self.chat_history = [] self._original_chat_state = None
Start a new chat with a unique ID
start_new_chat
python
huggingface/smollm
tools/smol_tools/smol_tools/chatter.py
https://github.com/huggingface/smollm/blob/master/tools/smol_tools/smol_tools/chatter.py
Apache-2.0
def save_current_chat(self, title: str = None, overwrite: bool = False): """Save the current chat to disk if it has any messages""" if not self.chat_history: return if title: # If overwriting, use existing chat_id if it matches the title if not ov...
Save the current chat to disk if it has any messages
save_current_chat
python
huggingface/smollm
tools/smol_tools/smol_tools/chatter.py
https://github.com/huggingface/smollm/blob/master/tools/smol_tools/smol_tools/chatter.py
Apache-2.0
def is_chat_modified(self) -> bool: """Check if the current chat has been modified since loading""" if self._original_chat_state is None: # New chat that hasn't been saved yet return len(self.chat_history) > 0 current_state = [msg.to_dict() for msg in self.ch...
Check if the current chat has been modified since loading
is_chat_modified
python
huggingface/smollm
tools/smol_tools/smol_tools/chatter.py
https://github.com/huggingface/smollm/blob/master/tools/smol_tools/smol_tools/chatter.py
Apache-2.0
def get_saved_chats(self) -> List[str]: """Get list of saved chat IDs""" chats = [] for filename in os.listdir(self.chats_dir): if filename.startswith('chat_') and filename.endswith('.json'): chat_id = filename[5:-5] # Remove 'chat_' prefix and '.json' suffix ...
Get list of saved chat IDs
get_saved_chats
python
huggingface/smollm
tools/smol_tools/smol_tools/chatter.py
https://github.com/huggingface/smollm/blob/master/tools/smol_tools/smol_tools/chatter.py
Apache-2.0
def _check_remaining_indices(self) -> List[int]: """When taking screenshots of some websites, it often fails for some reasons. Therefore, we do a try/except and skip the indices of the json where it failed. We can go through them again to increase our success rate. This function checks t...
When taking screenshots of some websites, it often fails for some reasons. Therefore, we do a try/except and skip the indices of the json where it failed. We can go through them again to increase our success rate. This function checks the indices of the json files that are yet to be processed. ...
_check_remaining_indices
python
huggingface/smollm
vision/data/datasets_processing_scripts/build_websight_v02/python_scripts/04_screenshot_html_codes.py
https://github.com/huggingface/smollm/blob/master/vision/data/datasets_processing_scripts/build_websight_v02/python_scripts/04_screenshot_html_codes.py
Apache-2.0
def _modify_image_urls(self, html_code: str) -> str: """When an image URL appears more than once, when the HTML is rendered, the same image is displayed. The trick is to add a `_` at the end of the keyword of the URL to generate another image, still corresponding to the same keyword. ...
When an image URL appears more than once, when the HTML is rendered, the same image is displayed. The trick is to add a `_` at the end of the keyword of the URL to generate another image, still corresponding to the same keyword.
_modify_image_urls
python
huggingface/smollm
vision/data/datasets_processing_scripts/build_websight_v02/python_scripts/04_screenshot_html_codes.py
https://github.com/huggingface/smollm/blob/master/vision/data/datasets_processing_scripts/build_websight_v02/python_scripts/04_screenshot_html_codes.py
Apache-2.0
def create_dict_qbench(split): """`split` is "train", "validation" or "test".""" dict_qbench = {"image": [], "question": [], "label": [], "tested_labels": []} # with open(PATHS_JSON_QBENCH[split], "r") as f: data_qbench = json.load(f) # for example in tqdm(data_qbench): dict_qben...
`split` is "train", "validation" or "test".
create_dict_qbench
python
huggingface/smollm
vision/data/datasets_processing_scripts/integrate_evaluation_benchmarks_chatbot/qbench.py
https://github.com/huggingface/smollm/blob/master/vision/data/datasets_processing_scripts/integrate_evaluation_benchmarks_chatbot/qbench.py
Apache-2.0
def require_torch(test_case): """ Decorator marking a test that requires PyTorch. These tests are skipped when PyTorch isn't installed. """ if not is_torch_available(): return unittest.skip("test requires PyTorch")(test_case) else: return test_case
Decorator marking a test that requires PyTorch. These tests are skipped when PyTorch isn't installed.
require_torch
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def require_torch_no_gpus(test_case): """ Decorator marking a test that requires a setup without GPUs (in PyTorch). These tests are skipped on a machine with GPUs. To run *only* the no gpu tests, assuming all test names contain no_gpu: $ pytest -sv ./tests -k "no_gpu" """ import torch if is_to...
Decorator marking a test that requires a setup without GPUs (in PyTorch). These tests are skipped on a machine with GPUs. To run *only* the no gpu tests, assuming all test names contain no_gpu: $ pytest -sv ./tests -k "no_gpu"
require_torch_no_gpus
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def require_torch_multi_gpu(test_case): """ Decorator marking a test that requires a multi-GPU setup (in PyTorch). These tests are skipped on a machine without multiple GPUs. To run *only* the multi_gpu tests, assuming all test names contain multi_gpu: $ pytest -sv ./tests -k "multi_gpu" """ if...
Decorator marking a test that requires a multi-GPU setup (in PyTorch). These tests are skipped on a machine without multiple GPUs. To run *only* the multi_gpu tests, assuming all test names contain multi_gpu: $ pytest -sv ./tests -k "multi_gpu"
require_torch_multi_gpu
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def require_torch_non_multi_gpu(test_case): """ Decorator marking a test that requires 0 or 1 GPU setup (in PyTorch). """ if not is_torch_available(): return unittest.skip("test requires PyTorch")(test_case) import torch if torch.cuda.device_count() > 1: return unittest.skip("t...
Decorator marking a test that requires 0 or 1 GPU setup (in PyTorch).
require_torch_non_multi_gpu
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def require_torch_up_to_2_gpus(test_case): """ Decorator marking a test that requires 0 or 1 or 2 GPU setup (in PyTorch). """ if not is_torch_available(): return unittest.skip("test requires PyTorch")(test_case) import torch if torch.cuda.device_count() > 2: return unittest.ski...
Decorator marking a test that requires 0 or 1 or 2 GPU setup (in PyTorch).
require_torch_up_to_2_gpus
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def require_torch_gpu(test_case): """Decorator marking a test that requires CUDA and PyTorch.""" if torch_device != "cuda": return unittest.skip("test requires CUDA")(test_case) else: return test_case
Decorator marking a test that requires CUDA and PyTorch.
require_torch_gpu
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def require_deepspeed(test_case): """ Decorator marking a test that requires deepspeed """ if not is_deepspeed_available(): return unittest.skip("test requires deepspeed")(test_case) else: return test_case
Decorator marking a test that requires deepspeed
require_deepspeed
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def require_bnb(test_case): """ Decorator marking a test that requires bitsandbytes """ if not is_bnb_available(): return unittest.skip("test requires bitsandbytes from https://github.com/facebookresearch/bitsandbytes")( test_case ) else: return test_case
Decorator marking a test that requires bitsandbytes
require_bnb
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def require_bnb_non_decorator(): """ Non-Decorator function that would skip a test if bitsandbytes is missing """ if not is_bnb_available(): raise SkipTest("Test requires bitsandbytes from https://github.com/facebookresearch/bitsandbytes")
Non-Decorator function that would skip a test if bitsandbytes is missing
require_bnb_non_decorator
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def set_seed(seed: int = 42): """ Helper function for reproducible behavior to set the seed in ``random``, ``numpy``, ``torch`` Args: seed (:obj:`int`): The seed to set. """ random.seed(seed) np.random.seed(seed) if is_torch_available(): torch.manual_seed(seed) torch...
Helper function for reproducible behavior to set the seed in ``random``, ``numpy``, ``torch`` Args: seed (:obj:`int`): The seed to set.
set_seed
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def get_gpu_count(): """ Return the number of available gpus (regardless of whether torch or tf is used) """ if is_torch_available(): import torch return torch.cuda.device_count() else: return 0
Return the number of available gpus (regardless of whether torch or tf is used)
get_gpu_count
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def torch_assert_equal(actual, expected, **kwargs): """ compare two tensors or non-tensor numbers for their equality """ # assert_close was added around pt-1.9, it does better checks - e.g will check dimensions match return torch.testing.assert_close(actual, expected, rtol=0.0, atol=0.0, **kwargs)
compare two tensors or non-tensor numbers for their equality
torch_assert_equal
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def torch_assert_close(actual, expected, **kwargs): """ compare two tensors or non-tensor numbers for their closeness. """ # assert_close was added around pt-1.9, it does better checks - e.g will check dimensions match return torch.testing.assert_close(actual, expected, **kwargs)
compare two tensors or non-tensor numbers for their closeness.
torch_assert_close
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def require_torch_bf16(test_case): """Decorator marking a test that requires CUDA hardware supporting bf16 and PyTorch >= 1.9.""" if not is_torch_bf16_available(): return unittest.skip("test requires CUDA hardware supporting bf16 and PyTorch >= 1.9")(test_case) else: return test_case
Decorator marking a test that requires CUDA hardware supporting bf16 and PyTorch >= 1.9.
require_torch_bf16
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def get_tests_dir(append_path=None): """ Args: append_path: optional path to append to the tests dir path Return: The full path to the `tests` dir, so that the tests can be invoked from anywhere. Optionally `append_path` is joined after the `tests` dir the former is provided. "...
Args: append_path: optional path to append to the tests dir path Return: The full path to the `tests` dir, so that the tests can be invoked from anywhere. Optionally `append_path` is joined after the `tests` dir the former is provided.
get_tests_dir
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def ExtendSysPath(path: Union[str, os.PathLike]) -> Iterator[None]: """ Temporary add given path to `sys.path`. Usage :: with ExtendSysPath('/path/to/dir'): mymodule = importlib.import_module('mymodule') """ path = os.fspath(path) try: sys.path.insert(0, path) ...
Temporary add given path to `sys.path`. Usage :: with ExtendSysPath('/path/to/dir'): mymodule = importlib.import_module('mymodule')
ExtendSysPath
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def get_env(self): """ Return a copy of the ``os.environ`` object that sets up ``PYTHONPATH`` correctly. This is useful for invoking external programs from the test suite - e.g. distributed training. It always inserts ``.`` first, then ``./tests`` depending on the test suite type and ...
Return a copy of the ``os.environ`` object that sets up ``PYTHONPATH`` correctly. This is useful for invoking external programs from the test suite - e.g. distributed training. It always inserts ``.`` first, then ``./tests`` depending on the test suite type and finally the preset ``PYT...
get_env
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def get_auto_remove_tmp_dir(self, tmp_dir=None, before=None, after=None): """ Args: tmp_dir (:obj:`string`, `optional`): if :obj:`None`: - a unique temporary path will be created - sets ``before=True`` if ``before`` is :obj:`None` ...
Args: tmp_dir (:obj:`string`, `optional`): if :obj:`None`: - a unique temporary path will be created - sets ``before=True`` if ``before`` is :obj:`None` - sets ``after=True`` if ``after`` is :obj:`None` else: ...
get_auto_remove_tmp_dir
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def mockenv_context(*remove, **update): """ Temporarily updates the ``os.environ`` dictionary in-place. Similar to mockenv The ``os.environ`` dictionary is updated in-place so that the modification is sure to work in all situations. Args: remove: Environment variables to remove. update: Di...
Temporarily updates the ``os.environ`` dictionary in-place. Similar to mockenv The ``os.environ`` dictionary is updated in-place so that the modification is sure to work in all situations. Args: remove: Environment variables to remove. update: Dictionary of environment variables and values to...
mockenv_context
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def get_xdist_worker_id(): """ when run under pytest-xdist returns the worker id (int), otherwise returns 0 """ worker_id_string = os.environ.get("PYTEST_XDIST_WORKER", "gw0") return int(worker_id_string[2:]) # strip "gw"
when run under pytest-xdist returns the worker id (int), otherwise returns 0
get_xdist_worker_id
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def pytest_addoption_shared(parser): """ This function is to be called from `conftest.py` via `pytest_addoption` wrapper that has to be defined there. It allows loading both `conftest.py` files at once without causing a failure due to adding the same `pytest` option. """ option = "--make-repor...
This function is to be called from `conftest.py` via `pytest_addoption` wrapper that has to be defined there. It allows loading both `conftest.py` files at once without causing a failure due to adding the same `pytest` option.
pytest_addoption_shared
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def pytest_terminal_summary_main(tr, id): """ Generate multiple reports at the end of test suite run - each report goes into a dedicated file in the current directory. The report files are prefixed with the test suite name. This function emulates --duration and -rA pytest arguments. This function ...
Generate multiple reports at the end of test suite run - each report goes into a dedicated file in the current directory. The report files are prefixed with the test suite name. This function emulates --duration and -rA pytest arguments. This function is to be called from `conftest.py` via `pytest_te...
pytest_terminal_summary_main
python
huggingface/smollm
vision/m4/testing_utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/testing_utils.py
Apache-2.0
def _compute_relaxed_vqa_accuracy(self, generated_texts_unique, answers_unique, normalize_text_fn): """ From https://aclanthology.org/2022.findings-acl.177.pdf We use a relaxed accuracy measure for the numeric answers to allow a minor inaccuracy that may result from the automatic data extraction...
From https://aclanthology.org/2022.findings-acl.177.pdf We use a relaxed accuracy measure for the numeric answers to allow a minor inaccuracy that may result from the automatic data extraction process. We consider an answer to be correct if it is within 5% of the gold answer. For non-numeric answers, w...
_compute_relaxed_vqa_accuracy
python
huggingface/smollm
vision/m4/evaluation/custom_metrics/open_ended_vqa_metrics.py
https://github.com/huggingface/smollm/blob/master/vision/m4/evaluation/custom_metrics/open_ended_vqa_metrics.py
Apache-2.0
def vqa_normalize_text(text: str) -> str: """Process a text Source: https://github.com/GT-Vision-Lab/VQA/blob/master/PythonEvaluationTools/vqaEvaluation/vqaEval.py 1. Conversion of characters to lower case 2. Replace breaking lines and tabulations by a white space 3. Replace punctuations by a white ...
Process a text Source: https://github.com/GT-Vision-Lab/VQA/blob/master/PythonEvaluationTools/vqaEvaluation/vqaEval.py 1. Conversion of characters to lower case 2. Replace breaking lines and tabulations by a white space 3. Replace punctuations by a white space 4. Conversion of numbers written in let...
vqa_normalize_text
python
huggingface/smollm
vision/m4/evaluation/custom_metrics/utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/evaluation/custom_metrics/utils.py
Apache-2.0
def check_is_number(string): """ Check if the given string is a number """ try: _ = convert_to_number(string) return True except ValueError: return False
Check if the given string is a number
check_is_number
python
huggingface/smollm
vision/m4/evaluation/custom_metrics/utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/evaluation/custom_metrics/utils.py
Apache-2.0
def normalize_str_mmmu(string): """ Normalize the str to lower case and make them float numbers if possible. """ # check if characters in the string # if number, numerize it. string = string.strip() if string.startswith("Answer: "): string = string.replace("Answer: ", "") is_nu...
Normalize the str to lower case and make them float numbers if possible.
normalize_str_mmmu
python
huggingface/smollm
vision/m4/evaluation/custom_metrics/utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/evaluation/custom_metrics/utils.py
Apache-2.0
def extract_numbers_mmmu(string): """ Exact all forms of numbers from a string with regex. """ # Pattern for numbers with commas pattern_commas = r"-?\b\d{1,3}(?:,\d{3})+\b" # Pattern for scientific notation pattern_scientific = r"-?\d+(?:\.\d+)?[eE][+-]?\d+" # Pattern for simple numbers...
Exact all forms of numbers from a string with regex.
extract_numbers_mmmu
python
huggingface/smollm
vision/m4/evaluation/custom_metrics/utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/evaluation/custom_metrics/utils.py
Apache-2.0
def parse_open_response_mmmu(response, normalize_text_fn): """ Parse the prediction from the generated response. Return a list of predicted strings or numbers """ def get_key_subresponses(response): key_responses = [] response = response.strip().strip(".").lower() sub_respon...
Parse the prediction from the generated response. Return a list of predicted strings or numbers
parse_open_response_mmmu
python
huggingface/smollm
vision/m4/evaluation/custom_metrics/utils.py
https://github.com/huggingface/smollm/blob/master/vision/m4/evaluation/custom_metrics/utils.py
Apache-2.0
def _split_to_single_caption(caption): """This function is mainly used in Localized Narratives where a paragraph can contain multiple relevant captions to a single image. We split the paragraph into multiple captions and then return each as an individual sample. """ extended = [] captions = capt...
This function is mainly used in Localized Narratives where a paragraph can contain multiple relevant captions to a single image. We split the paragraph into multiple captions and then return each as an individual sample.
_split_to_single_caption
python
huggingface/smollm
vision/m4/evaluation/scripts/create_sample_evaluation_datasets_simplified.py
https://github.com/huggingface/smollm/blob/master/vision/m4/evaluation/scripts/create_sample_evaluation_datasets_simplified.py
Apache-2.0
def fetch_training_run(training_run_name): """ Fetch training run. There can only be one corresponding training run. If not, double check the tags (killed, failed, etc.) """ matching_runs = [] runs = api.runs(f"{args.wandb_entity}/{args.wandb_training_project}") ...
Fetch training run. There can only be one corresponding training run. If not, double check the tags (killed, failed, etc.)
fetch_training_run
python
huggingface/smollm
vision/m4/evaluation/scripts/sync_evaluations_on_wandb.py
https://github.com/huggingface/smollm/blob/master/vision/m4/evaluation/scripts/sync_evaluations_on_wandb.py
Apache-2.0
def fetch_evaluation_run(evaluation_run_name): """ Fetch evaluation run. There can only be one corresponding evaluation run at most. If not, double check the tags (killed, failed, etc.) """ matching_runs = [] runs = api.runs(f"{args.wandb_entity}/{args.wandb_eval_project...
Fetch evaluation run. There can only be one corresponding evaluation run at most. If not, double check the tags (killed, failed, etc.)
fetch_evaluation_run
python
huggingface/smollm
vision/m4/evaluation/scripts/sync_evaluations_on_wandb.py
https://github.com/huggingface/smollm/blob/master/vision/m4/evaluation/scripts/sync_evaluations_on_wandb.py
Apache-2.0
def get_logged_eval_values(evaluation_run): """ If `evaluation_run` already exists, get the already logged values into a dictionary. """ logged_evaluation_values = defaultdict() if evaluation_run is not None: for row in evaluation_run.scan_history(): ...
If `evaluation_run` already exists, get the already logged values into a dictionary.
get_logged_eval_values
python
huggingface/smollm
vision/m4/evaluation/scripts/sync_evaluations_on_wandb.py
https://github.com/huggingface/smollm/blob/master/vision/m4/evaluation/scripts/sync_evaluations_on_wandb.py
Apache-2.0
def get_evaluations_values_from_json(): """ Load all values from the json file """ evaluation_values = defaultdict(lambda: defaultdict()) for evaluation_jsonl_file in args.evaluation_jsonl_files: with open(evaluation_jsonl_file, "r") as f: for line in ...
Load all values from the json file
get_evaluations_values_from_json
python
huggingface/smollm
vision/m4/evaluation/scripts/sync_evaluations_on_wandb.py
https://github.com/huggingface/smollm/blob/master/vision/m4/evaluation/scripts/sync_evaluations_on_wandb.py
Apache-2.0
def convert_training_run_to_dict(training_run): """ Get all the logged values from the training into a dictionary. """ training_history = training_run.scan_history() d = defaultdict(dict) for row in training_history: if "num_opt_steps" not in row: ...
Get all the logged values from the training into a dictionary.
convert_training_run_to_dict
python
huggingface/smollm
vision/m4/evaluation/scripts/sync_evaluations_on_wandb.py
https://github.com/huggingface/smollm/blob/master/vision/m4/evaluation/scripts/sync_evaluations_on_wandb.py
Apache-2.0
def from_pretrained(cls, *model_args, is_resume=False, new_model=False, **kwargs): """ Use this method when loading an already pretrained vloom model - either from a checkpoint or from hub. For creating an untrained model use `pretrained_models` instead. """ # config is: ...
Use this method when loading an already pretrained vloom model - either from a checkpoint or from hub. For creating an untrained model use `pretrained_models` instead.
from_pretrained
python
huggingface/smollm
vision/m4/models/custom_modules.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/custom_modules.py
Apache-2.0
def __init__( self, num_embeddings, num_additional_embeddings, embedding_dim, partially_freeze=False, device=None, dtype=None, padding_idx=None, **kwargs, ) -> None: """ num_additional_embeddings: int. Number of additional embed...
num_additional_embeddings: int. Number of additional embeddings. Only useful when you `partially_freeze=True`. partially_freeze: bool. If True, the regular `weight` will be frozen. `additional_weight` is never frozen. Note: there are a lot of other parameters to initialize a standard `nn.Embed...
__init__
python
huggingface/smollm
vision/m4/models/custom_modules.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/custom_modules.py
Apache-2.0
def forward(self, input_ids): """ we have 2 embeddings, with different indices - one pretrained self.weight and another self.additional_embedding.weight that is being trained. in order to make a lookup of the input ids, we: 1. find out the indices of the entries belonging to the...
we have 2 embeddings, with different indices - one pretrained self.weight and another self.additional_embedding.weight that is being trained. in order to make a lookup of the input ids, we: 1. find out the indices of the entries belonging to the 2nd embedding 2. extract those v...
forward
python
huggingface/smollm
vision/m4/models/custom_modules.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/custom_modules.py
Apache-2.0
def __init__( self, in_features: int, out_features: int, out_additional_features: int = 0, bias: bool = True, partially_freeze: bool = True, device=None, dtype=None, ) -> None: """ out_additional_features: int. Number of additional trai...
out_additional_features: int. Number of additional trainable dimensions. Only makes sense when `partially_freeze=True`. partially_freeze: bool. If True, the regular `weight` will be frozen and extra parameters (if any) will be trainable. If False, default to the regular behavior of nn.Linear.
__init__
python
huggingface/smollm
vision/m4/models/custom_modules.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/custom_modules.py
Apache-2.0
def extra_repr(self) -> str: """Overwriting `nn.Linear.extra_repr` to include new parameters.""" return "in_features={}, out_features={}, out_additional_features={}, bias={}, partially_freeze={}".format( self.in_features, self.out_features, self.out_additional_feature...
Overwriting `nn.Linear.extra_repr` to include new parameters.
extra_repr
python
huggingface/smollm
vision/m4/models/custom_modules.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/custom_modules.py
Apache-2.0
def to_dict(self): """ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`]. Returns: `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance, """ output = copy.deepcopy(self.__dict__) ...
Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`]. Returns: `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
to_dict
python
huggingface/smollm
vision/m4/models/idefics/configuration_idefics.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/idefics/configuration_idefics.py
Apache-2.0
def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, past_key_values_length: int = 0): """ Make causal mask used for bi-directional self-attention. """ bsz, tgt_len = input_ids_shape mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min)) mask_cond = torch.a...
Make causal mask used for bi-directional self-attention.
_make_causal_mask
python
huggingface/smollm
vision/m4/models/idefics/modeling_idefics.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/idefics/modeling_idefics.py
Apache-2.0
def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1)
Rotates half the hidden dims of the input.
rotate_half
python
huggingface/smollm
vision/m4/models/idefics/modeling_idefics.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/idefics/modeling_idefics.py
Apache-2.0
def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: Optional[bool] = False, use_cache: Optional[boo...
Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values...
forward
python
huggingface/smollm
vision/m4/models/idefics/modeling_idefics.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/idefics/modeling_idefics.py
Apache-2.0
def tie_weights(self): """ Overwrite `transformers.modeling_utils.PreTrainedModel.tie_weights` to handle the case of DecoupledLinear and DecoupledEmbedding. """ output_embeddings = self.get_output_embeddings() input_embeddings = self.get_input_embeddings() if getattr(sel...
Overwrite `transformers.modeling_utils.PreTrainedModel.tie_weights` to handle the case of DecoupledLinear and DecoupledEmbedding.
tie_weights
python
huggingface/smollm
vision/m4/models/idefics/modeling_idefics.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/idefics/modeling_idefics.py
Apache-2.0
def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, pix...
Args: labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `...
forward
python
huggingface/smollm
vision/m4/models/idefics/modeling_idefics.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/idefics/modeling_idefics.py
Apache-2.0
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_...
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
repeat_kv
python
huggingface/smollm
vision/m4/models/perceiver/perceiver.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/perceiver/perceiver.py
Apache-2.0
def __init__(self, config) -> None: """Perceiver Cross-Attention Module --> let long-form inputs be `context`, resampled embeddings be `latents`""" super().__init__() self.config = config self.hidden_size = config.hidden_size self.num_heads = config.perceiver_config.resampler_n...
Perceiver Cross-Attention Module --> let long-form inputs be `context`, resampled embeddings be `latents`
__init__
python
huggingface/smollm
vision/m4/models/perceiver/perceiver.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/perceiver/perceiver.py
Apache-2.0
def forward( self, latents: torch.Tensor, context: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: bool = False, use_cach...
Runs Perceiver Self-Attention, with special (context, latents) appended along the `seq` dimension! :param context: Tensor of shape [bsz, seq, embed_dim] representing long-form context to resample. :param latents: Tensor of shape [bsz, n_latents, embed_dim] representing fixed length latents to c...
forward
python
huggingface/smollm
vision/m4/models/perceiver/perceiver.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/perceiver/perceiver.py
Apache-2.0
def _flash_attention_forward( self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None, use_sliding_windows=False, ): """ Calls the forward method of Flash Attention - if the in...
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token first unpad the input, then computes the attention scores and pad the final attention scores. Args: query_states (`torch.Tensor`): Input query states to be pa...
_flash_attention_forward
python
huggingface/smollm
vision/m4/models/perceiver/perceiver.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/perceiver/perceiver.py
Apache-2.0
def forward( self, latents: torch.Tensor, context: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: Optional[bool] = False, ...
Args: latents (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` context (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(...
forward
python
huggingface/smollm
vision/m4/models/perceiver/perceiver.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/perceiver/perceiver.py
Apache-2.0
def __init__( self, config, ) -> None: """ Instantiates a Perceiver Resampler that operates over a sequence of embeddings (say from a ResNet or ViT or MAE) of a given dimension, performs `depth` blocks of cross-attention with a fixed `n_latents` inputs, then returns a...
Instantiates a Perceiver Resampler that operates over a sequence of embeddings (say from a ResNet or ViT or MAE) of a given dimension, performs `depth` blocks of cross-attention with a fixed `n_latents` inputs, then returns a Tensor of shape [bsz, n_latents, embed_dim]. :param embed_dim...
__init__
python
huggingface/smollm
vision/m4/models/perceiver/perceiver.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/perceiver/perceiver.py
Apache-2.0
def retrieve_idx_closest_examples(ref_embedding, embeddings_to_compare, num_examples): "Returns the indices of the `num_examples` closest embeddings in ascending order" sim = np.dot(embeddings_to_compare, ref_embedding) # We can achieve linear complexity because we don't need to sort...
Returns the indices of the `num_examples` closest embeddings in ascending order
retrieve_idx_closest_examples
python
huggingface/smollm
vision/m4/models/vgpt2/evaluation_captioning_in_context_vgpt2.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/vgpt2/evaluation_captioning_in_context_vgpt2.py
Apache-2.0
def prepare_dataset(self, exs: Dict, **kwargs) -> Dict: """ Prepare batch of examples. Each example (X, y) where y is among (y1, y2, ..., yN) - the labels options - is turned into [(X, y1), (X, y2), ... (X, yN)]. """ support_dataset: Dataset = kwargs["support_dataset"] ...
Prepare batch of examples. Each example (X, y) where y is among (y1, y2, ..., yN) - the labels options - is turned into [(X, y1), (X, y2), ... (X, yN)].
prepare_dataset
python
huggingface/smollm
vision/m4/models/vgpt2/evaluation_classification_in_context_vgpt2.py
https://github.com/huggingface/smollm/blob/master/vision/m4/models/vgpt2/evaluation_classification_in_context_vgpt2.py
Apache-2.0