add class to torch module list - pytorch

I am using libtorch to create a model. In that, I have a class named Layer1. I need to add it to the moduleList.
class Layer1 : torch::nn::Module {
public:
Layer1(int input_dim, int output_dim) {
....
}
}
class Model : torch::nn::Module {
public:
torch::nn::ModuleList layers;
Model(int input_dim, output_dim) {
this->layers->push_back(std::make_shared<Layer1>(input_dim, output_dim));
}
}
I am getting the following error on compilation
/opt/homebrew/include/torch/csrc/api/include/torch/nn/modules/container/modulelist.h:90:8: note: candidate function not viable: no known conversion from 'shared_ptr<Layer1>' to 'shared_ptr<torch::nn::Module>' for 1st argument

Related

TypeScript: Decorating a derived class with typed decorator function

I am trying to build an "Entity Framework"-like ORM library for node.js and MongoDB with TypeScript.
With this library, the consumer will be able to define a Model class (ex. Person) that will extend a Base class, and the class decorator will add additional data to the Person class (for example, instances array, that will contain all the Model's instances, and collection_name that will be the MongoDB collection name for the model, etc.).
Code in TypeScript playground.
So my first step was creating a Base class:
class Base<T>
{
static collection_name: string
static instances: Base<any>[]
_id: string
}
So the user will be able to define his model like so:
#decorator<Person>({collection_name: 'people'})
class Person extends Base<Person>
{
#field name
#field address
...
}
then I created a decorator class to set the collection_name and instances properties on the Person class:
function decorator<T>(config: { collection_name: string }) {
return function <T extends Base<T>>(Class: IClass<T>) {
Class.collection_name = config.collection_name;
Class.instances = [];
return Class
}
}
the decorator function receives the user-generated Class, and I am trying to create an interface that will describe the type of such class. I called it IClass:
interface IClass<T>
{
new(): Base<T>
instances: Base<T>[];
collection_name: string
}
new is the constructor (that returns a Base instance)
instances and collection_name are static properties of Base<T> and are non-static here (I'm not sure about this, is this right?)
However, when trying to define the user Model I get the following error:
#decorator<Person>({collection_name: 'people'}) // <==== ERROR HERE ===
class Person extends Base<Person>
{
}
Error:(23, 2) TS2345: Argument of type 'typeof Person' is not
assignable to parameter of type 'IClass>'.
Property 'instances' is missing in type 'typeof Person' but
Type 'typeof Person' is missing the following properties from type
required in type 'IClass>'.
It seems like the typescript compiler is ignoring the static members inherited from Base when checking the type of typeof Person.
How can I define the type of the Class property of the decorator function ?
The problem as jcalz points out is that your decorator is accepting a Class of a type that already has the static properties instances and collection_name. You need to use two different interfaces, one which is a type that simply constructs instances of T with the new(): T signature, and another that extends this interface to include the static properties your decorator will add.
class Base<T> {
static _id = 0;
private _id: number;
constructor () {
this._id = Base._id++;
}
}
interface BaseConstructor<T extends Base<T>> {
_id: number;
new(): T;
}
interface DecoratedBaseConstructor<T extends Base<T>> extends BaseConstructor<T> {
instances: T[];
collection_name: string;
}
function decorator<T extends Base<T>>(config: { collection_name: string }) {
return (baseConstructor: BaseConstructor<T>): DecoratedBaseConstructor<T> => {
const decoratedBaseConstructor = baseConstructor as Partial<DecoratedBaseConstructor<T>>;
decoratedBaseConstructor.collection_name = config.collection_name;
decoratedBaseConstructor.instances = [];
return decoratedBaseConstructor as DecoratedBaseConstructor<T>;
};
}
#decorator<Person>({collection_name: 'people'})
class Person extends Base<Person> {
name: string;
constructor () {
super();
this.name = 'foo';
}
}
With this approach, all of Base's static members must be public. Any static members of Base initialized in the decorator should go in the DecoratedBaseConstructor, and any remaining static members not initialized in the decorator should go in the BaseConstructor instead.
I assume that you use the generic type T in the Base class somehow in your actual code, but if you don't, you should remove the generic type from the Base class and everything else will still work the same.
Check out the above snippet in this playground.

Unable to instantiate nested exception class due to constructor not found

I want to define a BarException inside of class Foo for namespacing reason. This is what my Foo class looks like:
package org.company.utils
class Foo {
class BarException extends RuntimeException { }
def raise() {
def r = new RuntimeException("BOOM")
throw new BarException(r)
}
}
This is how I would have liked it to work:
void testFoo() {
shouldFail(Foo.BarException) {
def foo = new Foo()
foo.raise()
}
}
But the test failed with:
1) testFoo(test.FooTestCase)java.lang.AssertionError: Closure
test.FooTestCase$_testFoo_closure1#3eb25e1a should have failed with an
exception of type org.company.utils.Foo$BarException, instead got
Exception groovy.lang.GroovyRuntimeException: Could not find matching
constructor for:
org.company.utils.Foo$BarException(org.company.utils.Foo,
java.lang.RuntimeException)
I have tried instantiating BarException using new BarException(this, r), and putting groovy.transform.InheritConstructors around BarException, but nothing works for the compiler.
What's the problem?
Try making BarException static and add #InheritConstructors.
import groovy.transform.InheritConstructors
class Foo {
#InheritConstructors
static class BarException extends Exception { }
def raise() {
Throwable r = new RuntimeException("BOOM")
throw new BarException(r)
}
}
From the groovy docs:
The usage of static inner classes is the best supported one. If you
absolutely need an inner class, you should make it a static one.

Variant Generic Interfaces

I have a generic interface, and a class implementing that interface with a concrete type parameter. I also have a generic class using the generic interface as its type constraint, but the type parameter is restricted to be a subclass of a certain base class. I want to instance the generic class with the class implementing that interface but have a problem of converting the class to that interface. The following code illustrates all the classes I mentioned:
The base class:
class DomainBase
{
}
The class used as the type parameter in the interface
class Person : DomainBase
{
}
The generic interface:
public interface IRepository<T> where T : class
{
IEnumerable<T> Fetch();
T Persist(T item);
}
The class implementing the generic interface:
class PersonRepository : IRepository<Person>
{
public IEnumerable<Person> Fetch()
{
...
}
public Person Persist(Person item)
{
...
}
}
The generic class using the generic interface:
class DomainBaseViewModel<Repository>
where Repository : IRepository<DomainBase>, new()
{
private Repository repository = new Repository();
private ObservableCollection<DomainBase> items;
}
However, the following line can't get compiled because PersonRepository is unable to be converted to IRepository<DomainBase>:
var viewModel = new DomainBaseViewModel<PersonRepository>();
Although I can solve this issue by covariance but it disallows the use of the type parameter in parameter lists:
public interface IRepository<out T> where T : class
{
...
T Persist(object item);
}
class PersonRepository : IRepository<Person>
{
public Person Persist(object item)
{
...
}
}
So I have to convert the parameter to Person, which compromises type safety.
Is there a better way to allow covariance and the use of type parameter in parameter lists in this case?
No - the whole point of the restriction on covariance is that it guarantees safety. A PersonRepository isn't an IRepository<DomainBase> because you can't ask it to persist any arbitrary DomainBase object. What would you expect this code to do?
class Product : DomainBase {}
...
IRepository<DomainBase> repository = new PersonRepository();
repository.Persist(new Product());
PersonRepository doesn't know how to persist Product values.
If in some cases you only need the "read" parts of the repository interface, you could always call that out explicitly:
public interface IRepositoryReader<out T>
{
IEnumerable<T> Fetch();
}
public interface IRepository<T> : IRepositoryReader<T>
{
T Persist(T item);
}
Then your DomainBaseViewModel class could be:
class DomainBaseViewModel<TRepository>
where TRepository : IRepositoryReader<DomainBase>, new()
{
private TRepository repository = new TRepository();
private ObservableCollection<DomainBase> items;
}
That doesn't work if you want your DomainBaseViewModel to persist items as well though. In that case, perhaps it should be generic in the type of model as well:
class DomainBaseViewModel<TRepository, TEntity>
where TRepository : IRepository<TEntity>, new()
{
private TRepository repository = new Repository();
private ObservableCollection<TEntity> items;
}
Then:
var viewModel = new DomainBaseViewModel<PersonRepository, Person>();

How to reuse feature methods in a #Stepwise Spock specification?

I have two Spock specifications, both test a long procedure from a different starting point, so it's like
#Stepwise
class FooSpec extends Specification {
def "setup1"() {...}
def "setup2"() {...}
def "common1"() {...}
def "common2"() {...}
...
}
#Stepwise
class BarSpec extends Specification {
def "setup3"() {...}
def "setup4"() {...}
def "common1"() {...}
def "common2"() {...}
...
}
Now I'd like to refactor my code to deduplicate all the common* feature methods, that are to be executed after the different setups.
I tried to use subclassing, but the superclass' feature methods are executed before and not after the subclass' ones. I also tried to write an own Spock extension (Spock version 0.7 for Groovy 2), but couldn't find a way to implement my desired behaviour there.
Consulting the source code of StepwiseExtension, I finally managed to come up with my own solution:
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.RUNTIME)
#ExtensionAnnotation(BeforeSuperExtension)
#interface BeforeSuper {}
This annotation marks feature methods in a #Stepwise test, that should be executed before super's feature methods.
The extension implementation will rearrange the execution order accordingly:
class BeforeSuperExtension extends AbstractAnnotationDrivenExtension<BeforeSuper>
{
def beforeSuper = []
#Override
void visitFeatureAnnotation(BeforeSuper annotation, FeatureInfo feature)
{
beforeSuper << feature
}
#Override
void visitSpec(SpecInfo spec)
{
def superFeatures = spec.superSpec.allFeaturesInExecutionOrder
def afterSuper = spec.features - beforeSuper
(beforeSuper + superFeatures + afterSuper).eachWithIndex { f, i ->
f.executionOrder = i
}
}
}
Put the common* methods in a base class, and add two subclasses with a setupSpec() method (instead of the setup* methods).
I've implemented the opposite strategy, with an annotation #AfterSubSpec that tells common methods in the superclass to run after methods in the subclass:
class AfterSubSpecExtension extends AbstractAnnotationDrivenExtension<AfterSubSpec> {
def afterSub = []
#Override
void visitFeatureAnnotation(AfterSubSpec annotation, FeatureInfo feature) {
afterSub << feature
}
#Override
void visitSpec(SpecInfo spec) {
def subSpecFeatures = spec.bottomSpec.allFeaturesInExecutionOrder - afterSub
(subSpecFeatures + afterSub).eachWithIndex { f, i -> f.executionOrder = i }
}
}

