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 __getitem__(self, index): """ Args: index (int): Index Returns: tuple: Tuple (image, (target, masks, num_crowds)). target is the object returned by ``coco.loadAnns``. """ im, gt, masks, h, w, num_crowds = self.pull_item(index) ...
Args: index (int): Index Returns: tuple: Tuple (image, (target, masks, num_crowds)). target is the object returned by ``coco.loadAnns``.
__getitem__
python
dbolya/yolact
data/coco.py
https://github.com/dbolya/yolact/blob/master/data/coco.py
MIT
def pull_item(self, index): """ Args: index (int): Index Returns: tuple: Tuple (image, target, masks, height, width, crowd). target is the object returned by ``coco.loadAnns``. Note that if no crowd annotations exist, crowd will be None ...
Args: index (int): Index Returns: tuple: Tuple (image, target, masks, height, width, crowd). target is the object returned by ``coco.loadAnns``. Note that if no crowd annotations exist, crowd will be None
pull_item
python
dbolya/yolact
data/coco.py
https://github.com/dbolya/yolact/blob/master/data/coco.py
MIT
def enforce_size(img, targets, masks, num_crowds, new_w, new_h): """ Ensures that the image is the given size without distorting aspect ratio. """ with torch.no_grad(): _, h, w = img.size() if h == new_h and w == new_w: return img, targets, masks, num_crowds # Resiz...
Ensures that the image is the given size without distorting aspect ratio.
enforce_size
python
dbolya/yolact
data/coco.py
https://github.com/dbolya/yolact/blob/master/data/coco.py
MIT
def detection_collate(batch): """Custom collate fn for dealing with batches of images that have a different number of associated object annotations (bounding boxes). Arguments: batch: (tuple) A tuple of tensor images and (lists of annotations, masks) Return: A tuple containing: ...
Custom collate fn for dealing with batches of images that have a different number of associated object annotations (bounding boxes). Arguments: batch: (tuple) A tuple of tensor images and (lists of annotations, masks) Return: A tuple containing: 1) (tensor) batch of images stac...
detection_collate
python
dbolya/yolact
data/coco.py
https://github.com/dbolya/yolact/blob/master/data/coco.py
MIT
def copy(self, new_config_dict={}): """ Copies this config into a new config object, making the changes given by new_config_dict. """ ret = Config(vars(self)) for key, val in new_config_dict.items(): ret.__setattr__(key, val) return ret
Copies this config into a new config object, making the changes given by new_config_dict.
copy
python
dbolya/yolact
data/config.py
https://github.com/dbolya/yolact/blob/master/data/config.py
MIT
def replace(self, new_config_dict): """ Copies new_config_dict into this config object. Note: new_config_dict can also be a config object. """ if isinstance(new_config_dict, Config): new_config_dict = vars(new_config_dict) for key, val in new_config_dict.item...
Copies new_config_dict into this config object. Note: new_config_dict can also be a config object.
replace
python
dbolya/yolact
data/config.py
https://github.com/dbolya/yolact/blob/master/data/config.py
MIT
def set_cfg(config_name:str): """ Sets the active config. Works even if cfg is already imported! """ global cfg # Note this is not just an eval because I'm lazy, but also because it can # be used like ssd300_config.copy({'max_size': 400}) for extreme fine-tuning cfg.replace(eval(config_name)) ...
Sets the active config. Works even if cfg is already imported!
set_cfg
python
dbolya/yolact
data/config.py
https://github.com/dbolya/yolact/blob/master/data/config.py
MIT
def elemwise_box_iou(box_a, box_b): """ Does the same as above but instead of pairwise, elementwise along the inner dimension. """ max_xy = torch.min(box_a[:, 2:], box_b[:, 2:]) min_xy = torch.max(box_a[:, :2], box_b[:, :2]) inter = torch.clamp((max_xy - min_xy), min=0) inter = inter[:, 0] * inter[:...
Does the same as above but instead of pairwise, elementwise along the inner dimension.
elemwise_box_iou
python
dbolya/yolact
layers/box_utils.py
https://github.com/dbolya/yolact/blob/master/layers/box_utils.py
MIT
def mask_iou(masks_a, masks_b, iscrowd=False): """ Computes the pariwise mask IoU between two sets of masks of size [a, h, w] and [b, h, w]. The output is of size [a, b]. Wait I thought this was "box_utils", why am I putting this in here? """ masks_a = masks_a.view(masks_a.size(0), -1) mas...
Computes the pariwise mask IoU between two sets of masks of size [a, h, w] and [b, h, w]. The output is of size [a, b]. Wait I thought this was "box_utils", why am I putting this in here?
mask_iou
python
dbolya/yolact
layers/box_utils.py
https://github.com/dbolya/yolact/blob/master/layers/box_utils.py
MIT
def elemwise_mask_iou(masks_a, masks_b): """ Does the same as above but instead of pairwise, elementwise along the outer dimension. """ masks_a = masks_a.view(-1, masks_a.size(-1)) masks_b = masks_b.view(-1, masks_b.size(-1)) intersection = (masks_a * masks_b).sum(dim=0) area_a = masks_a.sum(dim=0)...
Does the same as above but instead of pairwise, elementwise along the outer dimension.
elemwise_mask_iou
python
dbolya/yolact
layers/box_utils.py
https://github.com/dbolya/yolact/blob/master/layers/box_utils.py
MIT
def change(gt, priors): """ Compute the d_change metric proposed in Box2Pix: https://lmb.informatik.uni-freiburg.de/Publications/2018/UB18/paper-box2pix.pdf Input should be in point form (xmin, ymin, xmax, ymax). Output is of shape [num_gt, num_priors] Note this returns -change so it can b...
Compute the d_change metric proposed in Box2Pix: https://lmb.informatik.uni-freiburg.de/Publications/2018/UB18/paper-box2pix.pdf Input should be in point form (xmin, ymin, xmax, ymax). Output is of shape [num_gt, num_priors] Note this returns -change so it can be a drop in replacement for ...
change
python
dbolya/yolact
layers/box_utils.py
https://github.com/dbolya/yolact/blob/master/layers/box_utils.py
MIT
def match(pos_thresh, neg_thresh, truths, priors, labels, crowd_boxes, loc_t, conf_t, idx_t, idx, loc_data): """Match each prior box with the ground truth box of the highest jaccard overlap, encode the bounding boxes, then return the matched indices corresponding to both confidence and location preds. A...
Match each prior box with the ground truth box of the highest jaccard overlap, encode the bounding boxes, then return the matched indices corresponding to both confidence and location preds. Args: pos_thresh: (float) IoU > pos_thresh ==> positive. neg_thresh: (float) IoU < neg_thresh ==> neg...
match
python
dbolya/yolact
layers/box_utils.py
https://github.com/dbolya/yolact/blob/master/layers/box_utils.py
MIT
def encode(matched, priors, use_yolo_regressors:bool=False): """ Encode bboxes matched with each prior into the format produced by the network. See decode for more details on this format. Note that encode(decode(x, p), p) = x. Args: - matched: A tensor of bboxes in point form with shape...
Encode bboxes matched with each prior into the format produced by the network. See decode for more details on this format. Note that encode(decode(x, p), p) = x. Args: - matched: A tensor of bboxes in point form with shape [num_priors, 4] - priors: The tensor of all priors with sh...
encode
python
dbolya/yolact
layers/box_utils.py
https://github.com/dbolya/yolact/blob/master/layers/box_utils.py
MIT
def decode(loc, priors, use_yolo_regressors:bool=False): """ Decode predicted bbox coordinates using the same scheme employed by Yolov2: https://arxiv.org/pdf/1612.08242.pdf b_x = (sigmoid(pred_x) - .5) / conv_w + prior_x b_y = (sigmoid(pred_y) - .5) / conv_h + prior_y b_w = prior_w...
Decode predicted bbox coordinates using the same scheme employed by Yolov2: https://arxiv.org/pdf/1612.08242.pdf b_x = (sigmoid(pred_x) - .5) / conv_w + prior_x b_y = (sigmoid(pred_y) - .5) / conv_h + prior_y b_w = prior_w * exp(loc_w) b_h = prior_h * exp(loc_h) Note t...
decode
python
dbolya/yolact
layers/box_utils.py
https://github.com/dbolya/yolact/blob/master/layers/box_utils.py
MIT
def sanitize_coordinates(_x1, _x2, img_size:int, padding:int=0, cast:bool=True): """ Sanitizes the input coordinates so that x1 < x2, x1 != x2, x1 >= 0, and x2 <= image_size. Also converts from relative to absolute coordinates and casts the results to long tensors. If cast is false, the result won't be...
Sanitizes the input coordinates so that x1 < x2, x1 != x2, x1 >= 0, and x2 <= image_size. Also converts from relative to absolute coordinates and casts the results to long tensors. If cast is false, the result won't be cast to longs. Warning: this does things in-place behind the scenes so copy if nece...
sanitize_coordinates
python
dbolya/yolact
layers/box_utils.py
https://github.com/dbolya/yolact/blob/master/layers/box_utils.py
MIT
def crop(masks, boxes, padding:int=1): """ "Crop" predicted masks by zeroing out everything not in the predicted bbox. Vectorized by Chong (thanks Chong). Args: - masks should be a size [h, w, n] tensor of masks - boxes should be a size [n, 4] tensor of bbox coords in relative point for...
"Crop" predicted masks by zeroing out everything not in the predicted bbox. Vectorized by Chong (thanks Chong). Args: - masks should be a size [h, w, n] tensor of masks - boxes should be a size [n, 4] tensor of bbox coords in relative point form
crop
python
dbolya/yolact
layers/box_utils.py
https://github.com/dbolya/yolact/blob/master/layers/box_utils.py
MIT
def index2d(src, idx): """ Indexes a tensor by a 2d index. In effect, this does out[i, j] = src[i, idx[i, j]] Both src and idx should have the same size. """ offs = torch.arange(idx.size(0), device=idx.device)[:, None].expand_as(idx) idx = idx + offs * idx.size(1) return...
Indexes a tensor by a 2d index. In effect, this does out[i, j] = src[i, idx[i, j]] Both src and idx should have the same size.
index2d
python
dbolya/yolact
layers/box_utils.py
https://github.com/dbolya/yolact/blob/master/layers/box_utils.py
MIT
def postprocess(det_output, w, h, batch_idx=0, interpolation_mode='bilinear', visualize_lincomb=False, crop_masks=True, score_threshold=0): """ Postprocesses the output of Yolact on testing mode into a format that makes sense, accounting for all the possible configuration settings. Args...
Postprocesses the output of Yolact on testing mode into a format that makes sense, accounting for all the possible configuration settings. Args: - det_output: The lost of dicts that Detect outputs. - w: The real with of the image. - h: The real height of the image. - batch_...
postprocess
python
dbolya/yolact
layers/output_utils.py
https://github.com/dbolya/yolact/blob/master/layers/output_utils.py
MIT
def undo_image_transformation(img, w, h): """ Takes a transformed image tensor and returns a numpy ndarray that is untransformed. Arguments w and h are the original height and width of the image. """ img_numpy = img.permute(1, 2, 0).cpu().numpy() img_numpy = img_numpy[:, :, (2, 1, 0)] # To BRG ...
Takes a transformed image tensor and returns a numpy ndarray that is untransformed. Arguments w and h are the original height and width of the image.
undo_image_transformation
python
dbolya/yolact
layers/output_utils.py
https://github.com/dbolya/yolact/blob/master/layers/output_utils.py
MIT
def __call__(self, predictions, net): """ Args: loc_data: (tensor) Loc preds from loc layers Shape: [batch, num_priors, 4] conf_data: (tensor) Shape: Conf preds from conf layers Shape: [batch, num_priors, num_classes] mask_data: (tenso...
Args: loc_data: (tensor) Loc preds from loc layers Shape: [batch, num_priors, 4] conf_data: (tensor) Shape: Conf preds from conf layers Shape: [batch, num_priors, num_classes] mask_data: (tensor) Mask preds from mask layers Sh...
__call__
python
dbolya/yolact
layers/functions/detection.py
https://github.com/dbolya/yolact/blob/master/layers/functions/detection.py
MIT
def detect(self, batch_idx, conf_preds, decoded_boxes, mask_data, inst_data): """ Perform nms for only the max scoring class that isn't background (class 0) """ cur_scores = conf_preds[batch_idx, 1:, :] conf_scores, _ = torch.max(cur_scores, dim=0) keep = (conf_scores > self.conf_thresh...
Perform nms for only the max scoring class that isn't background (class 0)
detect
python
dbolya/yolact
layers/functions/detection.py
https://github.com/dbolya/yolact/blob/master/layers/functions/detection.py
MIT
def forward(self, net, predictions, targets, masks, num_crowds): """Multibox Loss Args: predictions (tuple): A tuple containing loc preds, conf preds, mask preds, and prior boxes from SSD net. loc shape: torch.size(batch_size,num_priors,4) conf sha...
Multibox Loss Args: predictions (tuple): A tuple containing loc preds, conf preds, mask preds, and prior boxes from SSD net. loc shape: torch.size(batch_size,num_priors,4) conf shape: torch.size(batch_size,num_priors,num_classes) masks shap...
forward
python
dbolya/yolact
layers/modules/multibox_loss.py
https://github.com/dbolya/yolact/blob/master/layers/modules/multibox_loss.py
MIT
def focal_conf_loss(self, conf_data, conf_t): """ Focal loss as described in https://arxiv.org/pdf/1708.02002.pdf Adapted from https://github.com/clcarwin/focal_loss_pytorch/blob/master/focalloss.py Note that this uses softmax and not the original sigmoid from the paper. """ ...
Focal loss as described in https://arxiv.org/pdf/1708.02002.pdf Adapted from https://github.com/clcarwin/focal_loss_pytorch/blob/master/focalloss.py Note that this uses softmax and not the original sigmoid from the paper.
focal_conf_loss
python
dbolya/yolact
layers/modules/multibox_loss.py
https://github.com/dbolya/yolact/blob/master/layers/modules/multibox_loss.py
MIT
def focal_conf_sigmoid_loss(self, conf_data, conf_t): """ Focal loss but using sigmoid like the original paper. Note: To make things mesh easier, the network still predicts 81 class confidences in this mode. Because retinanet originally only predicts 80, we simply just don't use co...
Focal loss but using sigmoid like the original paper. Note: To make things mesh easier, the network still predicts 81 class confidences in this mode. Because retinanet originally only predicts 80, we simply just don't use conf_data[..., 0]
focal_conf_sigmoid_loss
python
dbolya/yolact
layers/modules/multibox_loss.py
https://github.com/dbolya/yolact/blob/master/layers/modules/multibox_loss.py
MIT
def focal_conf_objectness_loss(self, conf_data, conf_t): """ Instead of using softmax, use class[0] to be the objectness score and do sigmoid focal loss on that. Then for the rest of the classes, softmax them and apply CE for only the positive examples. If class[0] = 1 implies forground...
Instead of using softmax, use class[0] to be the objectness score and do sigmoid focal loss on that. Then for the rest of the classes, softmax them and apply CE for only the positive examples. If class[0] = 1 implies forground and class[0] = 0 implies background then you achieve something ...
focal_conf_objectness_loss
python
dbolya/yolact
layers/modules/multibox_loss.py
https://github.com/dbolya/yolact/blob/master/layers/modules/multibox_loss.py
MIT
def conf_objectness_loss(self, conf_data, conf_t, batch_size, loc_p, loc_t, priors): """ Instead of using softmax, use class[0] to be p(obj) * p(IoU) as in YOLO. Then for the rest of the classes, softmax them and apply CE for only the positive examples. """ conf_t = conf_t.view(...
Instead of using softmax, use class[0] to be p(obj) * p(IoU) as in YOLO. Then for the rest of the classes, softmax them and apply CE for only the positive examples.
conf_objectness_loss
python
dbolya/yolact
layers/modules/multibox_loss.py
https://github.com/dbolya/yolact/blob/master/layers/modules/multibox_loss.py
MIT
def direct_mask_loss(self, pos_idx, idx_t, loc_data, mask_data, priors, masks): """ Crops the gt masks using the predicted bboxes, scales them down, and outputs the BCE loss. """ loss_m = 0 for idx in range(mask_data.size(0)): with torch.no_grad(): cur_pos_idx = pos_i...
Crops the gt masks using the predicted bboxes, scales them down, and outputs the BCE loss.
direct_mask_loss
python
dbolya/yolact
layers/modules/multibox_loss.py
https://github.com/dbolya/yolact/blob/master/layers/modules/multibox_loss.py
MIT
def coeff_diversity_loss(self, coeffs, instance_t): """ coeffs should be size [num_pos, num_coeffs] instance_t should be size [num_pos] and be values from 0 to num_instances-1 """ num_pos = coeffs.size(0) instance_t = instance_t.view(-1) # juuuust to make sure ...
coeffs should be size [num_pos, num_coeffs] instance_t should be size [num_pos] and be values from 0 to num_instances-1
coeff_diversity_loss
python
dbolya/yolact
layers/modules/multibox_loss.py
https://github.com/dbolya/yolact/blob/master/layers/modules/multibox_loss.py
MIT
def mask_iou(mask1, mask2): """ Inputs inputs are matricies of size _ x N. Output is size _1 x _2. Note: if iscrowd is True, then mask2 should be the crowd. """ intersection = torch.matmul(mask1, mask2.t()) area1 = torch.sum(mask1, dim=1).view(1, -1) area2 = torch.sum(mask2, dim=1).view(1, -...
Inputs inputs are matricies of size _ x N. Output is size _1 x _2. Note: if iscrowd is True, then mask2 should be the crowd.
mask_iou
python
dbolya/yolact
scripts/compute_masks.py
https://github.com/dbolya/yolact/blob/master/scripts/compute_masks.py
MIT
def calc_size_preserve_ar(img_w, img_h, max_size): """ I mathed this one out on the piece of paper. Resulting width*height = approx max_size^2 """ ratio = sqrt(img_w / img_h) w = max_size * ratio h = max_size / ratio return int(w), int(h)
I mathed this one out on the piece of paper. Resulting width*height = approx max_size^2
calc_size_preserve_ar
python
dbolya/yolact
utils/augmentations.py
https://github.com/dbolya/yolact/blob/master/utils/augmentations.py
MIT
def add(self, elem): """ Adds an element to the window, removing the earliest element if necessary. """ if not math.isfinite(elem): print('Warning: Moving average ignored a value of %f' % elem) return self.window.append(elem) self.sum += elem if ...
Adds an element to the window, removing the earliest element if necessary.
add
python
dbolya/yolact
utils/functions.py
https://github.com/dbolya/yolact/blob/master/utils/functions.py
MIT
def reset(self): """ Resets the MovingAverage to its initial state. """ self.window = deque() self.sum = 0
Resets the MovingAverage to its initial state.
reset
python
dbolya/yolact
utils/functions.py
https://github.com/dbolya/yolact/blob/master/utils/functions.py
MIT
def init_console(): """ Initialize the console to be able to use ANSI escape characters on Windows. """ if os.name == 'nt': from colorama import init init()
Initialize the console to be able to use ANSI escape characters on Windows.
init_console
python
dbolya/yolact
utils/functions.py
https://github.com/dbolya/yolact/blob/master/utils/functions.py
MIT
def get_latest(save_folder, config): """ Note: config should be config.name. """ max_iter = -1 max_name = None for p in Path(save_folder).glob(config + '_*'): path_name = str(p) try: save = SavePath.from_str(path_name) except: ...
Note: config should be config.name.
get_latest
python
dbolya/yolact
utils/functions.py
https://github.com/dbolya/yolact/blob/master/utils/functions.py
MIT
def make_net(in_channels, conf, include_last_relu=True): """ A helper function to take a config setting and turn it into a network. Used by protonet and extrahead. Returns (network, out_channels) """ def make_layer(layer_cfg): nonlocal in_channels # Possible patterns: ...
A helper function to take a config setting and turn it into a network. Used by protonet and extrahead. Returns (network, out_channels)
make_net
python
dbolya/yolact
utils/functions.py
https://github.com/dbolya/yolact/blob/master/utils/functions.py
MIT
def _log_session_header(self, session_data:dict): """ Log information that does not change between iterations here. This is to cut down on the file size so you're not outputing this every iteration. """ info = {} info['type'] = 'session' info['session'] = self.ses...
Log information that does not change between iterations here. This is to cut down on the file size so you're not outputing this every iteration.
_log_session_header
python
dbolya/yolact
utils/logger.py
https://github.com/dbolya/yolact/blob/master/utils/logger.py
MIT
def log(self, type:str, data:dict={}, **kwdargs): """ Add an iteration to the log with the specified data points. Type should be the type of information this is (e.g., train, valid, etc.) You can either pass data points as kwdargs, or as a dictionary (or both!). Values s...
Add an iteration to the log with the specified data points. Type should be the type of information this is (e.g., train, valid, etc.) You can either pass data points as kwdargs, or as a dictionary (or both!). Values should be json-serializable.
log
python
dbolya/yolact
utils/logger.py
https://github.com/dbolya/yolact/blob/master/utils/logger.py
MIT
def sessions(self, path:str): """ Prints statistics about the sessions in the file. """ if not os.path.exists(path): print(path + ' doesn\'t exist!') return cur_session = None cur_time = 0 last_time = 0 num_entries = 0 def pop_session():...
Prints statistics about the sessions in the file.
sessions
python
dbolya/yolact
utils/logger.py
https://github.com/dbolya/yolact/blob/master/utils/logger.py
MIT
def add(self, path:str, session:Union[int,list]=None): """ Add a log file to the list of logs being considered. """ log = defaultdict(lambda: []) total_log = [] if not os.path.exists(path): print(path + ' doesn\'t exist!') return session_idx = 0 ...
Add a log file to the list of logs being considered.
add
python
dbolya/yolact
utils/logger.py
https://github.com/dbolya/yolact/blob/master/utils/logger.py
MIT
def query(self, x:Union[str, list], entry_type:str=None, x_idx:int=None, log_idx:int=None) -> list: """ Given a query string (can be already decoded for faster computation), query the entire log and return all values found by that query. If both log_idx and x_idx is None, this will be a ...
Given a query string (can be already decoded for faster computation), query the entire log and return all values found by that query. If both log_idx and x_idx is None, this will be a list of lists in the form [log_idx][result_idx]. If x_idx is not None, then the result will be a list o...
query
python
dbolya/yolact
utils/logger.py
https://github.com/dbolya/yolact/blob/master/utils/logger.py
MIT
def check(self, entry_type:str, x:str): """ Checks the log for the valid keys for this input. """ keys = set() x = self._decode(x) for log in self.logs: for datum in log[entry_type]: res = self._follow(datum, x) if type(res) == dict: ...
Checks the log for the valid keys for this input.
check
python
dbolya/yolact
utils/logger.py
https://github.com/dbolya/yolact/blob/master/utils/logger.py
MIT
def bar(self, entry_type:str, x:str, labels:list=None, diff:bool=False, x_idx:int=-1): """ Plot a bar chart. The result of x should be list or dictionary. """ query = self._decode(x) data_points = [] for idx, (log, name) in enumerate(zip(self.logs, self.log_names)): log = ...
Plot a bar chart. The result of x should be list or dictionary.
bar
python
dbolya/yolact
utils/logger.py
https://github.com/dbolya/yolact/blob/master/utils/logger.py
MIT
def elapsed_time(self, cond1:str='', cond2:str='', legible:bool=True) -> list: """ Returns the elapsed time between two entries based on the given conditionals. If a query isn't specified, the first / last entry will be used. The first query uses the first value and the second query uses...
Returns the elapsed time between two entries based on the given conditionals. If a query isn't specified, the first / last entry will be used. The first query uses the first value and the second query uses the last value in the results. Setting legible to true returns human-readable re...
elapsed_time
python
dbolya/yolact
utils/logger.py
https://github.com/dbolya/yolact/blob/master/utils/logger.py
MIT
def gpu_info() -> list: """ Returns a dictionary of stats mined from nvidia-smi for each gpu in a list. Adapted from nvgpu: https://pypi.org/project/nvgpu/, but mine has more info. """ gpus = [line for line in _run_cmd(['nvidia-smi', '-L']) if line] gpu_infos = [re.match('GPU ([0-9]+): ([^(]+) \...
Returns a dictionary of stats mined from nvidia-smi for each gpu in a list. Adapted from nvgpu: https://pypi.org/project/nvgpu/, but mine has more info.
gpu_info
python
dbolya/yolact
utils/nvinfo.py
https://github.com/dbolya/yolact/blob/master/utils/nvinfo.py
MIT
def visible_gpus() -> list: """ Returns a list of the indexes of all the gpus visible to pytorch. """ if 'CUDA_VISIBLE_DEVICES' not in os.environ: return list(range(len(gpu_info()))) else: return [int(x.strip()) for x in os.environ['CUDA_VISIBLE_DEVICES'].split(',')]
Returns a list of the indexes of all the gpus visible to pytorch.
visible_gpus
python
dbolya/yolact
utils/nvinfo.py
https://github.com/dbolya/yolact/blob/master/utils/nvinfo.py
MIT
def _run_cmd(cmd:list) -> list: """ Runs a command and returns a list of output lines. """ output = subprocess.check_output(cmd) output = output.decode('UTF-8') return output.split('\n')
Runs a command and returns a list of output lines.
_run_cmd
python
dbolya/yolact
utils/nvinfo.py
https://github.com/dbolya/yolact/blob/master/utils/nvinfo.py
MIT
def reset(): """ Resets the current timer. Call this at the start of an iteration. """ global _running_timer _total_times.clear() _start_times.clear() _timer_stack.clear() _running_timer = None
Resets the current timer. Call this at the start of an iteration.
reset
python
dbolya/yolact
utils/timer.py
https://github.com/dbolya/yolact/blob/master/utils/timer.py
MIT
def start(fn_name, use_stack=True): """ Start timing the specific function. Note: If use_stack is True, only one timer can be active at a time. Once you stop this timer, the previous one will start again. """ global _running_timer, _disable_all if _disable_all: return if use_stack: if _running_time...
Start timing the specific function. Note: If use_stack is True, only one timer can be active at a time. Once you stop this timer, the previous one will start again.
start
python
dbolya/yolact
utils/timer.py
https://github.com/dbolya/yolact/blob/master/utils/timer.py
MIT
def stop(fn_name=None, use_stack=True): """ If use_stack is True, this will stop the currently running timer and restore the previous timer on the stack if that exists. Note if use_stack is True, fn_name will be ignored. If use_stack is False, this will just stop timing the timer fn_name. """ global _running_ti...
If use_stack is True, this will stop the currently running timer and restore the previous timer on the stack if that exists. Note if use_stack is True, fn_name will be ignored. If use_stack is False, this will just stop timing the timer fn_name.
stop
python
dbolya/yolact
utils/timer.py
https://github.com/dbolya/yolact/blob/master/utils/timer.py
MIT
def print_stats(): """ Prints the current timing information into a table. """ print() all_fn_names = [k for k in _total_times.keys() if k not in _disabled_names] max_name_width = max([len(k) for k in all_fn_names] + [4]) if max_name_width % 2 == 1: max_name_width += 1 format_str = ' {:>%d} | {:>10.4f} ' % max_...
Prints the current timing information into a table.
print_stats
python
dbolya/yolact
utils/timer.py
https://github.com/dbolya/yolact/blob/master/utils/timer.py
MIT
def __init__(self, embedding_model, db_filename, batch_size, namespace): """ Initializes the class with necessary configurations and sets up the working directory. Parameters: embedding_model: The model used for embeddings. db_filename: The directory path where data will be stor...
Initializes the class with necessary configurations and sets up the working directory. Parameters: embedding_model: The model used for embeddings. db_filename: The directory path where data will be stored or retrieved. batch_size: The batch size used for processing. nam...
__init__
python
OSU-NLP-Group/HippoRAG
src/hipporag/embedding_store.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/embedding_store.py
MIT
def __init__(self, global_config=None, save_dir=None, llm_model_name=None, llm_base_url=None, embedding_model_name=None, embedding_base_url=None, azure_endpoint=None, azure_embedding_e...
Initializes an instance of the class and its related components. Attributes: global_config (BaseConfig): The global configuration settings for the instance. An instance of BaseConfig is used if no value is provided. saving_dir (str): The directory where specific...
__init__
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def initialize_graph(self): """ Initializes a graph using a Pickle file if available or creates a new graph. The function attempts to load a pre-existing graph stored in a Pickle file. If the file is not present or the graph needs to be created from scratch, it initializes a new directe...
Initializes a graph using a Pickle file if available or creates a new graph. The function attempts to load a pre-existing graph stored in a Pickle file. If the file is not present or the graph needs to be created from scratch, it initializes a new directed or undirected graph based on ...
initialize_graph
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def index(self, docs: List[str]): """ Indexes the given documents based on the HippoRAG 2 framework which generates an OpenIE knowledge graph based on the given documents and encodes passages, entities and facts separately for later retrieval. Parameters: docs : List[str] ...
Indexes the given documents based on the HippoRAG 2 framework which generates an OpenIE knowledge graph based on the given documents and encodes passages, entities and facts separately for later retrieval. Parameters: docs : List[str] A list of documents to be index...
index
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def delete(self, docs_to_delete: List[str]): """ Deletes the given documents from all data structures within the HippoRAG class. Note that triples and entities which are indexed from chunks that are not being removed will not be removed. Parameters: docs : List[str] ...
Deletes the given documents from all data structures within the HippoRAG class. Note that triples and entities which are indexed from chunks that are not being removed will not be removed. Parameters: docs : List[str] A list of documents to be deleted.
delete
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def retrieve(self, queries: List[str], num_to_retrieve: int = None, gold_docs: List[List[str]] = None) -> List[QuerySolution] | Tuple[List[QuerySolution], Dict]: """ Performs retrieval using the HippoRAG 2 framework, which consists of several steps: ...
Performs retrieval using the HippoRAG 2 framework, which consists of several steps: - Fact Retrieval - Recognition Memory for improved fact selection - Dense passage scoring - Personalized PageRank based re-ranking Parameters: queries: List[str] ...
retrieve
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def rag_qa(self, queries: List[str|QuerySolution], gold_docs: List[List[str]] = None, gold_answers: List[List[str]] = None) -> Tuple[List[QuerySolution], List[str], List[Dict]] | Tuple[List[QuerySolution], List[str], List[Dict], Dict, Dict]: """ Performs retr...
Performs retrieval-augmented generation enhanced QA using the HippoRAG 2 framework. This method can handle both string-based queries and pre-processed QuerySolution objects. Depending on its inputs, it returns answers only or additionally evaluate retrieval and answer quality using rec...
rag_qa
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def retrieve_dpr(self, queries: List[str], num_to_retrieve: int = None, gold_docs: List[List[str]] = None) -> List[QuerySolution] | Tuple[List[QuerySolution], Dict]: """ Performs retrieval using a DPR framework, which consists of several ste...
Performs retrieval using a DPR framework, which consists of several steps: - Dense passage scoring Parameters: queries: List[str] A list of query strings for which documents are to be retrieved. num_to_retrieve: int, optional The maximum ...
retrieve_dpr
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def rag_qa_dpr(self, queries: List[str|QuerySolution], gold_docs: List[List[str]] = None, gold_answers: List[List[str]] = None) -> Tuple[List[QuerySolution], List[str], List[Dict]] | Tuple[List[QuerySolution], List[str], List[Dict], Dict, Dict]: """ Performs ...
Performs retrieval-augmented generation enhanced QA using a standard DPR framework. This method can handle both string-based queries and pre-processed QuerySolution objects. Depending on its inputs, it returns answers only or additionally evaluate retrieval and answer quality using rec...
rag_qa_dpr
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def qa(self, queries: List[QuerySolution]) -> Tuple[List[QuerySolution], List[str], List[Dict]]: """ Executes question-answering (QA) inference using a provided set of query solutions and a language model. Parameters: queries: List[QuerySolution] A list of QuerySolut...
Executes question-answering (QA) inference using a provided set of query solutions and a language model. Parameters: queries: List[QuerySolution] A list of QuerySolution objects that contain the user queries, retrieved documents, and other related information. Retu...
qa
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def add_fact_edges(self, chunk_ids: List[str], chunk_triples: List[Tuple]): """ Adds fact edges from given triples to the graph. The method processes chunks of triples, computes unique identifiers for entities and relations, and updates various internal statistics to build and m...
Adds fact edges from given triples to the graph. The method processes chunks of triples, computes unique identifiers for entities and relations, and updates various internal statistics to build and maintain the graph structure. Entities are uniquely identified and linked based ...
add_fact_edges
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def add_passage_edges(self, chunk_ids: List[str], chunk_triple_entities: List[List[str]]): """ Adds edges connecting passage nodes to phrase nodes in the graph. This method is responsible for iterating through a list of chunk identifiers and their corresponding triple entities. It calcu...
Adds edges connecting passage nodes to phrase nodes in the graph. This method is responsible for iterating through a list of chunk identifiers and their corresponding triple entities. It calculates and adds new edges between the passage nodes (defined by the chunk identifiers) and the ...
add_passage_edges
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def add_synonymy_edges(self): """ Adds synonymy edges between similar nodes in the graph to enhance connectivity by identifying and linking synonym entities. This method performs key operations to compute and add synonymy edges. It first retrieves embeddings for all nodes, then conducts ...
Adds synonymy edges between similar nodes in the graph to enhance connectivity by identifying and linking synonym entities. This method performs key operations to compute and add synonymy edges. It first retrieves embeddings for all nodes, then conducts a nearest neighbor (KNN) search to find ...
add_synonymy_edges
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def load_existing_openie(self, chunk_keys: List[str]) -> Tuple[List[dict], Set[str]]: """ Loads existing OpenIE results from the specified file if it exists and combines them with new content while standardizing indices. If the file does not exist or is configured to be re-initialized fr...
Loads existing OpenIE results from the specified file if it exists and combines them with new content while standardizing indices. If the file does not exist or is configured to be re-initialized from scratch with the flag `force_openie_from_scratch`, it prepares new entries for process...
load_existing_openie
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def merge_openie_results(self, all_openie_info: List[dict], chunks_to_save: Dict[str, dict], ner_results_dict: Dict[str, NerRawOutput], triple_results_dict: Dict[str, TripleRawOutput]) -> List[dict]: ...
Merges OpenIE extraction results with corresponding passage and metadata. This function integrates the OpenIE extraction results, including named-entity recognition (NER) entities and triples, with their respective text passages using the provided chunk keys. The resulting merged data ...
merge_openie_results
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def save_openie_results(self, all_openie_info: List[dict]): """ Computes statistics on extracted entities from OpenIE results and saves the aggregated data in a JSON file. The function calculates the average character and word lengths of the extracted entities and writes them along with ...
Computes statistics on extracted entities from OpenIE results and saves the aggregated data in a JSON file. The function calculates the average character and word lengths of the extracted entities and writes them along with the provided OpenIE information to a file. Parameters: ...
save_openie_results
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def augment_graph(self): """ Provides utility functions to augment a graph by adding new nodes and edges. It ensures that the graph structure is extended to include additional components, and logs the completion status along with printing the updated graph information. """ ...
Provides utility functions to augment a graph by adding new nodes and edges. It ensures that the graph structure is extended to include additional components, and logs the completion status along with printing the updated graph information.
augment_graph
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def add_new_nodes(self): """ Adds new nodes to the graph from entity and passage embedding stores based on their attributes. This method identifies and adds new nodes to the graph by comparing existing nodes in the graph and nodes retrieved from the entity embedding store and the passag...
Adds new nodes to the graph from entity and passage embedding stores based on their attributes. This method identifies and adds new nodes to the graph by comparing existing nodes in the graph and nodes retrieved from the entity embedding store and the passage embedding store. The metho...
add_new_nodes
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def add_new_edges(self): """ Processes edges from `node_to_node_stats` to add them into a graph object while managing adjacency lists, validating edges, and logging invalid edge cases. """ graph_adj_list = defaultdict(dict) graph_inverse_adj_list = defaultdict(dict) ...
Processes edges from `node_to_node_stats` to add them into a graph object while managing adjacency lists, validating edges, and logging invalid edge cases.
add_new_edges
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def get_graph_info(self) -> Dict: """ Obtains detailed information about the graph such as the number of nodes, triples, and their classifications. This method calculates various statistics about the graph based on the stores and node-to-node relationships, including counts of p...
Obtains detailed information about the graph such as the number of nodes, triples, and their classifications. This method calculates various statistics about the graph based on the stores and node-to-node relationships, including counts of phrase and passage nodes, total nodes,...
get_graph_info
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def prepare_retrieval_objects(self): """ Prepares various in-memory objects and attributes necessary for fast retrieval processes, such as embedding data and graph relationships, ensuring consistency and alignment with the underlying graph structure. """ logger.info("Preparing f...
Prepares various in-memory objects and attributes necessary for fast retrieval processes, such as embedding data and graph relationships, ensuring consistency and alignment with the underlying graph structure.
prepare_retrieval_objects
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def get_query_embeddings(self, queries: List[str] | List[QuerySolution]): """ Retrieves embeddings for given queries and updates the internal query-to-embedding mapping. The method determines whether each query is already present in the `self.query_to_embedding` dictionary under the keys 'triple...
Retrieves embeddings for given queries and updates the internal query-to-embedding mapping. The method determines whether each query is already present in the `self.query_to_embedding` dictionary under the keys 'triple' and 'passage'. If a query is not present in either, it is encoded into embe...
get_query_embeddings
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def get_fact_scores(self, query: str) -> np.ndarray: """ Retrieves and computes normalized similarity scores between the given query and pre-stored fact embeddings. Parameters: query : str The input query text for which similarity scores with fact embeddings need...
Retrieves and computes normalized similarity scores between the given query and pre-stored fact embeddings. Parameters: query : str The input query text for which similarity scores with fact embeddings need to be computed. Returns: numpy.ndarray ...
get_fact_scores
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def dense_passage_retrieval(self, query: str) -> Tuple[np.ndarray, np.ndarray]: """ Conduct dense passage retrieval to find relevant documents for a query. This function processes a given query using a pre-trained embedding model to generate query embeddings. The similarity scores betwe...
Conduct dense passage retrieval to find relevant documents for a query. This function processes a given query using a pre-trained embedding model to generate query embeddings. The similarity scores between the query embedding and passage embeddings are computed using dot product, follo...
dense_passage_retrieval
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def get_top_k_weights(self, link_top_k: int, all_phrase_weights: np.ndarray, linking_score_map: Dict[str, float]) -> Tuple[np.ndarray, Dict[str, float]]: """ This function filters the all_phrase_weights to retain only the weig...
This function filters the all_phrase_weights to retain only the weights for the top-ranked phrases in terms of the linking_score_map. It also filters linking scores to retain only the top `link_top_k` ranked nodes. Non-selected phrases in phrase weights are reset to a weight of 0.0. ...
get_top_k_weights
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def graph_search_with_fact_entities(self, query: str, link_top_k: int, query_fact_scores: np.ndarray, top_k_facts: List[Tuple], top_k_fact_indices: List[str], ...
Computes document scores based on fact-based similarity and relevance using personalized PageRank (PPR) and dense retrieval models. This function combines the signal from the relevant facts identified with passage similarity and graph-based search for enhanced result ranking. Parameter...
graph_search_with_fact_entities
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def rerank_facts(self, query: str, query_fact_scores: np.ndarray) -> Tuple[List[int], List[Tuple], dict]: """ Args: Returns: top_k_fact_indicies: top_k_facts: rerank_log (dict): {'facts_before_rerank': candidate_facts, 'facts_after_rerank': top_k_facts} ...
Args: Returns: top_k_fact_indicies: top_k_facts: rerank_log (dict): {'facts_before_rerank': candidate_facts, 'facts_after_rerank': top_k_facts} - candidate_facts (list): list of link_top_k facts (each fact is a relation triple in tuple data type). ...
rerank_facts
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def run_ppr(self, reset_prob: np.ndarray, damping: float =0.5) -> Tuple[np.ndarray, np.ndarray]: """ Runs Personalized PageRank (PPR) on a graph and computes relevance scores for nodes corresponding to document passages. The method utilizes a damping facto...
Runs Personalized PageRank (PPR) on a graph and computes relevance scores for nodes corresponding to document passages. The method utilizes a damping factor for teleportation during rank computation and can take a reset probability array to influence the starting state of the computatio...
run_ppr
python
OSU-NLP-Group/HippoRAG
src/hipporag/HippoRAG.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/HippoRAG.py
MIT
def __init__(self, hipporag): """ Initializes the object with the necessary configurations and templates for processing input and output messages. Parameters: hipporag : An object that provides the global configuration and the LLM model required for inference. Attributes: ...
Initializes the object with the necessary configurations and templates for processing input and output messages. Parameters: hipporag : An object that provides the global configuration and the LLM model required for inference. Attributes: dspy_file_path : The file path for rer...
__init__
python
OSU-NLP-Group/HippoRAG
src/hipporag/rerank.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/rerank.py
MIT
def from_dict(cls, config_dict: Dict[str, Any]) -> "LLMConfig": """Create an LLMConfig instance from a dictionary.""" instance = cls() instance.batch_upsert(config_dict) return instance
Create an LLMConfig instance from a dictionary.
from_dict
python
OSU-NLP-Group/HippoRAG
src/hipporag/embedding_model/base.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/embedding_model/base.py
MIT
def from_json(cls, json_str: str) -> "LLMConfig": """Create an LLMConfig instance from a JSON string.""" instance = cls() instance.batch_upsert(json.loads(json_str)) return instance
Create an LLMConfig instance from a JSON string.
from_json
python
OSU-NLP-Group/HippoRAG
src/hipporag/embedding_model/base.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/embedding_model/base.py
MIT
def set(cls, content, embedding): """Store an embedding in the cache.""" with cls._lock: # Ensures thread safety cls._cache[content] = embedding
Store an embedding in the cache.
set
python
OSU-NLP-Group/HippoRAG
src/hipporag/embedding_model/base.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/embedding_model/base.py
MIT
def _init_embedding_config(self) -> None: """ Extract embedding model-specific parameters to init the EmbeddingConfig. Returns: None """ config_dict = { "embedding_model_name": self.embedding_model_name, "norm": self.global_config.embedding_r...
Extract embedding model-specific parameters to init the EmbeddingConfig. Returns: None
_init_embedding_config
python
OSU-NLP-Group/HippoRAG
src/hipporag/embedding_model/Contriever.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/embedding_model/Contriever.py
MIT
def _init_embedding_config(self) -> None: """ Extract embedding model-specific parameters to init the EmbeddingConfig. Returns: None """ config_dict = { "embedding_model_name": self.embedding_model_name, "norm": self.global_config.emb...
Extract embedding model-specific parameters to init the EmbeddingConfig. Returns: None
_init_embedding_config
python
OSU-NLP-Group/HippoRAG
src/hipporag/embedding_model/GritLM.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/embedding_model/GritLM.py
MIT
def calculate_metric_scores(self, gold_answers: List[List[str]], predicted_answers: List[str], aggregation_fn: Callable = np.max) -> Tuple[Dict[str, float], List[Dict[str, float]]]: """ Calculates the Exact Match (EM) score. Args: gold_answers (List[List[str]]): List of lists contai...
Calculates the Exact Match (EM) score. Args: gold_answers (List[List[str]]): List of lists containing ground truth answers. predicted_answers (List[str]): List of predicted answers. aggregation_fn (Callable): Function to aggregate scores across multiple gold answers...
calculate_metric_scores
python
OSU-NLP-Group/HippoRAG
src/hipporag/evaluation/qa_eval.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/evaluation/qa_eval.py
MIT
def calculate_metric_scores(self, gold_answers: List[List[str]], predicted_answers: List[str], aggregation_fn: Callable = np.max) -> Tuple[Dict[str, float], List[Dict[str, float]]]: """ Calculates the F1 score. Args: gold_answers (List[List[str]]): List of lists containing ground tr...
Calculates the F1 score. Args: gold_answers (List[List[str]]): List of lists containing ground truth answers. predicted_answers (List[str]): List of predicted answers. aggregation_fn (Callable): Function to aggregate scores across multiple gold answers (default: np....
calculate_metric_scores
python
OSU-NLP-Group/HippoRAG
src/hipporag/evaluation/qa_eval.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/evaluation/qa_eval.py
MIT
def calculate_metric_scores(self, gold_docs: List[List[str]], retrieved_docs: List[List[str]], k_list: List[int] = [1, 5, 10, 20]) -> Tuple[Dict[str, float], List[Dict[str, float]]]: """ Calculates Recall@k for each example and pools results for all queries. Args: gold_docs (List[Li...
Calculates Recall@k for each example and pools results for all queries. Args: gold_docs (List[List[str]]): List of lists containing the ground truth (relevant documents) for each query. retrieved_docs (List[List[str]]): List of lists containing the retrieved documents for each ...
calculate_metric_scores
python
OSU-NLP-Group/HippoRAG
src/hipporag/evaluation/retrieval_eval.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/evaluation/retrieval_eval.py
MIT
def batch_openie(self, chunks: Dict[str, ChunkInfo]) -> Tuple[Dict[str, NerRawOutput], Dict[str, TripleRawOutput]]: """ Conduct batch OpenIE synchronously using multi-threading which includes NER and triple extraction. Args: chunks (Dict[str, ChunkInfo]): chunks to be incorporated i...
Conduct batch OpenIE synchronously using multi-threading which includes NER and triple extraction. Args: chunks (Dict[str, ChunkInfo]): chunks to be incorporated into graph. Each key is a hashed chunk and the corresponding value is the chunk info to insert. Returns: ...
batch_openie
python
OSU-NLP-Group/HippoRAG
src/hipporag/information_extraction/openie_openai.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/information_extraction/openie_openai.py
MIT
def batch_openie(self, chunks: Dict[str, ChunkInfo]) -> Tuple[Dict[str, NerRawOutput], Dict[str, TripleRawOutput]]: """ Conduct batch OpenIE synchronously using vLLM offline batch mode, including NER and triple extraction Args: chunks (Dict[str, ChunkInfo]): chunks to be incorporate...
Conduct batch OpenIE synchronously using vLLM offline batch mode, including NER and triple extraction Args: chunks (Dict[str, ChunkInfo]): chunks to be incorporated into graph. Each key is a hashed chunk and the corresponding value is the chunk info to insert. Returns:...
batch_openie
python
OSU-NLP-Group/HippoRAG
src/hipporag/information_extraction/openie_vllm_offline.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/information_extraction/openie_vllm_offline.py
MIT
def batch_upsert_llm_config(self, updates: Dict[str, Any]) -> None: """ Upsert self.llm_config with attribute-value pairs specified by a dict. Args: updates (Dict[str, Any]): a dict to be integrated into self.llm_config. Returns: None ...
Upsert self.llm_config with attribute-value pairs specified by a dict. Args: updates (Dict[str, Any]): a dict to be integrated into self.llm_config. Returns: None
batch_upsert_llm_config
python
OSU-NLP-Group/HippoRAG
src/hipporag/llm/base.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/llm/base.py
MIT
def __post_init__(self) -> None: """ Initialize the templates directory and load templates. """ # if self.templates_dir is None: # current_file_path = os.path.abspath(__file__) # package_dir = os.path.dirname(current_file_path) # self.templates_dir = o...
Initialize the templates directory and load templates.
__post_init__
python
OSU-NLP-Group/HippoRAG
src/hipporag/prompts/prompt_template_manager.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/prompts/prompt_template_manager.py
MIT
def _load_templates(self) -> None: """ Load all templates from Python scripts in the templates directory. """ if not os.path.exists(self.templates_dir): logger.error(f"Templates directory '{self.templates_dir}' does not exist.") raise FileNotFoundError(f"Templates...
Load all templates from Python scripts in the templates directory.
_load_templates
python
OSU-NLP-Group/HippoRAG
src/hipporag/prompts/prompt_template_manager.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/prompts/prompt_template_manager.py
MIT
def render(self, name: str, **kwargs) -> Union[str, List[Dict[str, Any]]]: """ Render a template with the provided variables. Args: name (str): The name of the template. kwargs: Placeholder values for the template. Returns: Union[str, List[Dict[str, ...
Render a template with the provided variables. Args: name (str): The name of the template. kwargs: Placeholder values for the template. Returns: Union[str, List[Dict[str, Any]]]: The rendered template or chat history. Raises: ValueError...
render
python
OSU-NLP-Group/HippoRAG
src/hipporag/prompts/prompt_template_manager.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/prompts/prompt_template_manager.py
MIT
def get_template(self, name: str) -> Union[Template, List[Dict[str, Any]]]: """ Retrieve a template by name. Args: name (str): The name of the template. Returns: Union[Template, List[Dict[str, Any]]]: The requested template. Raises: KeyError...
Retrieve a template by name. Args: name (str): The name of the template. Returns: Union[Template, List[Dict[str, Any]]]: The requested template. Raises: KeyError: If the template is not found.
get_template
python
OSU-NLP-Group/HippoRAG
src/hipporag/prompts/prompt_template_manager.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/prompts/prompt_template_manager.py
MIT
def print_template(self, name: str) -> None: """ Print the prompt template string or chat history structure for the given template name. Args: name (str): The name of the template. Raises: KeyError: If the template is not found. """ try: ...
Print the prompt template string or chat history structure for the given template name. Args: name (str): The name of the template. Raises: KeyError: If the template is not found.
print_template
python
OSU-NLP-Group/HippoRAG
src/hipporag/prompts/prompt_template_manager.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/prompts/prompt_template_manager.py
MIT
def retrieve_knn(query_ids: List[str], key_ids: List[str], query_vecs, key_vecs, k=2047, query_batch_size=1000, key_batch_size=10000): """ Retrieve the top-k nearest neighbors for each query id from the key ids. Args: query_ids: key_ids: k: top-k query_batch_...
Retrieve the top-k nearest neighbors for each query id from the key ids. Args: query_ids: key_ids: k: top-k query_batch_size: key_batch_size: Returns:
retrieve_knn
python
OSU-NLP-Group/HippoRAG
src/hipporag/utils/embed_utils.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/utils/embed_utils.py
MIT
def normalize_answer(answer: str) -> str: """ Normalize a given string by applying the following transformations: 1. Convert the string to lowercase. 2. Remove punctuation characters. 3. Remove the articles "a", "an", and "the". 4. Normalize whitespace by collapsing multiple spaces into one. ...
Normalize a given string by applying the following transformations: 1. Convert the string to lowercase. 2. Remove punctuation characters. 3. Remove the articles "a", "an", and "the". 4. Normalize whitespace by collapsing multiple spaces into one. Args: answer (str): The input string to...
normalize_answer
python
OSU-NLP-Group/HippoRAG
src/hipporag/utils/eval_utils.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/utils/eval_utils.py
MIT
def convert_format_to_template(original_string: str, placeholder_mapping: Optional[dict] = None, static_values: Optional[dict] = None) -> str: """ Converts a .format() style string to a Template-style string. Args: original_string (str): The original string using .format() placeholders. pla...
Converts a .format() style string to a Template-style string. Args: original_string (str): The original string using .format() placeholders. placeholder_mapping (dict, optional): Mapping from original placeholder names to new placeholder names. static_values (dict, optional): Mapping f...
convert_format_to_template
python
OSU-NLP-Group/HippoRAG
src/hipporag/utils/llm_utils.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/utils/llm_utils.py
MIT
def safe_unicode_decode(content: Union[bytes, str]) -> str: """ Safely decodes a string or byte sequence containing Unicode escape sequences into a properly decoded Unicode string. Args: content (Union[bytes, str]): The input data, either as a byte sequence or a string, which may contain Unicode es...
Safely decodes a string or byte sequence containing Unicode escape sequences into a properly decoded Unicode string. Args: content (Union[bytes, str]): The input data, either as a byte sequence or a string, which may contain Unicode escape sequences. Returns: str: The decoded Unicode stri...
safe_unicode_decode
python
OSU-NLP-Group/HippoRAG
src/hipporag/utils/llm_utils.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/utils/llm_utils.py
MIT
def dynamic_retry(experiment_config: BaseConfig): """ Factory function to create a retry decorator with dynamic parameters. Args: experiment_config (BaseConfig): Configuration containing stop and wait parameters. Expected to use the global config for running all experiments. Returns: ...
Factory function to create a retry decorator with dynamic parameters. Args: experiment_config (BaseConfig): Configuration containing stop and wait parameters. Expected to use the global config for running all experiments. Returns: Callable: A retry decorator with dynamically set paramete...
dynamic_retry
python
OSU-NLP-Group/HippoRAG
src/hipporag/utils/llm_utils.py
https://github.com/OSU-NLP-Group/HippoRAG/blob/master/src/hipporag/utils/llm_utils.py
MIT