Skip to main content

A collection of functions/classes that supplements torch functionality.

Project description


More convenient features based on PyTorch (originally Torchure)


TorchFun project was initiated long ago and was published in 2018-6-13.

The purposed of TorchFun is to provide functions which are important and convenient, but absent in PyTorch, like some layers and visualization utils.

This project has been undergoing in secret so that the author could credit TorchFun to his beloved as a little supprise of help, one day when this project is well-enriched or gets famous.

Interestingly, The original project name given by the author, is Torchure. That is because he was always multi-tasking trivial affairs in school and got scorched, and when he was learning this new framework in hope to help his beloved, he found plenty of issues/missing-functionalities. He felt that this was totally a torture. So, this project was named "Torchure" to satirize the lame PyTorch (you can still found Torchure in PyPi). And, the author hoped, by developing Torchure, his beloved could feel ease even when encountering the crappy-parts of PyTorch.

This history-of-project was appended recently, because his adorable little beloved wants a supprise immediately, or she will keep rolling on the floor.

Latest Documentation:

Please visit:


  • Flatten
  • flatten()
  • Subpixel
  • subpixel()
  • imshow()
  • load()
  • save()
  • count_parameters()
  • Packsearch
  • packsearch()
  • hash_parameters()
  • force_exist()
  • whereis()

Install TorchFun


pip install torchfun


pip install -U torchfun


Flatten [Module]

used to reshape outputs


    flat = Flatten()
    out = flat(x)

flatten(x) [Function]


    out = flatten(x)

subpixel(x,out_channels) [Function]

Unfold channel/depth dimensions to enlarge the feature map


Output size is deducted. 
The size of the unfold square is automatically determined

e.g. :

images: 100x16x16x9.  9=3x3 square
subpixel-out: 100x48x48x1


out_channels, channel number of output feature map

Subpixel Layer [Module]

Same functionality as subpixel(x), but with Module interface.

s = Subpixel(out_channels=1)
out = s(x)

imshow(x,title=None,auto_close=True) [Function]

only deal with torch channel-first image batch,


  • x: input data cube, torch tensor or numpy array.
  • title: add title to plot. (Default None)
    • title can be string, or any string-able object.
  • auto_close: (default True)
    • Close the pyplot session afterwards.
    • Clean the environment just like you had never used matplotlib here.
    • if set to False, the plot will remain in the memory for further drawings.




    TorchFun:imshow:Warning, you are using WebAgg backend for Matplotlib. 
    Please consider windowed display SDKs such as TkAgg backend and GTK* backends.

This means your matplotlib is using web-browser for figure display. We strongly recommend you to use window-based native display because browser-based backends are fragile and tend to crash. You can change the display mamanger for matplotlib each time you execute your script by:

import matplotlib
matplotlib.use('TkAgg') # or GTK GTKAgg

or permanantly by editing: site-packages/matplotlib/mpl-data/matplotlibrc and change backend to TkAgg

A full list of available backends can be found at:

import matplotlib

and, the TCL/TK GUI library for tkinter can be downloaded here.

load(a,b) [Function]


  • arbitrary arguemnts named : a and b Load weight a into model b, or load model b using weight a The order of the arguments doesn't matter. Example:




    >f = open('weight.pts')



Return value:

  • None

save(a,b) [Function]


  • arbitrary arguemnts named : a and b

save weight a into target b, or save model b into target a The order of the arguments doesn't matter.






    >f = open('weight.pts')







Return value: None

count_parameters(model_or_dict_or_param) [Function]

Count parameter numer of a module/state_dict/layer/tensor. This function can also print the occupied memory of parameters in MBs


  • model_or_dict_or_param: model or state dictionary or parameters()

Return: parameter amount in python-int Returns 0 if datatype not understood


    count_parameters(state_dict) #all params 
    count_parameters(model.parameters()) #only trainable params

Packsearch [Module]

This is a very useful thing you definitly have been dreaming of.

You can now use packsearch to query names inside any package!

Given an module object as input:

   > p = Packsearch(torch) 
or > p = Packsarch(numpy) whatever

the instance p provide method. So that you can search everything inside this package



Packsearch: 35 results found:
-------------results start-------------
0        torch.nn.AdaptiveMaxPool1d
1        torch.nn.AdaptiveMaxPool2d
2        torch.nn.AdaptiveMaxPool3d
3        torch.nn.FractionalMaxPool2d
4        torch.nn.MaxPool1d
5        torch.nn.MaxPool2d

packsearch(module,keyword) [Function]

or packsearch(keyword,module)

Given an module object, and search pattern string as input:

> packsearch(torch,'maxpoo')


> packsearch('maxpoo',torch)

    Packsearch: 35 results found:
    -------------results start-------------
    0        torch.nn.AdaptiveMaxPool1d
    1        torch.nn.AdaptiveMaxPool2d
    2        torch.nn.AdaptiveMaxPool3d
    3        torch.nn.FractionalMaxPool2d
    4        torch.nn.MaxPool1d
    5        torch.nn.MaxPool2d

you can search for everything inside any package

hash_parameters(module_or_statdict_or_param) [Function]

return the summary of all variables.

This is used to detect chaotic changes of weights. You can check the sum_parameters before and after some operations, to know if there is any change made to the params.

I use this function to verify gradient behaviours.

By default, This only hash the trainable parameters!


  • module_or_statdict_or_param: torch.nn.module, or model.state_dict(), or model.parameters().
  • use_sum: return the sum instead of mean value of all params.

Usage demo:

model = MyNet()
print(hash_parameters(model)) # see params
print(hash_parameters(model)) # see if params are updated
print(hash_parameters(model.state_dict())) # see if trainable+un-trainable params are updated

force_exist(dirname,verbose=True) [Function]

force a series of hierachical directories to exist.

force_exist can automatically create directory with any depth.


  • dirname: path of the desired directory
  • verbose: print every directory creation. default True.



sort_args(args_or_types,types_or_args) [Function]

This is a very interesting function. It is used to support arbitrary-arguments-ordering in TorchFun.

Input: The function takes a list of types, and a list of arguments.

Returns: a list of arguments, with the same order as the types-list.

Of course, sort_args supports arbitrary-arguments-ordering by itself.

whereis(module_or_string) [Function]

find the source file location of a module arguments:

  • module_or_string: target module object, or it's string path like torch.nn
  • open_gui: open the folder with default window-manager.


  • module file name, or None

Project details

Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for torchfun, version 1.0.83
Filename, size File type Python version Upload date Hashes
Filename, size torchfun-1.0.83-py3-none-any.whl (49.9 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size torchfun-1.0.83.tar.gz (47.4 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page