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 get_dataset_type_fast(file_path: str, max_chars: int = 100) -> Union[str, None]:
'''Get the type values from the first and last n lines of a large json dataset.
'''
file_content_preview = []
dataset_type = None
dataset_type_pattern = re.compile(r'[\"\']type[\"\']:\s*[\'\"]([^"]+)[\'\"]')
fil... | Get the type values from the first and last n lines of a large json dataset.
| get_dataset_type_fast | python | OptimalScale/LMFlow | src/lmflow/utils/data_utils.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/data_utils.py | Apache-2.0 |
def check_dataset_instances_key_fast(file_path: str, instances_key: str, max_lines: int = 100) -> bool:
'''Check if the dataset instances key matches the instance_key.
'''
file_content_preview = []
instance_key_pattern = re.compile(r'[\"\']' + instances_key + r'[\"\']')
file_content_preview.extend(p... | Check if the dataset instances key matches the instance_key.
| check_dataset_instances_key_fast | python | OptimalScale/LMFlow | src/lmflow/utils/data_utils.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/data_utils.py | Apache-2.0 |
def answer_extraction(response, answer_type=None): #use this funtion to extract answers from generated text
"""
Use this funtion to extract answers from generated text
Parameters
------------
args :
Arguments.
response : str
plain string response.
Returns
---------... |
Use this funtion to extract answers from generated text
Parameters
------------
args :
Arguments.
response : str
plain string response.
Returns
------------
answer:
Decoded answer (such as A, B, C, D, E for mutiple-choice QA).
| answer_extraction | python | OptimalScale/LMFlow | src/lmflow/utils/data_utils.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/data_utils.py | Apache-2.0 |
def format(self, **kwargs) -> list:
"""Format the string components with the provided keyword arguments.
Mostly used for formatting system prompt, user and assistant messages.
Parameters
----------
**kwargs : dict
Keyword arguments containing values to replace in th... | Format the string components with the provided keyword arguments.
Mostly used for formatting system prompt, user and assistant messages.
Parameters
----------
**kwargs : dict
Keyword arguments containing values to replace in the template components.
Returns
... | format | python | OptimalScale/LMFlow | src/lmflow/utils/conversation_template/base.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/conversation_template/base.py | Apache-2.0 |
def encode_conversation(
self,
tokenizer: PreTrainedTokenizer,
messages: List[Dict[str, str]],
system: Optional[str] = None,
tools: Optional[List[str]] = None,
**kwargs
) -> Sequence[Tuple[List[int], List[int]]]:
r'''
Messages here should be guaranteed... |
Messages here should be guaranteed to be in pairs, with the first message being the user message and the second message being the system message.
Data example:
```json
{
"conversation_id": 2,
"system": "sysinfo1",
"tools": ["tool_1_desc"],
... | encode_conversation | python | OptimalScale/LMFlow | src/lmflow/utils/conversation_template/base.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/conversation_template/base.py | Apache-2.0 |
def _encode_template(
self,
template: List[TemplateComponent],
tokenizer: PreTrainedTokenizer,
**kwargs
) -> List[int]:
"""Encode template components into token ids.
Parameters
----------
template : List[TemplateComponent]
Formatted templ... | Encode template components into token ids.
Parameters
----------
template : List[TemplateComponent]
Formatted template components.
tokenizer : PreTrainedTokenizer
Tokenizer to convert tokens into token ids.
Returns
-------
List[int]
... | _encode_template | python | OptimalScale/LMFlow | src/lmflow/utils/conversation_template/base.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/conversation_template/base.py | Apache-2.0 |
def _ensure_id_list(self, obj: Union[int, List[int]]) -> List[int]:
'''Make sure the object is a list of integers. Useful for handling token ids.
'''
if isinstance(obj, int):
return [obj]
elif isinstance(obj, list):
return obj
else:
raise Value... | Make sure the object is a list of integers. Useful for handling token ids.
| _ensure_id_list | python | OptimalScale/LMFlow | src/lmflow/utils/conversation_template/base.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/conversation_template/base.py | Apache-2.0 |
def encode_conversation(
self,
tokenizer: PreTrainedTokenizer,
messages: List[Dict[str, str]],
system: Optional[str] = None,
tools: Optional[List[str]] = None,
**kwargs
) -> Sequence[Tuple[List[int], List[int]]]:
r'''
Messages here should be guaranteed... |
Messages here should be guaranteed to be in pairs, with the first message being the user message and the second message being the system message.
Data example:
```json
{
"conversation_id": 2,
"system": "sysinfo1",
"tools": ["tool_1_desc"],
... | encode_conversation | python | OptimalScale/LMFlow | src/lmflow/utils/conversation_template/base.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/conversation_template/base.py | Apache-2.0 |
def _encode_template(
self,
template: List[TemplateComponent],
tokenizer: PreTrainedTokenizer,
**kwargs
) -> List[int]:
"""Encode template components into token ids.
Parameters
----------
template : List[TemplateComponent]
Formatted templ... | Encode template components into token ids.
Parameters
----------
template : List[TemplateComponent]
Formatted template components.
tokenizer : PreTrainedTokenizer
Tokenizer to convert tokens into token ids.
Returns
-------
List[int]
... | _encode_template | python | OptimalScale/LMFlow | src/lmflow/utils/conversation_template/base.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/conversation_template/base.py | Apache-2.0 |
def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None):
"""
qkv: (batch, seqlen, 3, nheads, headdim)
bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
... |
qkv: (batch, seqlen, 3, nheads, headdim)
bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen)
... | forward | python | OptimalScale/LMFlow | src/lmflow/utils/flash_attention/triton_flash_attention.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/flash_attention/triton_flash_attention.py | Apache-2.0 |
def forward(ctx, q, kv, bias=None, causal=False, softmax_scale=None):
"""
q: (batch, seqlen_q, nheads, headdim)
kv: (batch, seqlen_k, 2, nheads, headdim)
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
For example, ALiBi mask for ca... |
q: (batch, seqlen_q, nheads, headdim)
kv: (batch, seqlen_k, 2, nheads, headdim)
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
ALiBi mask for no... | forward | python | OptimalScale/LMFlow | src/lmflow/utils/flash_attention/triton_flash_attention.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/flash_attention/triton_flash_attention.py | Apache-2.0 |
def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None):
"""
q: (batch_size, seqlen_q, nheads, headdim)
k, v: (batch_size, seqlen_k, nheads, headdim)
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
For example, ALiBi ... |
q: (batch_size, seqlen_q, nheads, headdim)
k, v: (batch_size, seqlen_k, nheads, headdim)
bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
ALiBi ma... | forward | python | OptimalScale/LMFlow | src/lmflow/utils/flash_attention/triton_flash_attention.py | https://github.com/OptimalScale/LMFlow/blob/master/src/lmflow/utils/flash_attention/triton_flash_attention.py | Apache-2.0 |
def find_abbreviation(
long_form_candidate: Span, short_form_candidate: Span
) -> Tuple[Span, Optional[Span]]:
"""
Implements the abbreviation detection algorithm in "A simple algorithm
for identifying abbreviation definitions in biomedical text.", (Schwartz & Hearst, 2003).
The algorithm works by ... |
Implements the abbreviation detection algorithm in "A simple algorithm
for identifying abbreviation definitions in biomedical text.", (Schwartz & Hearst, 2003).
The algorithm works by enumerating the characters in the short form of the abbreviation,
checking that they can be matched against characters... | find_abbreviation | python | allenai/scispacy | scispacy/abbreviation.py | https://github.com/allenai/scispacy/blob/master/scispacy/abbreviation.py | Apache-2.0 |
def find(self, span: Span, doc: Doc) -> Tuple[Span, Set[Span]]:
"""
Functional version of calling the matcher for a single span.
This method is helpful if you already have an abbreviation which
you want to find a definition for.
"""
dummy_matches = [(-1, int(span.start), ... |
Functional version of calling the matcher for a single span.
This method is helpful if you already have an abbreviation which
you want to find a definition for.
| find | python | allenai/scispacy | scispacy/abbreviation.py | https://github.com/allenai/scispacy/blob/master/scispacy/abbreviation.py | Apache-2.0 |
def make_short_form_serializable(self, abbreviation: Span):
"""
Converts the abbreviations into a short form that is serializable to enable multiprocessing
Parameters
----------
abbreviation: Span
The abbreviation span identified by the detector
"""
l... |
Converts the abbreviations into a short form that is serializable to enable multiprocessing
Parameters
----------
abbreviation: Span
The abbreviation span identified by the detector
| make_short_form_serializable | python | allenai/scispacy | scispacy/abbreviation.py | https://github.com/allenai/scispacy/blob/master/scispacy/abbreviation.py | Apache-2.0 |
def load_approximate_nearest_neighbours_index(
linker_paths: LinkerPaths,
ef_search: int = 200,
) -> FloatIndex:
"""
Load an approximate nearest neighbours index from disk.
Parameters
----------
linker_paths: LinkerPaths, required.
Contains the paths to the data required for the ent... |
Load an approximate nearest neighbours index from disk.
Parameters
----------
linker_paths: LinkerPaths, required.
Contains the paths to the data required for the entity linker.
ef_search: int, optional (default = 200)
Controls speed performance at query time. Max value is 2000,
... | load_approximate_nearest_neighbours_index | python | allenai/scispacy | scispacy/candidate_generation.py | https://github.com/allenai/scispacy/blob/master/scispacy/candidate_generation.py | Apache-2.0 |
def nmslib_knn_with_zero_vectors(
self, vectors: numpy.ndarray, k: int
) -> Tuple[numpy.ndarray, numpy.ndarray]:
"""
ann_index.knnQueryBatch crashes if any of the vectors is all zeros.
This function is a wrapper around `ann_index.knnQueryBatch` that solves this problem. It works as f... |
ann_index.knnQueryBatch crashes if any of the vectors is all zeros.
This function is a wrapper around `ann_index.knnQueryBatch` that solves this problem. It works as follows:
- remove empty vectors from `vectors`.
- call `ann_index.knnQueryBatch` with the non-empty vectors only. This re... | nmslib_knn_with_zero_vectors | python | allenai/scispacy | scispacy/candidate_generation.py | https://github.com/allenai/scispacy/blob/master/scispacy/candidate_generation.py | Apache-2.0 |
def __call__(
self, mention_texts: List[str], k: int
) -> List[List[MentionCandidate]]:
"""
Given a list of mention texts, returns a list of candidate neighbors.
NOTE: Because we include canonical name aliases in the ann index, the list
of candidates returned will not necess... |
Given a list of mention texts, returns a list of candidate neighbors.
NOTE: Because we include canonical name aliases in the ann index, the list
of candidates returned will not necessarily be of length k for each candidate,
because we then map these to canonical ids only.
NOTE... | __call__ | python | allenai/scispacy | scispacy/candidate_generation.py | https://github.com/allenai/scispacy/blob/master/scispacy/candidate_generation.py | Apache-2.0 |
def create_tfidf_ann_index(
out_path: str, kb: Optional[KnowledgeBase] = None
) -> Tuple[List[str], TfidfVectorizer, FloatIndex]:
"""
Build tfidf vectorizer and ann index.
Parameters
----------
out_path: str, required.
The path where the various model pieces will be saved.
kb : Know... |
Build tfidf vectorizer and ann index.
Parameters
----------
out_path: str, required.
The path where the various model pieces will be saved.
kb : KnowledgeBase, optional.
The kb items to generate the index and vectors for.
| create_tfidf_ann_index | python | allenai/scispacy | scispacy/candidate_generation.py | https://github.com/allenai/scispacy/blob/master/scispacy/candidate_generation.py | Apache-2.0 |
def pysbd_sentencizer(doc: Doc) -> Doc:
"""Adds sentence boundaries to a Doc.
Intended to be used as a pipe in a spaCy pipeline.
Uses https://github.com/nipunsadvilkar/pySBD to get proper sentence and
respective char_spans
Handle special cases:
New lines cannot be end of sentence tokens.
Ne... | Adds sentence boundaries to a Doc.
Intended to be used as a pipe in a spaCy pipeline.
Uses https://github.com/nipunsadvilkar/pySBD to get proper sentence and
respective char_spans
Handle special cases:
New lines cannot be end of sentence tokens.
New lines that separate sentences will be added t... | pysbd_sentencizer | python | allenai/scispacy | scispacy/custom_sentence_segmenter.py | https://github.com/allenai/scispacy/blob/master/scispacy/custom_sentence_segmenter.py | Apache-2.0 |
def remove_new_lines(text: str) -> str:
"""Used to preprocess away new lines in the middle of words. This function
is intended to be called on a raw string before it is passed through a
spaCy pipeline
@param text: a string of text to be processed
"""
text = text.replace("-\n\n", "")
t... | Used to preprocess away new lines in the middle of words. This function
is intended to be called on a raw string before it is passed through a
spaCy pipeline
@param text: a string of text to be processed
| remove_new_lines | python | allenai/scispacy | scispacy/custom_tokenizer.py | https://github.com/allenai/scispacy/blob/master/scispacy/custom_tokenizer.py | Apache-2.0 |
def process_example(lines: List[str]) -> MedMentionExample:
"""
Processes the text lines of a file corresponding to a single MedMention abstract,
extracts the title, abstract, pubmed id and entities. The lines of the file should
have the following format:
PMID | t | Title text
PMID | a | Abstrac... |
Processes the text lines of a file corresponding to a single MedMention abstract,
extracts the title, abstract, pubmed id and entities. The lines of the file should
have the following format:
PMID | t | Title text
PMID | a | Abstract text
PMID TAB StartIndex TAB EndIndex TAB MentionTextSegment ... | process_example | python | allenai/scispacy | scispacy/data_util.py | https://github.com/allenai/scispacy/blob/master/scispacy/data_util.py | Apache-2.0 |
def med_mentions_example_iterator(filename: str) -> Iterator[MedMentionExample]:
"""
Iterates over a Med Mentions file, yielding examples.
"""
with open(filename, "r", encoding="utf-8") as med_mentions_file:
lines = []
for line in med_mentions_file:
line = line.strip()
... |
Iterates over a Med Mentions file, yielding examples.
| med_mentions_example_iterator | python | allenai/scispacy | scispacy/data_util.py | https://github.com/allenai/scispacy/blob/master/scispacy/data_util.py | Apache-2.0 |
def select_subset_of_overlapping_chain(
chain: List[Tuple[int, int, str]]
) -> List[Tuple[int, int, str]]:
"""
Select the subset of entities in an overlapping chain to return by greedily choosing the
longest entity in the chain until there are no entities remaining
"""
sorted_chain = sorted(chai... |
Select the subset of entities in an overlapping chain to return by greedily choosing the
longest entity in the chain until there are no entities remaining
| select_subset_of_overlapping_chain | python | allenai/scispacy | scispacy/data_util.py | https://github.com/allenai/scispacy/blob/master/scispacy/data_util.py | Apache-2.0 |
def remove_overlapping_entities(
sorted_spacy_format_entities: List[Tuple[int, int, str]]
) -> List[Tuple[int, int, str]]:
"""
Removes overlapping entities from the entity set, by greedilytaking the longest
entity from each overlapping chain. The input list of entities should be sorted
and follow th... |
Removes overlapping entities from the entity set, by greedilytaking the longest
entity from each overlapping chain. The input list of entities should be sorted
and follow the spacy format.
| remove_overlapping_entities | python | allenai/scispacy | scispacy/data_util.py | https://github.com/allenai/scispacy/blob/master/scispacy/data_util.py | Apache-2.0 |
def _handle_sentence(examples: List[Tuple[str, str]]) -> SpacyNerExample:
"""
Processes a single sentence by building it up as a space separated string
with its corresponding typed entity spans.
"""
start_index = -1
current_index = 0
in_entity = False
entity_type: str = ""
sent = ""
... |
Processes a single sentence by building it up as a space separated string
with its corresponding typed entity spans.
| _handle_sentence | python | allenai/scispacy | scispacy/data_util.py | https://github.com/allenai/scispacy/blob/master/scispacy/data_util.py | Apache-2.0 |
def read_ner_from_tsv(filename: str) -> List[SpacyNerExample]:
"""
Reads BIO formatted NER data from a TSV file, such as the
NER data found here:
https://github.com/cambridgeltl/MTL-Bioinformatics-2016
Data is expected to be 2 tab seperated tokens per line, with
sentences denoted by empty lines... |
Reads BIO formatted NER data from a TSV file, such as the
NER data found here:
https://github.com/cambridgeltl/MTL-Bioinformatics-2016
Data is expected to be 2 tab seperated tokens per line, with
sentences denoted by empty lines. Sentences read by this
function will be already tokenized, but r... | read_ner_from_tsv | python | allenai/scispacy | scispacy/data_util.py | https://github.com/allenai/scispacy/blob/master/scispacy/data_util.py | Apache-2.0 |
def cached_path(
url_or_filename: Union[str, Path], cache_dir: Optional[str] = None
) -> str:
"""
Given something that might be a URL (or might be a local path),
determine which. If it's a URL, download the file and cache it, and
return the path to the cached file. If it's already a local path,
... |
Given something that might be a URL (or might be a local path),
determine which. If it's a URL, download the file and cache it, and
return the path to the cached file. If it's already a local path,
make sure the file exists and then return the path.
| cached_path | python | allenai/scispacy | scispacy/file_cache.py | https://github.com/allenai/scispacy/blob/master/scispacy/file_cache.py | Apache-2.0 |
def filename_to_url(filename: str, cache_dir: Optional[str] = None) -> Tuple[str, str]:
"""
Return the url and etag (which may be ``None``) stored for `filename`.
Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.
"""
if cache_dir is None:
cache_dir = DATASET_CACH... |
Return the url and etag (which may be ``None``) stored for `filename`.
Raise ``FileNotFoundError`` if `filename` or its stored metadata do not exist.
| filename_to_url | python | allenai/scispacy | scispacy/file_cache.py | https://github.com/allenai/scispacy/blob/master/scispacy/file_cache.py | Apache-2.0 |
def get_from_cache(url: str, cache_dir: Optional[str] = None) -> str:
"""
Given a URL, look for the corresponding dataset in the local cache.
If it's not there, download it. Then return the path to the cached file.
"""
if cache_dir is None:
cache_dir = DATASET_CACHE
os.makedirs(cache_di... |
Given a URL, look for the corresponding dataset in the local cache.
If it's not there, download it. Then return the path to the cached file.
| get_from_cache | python | allenai/scispacy | scispacy/file_cache.py | https://github.com/allenai/scispacy/blob/master/scispacy/file_cache.py | Apache-2.0 |
def expand_to_noun_compound(self, token: Token, doc: Doc):
"""
Expand a token to it's noun phrase based
on a simple POS tag heuristic.
"""
start = token.i
while True:
if start - 1 < 0:
break
previous_token = doc[start - 1]
... |
Expand a token to it's noun phrase based
on a simple POS tag heuristic.
| expand_to_noun_compound | python | allenai/scispacy | scispacy/hyponym_detector.py | https://github.com/allenai/scispacy/blob/master/scispacy/hyponym_detector.py | Apache-2.0 |
def __call__(self, doc: Doc):
"""
Runs the matcher on the Doc object and sets token and
doc level attributes for hypernym and hyponym relations.
"""
# Find matches in doc
matches = self.matcher(doc)
# If none are found then return None
if not matches:
... |
Runs the matcher on the Doc object and sets token and
doc level attributes for hypernym and hyponym relations.
| __call__ | python | allenai/scispacy | scispacy/hyponym_detector.py | https://github.com/allenai/scispacy/blob/master/scispacy/hyponym_detector.py | Apache-2.0 |
def get_metric(self, reset: bool = False):
"""
Returns
-------
A Dict per label containing following the span based metrics:
precision : float
recall : float
f1-measure : float
Additionally, an ``overall`` key is included, which provides the precision,
... |
Returns
-------
A Dict per label containing following the span based metrics:
precision : float
recall : float
f1-measure : float
Additionally, an ``overall`` key is included, which provides the precision,
recall and f1-measure for all spans.
| get_metric | python | allenai/scispacy | scispacy/per_class_scorer.py | https://github.com/allenai/scispacy/blob/master/scispacy/per_class_scorer.py | Apache-2.0 |
def get_children(self, node: SemanticTypeNode) -> List[SemanticTypeNode]:
"""
Recursively build up a flat list of all a node's children.
"""
children = []
for child in node.children:
children.append(child)
children.extend(self.get_children(child))
... |
Recursively build up a flat list of all a node's children.
| get_children | python | allenai/scispacy | scispacy/umls_semantic_type_tree.py | https://github.com/allenai/scispacy/blob/master/scispacy/umls_semantic_type_tree.py | Apache-2.0 |
def get_parent(self, node: SemanticTypeNode) -> Optional[SemanticTypeNode]:
"""
Returns the parent of the input node, returning None if the input node is the root of the tree
"""
current_depth = node.level
possible_parents = self.get_nodes_at_depth(current_depth - 1)
for... |
Returns the parent of the input node, returning None if the input node is the root of the tree
| get_parent | python | allenai/scispacy | scispacy/umls_semantic_type_tree.py | https://github.com/allenai/scispacy/blob/master/scispacy/umls_semantic_type_tree.py | Apache-2.0 |
def get_collapsed_type_id_map_at_level(self, level: int) -> Dict[str, str]:
"""
Constructs a label mapping from the original tree labels to a tree of a fixed depth,
collapsing labels greater than the depth specified to the closest parent which is
still present in the new fixed depth tree... |
Constructs a label mapping from the original tree labels to a tree of a fixed depth,
collapsing labels greater than the depth specified to the closest parent which is
still present in the new fixed depth tree. This is effectively mapping to a _coarser_
label space.
| get_collapsed_type_id_map_at_level | python | allenai/scispacy | scispacy/umls_semantic_type_tree.py | https://github.com/allenai/scispacy/blob/master/scispacy/umls_semantic_type_tree.py | Apache-2.0 |
def construct_umls_tree_from_tsv(filepath: str) -> UmlsSemanticTypeTree:
"""
Reads in a tsv file which is formatted as a depth first traversal of
a hierarchy tree, where nodes are of the format:
Name TAB UMLS Semantic Type TAB Tree Depth
Event T051 1
Activity T052 2
Behav... |
Reads in a tsv file which is formatted as a depth first traversal of
a hierarchy tree, where nodes are of the format:
Name TAB UMLS Semantic Type TAB Tree Depth
Event T051 1
Activity T052 2
Behavior T053 3
Social Behavior T054 4
Individual Beh... | construct_umls_tree_from_tsv | python | allenai/scispacy | scispacy/umls_semantic_type_tree.py | https://github.com/allenai/scispacy/blob/master/scispacy/umls_semantic_type_tree.py | Apache-2.0 |
def read_umls_file_headers(meta_path: str, filename: str) -> List[str]:
"""
Read the file descriptor MRFILES.RRF from a UMLS release and get column headers (names)
for the given file
MRFILES.RRF file format: a pipe-separated values
Useful columns:
column 0: name of one of the files in the M... |
Read the file descriptor MRFILES.RRF from a UMLS release and get column headers (names)
for the given file
MRFILES.RRF file format: a pipe-separated values
Useful columns:
column 0: name of one of the files in the META directory
column 2: column names of that file
Args:
me... | read_umls_file_headers | python | allenai/scispacy | scispacy/umls_utils.py | https://github.com/allenai/scispacy/blob/master/scispacy/umls_utils.py | Apache-2.0 |
def read_umls_concepts(
meta_path: str,
concept_details: Dict,
source: Optional[str] = None,
lang: str = "ENG",
non_suppressed: bool = True,
):
"""
Read the concepts file MRCONSO.RRF from a UMLS release and store it in
concept_details dictionary. Each concept is represented with
- co... |
Read the concepts file MRCONSO.RRF from a UMLS release and store it in
concept_details dictionary. Each concept is represented with
- concept_id
- canonical_name
- aliases
- types
- definition
This function fills the first three. If a canonical name is not found, it is left empty.
... | read_umls_concepts | python | allenai/scispacy | scispacy/umls_utils.py | https://github.com/allenai/scispacy/blob/master/scispacy/umls_utils.py | Apache-2.0 |
def read_umls_types(meta_path: str, concept_details: Dict):
"""
Read the types file MRSTY.RRF from a UMLS release and store it in
concept_details dictionary. This function adds the `types` field
to the information of each concept
MRSTY.RRF file format: a pipe-separated values
Useful columns: CU... |
Read the types file MRSTY.RRF from a UMLS release and store it in
concept_details dictionary. This function adds the `types` field
to the information of each concept
MRSTY.RRF file format: a pipe-separated values
Useful columns: CUI, TUI
Args:
meta_path: path to the META directory of ... | read_umls_types | python | allenai/scispacy | scispacy/umls_utils.py | https://github.com/allenai/scispacy/blob/master/scispacy/umls_utils.py | Apache-2.0 |
def read_umls_definitions(meta_path: str, concept_details: Dict):
"""
Read the types file MRDEF.RRF from a UMLS release and store it in
concept_details dictionary. This function adds the `definition` field
to the information of each concept
MRDEF.RRF file format: a pipe-separated values
Useful ... |
Read the types file MRDEF.RRF from a UMLS release and store it in
concept_details dictionary. This function adds the `definition` field
to the information of each concept
MRDEF.RRF file format: a pipe-separated values
Useful columns: CUI, SAB, SUPPRESS, DEF
Args:
meta_path: path to th... | read_umls_definitions | python | allenai/scispacy | scispacy/umls_utils.py | https://github.com/allenai/scispacy/blob/master/scispacy/umls_utils.py | Apache-2.0 |
def count_frequencies(language_class: Language, input_path: Path):
"""
Given a file containing single documents per line
(for scispacy, these are Pubmed abstracts), split the text
using a science specific tokenizer and compute word and
document frequencies for all words.
"""
print(f"Processi... |
Given a file containing single documents per line
(for scispacy, these are Pubmed abstracts), split the text
using a science specific tokenizer and compute word and
document frequencies for all words.
| count_frequencies | python | allenai/scispacy | scripts/count_word_frequencies.py | https://github.com/allenai/scispacy/blob/master/scripts/count_word_frequencies.py | Apache-2.0 |
def merge_counts(frequencies: List[Tuple[Counter, Counter]], output_path: str):
"""
Merge a number of frequency counts generated from `count_frequencies`
into a single file, written to `output_path`.
"""
counts = Counter()
doc_counts = Counter()
for word_count, doc_count in frequencies:
... |
Merge a number of frequency counts generated from `count_frequencies`
into a single file, written to `output_path`.
| merge_counts | python | allenai/scispacy | scripts/count_word_frequencies.py | https://github.com/allenai/scispacy/blob/master/scripts/count_word_frequencies.py | Apache-2.0 |
def get_spacy_model(
spacy_model_name: str,
pos_tags: bool,
parse: bool,
ner: bool,
with_custom_tokenizer: bool = False,
with_sentence_segmenter: bool = False,
with_serializable_abbreviation_detector: Optional[bool] = None,
) -> SpacyModelType:
"""
In order to avoid loading spacy mod... |
In order to avoid loading spacy models repeatedly,
we'll save references to them, keyed by the options
we used to create the spacy model, so any particular
configuration only gets loaded once.
| get_spacy_model | python | allenai/scispacy | tests/conftest.py | https://github.com/allenai/scispacy/blob/master/tests/conftest.py | Apache-2.0 |
def __call__(self, position: Position, rng_key: Optional[PRNGKey]) -> State:
"""Initialize the algorithm's state.
Parameters
----------
position
A chain position.
Returns
-------
The kernel state that corresponds to the position.
""" | Initialize the algorithm's state.
Parameters
----------
position
A chain position.
Returns
-------
The kernel state that corresponds to the position.
| __call__ | python | blackjax-devs/blackjax | blackjax/base.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/base.py | Apache-2.0 |
def __call__(self, rng_key: PRNGKey, state: State) -> tuple[State, Info]:
"""Update the current state using the sampling algorithm.
Parameters
----------
rng_key:
The random state used by JAX's random numbers generator.
state:
The current kernel state. Th... | Update the current state using the sampling algorithm.
Parameters
----------
rng_key:
The random state used by JAX's random numbers generator.
state:
The current kernel state. The kernel state contains the current
chain position as well as other infor... | __call__ | python | blackjax-devs/blackjax | blackjax/base.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/base.py | Apache-2.0 |
def potential_scale_reduction(
input_array: ArrayLike, chain_axis: int = 0, sample_axis: int = 1
) -> Array:
"""Gelman and Rubin (1992)'s potential scale reduction for computing multiple MCMC chain convergence.
Parameters
----------
input_array:
An array representing multiple chains of MCMC... | Gelman and Rubin (1992)'s potential scale reduction for computing multiple MCMC chain convergence.
Parameters
----------
input_array:
An array representing multiple chains of MCMC samples. The array must
contains a chain dimension and a sample dimension.
chain_axis
The axis indi... | potential_scale_reduction | python | blackjax-devs/blackjax | blackjax/diagnostics.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/diagnostics.py | Apache-2.0 |
def effective_sample_size(
input_array: ArrayLike, chain_axis: int = 0, sample_axis: int = 1
) -> Array:
"""Compute estimate of the effective sample size (ess).
Parameters
----------
input_array:
An array representing multiple chains of MCMC samples. The array must
contains a chain ... | Compute estimate of the effective sample size (ess).
Parameters
----------
input_array:
An array representing multiple chains of MCMC samples. The array must
contains a chain dimension and a sample dimension.
chain_axis
The axis indicating the multiple chains. Default to 0.
... | effective_sample_size | python | blackjax-devs/blackjax | blackjax/diagnostics.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/diagnostics.py | Apache-2.0 |
def _update_progress_bar(iter_num, chain_id):
"Updates progress bar of a JAX scan or loop"
chain_id = lax.cond(
# update every multiple of `print_rate` except at the end
(iter_num % print_rate == 0) | (iter_num == (num_samples - 1)),
lambda _: io_callback(_update_bar... | Updates progress bar of a JAX scan or loop | _update_progress_bar | python | blackjax-devs/blackjax | blackjax/progress_bar.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/progress_bar.py | Apache-2.0 |
def _progress_bar_scan(func):
"""Decorator that adds a progress bar to `body_fun` used in `lax.scan`.
Note that `body_fun` must either be looping over `np.arange(num_samples)`,
or be looping over a tuple who's first element is `np.arange(num_samples)`
This means that `iter_num` is the cu... | Decorator that adds a progress bar to `body_fun` used in `lax.scan`.
Note that `body_fun` must either be looping over `np.arange(num_samples)`,
or be looping over a tuple who's first element is `np.arange(num_samples)`
This means that `iter_num` is the current iteration number
| _progress_bar_scan | python | blackjax-devs/blackjax | blackjax/progress_bar.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/progress_bar.py | Apache-2.0 |
def linear_map(diag_or_dense_a, b, *, precision="highest"):
"""Perform a linear map of the form y = Ax.
Dispatch matrix multiplication to either jnp.dot or jnp.multiply.
Unlike jax.numpy.dot, this function output an Array that match the dtype
and shape of the 2nd input:
- diag_or_dense_a is a scal... | Perform a linear map of the form y = Ax.
Dispatch matrix multiplication to either jnp.dot or jnp.multiply.
Unlike jax.numpy.dot, this function output an Array that match the dtype
and shape of the 2nd input:
- diag_or_dense_a is a scalar or 1d vector, `diag_or_dense_a * b` is returned
- diag_or_de... | linear_map | python | blackjax-devs/blackjax | blackjax/util.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/util.py | Apache-2.0 |
def generate_gaussian_noise(
rng_key: PRNGKey,
position: ArrayLikeTree,
mu: Union[float, Array] = 0.0,
sigma: Union[float, Array] = 1.0,
) -> ArrayTree:
"""Generate N(mu, sigma) noise with output structure that match a given PyTree.
Parameters
----------
rng_key:
The pseudo-rand... | Generate N(mu, sigma) noise with output structure that match a given PyTree.
Parameters
----------
rng_key:
The pseudo-random number generator key used to generate random numbers.
position:
PyTree that the structure the output should to match.
mu:
The mean of the Gaussian di... | generate_gaussian_noise | python | blackjax-devs/blackjax | blackjax/util.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/util.py | Apache-2.0 |
def generate_unit_vector(
rng_key: PRNGKey,
position: ArrayLikeTree,
) -> Array:
"""Generate a random unit vector with output structure that match a given PyTree.
Parameters
----------
rng_key:
The pseudo-random number generator key used to generate random numbers.
position:
... | Generate a random unit vector with output structure that match a given PyTree.
Parameters
----------
rng_key:
The pseudo-random number generator key used to generate random numbers.
position:
PyTree that the structure the output should to match.
Returns
-------
Random unit ... | generate_unit_vector | python | blackjax-devs/blackjax | blackjax/util.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/util.py | Apache-2.0 |
def index_pytree(input_pytree: ArrayLikeTree) -> ArrayTree:
"""Builds a PyTree with elements indicating its corresponding index on a flat array.
Various algorithms in BlackJAX take as input a 1 or 2 dimensional array which somehow
affects the sampling or approximation of a PyTree. For instance, in HMC a 1 ... | Builds a PyTree with elements indicating its corresponding index on a flat array.
Various algorithms in BlackJAX take as input a 1 or 2 dimensional array which somehow
affects the sampling or approximation of a PyTree. For instance, in HMC a 1 or 2
dimensional inverse mass matrix is used when simulating Ha... | index_pytree | python | blackjax-devs/blackjax | blackjax/util.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/util.py | Apache-2.0 |
def run_inference_algorithm(
rng_key: PRNGKey,
inference_algorithm: Union[SamplingAlgorithm, VIAlgorithm],
num_steps: int,
initial_state: ArrayLikeTree = None,
initial_position: ArrayLikeTree = None,
progress_bar: bool = False,
transform: Callable = lambda state, info: (state, info),
) -> tu... | Wrapper to run an inference algorithm.
Note that this utility function does not work for Stochastic Gradient MCMC samplers
like sghmc, as SG-MCMC samplers require additional control flow for batches of data
to be passed in during each sample.
Parameters
----------
rng_key
The random st... | run_inference_algorithm | python | blackjax-devs/blackjax | blackjax/util.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/util.py | Apache-2.0 |
def store_only_expectation_values(
sampling_algorithm,
state_transform=lambda x: x,
incremental_value_transform=lambda x: x,
burn_in=0,
):
"""Takes a sampling algorithm and constructs from it a new sampling algorithm object. The new sampling algorithm has the same
kernel but only stores the str... | Takes a sampling algorithm and constructs from it a new sampling algorithm object. The new sampling algorithm has the same
kernel but only stores the streaming expectation values of some observables, not the full states; to save memory.
It saves incremental_value_transform(E[state_transform(x)]) at each step ... | store_only_expectation_values | python | blackjax-devs/blackjax | blackjax/util.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/util.py | Apache-2.0 |
def incremental_value_update(
expectation, incremental_val, weight=1.0, zero_prevention=0.0
):
"""Compute the streaming average of a function O(x) using a weight.
Parameters:
----------
expectation
the value of the expectation at the current timestep
incremental_val
... | Compute the streaming average of a function O(x) using a weight.
Parameters:
----------
expectation
the value of the expectation at the current timestep
incremental_val
tuple of (total, average) where total is the sum of weights and average is the current average
... | incremental_value_update | python | blackjax-devs/blackjax | blackjax/util.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/util.py | Apache-2.0 |
def adjusted_mclmc_find_L_and_step_size(
mclmc_kernel,
num_steps,
state,
rng_key,
target,
frac_tune1=0.1,
frac_tune2=0.1,
frac_tune3=0.0,
diagonal_preconditioning=True,
params=None,
max="avg",
num_windows=1,
tuning_factor=1.3,
):
"""
Finds the optimal value of... |
Finds the optimal value of the parameters for the MH-MCHMC algorithm.
Parameters
----------
mclmc_kernel
The kernel function used for the MCMC algorithm.
num_steps
The number of MCMC steps that will subsequently be run, after tuning.
state
The initial state of the MCMC ... | adjusted_mclmc_find_L_and_step_size | python | blackjax-devs/blackjax | blackjax/adaptation/adjusted_mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/adjusted_mclmc_adaptation.py | Apache-2.0 |
def adjusted_mclmc_make_L_step_size_adaptation(
kernel,
dim,
frac_tune1,
frac_tune2,
target,
diagonal_preconditioning,
fix_L_first_da=False,
max="avg",
tuning_factor=1.0,
):
"""Adapts the stepsize and L of the MCLMC kernel. Designed for adjusted MCLMC"""
def dual_avg_step(fi... | Adapts the stepsize and L of the MCLMC kernel. Designed for adjusted MCLMC | adjusted_mclmc_make_L_step_size_adaptation | python | blackjax-devs/blackjax | blackjax/adaptation/adjusted_mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/adjusted_mclmc_adaptation.py | Apache-2.0 |
def dual_avg_step(fix_L, update_da):
"""does one step of the dynamics and updates the estimate of the posterior size and optimal stepsize"""
def step(iteration_state, weight_and_key):
mask, rng_key = weight_and_key
(
previous_state,
params,
... | does one step of the dynamics and updates the estimate of the posterior size and optimal stepsize | dual_avg_step | python | blackjax-devs/blackjax | blackjax/adaptation/adjusted_mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/adjusted_mclmc_adaptation.py | Apache-2.0 |
def adjusted_mclmc_make_adaptation_L(
kernel, frac, Lfactor, max="avg", eigenvector=None
):
"""determine L by the autocorrelations (around 10 effective samples are needed for this to be accurate)"""
def adaptation_L(state, params, num_steps, key):
num_steps = int(num_steps * frac)
adaptatio... | determine L by the autocorrelations (around 10 effective samples are needed for this to be accurate) | adjusted_mclmc_make_adaptation_L | python | blackjax-devs/blackjax | blackjax/adaptation/adjusted_mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/adjusted_mclmc_adaptation.py | Apache-2.0 |
def handle_nans(previous_state, next_state, step_size, step_size_max, kinetic_change):
"""if there are nans, let's reduce the stepsize, and not update the state. The
function returns the old state in this case."""
reduced_step_size = 0.8
p, unravel_fn = ravel_pytree(next_state.position)
nonans = jn... | if there are nans, let's reduce the stepsize, and not update the state. The
function returns the old state in this case. | handle_nans | python | blackjax-devs/blackjax | blackjax/adaptation/adjusted_mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/adjusted_mclmc_adaptation.py | Apache-2.0 |
def get_filter_adapt_info_fn(
state_keys: Set[str] = set(),
info_keys: Set[str] = set(),
adapt_state_keys: Set[str] = set(),
):
"""Generate a function to filter what is saved in AdaptationInfo. Used
for adptation_info_fn parameters of the adaptation algorithms.
adaptation_info_fn=get_filter_ada... | Generate a function to filter what is saved in AdaptationInfo. Used
for adptation_info_fn parameters of the adaptation algorithms.
adaptation_info_fn=get_filter_adapt_info_fn() saves no auxiliary information
| get_filter_adapt_info_fn | python | blackjax-devs/blackjax | blackjax/adaptation/base.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/base.py | Apache-2.0 |
def base(
jitter_generator: Callable,
next_random_arg_fn: Callable,
optim: optax.GradientTransformation,
target_acceptance_rate: float,
decay_rate: float,
) -> Tuple[Callable, Callable]:
"""Maximizing the Change in the Estimator of the Expected Square criterion
(trajectory length) and dual a... | Maximizing the Change in the Estimator of the Expected Square criterion
(trajectory length) and dual averaging procedure (step size) for the jittered
Hamiltonian Monte Carlo kernel :cite:p:`hoffman2021adaptive`.
This adaptation algorithm tunes the step size and trajectory length, i.e.
number of integra... | base | python | blackjax-devs/blackjax | blackjax/adaptation/chees_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/chees_adaptation.py | Apache-2.0 |
def compute_parameters(
proposed_positions: ArrayLikeTree,
proposed_momentums: ArrayLikeTree,
initial_positions: ArrayLikeTree,
acceptance_probabilities: Array,
is_divergent: Array,
initial_adaptation_state: ChEESAdaptationState,
) -> ChEESAdaptationState:
"""... | Compute values for the parameters based on statistics collected from
multiple chains.
Parameters
----------
proposed_positions:
A PyTree that contains the position proposed by the HMC algorithm of
every chain (proposal that is accepted or rejected using MH).
... | compute_parameters | python | blackjax-devs/blackjax | blackjax/adaptation/chees_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/chees_adaptation.py | Apache-2.0 |
def update(
adaptation_state: ChEESAdaptationState,
proposed_positions: ArrayLikeTree,
proposed_momentums: ArrayLikeTree,
initial_positions: ArrayLikeTree,
acceptance_probabilities: Array,
is_divergent: Array,
):
"""Update the adaptation state and parameter va... | Update the adaptation state and parameter values.
Parameters
----------
adaptation_state
The current state of the adaptation algorithm
proposed_positions:
The position proposed by the HMC algorithm of every chain.
proposed_momentums:
The momen... | update | python | blackjax-devs/blackjax | blackjax/adaptation/chees_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/chees_adaptation.py | Apache-2.0 |
def chees_adaptation(
logdensity_fn: Callable,
num_chains: int,
*,
jitter_generator: Optional[Callable] = None,
jitter_amount: float = 1.0,
target_acceptance_rate: float = OPTIMAL_TARGET_ACCEPTANCE_RATE,
decay_rate: float = 0.5,
adaptation_info_fn: Callable = return_all_adapt_info,
) -> ... | Adapt the step size and trajectory length (number of integration steps / step size)
parameters of the jittered HMC algorthm.
The jittered HMC algorithm depends on the value of a step size, controlling
the discretization step of the integrator, and a trajectory length, given by the
number of integration... | chees_adaptation | python | blackjax-devs/blackjax | blackjax/adaptation/chees_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/chees_adaptation.py | Apache-2.0 |
def mass_matrix_adaptation(
is_diagonal_matrix: bool = True,
) -> tuple[Callable, Callable, Callable]:
"""Adapts the values in the mass matrix by computing the covariance
between parameters.
Parameters
----------
is_diagonal_matrix
When True the algorithm adapts and returns a diagonal m... | Adapts the values in the mass matrix by computing the covariance
between parameters.
Parameters
----------
is_diagonal_matrix
When True the algorithm adapts and returns a diagonal mass matrix
(default), otherwise adaps and returns a dense mass matrix.
Returns
-------
init
... | mass_matrix_adaptation | python | blackjax-devs/blackjax | blackjax/adaptation/mass_matrix.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mass_matrix.py | Apache-2.0 |
def init(n_dims: int) -> MassMatrixAdaptationState:
"""Initialize the matrix adaptation.
Parameters
----------
ndims
The number of dimensions of the mass matrix, which corresponds to
the number of dimensions of the chain position.
"""
if is_diago... | Initialize the matrix adaptation.
Parameters
----------
ndims
The number of dimensions of the mass matrix, which corresponds to
the number of dimensions of the chain position.
| init | python | blackjax-devs/blackjax | blackjax/adaptation/mass_matrix.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mass_matrix.py | Apache-2.0 |
def update(
mm_state: MassMatrixAdaptationState, position: ArrayLike
) -> MassMatrixAdaptationState:
"""Update the algorithm's state.
Parameters
----------
state:
The current state of the mass matrix adapation.
position:
The current position o... | Update the algorithm's state.
Parameters
----------
state:
The current state of the mass matrix adapation.
position:
The current position of the chain.
| update | python | blackjax-devs/blackjax | blackjax/adaptation/mass_matrix.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mass_matrix.py | Apache-2.0 |
def final(mm_state: MassMatrixAdaptationState) -> MassMatrixAdaptationState:
"""Final iteration of the mass matrix adaptation.
In this step we compute the mass matrix from the covariance matrix computed
by the Welford algorithm, and re-initialize the later.
"""
_, wc_state = mm... | Final iteration of the mass matrix adaptation.
In this step we compute the mass matrix from the covariance matrix computed
by the Welford algorithm, and re-initialize the later.
| final | python | blackjax-devs/blackjax | blackjax/adaptation/mass_matrix.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mass_matrix.py | Apache-2.0 |
def welford_algorithm(is_diagonal_matrix: bool) -> tuple[Callable, Callable, Callable]:
r"""Welford's online estimator of covariance.
It is possible to compute the variance of a population of values in an
on-line fashion to avoid storing intermediate results. The naive recurrence
relations between the ... | Welford's online estimator of covariance.
It is possible to compute the variance of a population of values in an
on-line fashion to avoid storing intermediate results. The naive recurrence
relations between the sample mean and variance at a step and the next are
however not numerically stable.
Wel... | welford_algorithm | python | blackjax-devs/blackjax | blackjax/adaptation/mass_matrix.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mass_matrix.py | Apache-2.0 |
def init(n_dims: int) -> WelfordAlgorithmState:
"""Initialize the covariance estimation.
When the matrix is diagonal it is sufficient to work with an array that contains
the diagonal value. Otherwise we need to work with the matrix in full.
Parameters
----------
n_dims:... | Initialize the covariance estimation.
When the matrix is diagonal it is sufficient to work with an array that contains
the diagonal value. Otherwise we need to work with the matrix in full.
Parameters
----------
n_dims: int
The number of dimensions of the problem, w... | init | python | blackjax-devs/blackjax | blackjax/adaptation/mass_matrix.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mass_matrix.py | Apache-2.0 |
def update(
wa_state: WelfordAlgorithmState, value: ArrayLike
) -> WelfordAlgorithmState:
"""Update the M2 matrix using the new value.
Parameters
----------
wa_state:
The current state of the Welford Algorithm
value: Array, shape (1,)
The new ... | Update the M2 matrix using the new value.
Parameters
----------
wa_state:
The current state of the Welford Algorithm
value: Array, shape (1,)
The new sample (typically position of the chain) used to update m2
| update | python | blackjax-devs/blackjax | blackjax/adaptation/mass_matrix.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mass_matrix.py | Apache-2.0 |
def mclmc_find_L_and_step_size(
mclmc_kernel,
num_steps,
state,
rng_key,
frac_tune1=0.1,
frac_tune2=0.1,
frac_tune3=0.1,
desired_energy_var=5e-4,
trust_in_estimate=1.5,
num_effective_samples=150,
diagonal_preconditioning=True,
params=None,
):
"""
Finds the optimal... |
Finds the optimal value of the parameters for the MCLMC algorithm.
Parameters
----------
mclmc_kernel
The kernel function used for the MCMC algorithm.
num_steps
The number of MCMC steps that will subsequently be run, after tuning.
state
The initial state of the MCMC alg... | mclmc_find_L_and_step_size | python | blackjax-devs/blackjax | blackjax/adaptation/mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mclmc_adaptation.py | Apache-2.0 |
def make_L_step_size_adaptation(
kernel,
dim,
frac_tune1,
frac_tune2,
diagonal_preconditioning,
desired_energy_var=1e-3,
trust_in_estimate=1.5,
num_effective_samples=150,
):
"""Adapts the stepsize and L of the MCLMC kernel. Designed for unadjusted MCLMC"""
decay_rate = (num_effe... | Adapts the stepsize and L of the MCLMC kernel. Designed for unadjusted MCLMC | make_L_step_size_adaptation | python | blackjax-devs/blackjax | blackjax/adaptation/mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mclmc_adaptation.py | Apache-2.0 |
def predictor(previous_state, params, adaptive_state, rng_key):
"""does one step with the dynamics and updates the prediction for the optimal stepsize
Designed for the unadjusted MCHMC"""
time, x_average, step_size_max = adaptive_state
rng_key, nan_key = jax.random.split(rng_key)
... | does one step with the dynamics and updates the prediction for the optimal stepsize
Designed for the unadjusted MCHMC | predictor | python | blackjax-devs/blackjax | blackjax/adaptation/mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mclmc_adaptation.py | Apache-2.0 |
def step(iteration_state, weight_and_key):
"""does one step of the dynamics and updates the estimate of the posterior size and optimal stepsize"""
mask, rng_key = weight_and_key
state, params, adaptive_state, streaming_avg = iteration_state
state, params, adaptive_state, success = pred... | does one step of the dynamics and updates the estimate of the posterior size and optimal stepsize | step | python | blackjax-devs/blackjax | blackjax/adaptation/mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mclmc_adaptation.py | Apache-2.0 |
def make_adaptation_L(kernel, frac, Lfactor):
"""determine L by the autocorrelations (around 10 effective samples are needed for this to be accurate)"""
def adaptation_L(state, params, num_steps, key):
num_steps_3 = round(num_steps * frac)
adaptation_L_keys = jax.random.split(key, num_steps_3)
... | determine L by the autocorrelations (around 10 effective samples are needed for this to be accurate) | make_adaptation_L | python | blackjax-devs/blackjax | blackjax/adaptation/mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mclmc_adaptation.py | Apache-2.0 |
def handle_nans(
previous_state, next_state, step_size, step_size_max, kinetic_change, key
):
"""if there are nans, let's reduce the stepsize, and not update the state. The
function returns the old state in this case."""
reduced_step_size = 0.8
p, unravel_fn = ravel_pytree(next_state.position)
... | if there are nans, let's reduce the stepsize, and not update the state. The
function returns the old state in this case. | handle_nans | python | blackjax-devs/blackjax | blackjax/adaptation/mclmc_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/mclmc_adaptation.py | Apache-2.0 |
def base():
"""Maximum-Eigenvalue Adaptation of damping and step size for the generalized
Hamiltonian Monte Carlo kernel :cite:p:`hoffman2022tuning`.
This algorithm performs a cross-chain adaptation scheme for the generalized
HMC algorithm that automatically selects values for the generalized HMC's
... | Maximum-Eigenvalue Adaptation of damping and step size for the generalized
Hamiltonian Monte Carlo kernel :cite:p:`hoffman2022tuning`.
This algorithm performs a cross-chain adaptation scheme for the generalized
HMC algorithm that automatically selects values for the generalized HMC's
tunable parameter... | base | python | blackjax-devs/blackjax | blackjax/adaptation/meads_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/meads_adaptation.py | Apache-2.0 |
def compute_parameters(
positions: ArrayLikeTree, logdensity_grad: ArrayLikeTree, current_iteration: int
):
"""Compute values for the parameters based on statistics collected from
multiple chains.
Parameters
----------
positions:
A PyTree that contains th... | Compute values for the parameters based on statistics collected from
multiple chains.
Parameters
----------
positions:
A PyTree that contains the current position of every chains.
logdensity_grad:
A PyTree that contains the gradients of the logdensity
... | compute_parameters | python | blackjax-devs/blackjax | blackjax/adaptation/meads_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/meads_adaptation.py | Apache-2.0 |
def update(
adaptation_state: MEADSAdaptationState,
positions: ArrayLikeTree,
logdensity_grad: ArrayLikeTree,
) -> MEADSAdaptationState:
"""Update the adaptation state and parameter values.
We find new optimal values for the parameters of the generalized HMC
kernel u... | Update the adaptation state and parameter values.
We find new optimal values for the parameters of the generalized HMC
kernel using heuristics based on the maximum eigenvalue of the
covariance and gradient matrices given by an ensemble of chains.
Parameters
----------
a... | update | python | blackjax-devs/blackjax | blackjax/adaptation/meads_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/meads_adaptation.py | Apache-2.0 |
def meads_adaptation(
logdensity_fn: Callable,
num_chains: int,
adaptation_info_fn: Callable = return_all_adapt_info,
) -> AdaptationAlgorithm:
"""Adapt the parameters of the Generalized HMC algorithm.
The Generalized HMC algorithm depends on three parameters, each controlling
one element of it... | Adapt the parameters of the Generalized HMC algorithm.
The Generalized HMC algorithm depends on three parameters, each controlling
one element of its behaviour: step size controls the integrator's dynamics,
alpha controls the persistency of the momentum variable, and delta controls
the deterministic tr... | meads_adaptation | python | blackjax-devs/blackjax | blackjax/adaptation/meads_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/meads_adaptation.py | Apache-2.0 |
def maximum_eigenvalue(matrix: ArrayLikeTree) -> Array:
"""Estimate the largest eigenvalues of a matrix.
We calculate an unbiased estimate of the ratio between the sum of the
squared eigenvalues and the sum of the eigenvalues from the input
matrix. This ratio approximates the largest eigenvalue well ex... | Estimate the largest eigenvalues of a matrix.
We calculate an unbiased estimate of the ratio between the sum of the
squared eigenvalues and the sum of the eigenvalues from the input
matrix. This ratio approximates the largest eigenvalue well except in
cases when there are a large number of small eigenv... | maximum_eigenvalue | python | blackjax-devs/blackjax | blackjax/adaptation/meads_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/meads_adaptation.py | Apache-2.0 |
def base(
target_acceptance_rate: float = 0.80,
):
"""Warmup scheme for sampling procedures based on euclidean manifold HMC.
This adaptation runs in two steps:
1. The Pathfinder algorithm is ran and we subsequently compute an estimate
for the value of the inverse mass matrix, as well as a new init... | Warmup scheme for sampling procedures based on euclidean manifold HMC.
This adaptation runs in two steps:
1. The Pathfinder algorithm is ran and we subsequently compute an estimate
for the value of the inverse mass matrix, as well as a new initialization
point for the markov chain that is supposedly c... | base | python | blackjax-devs/blackjax | blackjax/adaptation/pathfinder_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/pathfinder_adaptation.py | Apache-2.0 |
def init(
alpha,
beta,
gamma,
initial_step_size: float,
) -> PathfinderAdaptationState:
"""Initialze the adaptation state and parameter values.
We use the Pathfinder algorithm to compute an estimate of the inverse
mass matrix that will stay constant throughou... | Initialze the adaptation state and parameter values.
We use the Pathfinder algorithm to compute an estimate of the inverse
mass matrix that will stay constant throughout the rest of the
adaptation.
Parameters
----------
alpha, beta, gamma
Factored representa... | init | python | blackjax-devs/blackjax | blackjax/adaptation/pathfinder_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/pathfinder_adaptation.py | Apache-2.0 |
def update(
adaptation_state: PathfinderAdaptationState,
position: ArrayLikeTree,
acceptance_rate: float,
) -> PathfinderAdaptationState:
"""Update the adaptation state and parameter values.
Since the value of the inverse mass matrix is already known we only
update t... | Update the adaptation state and parameter values.
Since the value of the inverse mass matrix is already known we only
update the state of the step size adaptation algorithm.
Parameters
----------
adaptation_state
Current adptation state.
position
... | update | python | blackjax-devs/blackjax | blackjax/adaptation/pathfinder_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/pathfinder_adaptation.py | Apache-2.0 |
def final(warmup_state: PathfinderAdaptationState) -> tuple[float, Array]:
"""Return the final values for the step size and inverse mass matrix."""
step_size = jnp.exp(warmup_state.ss_state.log_step_size_avg)
inverse_mass_matrix = warmup_state.inverse_mass_matrix
return step_size, invers... | Return the final values for the step size and inverse mass matrix. | final | python | blackjax-devs/blackjax | blackjax/adaptation/pathfinder_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/pathfinder_adaptation.py | Apache-2.0 |
def pathfinder_adaptation(
algorithm,
logdensity_fn: Callable,
initial_step_size: float = 1.0,
target_acceptance_rate: float = 0.80,
adaptation_info_fn: Callable = return_all_adapt_info,
**extra_parameters,
) -> AdaptationAlgorithm:
"""Adapt the value of the inverse mass matrix and step size... | Adapt the value of the inverse mass matrix and step size parameters of
algorithms in the HMC fmaily.
Parameters
----------
algorithm
The algorithm whose parameters are being tuned.
logdensity_fn
The log density probability density function from which we wish to sample.
initial_s... | pathfinder_adaptation | python | blackjax-devs/blackjax | blackjax/adaptation/pathfinder_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/pathfinder_adaptation.py | Apache-2.0 |
def dual_averaging_adaptation(
target: float, t0: int = 10, gamma: float = 0.05, kappa: float = 0.75
) -> tuple[Callable, Callable, Callable]:
"""Tune the step size in order to achieve a desired target acceptance rate.
Let us note :math:`\\epsilon` the current step size, :math:`\\alpha_t` the
metropoli... | Tune the step size in order to achieve a desired target acceptance rate.
Let us note :math:`\epsilon` the current step size, :math:`\alpha_t` the
metropolis acceptance rate at time :math:`t` and :math:`\delta` the desired
aceptance rate. We define:
.. math:
H_t = \delta - \alpha_t
the err... | dual_averaging_adaptation | python | blackjax-devs/blackjax | blackjax/adaptation/step_size.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/step_size.py | Apache-2.0 |
def update(
da_state: DualAveragingAdaptationState, acceptance_rate: float
) -> DualAveragingAdaptationState:
"""Update the state of the Dual Averaging adaptive algorithm.
Parameters
----------
da_state:
The current state of the dual averaging algorithm.
... | Update the state of the Dual Averaging adaptive algorithm.
Parameters
----------
da_state:
The current state of the dual averaging algorithm.
acceptance_rate: float in [0, 1]
The current metropolis acceptance rate.
Returns
-------
The upd... | update | python | blackjax-devs/blackjax | blackjax/adaptation/step_size.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/step_size.py | Apache-2.0 |
def find_reasonable_step_size(
rng_key: PRNGKey,
kernel_generator: Callable[[float], Callable],
reference_state: HMCState,
initial_step_size: float,
target_accept: float = 0.65,
) -> float:
"""Find a reasonable initial step size during warmup.
While the dual averaging scheme is guaranteed t... | Find a reasonable initial step size during warmup.
While the dual averaging scheme is guaranteed to converge to a reasonable
value for the step size starting from any value, choosing a good first
value can speed up the convergence. This heuristics doubles and halves the
step size until the acceptance p... | find_reasonable_step_size | python | blackjax-devs/blackjax | blackjax/adaptation/step_size.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/step_size.py | Apache-2.0 |
def do_continue(rss_state: ReasonableStepSizeState) -> bool:
"""Decides whether the search should continue.
The search stops when it crosses the `target_accept` threshold, i.e.
when the current direction is opposite to the previous direction.
Note
----
Per JAX's documen... | Decides whether the search should continue.
The search stops when it crosses the `target_accept` threshold, i.e.
when the current direction is opposite to the previous direction.
Note
----
Per JAX's documentation :cite:p:`jax_finfo` the `jnp.finfo` object is cached so we do not... | do_continue | python | blackjax-devs/blackjax | blackjax/adaptation/step_size.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/step_size.py | Apache-2.0 |
def update(rss_state: ReasonableStepSizeState) -> ReasonableStepSizeState:
"""Perform one step of the step size search."""
i, direction, _, step_size = rss_state
subkey = jax.random.fold_in(rng_key, i)
step_size = (2.0**direction) * step_size
kernel = kernel_generator(step_size)... | Perform one step of the step size search. | update | python | blackjax-devs/blackjax | blackjax/adaptation/step_size.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/step_size.py | Apache-2.0 |
def base(
is_mass_matrix_diagonal: bool,
target_acceptance_rate: float = 0.80,
) -> tuple[Callable, Callable, Callable]:
"""Warmup scheme for sampling procedures based on euclidean manifold HMC.
The schedule and algorithms used match Stan's :cite:p:`stan_hmc_param` as closely as possible.
Unlike se... | Warmup scheme for sampling procedures based on euclidean manifold HMC.
The schedule and algorithms used match Stan's :cite:p:`stan_hmc_param` as closely as possible.
Unlike several other libraries, we separate the warmup and sampling phases
explicitly. This ensure a better modularity; a change in the warmu... | base | python | blackjax-devs/blackjax | blackjax/adaptation/window_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py | Apache-2.0 |
def init(
position: ArrayLikeTree, initial_step_size: float
) -> WindowAdaptationState:
"""Initialze the adaptation state and parameter values.
Unlike the original Stan window adaptation we do not use the
`find_reasonable_step_size` algorithm which we found to be unnecessary.
... | Initialze the adaptation state and parameter values.
Unlike the original Stan window adaptation we do not use the
`find_reasonable_step_size` algorithm which we found to be unnecessary.
We may reconsider this choice in the future.
| init | python | blackjax-devs/blackjax | blackjax/adaptation/window_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py | Apache-2.0 |
def fast_update(
position: ArrayLikeTree,
acceptance_rate: float,
warmup_state: WindowAdaptationState,
) -> WindowAdaptationState:
"""Update the adaptation state when in a "fast" window.
Only the step size is adapted in fast windows. "Fast" refers to the fact
that th... | Update the adaptation state when in a "fast" window.
Only the step size is adapted in fast windows. "Fast" refers to the fact
that the optimization algorithms are relatively fast to converge
compared to the covariance estimation with Welford's algorithm
| fast_update | python | blackjax-devs/blackjax | blackjax/adaptation/window_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py | Apache-2.0 |
def slow_update(
position: ArrayLikeTree,
acceptance_rate: float,
warmup_state: WindowAdaptationState,
) -> WindowAdaptationState:
"""Update the adaptation state when in a "slow" window.
Both the mass matrix adaptation *state* and the step size state are
adapted in s... | Update the adaptation state when in a "slow" window.
Both the mass matrix adaptation *state* and the step size state are
adapted in slow windows. The value of the step size is updated as well,
but the new value of the inverse mass matrix is only computed at the end
of the slow window. "... | slow_update | python | blackjax-devs/blackjax | blackjax/adaptation/window_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py | Apache-2.0 |
def slow_final(warmup_state: WindowAdaptationState) -> WindowAdaptationState:
"""Update the parameters at the end of a slow adaptation window.
We compute the value of the mass matrix and reset the mass matrix
adapation's internal state since middle windows are "memoryless".
"""
... | Update the parameters at the end of a slow adaptation window.
We compute the value of the mass matrix and reset the mass matrix
adapation's internal state since middle windows are "memoryless".
| slow_final | python | blackjax-devs/blackjax | blackjax/adaptation/window_adaptation.py | https://github.com/blackjax-devs/blackjax/blob/master/blackjax/adaptation/window_adaptation.py | Apache-2.0 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.