Type of 'return this' in a Groovy #Mixin

I have a mixin class that bundles functionality for different types that do not share a common heritage. The mixing is applied using the #Mixin annotation, so it is handled at compile time.
Some of the mixin methods return this as the result of a method call. The problem is that the this is of the mixing type and not the type of the base class. When I want to work typed in the rest of the application a ClassCastException is thrown saying that the mixing type can not be cast to the base type.
In the example code below return this returns an object of type AMixin instead of an Object of type BaseClass.
How can I have return this return an object of type BaseClass instead of an object of type AMixin?
class AMixin {
def getWhatIWant(){
if(isWhatIwant){
return this
} else {
getChildWhatIWant()
}
}
def getChildWhatIWant(){
for (def child in childred) {
def whatIWant = child.getWhatIWant()
if (whatIWant) {
return whatIWant
}
}
return null
}
}
#Mixin(AMixin)
class BaseClass {
boolean isWhatiWant
List<baseClass> children
}
I just ran into this same situation. I solved it by setting 'this' from the concrete class into a private variable 'me' inside the concrete class and return 'me' in the Mixin classes. For example:
class MyMixin {
def mixinMethod() {
// do stuff
return me
}
}
#Mixin(MyMixin)
class MyConcreteClass {
private MyConcreteClass me
MyConcreteClass() {
me = this
}
}
I feel like it's a bit kludgy, but I think it's a lot simpler than this other solution. I personally need the ability to use the same Mixin in multiple classes, and it sounds like this other proposed solution would not allow for that if you cannot assign multiple Categories to a single Mixin class.
I created the class Base added the category to the AMixin Class and the BaseClass extends from Base.....(http://groovy.codehaus.org/Category+and+Mixin+transformations)
Executed this in GroovyConsole I get
BaseClass#39c931fb
class Base {
boolean isWhatIwant
List<BaseClass> children
}
#Category(Base)
class AMixin {
def getWhatIWant(){
if(isWhatIwant){
return this
} else {
getChildWhatIWant()
}
}
def getChildWhatIWant(){
for (def child in children) {
def whatIWant = child.getWhatIWant()
if (whatIWant) {
return whatIWant
}
}
return null
}
}
#Mixin(AMixin)
public class BaseClass extends Base {
}
def b = new BaseClass(isWhatIwant:true)
println b.getWhatIWant()
EDIT just a DummyClass. I know it's very awkward that It works....I'm sure Guillaume Laforge could answer how this works...
class DummyClass {
}
#Category(DummyClass)
class AMixin {
def getWhatIWant(){
if(isWhatIwant){
return this
} else {
getChildWhatIWant()
}
}
def getChildWhatIWant(){
for (def child in children) {
def whatIWant = child.getWhatIWant()
if (whatIWant) {
return whatIWant
}
}
return null
}
}
#Mixin(AMixin)
public class BaseClass extends DummyClass {
boolean isWhatIwant
List<BaseClass> children
}
def b = new BaseClass(isWhatIwant:true)
println b.getWhatIWant()

Resources